Commits

Anonymous committed 9df9fca

reorganized code, so it can be used without hg

  • Participants
  • Parent commits 0fb6ab8

Comments (0)

Files changed (5)

 [patterns]
 .deps = native
+.dmrc = native
 .hgignore = native
+.hgignorechecks = native
 .hgeol = native
 **.txt = native
 **.pyva = native

File hghooks/__init__.py

 # You should have received a copy of the GNU Lesser General Public License
 # along with hghooks.  If not, see <http://www.gnu.org/licenses/>.
 
-from mercurial import match, ignore, util
-import os
-import re
-import shutil
-import tempfile
-
 version = "0.4.3dev"
-
-re_options = re.IGNORECASE | re.MULTILINE | re.DOTALL
-skip_pattern = re.compile('# hghooks: (.*)', re_options)
-
-
-class CheckerManager(object):
-
-    def __init__(self, ui, repo, node, skip_text=None):
-        self.ui = ui
-        self.repo = repo
-        self.node = node
-        self.skip_text = skip_text
-
-    def skip_file(self, filename, filedata):
-        if not filename.endswith('.py'):
-            return True
-
-        for match in skip_pattern.findall(filedata):
-            if self.skip_text in match:
-                return True
-
-        return False
-
-    def check(self, checker):
-        # TODO: Test latest revision on all new/modified heads
-
-        current_rev = self.repo[self.node].rev()
-        total_revs = len(self.repo.changelog)
-        test_revs = range(current_rev, total_revs)
-        latest_rev = total_revs - 1
-
-        warnings = 0
-        ctx = self.repo[latest_rev]
-        existing_files = set(ctx)
-        modified_files = {}
-        ignorefunc = lambda x: False
-
-        if '.hgignorechecks' in existing_files:
-            filectx = ctx.filectx('.hgignorechecks')
-            filedata = filectx.data()
-            ignore_pattern, pattern_warnings = ignore.ignorepats(filedata.splitlines())
-            if pattern_warnings:
-                self.ui.warn('\nBad .hgignorechecks:\n%s\n\n'
-                             % '\n'.join(pattern_warnings))
-                return True
-            if ignore_pattern:
-                ignorefunc = match.match('', '', [], ignore_pattern)
-
-        directory = tempfile.mkdtemp(prefix='hghooks')
-
-        for revision in test_revs:
-            self.ui.debug("Checking revision %d\n" % revision)
-            revctx = self.repo[revision]
-
-            for filename in revctx.files():
-                if filename not in existing_files or ignorefunc(filename):
-                    continue
-
-                full_path = os.path.join(directory, filename)
-                if full_path in modified_files:
-                    # Already checked
-                    continue
-
-                filectx = ctx.filectx(filename)
-                filedata = filectx.data()
-
-                if self.skip_text and self.skip_file(filename, filedata):
-                    continue
-
-                modified_files[full_path] = filedata
-
-        if modified_files:
-            warnings += checker(modified_files)
-
-        if warnings:
-            self.ui.warn('%d warning(s) found\n' % warnings)
-        else:
-            self.ui.debug('No warnings found. Good job!\n')
-
-        shutil.rmtree(directory)
-        return bool(warnings)

File hghooks/checkers.py

+# Copyright (c) 2010 by Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
+#
+# This file is part of hghooks.
+#
+# hghooks is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# hghooks is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with hghooks.  If not, see <http://www.gnu.org/licenses/>.
+
+import compiler
+import re
+import os
+import pep8
+import pyflakes.checker
+import sys
+
+re_options = re.IGNORECASE | re.MULTILINE | re.DOTALL
+
+pdb_catcher = re.compile(r'^[^#]*pdb\.set_trace\(\)', re_options)
+
+def pdb_checker(files_to_check):
+    def check_one_file(data, filename):
+        warnings = len(pdb_catcher.findall(data))
+        if warnings > 0:
+            print '%s: pdb found' % filename
+        return warnings
+
+    return sum([check_one_file(data, filename)
+                for filename, data in files_to_check.items()])
+
+def pep8_checker(ignore='', parameters=''):
+    extra_args = parameters.split()
+    if ignore:
+        ignore_spec = ','.join([ign.strip(', ') for ign in ignore.split()
+                                if ign.strip(', ')])
+        extra_args.append('--ignore=%s' % ignore_spec)
+
+    def check_pep8(files_to_check):
+        for filename, data in files_to_check.items():
+            parentdir = os.path.dirname(filename)
+            if not os.path.exists(parentdir):
+                os.makedirs(parentdir)
+            open(filename, 'w').write(data)
+
+        # monkey patch sys.argv options so we can call pep8
+        old_args = sys.argv
+        sys.argv = ['pep8'] + files_to_check.keys() + extra_args
+        options, args = pep8.process_options()
+        sys.argv = old_args
+        for path in args:
+            pep8.input_file(path)
+
+        return pep8.get_count()
+
+    return check_pep8
+
+def pyflakes_check(data, filename):
+    """
+    Check the Python source given by C{data} for flakes.
+
+    It's like pyflakes.scripts.check function but ignores those lines which
+    ends with ends with a "pyflakes:ignore" comment.
+
+    Code adapted from http://djangosnippets.org/snippets/1762/ which is adapted
+    from pyflakes.scripts.pyflakes.check function.
+    """
+    # Since compiler.parse does not reliably report syntax errors, use the
+    # built in compiler first to detect those.
+    try:
+        try:
+            compile(data, filename, "exec")
+        except MemoryError:
+            # Python 2.4 will raise MemoryError if the source can't be
+            # decoded.
+            if sys.version_info[:2] == (2, 4):
+                raise SyntaxError(None)
+            raise
+    except (SyntaxError, IndentationError), value:
+        msg = value.args[0]
+
+        (lineno, offset, text) = value.lineno, value.offset, value.text
+
+        # If there's an encoding problem with the file, the text is None.
+        if text is None:
+            # Avoid using msg, since for the only known case, it contains a
+            # bogus message that claims the encoding the file declared was
+            # unknown.
+            print >> sys.stderr, "%s: problem decoding source" % (filename, )
+        else:
+            line = text.splitlines()[-1]
+
+            if offset is not None:
+                offset = offset - (len(text) - len(line))
+
+            print >> sys.stderr, '%s:%d: %s' % (filename, lineno, msg)
+        return 1
+    else:
+        # Okay, it's syntactically valid.  Now parse it into an ast and check
+        # it.
+        tree = compiler.parse(data)
+        w = pyflakes.checker.Checker(tree, filename)
+
+        lines = data.split('\n')
+        # Ignoring lines with a "pyflakes:ignore" comment at the end
+        messages = [message for message in w.messages
+                    if lines[message.lineno - 1].find('pyflakes:ignore') < 0]
+        messages.sort(lambda a, b: cmp(a.lineno, b.lineno))
+        for warning in messages:
+            print warning
+        return len(messages)
+
+def pyflakes_checker(files_to_check):
+    return sum([pyflakes_check(data, filename)
+                for filename, data in files_to_check.items()])
+

File hghooks/code.py

 # You should have received a copy of the GNU Lesser General Public License
 # along with hghooks.  If not, see <http://www.gnu.org/licenses/>.
 
-import compiler
-import os
-import re
-import sys
-
-import pep8
-import pyflakes.checker
-
-from hghooks import CheckerManager, re_options
-
-
-def pep8_checker(ignore='', parameters=''):
-    extra_args = parameters.split()
-    if ignore:
-        ignore_spec = ','.join([ign.strip(', ') for ign in ignore.split()
-                                if ign.strip(', ')])
-        extra_args.append('--ignore=%s' % ignore_spec)
-
-    def check_pep8(files_to_check):
-        for filename, data in files_to_check.items():
-            parentdir = os.path.dirname(filename)
-            if not os.path.exists(parentdir):
-                os.makedirs(parentdir)
-            open(filename, 'w').write(data)
-
-        # monkey patch sys.argv options so we can call pep8
-        old_args = sys.argv
-        sys.argv = ['pep8'] + files_to_check.keys() + extra_args
-        options, args = pep8.process_options()
-        sys.argv = old_args
-        for path in args:
-            pep8.input_file(path)
-
-        return pep8.get_count()
-
-    return check_pep8
-
+from hghooks.manager import CheckerManager
+from hghooks.checkers import pep8_checker, pyflakes_checker, pdb_checker
 
 def pep8hook(ui, repo, hooktype, node, pending, **kwargs):
     pep8_ignores = ui.config('pep8', 'ignore', '')
     checker_manager = CheckerManager(ui, repo, node, 'no-pep8')
     return checker_manager.check(pep8_checker(pep8_ignores, pep8_params))
 
-
-pdb_catcher = re.compile(r'^[^#]*pdb\.set_trace\(\)', re_options)
-
-
-def pdb_checker(files_to_check):
-    def check_one_file(data, filename):
-        warnings = len(pdb_catcher.findall(data))
-        if warnings > 0:
-            print '%s: pdb found' % filename
-        return warnings
-
-    return sum([check_one_file(data, filename)
-                for filename, data in files_to_check.items()])
-
-
 def pdbhook(ui, repo, hooktype, node, pending, **kwargs):
     checker_manager = CheckerManager(ui, repo, node, 'no-pdb')
     return checker_manager.check(pdb_checker)
 
-
-def pyflakes_check(data, filename):
-    """
-    Check the Python source given by C{data} for flakes.
-
-    It's like pyflakes.scripts.check function but ignores those lines which
-    ends with ends with a "pyflakes:ignore" comment.
-
-    Code adapted from http://djangosnippets.org/snippets/1762/ which is adapted
-    from pyflakes.scripts.pyflakes.check function.
-    """
-    # Since compiler.parse does not reliably report syntax errors, use the
-    # built in compiler first to detect those.
-    try:
-        try:
-            compile(data, filename, "exec")
-        except MemoryError:
-            # Python 2.4 will raise MemoryError if the source can't be
-            # decoded.
-            if sys.version_info[:2] == (2, 4):
-                raise SyntaxError(None)
-            raise
-    except (SyntaxError, IndentationError), value:
-        msg = value.args[0]
-
-        (lineno, offset, text) = value.lineno, value.offset, value.text
-
-        # If there's an encoding problem with the file, the text is None.
-        if text is None:
-            # Avoid using msg, since for the only known case, it contains a
-            # bogus message that claims the encoding the file declared was
-            # unknown.
-            print >> sys.stderr, "%s: problem decoding source" % (filename, )
-        else:
-            line = text.splitlines()[-1]
-
-            if offset is not None:
-                offset = offset - (len(text) - len(line))
-
-            print >> sys.stderr, '%s:%d: %s' % (filename, lineno, msg)
-        return 1
-    else:
-        # Okay, it's syntactically valid.  Now parse it into an ast and check
-        # it.
-        tree = compiler.parse(data)
-        w = pyflakes.checker.Checker(tree, filename)
-
-        lines = data.split('\n')
-        # Ignoring lines with a "pyflakes:ignore" comment at the end
-        messages = [message for message in w.messages
-                    if lines[message.lineno - 1].find('pyflakes:ignore') < 0]
-        messages.sort(lambda a, b: cmp(a.lineno, b.lineno))
-        for warning in messages:
-            print warning
-        return len(messages)
-
-
-def pyflakes_checker(files_to_check):
-    return sum([pyflakes_check(data, filename)
-                for filename, data in files_to_check.items()])
-
-
 def pyflakeshook(ui, repo, hooktype, node, pending, **kwargs):
     checker_manager = CheckerManager(ui, repo, node, 'no-pyflakes')
     return checker_manager.check(pyflakes_checker)
 
-
 def allhook(*args, **kwargs):
     results = (
         pep8hook(*args, **kwargs),

File hghooks/manager.py

+# Copyright (c) 2010 by Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
+#
+# This file is part of hghooks.
+#
+# hghooks is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# hghooks is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with hghooks.  If not, see <http://www.gnu.org/licenses/>.
+
+from mercurial import match, ignore, util
+import os
+import re
+import shutil
+import tempfile
+from hghooks.checkers import re_options
+
+skip_pattern = re.compile('# hghooks: (.*)', re_options)
+
+class CheckerManager(object):
+
+    def __init__(self, ui, repo, node, skip_text=None):
+        self.ui = ui
+        self.repo = repo
+        self.node = node
+        self.skip_text = skip_text
+
+    def skip_file(self, filename, filedata):
+        if not filename.endswith('.py'):
+            return True
+
+        for match in skip_pattern.findall(filedata):
+            if self.skip_text in match:
+                return True
+
+        return False
+
+    def check(self, checker):
+        # TODO: Test latest revision on all new/modified heads
+
+        current_rev = self.repo[self.node].rev()
+        total_revs = len(self.repo.changelog)
+        test_revs = range(current_rev, total_revs)
+        latest_rev = total_revs - 1
+
+        warnings = 0
+        ctx = self.repo[latest_rev]
+        existing_files = set(ctx)
+        modified_files = {}
+        ignorefunc = lambda x: False
+
+        if '.hgignorechecks' in existing_files:
+            filectx = ctx.filectx('.hgignorechecks')
+            filedata = filectx.data()
+            ignore_pattern, pattern_warnings = ignore.ignorepats(filedata.splitlines())
+            if pattern_warnings:
+                self.ui.warn('\nBad .hgignorechecks:\n%s\n\n'
+                             % '\n'.join(pattern_warnings))
+                return True
+            if ignore_pattern:
+                ignorefunc = match.match('', '', [], ignore_pattern)
+
+        directory = tempfile.mkdtemp(prefix='hghooks')
+
+        for revision in test_revs:
+            self.ui.debug("Checking revision %d\n" % revision)
+            revctx = self.repo[revision]
+
+            for filename in revctx.files():
+                if filename not in existing_files or ignorefunc(filename):
+                    continue
+
+                full_path = os.path.join(directory, filename)
+                if full_path in modified_files:
+                    # Already checked
+                    continue
+
+                filectx = ctx.filectx(filename)
+                filedata = filectx.data()
+
+                if self.skip_text and self.skip_file(filename, filedata):
+                    continue
+
+                modified_files[full_path] = filedata
+
+        if modified_files:
+            warnings += checker(modified_files)
+
+        if warnings:
+            self.ui.warn('%d warning(s) found\n' % warnings)
+        else:
+            self.ui.debug('No warnings found. Good job!\n')
+
+        shutil.rmtree(directory)
+        return bool(warnings)