Skip to content
This repository has been archived by the owner on Apr 12, 2021. It is now read-only.

Python 3 #39

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.tox/
*.clouseau
*.swn
*.egg-info
Expand Down
8 changes: 4 additions & 4 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
language: python
python:
- "2.7"
- 2.7
- 3.6
install:
- pip install -r requirements.txt
- pip install -r requirements.txt
script:
- pip freeze
- nosetests -d
- nosetests
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ See the **Get Involved** section at the end of this readme to see the current st
- Unix-based OS, such as Mac or Linux (Windows support is unclear at this time.)
- [git](http://git-scm.com/)
- [Python 2.7](https://www.python.org/download/releases/2.7/)
or [Python 3.4](https://www.python.org/downloads/release/python-343/)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If tox and Travis are using 3.6, want to bump this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good call

- [virtualenv](https://virtualenv.pypa.io/en/latest/)

See the [requirements.txt](requirements.txt) file for additional dependencies to be installed in the quick setup.
Expand Down
6 changes: 3 additions & 3 deletions clouseau/clients/abstract.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from builtins import object

from abc import ABCMeta, abstractmethod
from future.utils import with_metaclass



class AbstractClient:
__metaclass__ = ABCMeta

class AbstractClient(with_metaclass(ABCMeta, object)):
@abstractmethod
def render(self,data):
"""
Expand Down
25 changes: 13 additions & 12 deletions clouseau/clients/console.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from abstract import AbstractClient
from __future__ import absolute_import
from .abstract import AbstractClient
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we're doing this, could we just use the full paths to the imports?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably? This came from the earlier Python 3 PR, so it's not code I wrote. I'll take a look, though

from jinja2 import Template, Environment, PackageLoader
from colors import *
from .colors import *
import codecs
import re
import subprocess
import sys
import os
import tempfile

class ConsoleClient(AbstractClient):
"""
Expand Down Expand Up @@ -62,20 +65,18 @@ def render(self, terms, data):
#m[1] = m[1].replace(term, orange_bg(term) )




data_to_render = template.render(data=data)
scratchfile_handle, scratchfile_path = tempfile.mkstemp()
rendered = template.render(data=data)

with codecs.open(scratchfile_path, 'w', 'utf-8') as scratchfile:
scratchfile.write(rendered)

try:
pager = subprocess.Popen(['less', '-F', '-R', '-S', '-X', '-K'], stdin=subprocess.PIPE, stdout=sys.stdout)
lines = data_to_render.split('\n')
for line in lines:
pager.stdin.write( line.encode('utf-8') + '\n' )
pager.stdin.close()
pager.wait()
subprocess.call(['less', '-F', '-R', '-S', '-X', '-K'], stdin=scratchfile_handle)
except KeyboardInterrupt:
pass

finally:
os.remove(scratchfile_path)



Expand Down
6 changes: 4 additions & 2 deletions clouseau/clients/console_thin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from abstract import AbstractClient
from __future__ import print_function
from __future__ import absolute_import
from .abstract import AbstractClient
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same with the import path

from jinja2 import Template, Environment, PackageLoader

class ConsoleThinClient(AbstractClient):
Expand All @@ -19,4 +21,4 @@ def render(self, terms, data):
template = env.get_template('console_thin.html')

data_to_render = template.render(data=data, has_matches=len(matches) > 0)
print data_to_render
print(data_to_render)
28 changes: 16 additions & 12 deletions clouseau/clouseau.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from __future__ import print_function
from __future__ import absolute_import
from builtins import object
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it work that these imports are above the #! and coding lines?

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
Expand All @@ -9,17 +12,17 @@
import pprint
import sys
import subprocess
from clients import *
from clients.colors import *
from parser import Parser
from commit_parser import CommitParser
from terms_collector import TermsCollector
from clouseau_model import ClouseauModel
from .clients import *
from .clients.colors import *
from .parser import Parser
from .commit_parser import CommitParser
from .terms_collector import TermsCollector
from .clouseau_model import ClouseauModel
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above re: imports



VERSION='0.2.0'

class Clouseau:
class Clouseau(object):
"""
Wrap and delegate
"""
Expand All @@ -41,7 +44,7 @@ def main(self , _args, client):
if(not args['skip']):
self.clone_repo( args['url'], args['repo_dir'] )
else:
print blue( 'Skipping git-clone or git-pull as --skip was found on the command line.' )
print(blue( 'Skipping git-clone or git-pull as --skip was found on the command line.' ))

if args['revlist'] != None and args['revlist'] != 'all':
parser = CommitParser()
Expand All @@ -61,14 +64,14 @@ def clone_repo(self, url, destination):
_out = subprocess.check_output(['git', 'clone', url, destination])

except subprocess.CalledProcessError:
print blue( "Directory, %s, exits. Trying git-pull instead of clone." % destination )
print(blue( "Directory, %s, exits. Trying git-pull instead of clone." % destination ))
_out = subprocess.check_output(['git', '--git-dir=%s/.git' % destination, 'pull'])
print smoke( "Git says: %s" % _out )
print(smoke( "Git says: %s" % _out ))
return _out

except :
e = sys.exc_info()[0]
print red( 'Problem writing to destination: %s' % destination )
print(red( 'Problem writing to destination: %s' % destination ))
raise

return _out
Expand All @@ -83,7 +86,8 @@ def parse_args( self, arguments ):
_pattern_path = os.path.join( _dir, _default_pattern_file )
_temp = os.path.join( _dir, "../temp")

p = arse.ArgumentParser (prog="clouseau", description=" Clouseau: A silly git inspector", version=VERSION)
p = arse.ArgumentParser (prog="clouseau", description=" Clouseau: A silly git inspector")
p.add_argument('--version', action='version', version=VERSION)
p.add_argument('--url', '-u', required=True, action="store", dest="url",
help="The fully qualified git URL (http://www.kernel.org/pub/software/scm/git/docs/git-clone.html)")
p.add_argument('--term', '-t', required=False, action="store", dest="term",
Expand Down
1 change: 1 addition & 0 deletions clouseau/clouseau_model.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from builtins import object
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above re: placement above the #!.

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
Expand Down
11 changes: 7 additions & 4 deletions clouseau/commit_parser.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
from __future__ import print_function
from __future__ import absolute_import
from builtins import object

import os
import sys
import re
import subprocess
import pprint
from clouseau_model import ClouseauModel
from .clouseau_model import ClouseauModel
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same re: imports



# -----------------------------------------------------------------------------------------------
class CommitParser:
class CommitParser(object):
"""
Converts git-show's stdout to Python dictionary for any commit messages and file changes that match the terms in the patterns files
"""
Expand All @@ -25,7 +28,7 @@ def parse( self, terms, repo, revlist, clouseau_model, **kwargs ):
for rev in revlist.strip().split(' '):
output = self.get_commit(git_dir, rev)
if output.strip() == '':
print "WARNING: No output was returned from git for commit [%s]. Ensure the commit exists" % rev
print("WARNING: No output was returned from git for commit [%s]. Ensure the commit exists" % rev)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we use .format() string formatting? From there it's not a huge jump to f-strings when we go python 3.6+ only 😈 .

else:
self.parse_commit( terms, output, clouseau_model )

Expand All @@ -38,7 +41,7 @@ def get_commit(self, git_dir, commit):
git_show = subprocess.Popen(git_show_cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE) # , cwd=git_dir
(out,err) = git_show.communicate()
if err:
print "ERROR running git command [%s]: %s" % (git_show_cmd, err)
print("ERROR running git command [%s]: %s" % (git_show_cmd, err))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above re: string formatting.


return out

Expand Down
16 changes: 9 additions & 7 deletions clouseau/parser.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from builtins import str
from builtins import object

import os
import sys
import re
import subprocess

# -----------------------------------------------------------------------------------------------
class Parser:
class Parser(object):
"""
Converts git-grep's stdout to Python dictionary
"""
Expand Down Expand Up @@ -60,32 +62,32 @@ def search( self, git_dir, terms, revlist, clouseau ):
stdout=subprocess.PIPE)

(out,err) = git_grep.communicate()

clouseau.update( {term: {}} )

for line in out.split('\n'):
for line in out.split(b'\n'):
# We don't know how a lot of the data is encoded, so make sure it's utf-8 before
# processing
if line == '':
continue
try:
line = unicode( line, 'utf-8' )
line = str( line, 'utf-8' )
except UnicodeDecodeError:
line = unicode( line, 'latin-1' )
line = str( line, 'latin-1' )
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More a comment than anything specific to this PR, this seems like an incredibly fragile way to test encoding.



if file_name_heading.match( line ):
title = line.split(':', 1)[1]
title = line.replace('/','_')
title = title.replace('.','_').strip()
_src = line.strip().encode('utf-8')
_srca = _src.split(':', 1)
_srca = _src.split(b':', 1)
clouseau[term][title] = {'src' : _srca[1] }
clouseau[term][title]['refspec'] = _srca[0]
git_log_cmd = subprocess.Popen( ['git', '--git-dir', git_dir, 'log', _srca[0] , '-1'],\
stderr=subprocess.PIPE, stdout=subprocess.PIPE )
git_log = git_log_cmd.communicate()[0]
clouseau[term][title]['git_log'] = [ x.strip() for x in git_log.split('\n') if x != '' ]
clouseau[term][title]['git_log'] = [ x.strip() for x in git_log.split(b'\n') if x != '' ]
#clouseau[term][title] = {'ref' : _srca[0] }
clouseau[term][title]['matched_lines'] = []
continue
Expand Down
3 changes: 2 additions & 1 deletion clouseau/terms_collector.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from builtins import object
import os
import sys


# -----------------------------------------------------------------------------------------------
class TermsCollector:
class TermsCollector(object):
"""
Collects all search terms from the patterns files
"""
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
jinja2
nose
nose-progressive
future
1 change: 0 additions & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
[nosetests]
verbosity=2
nocapture=1
with-progressive=1
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
'download_url': 'http://tbd.com',
'author_email': 'bill@if.io',
'version': '0.2.0',
'install_requires': ['jinja2','nose','nose-progressive'],
'install_requires': ['jinja2','nose'],
'packages': ['clouseau','tests'],
'package_data': {'clouseau': ['clients/*.py', 'patterns/*.txt', 'templates/*.html']},
'py_modules': [],
Expand Down
2 changes: 1 addition & 1 deletion tests/clouseau_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def commit_parser_merge_only_test():
terms = TermsCollector().collect_terms('clouseau/patterns/default.txt', None)
model = ClouseauModel('https://github.com/cfpb/clouseau', terms)
parser.parse_commit(terms, commit_output.read(), model)
exec_in_commit = model.model['exec'].keys()[0]
exec_in_commit = list(model.model['exec'].keys())[0]
eq_(1, model.model['exec'][exec_in_commit]['matched_lines'][0][0])
eq_('Commit Message', model.model['exec'][exec_in_commit]['src'])

Expand Down
15 changes: 8 additions & 7 deletions tests/color_tests.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function
from clouseau.clients import colors




print dir( colors )
print(dir( colors ))

for c in colors.codes:
print colors.color( c, c )
print(colors.color( c, c ))


print colors.ok()
print colors.fail()
print(colors.ok())
print(colors.fail())

print colors.ok( 'OK with text' )
print colors.fail( 'Fail with text' )
print(colors.ok( 'OK with text' ))
print(colors.fail( 'Fail with text' ))


print ('-------------------')

print colors.gray('Gray Text')
print(colors.gray('Gray Text'))



Expand Down
3 changes: 2 additions & 1 deletion tests/integration_tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
import os
from nose.tools import *
from clouseau.clouseau import Clouseau
Expand All @@ -15,7 +16,7 @@ def console_client_test():
terms = ['password']
args = ['-u', 'https://github.com/virtix/cato.git']
parsed = clouseau.parse_args( args )
print parsed
print(parsed)
ids = parser.parse( terms=terms, repo=parsed['repo_dir'], revlist=parsed['revlist'],
before=parsed['before'], after=parsed['after'], author=parsed['author'],
github_url=parsed['github_url'])
Expand Down
6 changes: 6 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[tox]
envlist=py27,py36,py37

[testenv]
deps=-rrequirements.txt
commands=nosetests
Empty file modified travis_clouseau.sh
100644 → 100755
Empty file.