1. Tarek Ziadé
  2. flake8

Commits

Ian Cordasco  committed 66003ac Merge

Merge flint-merge branch

  • Participants
  • Parent commits 2391356, 647d306
  • Branches default

Comments (0)

Files changed (16)

File CHANGES.rst

View file
  • Ignore whitespace
+CHANGES
+=======
+
+2.0.0 - 2013-02-xx
+------------------
+
+- Fixes #13: pep8 and pyflakes are now external dependencies
+- Split run.py into main.py and hooks.py for better logic
+- Expose our parser for our users
+- New feature: Install git and hg hooks automagically
+- By relying on pyflakes (0.6.1), we also fixed #45 and #35
+
+
+1.7.0 - 2012-12-21
+------------------
+
+- Fixes part of #35: Exception for no WITHITEM being an attribute of Checker
+  for Python 3.3
+- Support stdin
+- Incorporate @phd's builtins pull request
+- Fix the git hook
+- Update pep8.py to the latest version
+
+
+1.6.2 - 2012-11-25
+------------------
+
+- fixed the NameError: global name 'message' is not defined (#46)
+
+
+1.6.1 - 2012-11-24
+------------------
+
+- fixed the mercurial hook, a change from a previous patch was not properly
+  applied
+- fixed an assumption about warnings/error messages that caused an exception
+  to be thrown when McCabe is used
+
+
+1.6 - 2012-11-16
+----------------
+
+- changed the signatures of the ``check_file`` function in flake8/run.py,
+  ``skip_warning`` in flake8/util.py and the ``check``, ``checkPath``
+  functions in flake8/pyflakes.py.
+- fix ``--exclude`` and ``--ignore`` command flags (#14, #19)
+- fix the git hook that wasn't catching files not already added to the index
+  (#29)
+- pre-emptively includes the addition to pep8 to ignore certain lines.
+  Add ``# nopep8`` to the end of a line to ignore it. (#37)
+- ``check_file`` can now be used without any special prior setup (#21)
+- unpacking exceptions will no longer cause an exception (#20)
+- fixed crash on non-existent file (#38)
+
+
+1.5 - 2012-10-13
+----------------
+
+- fixed the stdin
+- make sure mccabe catches the syntax errors as warnings
+- pep8 upgrade
+- added max_line_length default value
+- added Flake8Command and entry points is setuptools is around
+- using the setuptools console wrapper when available
+
+
+1.4 - 2012-07-12
+----------------
+
+- git_hook: Only check staged changes for compliance
+- use pep8 1.2
+
+
+1.3.1 - 2012-05-19
+------------------
+
+- fixed support for Python 2.5
+
+
+1.3 - 2012-03-12
+----------------
+
+- fixed false W402 warning on exception blocks.
+
+
+1.2 - 2012-02-12
+----------------
+
+- added a git hook
+- now Python 3 compatible
+- mccabe and pyflakes have warning codes like pep8 now
+
+
+1.1 - 2012-02-14
+----------------
+
+- fixed the value returned by --version
+- allow the flake8: header to be more generic
+- fixed the "hg hook raises 'physical lines'" bug
+- allow three argument form of raise
+- now uses setuptools if available, for 'develop' command
+
+
+1.0 - 2011-11-29
+----------------
+
+- Deactivates by default the complexity checker
+- Introduces the complexity option in the HG hook and the command line.
+
+
+0.9 - 2011-11-09
+----------------
+
+- update pep8 version to 0.6.1
+- mccabe check: gracefully handle compile failure
+
+
+0.8 - 2011-02-27
+----------------
+
+- fixed hg hook
+- discard unexisting files on hook check
+
+
+0.7 - 2010-02-18
+----------------
+
+- Fix pep8 initialization when run through Hg
+- Make pep8 short options work when run through the command line
+- Skip duplicates when controlling files via Hg
+
+
+0.6 - 2010-02-15
+----------------
+
+- Fix the McCabe metric on some loops

File CONTRIBUTORS.txt

View file
  • Ignore whitespace
 - Miki Tebeka
 - David Cramer
 - Peter Teichman
+- Ian Cordasco
 - Oleg Broytman
 - Marc Labbé
 - Bruno Miguel Custódio
+- Florent Xicluna

File LICENSE

View file
  • Ignore whitespace
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
-
-
-
-== McCabe License (MIT) ==
-
-Copyright (C) <year> Ned Batchelder
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-of the Software, and to permit persons to whom the Software is furnished to do
-so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-
-
-== PyFlakes license (MIT) ==
-
-Copyright (c) 2005 Divmod, Inc., http://www.divmod.com/
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-== pep8 license (expat) ==
-
-Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-

File MANIFEST.in

View file
  • Ignore whitespace
+include *.rst
 include CONTRIBUTORS.txt
-include README
 include LICENSE
 recursive-include scripts flake8.*

File README.rst

View file
  • Ignore whitespace
 - pep8
 - Ned's McCabe script
 
-Flake8 runs all tools by launching the single 'flake8' script, but ignores pep8
-and PyFlakes extended options and just uses defaults. It displays the warnings
-in a per-file, merged output.
+Flake8 runs all the tools by launching the single 'flake8' script.
+It displays the warnings in a per-file, merged output.
 
 It also adds a few features:
 
-- files that contains with this header are skipped::
+- files that contain this line are skipped::
 
     # flake8: noqa
 
-- lines that contain a "# NOQA" comment at the end will not issue pyflakes 
-  warnings.
-- lines that contain a "# NOPEP8" comment at the end will not issue pep8 
-  warnings.
-- a Mercurial hook.
+- lines that contain a "# noqa" comment at the end will not issue warnings.
+- a Git and a Mercurial hook.
 - a McCabe complexity checker.
+- extendable through ``flake8.extension`` entry points.
+
 
 QuickStart
 ==========
 To run flake8 just invoke it against any directory or Python module::
 
     $ flake8 coolproject
-    coolproject/mod.py:1027: local variable 'errors' is assigned to but never used
-    coolproject/mod.py:97: 'shutil' imported but unused
-    coolproject/mod.py:729: redefinition of function 'readlines' from line 723
-    coolproject/mod.py:1028: local variable 'errors' is assigned to but never used
+    coolproject/mod.py:97:1: F401 'shutil' imported but unused
     coolproject/mod.py:625:17: E225 missing whitespace around operato
+    coolproject/mod.py:729:1: F811 redefinition of function 'readlines' from line 723
+    coolproject/mod.py:1028:1: F841 local variable 'errors' is assigned to but never used
 
-The output of PyFlakes *and* pep8 is merged and returned.
+The outputs of PyFlakes *and* pep8 (and the optional plugins) are merged
+and returned.
 
-flake8 offers an extra option: --max-complexity, which will emit a warning if the
-McCabe complexityu of a function is higher that the value. By default it's
+flake8 offers an extra option: --max-complexity, which will emit a warning if
+the McCabe complexity of a function is higher than the value.  By default it's
 deactivated::
 
-    $ bin/flake8 --max-complexity 12 flake8
-    coolproject/mod.py:97: 'shutil' imported but unused
-    coolproject/mod.py:729: redefinition of function 'readlines' from line 723
-    coolproject/mod.py:1028: local variable 'errors' is assigned to but never used
+    $ flake8 --max-complexity 12 coolproject
+    coolproject/mod.py:97:1: F401 'shutil' imported but unused
     coolproject/mod.py:625:17: E225 missing whitespace around operator
-    coolproject/mod.py:452:1: 'missing_whitespace_around_operator' is too complex (18)
-    coolproject/mod.py:939:1: 'Checker.check_all' is too complex (12)
-    coolproject/mod.py:1204:1: 'selftest' is too complex (14)
+    coolproject/mod.py:729:1: F811 redefinition of unused 'readlines' from line 723
+    coolproject/mod.py:939:1: C901 'Checker.check_all' is too complex (12)
+    coolproject/mod.py:1028:1: F841 local variable 'errors' is assigned to but never used
+    coolproject/mod.py:1204:1: C901 'selftest' is too complex (14)
 
-This feature is quite useful to detect over-complex code. According to McCabe, anything
-that goes beyond 10 is too complex.
+This feature is quite useful to detect over-complex code.  According to McCabe,
+anything that goes beyond 10 is too complex.
 See https://en.wikipedia.org/wiki/Cyclomatic_complexity.
 
 
+Configuration
+-------------
+
+The behaviour may be configured at two levels.
+
+The user settings are read from the ``~/.config/flake8`` file.
+Example::
+
+  [flake8]
+  ignore = E226,E302,E41
+  max-line-length = 160
+
+At the project level, a ``tox.ini`` file or a ``setup.cfg`` file is read
+if present.  Only the first file is considered.  If this file does not
+have a ``[flake8]`` section, no project specific configuration is loaded.
+
+If the ``ignore`` option is not in the configuration and not in the arguments,
+only the error codes ``E226`` and ``E241/E242`` are ignored
+(see codes in the table below).
+
+
 Mercurial hook
 ==============
 
-To use the Mercurial hook on any *commit* or *qrefresh*, change your .hg/rc file
-like this::
+To use the Mercurial hook on any *commit* or *qrefresh*, change your .hg/hgrc
+file like this::
 
     [hooks]
     commit = python:flake8.run.hg_hook
 
 
 If *strict* option is set to **1**, any warning will block the commit. When
-*strict* is set to **0**, warnings are just displayed in the standard output.
+*strict* is set to **0**, warnings are just printed to the standard output.
 
 *complexity* defines the maximum McCabe complexity allowed before a warning
-is emited. If you don't specify it it's just ignored. If specified, must
-be a positive value. 12 is usually a good value.
+is emitted.  If you don't specify it, it's just ignored.  If specified, it must
+be a positive value.  12 is usually a good value.
+
 
 Git hook
 ========
 
 
 If *strict* option is set to **True**, any warning will block the commit. When
-*strict* is set to **False** or omited, warnings are just displayed in the
+*strict* is set to **False** or omitted, warnings are just printed to the
 standard output.
 
 *complexity* defines the maximum McCabe complexity allowed before a warning
-is emited. If you don't specify it or set it to **-1**, it's just ignored.
-If specified, it must be a positive value. 12 is usually a good value.
+is emitted.  If you don't specify it or set it to **-1**, it's just ignored.
+If specified, it must be a positive value.  12 is usually a good value.
 
-*lazy* when set to ``True`` will also take into account files not added to the 
+*lazy* when set to ``True`` will also take into account files not added to the
 index.
 
 Also, make sure the file is executable and adapt the shebang line so it
-point to your python interpreter.
+points to your Python interpreter.
 
 
 Buildout integration
 ======================
 
 If setuptools is available, Flake8 provides a command that checks the
-Python files declared by your project. To use it, add flake8 to your
+Python files declared by your project.  To use it, add flake8 to your
 setup_requires::
 
     setup(
     )
 
 Running ``python setup.py flake8`` on the command line will check the
-files listed in your ``py_modules`` and ``packages``. If any warnings
-are found, the command will exit with an error code::
+files listed in your ``py_modules`` and ``packages``.  If any warning
+is found, the command will exit with an error code::
 
     $ python setup.py flake8
 
 Flake8 is just a glue project, all the merits go to the creators of the original
 projects:
 
-- pep8: https://github.com/jcrocholl/pep8/
-- PyFlakes: http://divmod.org/trac/wiki/DivmodPyflakes
-- flakey: https://bitbucket.org/icordasc/flakey
+- pep8: https://github.com/jcrocholl/pep8
+- PyFlakes: https://launchpad.net/pyflakes
 - McCabe: http://nedbatchelder.com/blog/200803/python_code_complexity_microtool.html
 
+
 Warning / Error codes
 =====================
 
-Below are lists of all warning and error codes flake8 will generate, broken
-out by component.
+The convention of Flake8 is to assign a code to each error or warning, like
+the ``pep8`` tool.  These codes are used to configure the list of errors
+which are selected or ignored.
 
-pep8:
+Each code consists of an upper case ASCII letter followed by three digits.
+The recommendation is to use a different prefix for each plugin. A list of the
+known prefixes is published below:
 
-- E101: indentation contains mixed spaces and tabs
-- E111: indentation is not a multiple of four
-- E112: expected an indented block
-- E113: unexpected indentation
-- E127: continuation line over-indented for visual indent
-- E128: continuation line under-indented for visual indent
-- E201: whitespace after char
-- E202: whitespace before char
-- E203: whitespace before char
-- E211: whitespace before text
-- E223: tab / multiple spaces before operator
-- E224: tab / multiple spaces after operator
-- E225: missing whitespace around operator
-- E225: missing whitespace around operator
-- E231: missing whitespace after char
-- E241: multiple spaces after separator
-- E242: tab after separator
-- E251: no spaces around keyword / parameter equals
-- E262: inline comment should start with '# '
-- E301: expected 1 blank line, found 0
-- E302: expected 2 blank lines, found <n>
-- E303: too many blank lines (<n>)
-- E304: blank lines found after function decorator
-- E401: multiple imports on one line
-- E501: line too long (<n> characters)
-- E701: multiple statements on one line (colon)
-- E702: multiple statements on one line (semicolon)
-- W191: indentation contains tabs
-- W291: trailing whitespace
-- W292: no newline at end of file
-- W293: blank line contains whitespace
-- W391: blank line at end of file
-- W601: .has_key() is deprecated, use 'in'
-- W602: deprecated form of raising exception
-- W603: '<>' is deprecated, use '!='
-- W604: backticks are deprecated, use 'repr()'
+- ``E***``/``W***``: `pep8 errors and warnings
+  <http://pep8.readthedocs.org/en/latest/intro.html#error-codes>`_
+- ``F***``: PyFlakes codes (see below)
+- ``C9**``: McCabe complexity plugin `mccabe
+  <https://github.com/flintwork/mccabe>`_
+- ``N8**``: Naming Conventions plugin `pep8-naming
+  <https://github.com/flintwork/pep8-naming>`_
 
-flakey:
 
-- W402: <module> imported but unused
-- W403: import <module> from line <n> shadowed by loop variable
-- W404: 'from <module> import ``*``' used; unable to detect undefined names
-- W405: future import(s) <name> after other statements
-- W801: redefinition of unused <name> from line <n>
-- W802: undefined name <name>
-- W803: undefined name <name> in __all__
-- W804: local variable <name> (defined in enclosing scope on line <n>) referenced before assignment
-- W805: duplicate argument <name> in function definition
-- W806: redefinition of function <name> from line <n>
-- W806: local variable <name> is assigned to but never used
+The original PyFlakes does not provide error codes.  Flake8 patches the
+PyFlakes messages to add the following codes:
 
-McCabe:
++------+--------------------------------------------------------------------+
+| code | sample message                                                     |
++======+====================================================================+
+| F401 | ``module`` imported but unused                                     |
++------+--------------------------------------------------------------------+
+| F402 | import ``module`` from line ``N`` shadowed by loop variable        |
++------+--------------------------------------------------------------------+
+| F403 | 'from ``module`` import \*' used; unable to detect undefined names |
++------+--------------------------------------------------------------------+
+| F404 | future import(s) ``name`` after other statements                   |
++------+--------------------------------------------------------------------+
++------+--------------------------------------------------------------------+
+| F811 | redefinition of unused ``name`` from line ``N``                    |
++------+--------------------------------------------------------------------+
+| F812 | list comprehension redefines ``name`` from line ``N``              |
++------+--------------------------------------------------------------------+
+| F821 | undefined name ``name``                                            |
++------+--------------------------------------------------------------------+
+| F822 | undefined name ``name`` in __all__                                 |
++------+--------------------------------------------------------------------+
+| F823 | local variable ``name`` ... referenced before assignment           |
++------+--------------------------------------------------------------------+
+| F831 | duplicate argument ``name`` in function definition                 |
++------+--------------------------------------------------------------------+
+| F841 | local variable ``name`` is assigned to but never used              |
++------+--------------------------------------------------------------------+
 
-- W901: '<function_name>' is too complex ('<complexity_level>')
 
-CHANGES
-=======
+Links
+-----
 
-2.0.0 - 2013-01-xx
-------------------
+* `pep8 documentation <http://pep8.readthedocs.org/>`_
 
-- Fixes #13: pep8 and pyflakes are now external dependencies
-- Split run.py into main.py and hooks.py for better logic
-- Expose our parser for our users
-- New feature: Install git and hg hooks automagically
-- By relying on pyflakes (0.6.1), we also fixed #45 and #35
-
-1.7.0 - 2012-12-21
-------------------
-
-- Fixes part of #35: Exception for no WITHITEM being an attribute of Checker 
-  for python 3.3
-- Support stdin
-- Incorporate @phd's builtins pull request
-- Fix the git hook
-- Update pep8.py to the latest version
-
-1.6.2 - 2012-11-25
-------------------
-
-- fixed the NameError: global name 'message' is not defined (#46)
-
-
-1.6.1 - 2012-11-24
-------------------
-
-- fixed the mercurial hook, a change from a previous patch was not properly 
-  applied
-- fixed an assumption about warnings/error messages that caused an exception 
-  to be thrown when McCabe is used
-
-1.6 - 2012-11-16
-----------------
-
-- changed the signatures of the ``check_file`` function in flake8/run.py, 
-  ``skip_warning`` in flake8/util.py and the ``check``, ``checkPath``
-  functions in flake8/pyflakes.py.
-- fix ``--exclude`` and ``--ignore`` command flags (#14, #19)
-- fix the git hook that wasn't catching files not already added to the index 
-  (#29)
-- pre-emptively includes the addition to pep8 to ignore certain lines. Add ``# 
-  nopep8`` to the end of a line to ignore it. (#37)
-- ``check_file`` can now be used without any special prior setup (#21)
-- unpacking exceptions will no longer cause an exception (#20)
-- fixed crash on non-existant file (#38)
-
-
-
-1.5 - 2012-10-13
-----------------
-
-- fixed the stdin
-- make sure mccabe catches the syntax errors as warnings
-- pep8 upgrade
-- added max_line_length default value
-- added Flake8Command and entry points is setuptools is around
-- using the setuptools console wrapper when available
-
-
-1.4 - 2012-07-12
-----------------
-
-- git_hook: Only check staged changes for compliance
-- use pep8 1.2
-
-
-1.3.1 - 2012-05-19
-------------------
-
-- fixed support for Python 2.5
-
-
-1.3 - 2012-03-12
-----------------
-
-- fixed false W402 warning on exception blocks.
-
-
-1.2 - 2012-02-12
-----------------
-
-- added a git hook
-- now python 3 compatible 
-- mccabe and pyflakes have warning codes like pep8 now
-
-
-1.1 - 2012-02-14
-----------------
-
-- fixed the value returned by --version
-- allow the flake8: header to be more generic
-- fixed the "hg hook raises 'physical lines'" bug
-- allow three argument form of raise
-- now uses setuptools if available, for 'develop' command
-
-1.0 - 2011-11-29
-----------------
-
-- Deactivates by default the complexity checker
-- Introduces the complexity option in the HG hook and the command line.
-
-
-0.9 - 2011-11-09
-----------------
-
-- update pep8 version to 0.6.1
-- mccabe check: gracefully handle compile failure
-
-0.8 - 2011-02-27
-----------------
-
-- fixed hg hook
-- discard unexisting files on hook check
-
-
-0.7 - 2010-02-18
-----------------
-
-- Fix pep8 intialization when run through Hg
-- Make pep8 short options work when run throug the command line
-- skip duplicates when controlling files via Hg
-
-
-0.6 - 2010-02-15
-----------------
-
-- Fix the McCabe metric on some loops
-
-
+* `flake8 documentation <https://bitbucket.org/tarek/flake8/src/tip/README.rst>`_

File flake8/__init__.py

View file
  • Ignore whitespace
 
-__version__ = '2.0'
+__version__ = '2.0a1'

File flake8/_pyflakes.py

View file
  • Ignore whitespace
+# -*- coding: utf-8 -*-
+import pyflakes
+import pyflakes.checker
+
+
+def patch_pyflakes():
+    """Add error codes to Pyflakes messages."""
+    codes = dict([line.split()[::-1] for line in (
+        'F401 UnusedImport',
+        'F402 ImportShadowedByLoopVar',
+        'F403 ImportStarUsed',
+        'F404 LateFutureImport',
+        'F810 Redefined',               # XXX Obsolete?
+        'F811 RedefinedWhileUnused',
+        'F812 RedefinedInListComp',
+        'F821 UndefinedName',
+        'F822 UndefinedExport',
+        'F823 UndefinedLocal',
+        'F831 DuplicateArgument',
+        'F841 UnusedVariable',
+    )])
+
+    for name, obj in vars(pyflakes.messages).items():
+        if name[0].isupper() and obj.message:
+            obj.flake8_msg = '%s %s' % (codes.get(name, 'F999'), obj.message)
+patch_pyflakes()
+
+
+class FlakesChecker(pyflakes.checker.Checker):
+    """Subclass the Pyflakes checker to conform with the flake8 API."""
+    name = 'pyflakes'
+    version = pyflakes.__version__
+
+    @classmethod
+    def add_options(cls, parser):
+        parser.add_option('--builtins',
+                          help="define more built-ins, comma separated")
+        parser.config_options.append('builtins')
+
+    @classmethod
+    def parse_options(cls, options):
+        if options.builtins:
+            cls.builtIns = cls.builtIns.union(options.builtins.split(','))
+
+    def run(self):
+        for m in self.messages:
+            yield m.lineno, 0, (m.flake8_msg % m.message_args), m.__class__

File flake8/engine.py

View file
  • Ignore whitespace
+# -*- coding: utf-8 -*-
+import re
+
+import pep8
+
+from flake8 import __version__
+from flake8.util import OrderedSet
+
+_flake8_noqa = re.compile(r'flake8[:=]\s*noqa', re.I).search
+
+
+def _register_extensions():
+    """Register all the extensions."""
+    extensions = OrderedSet()
+    extensions.add(('pep8', pep8.__version__))
+    parser_hooks = []
+    options_hooks = []
+    try:
+        from pkg_resources import iter_entry_points
+    except ImportError:
+        pass
+    else:
+        for entry in iter_entry_points('flake8.extension'):
+            checker = entry.load()
+            pep8.register_check(checker, codes=[entry.name])
+            extensions.add((checker.name, checker.version))
+            if hasattr(checker, 'add_options'):
+                parser_hooks.append(checker.add_options)
+            if hasattr(checker, 'parse_options'):
+                options_hooks.append(checker.parse_options)
+    return extensions, parser_hooks, options_hooks
+
+
+def get_parser():
+    (extensions, parser_hooks, options_hooks) = _register_extensions()
+    details = ', '.join(['%s: %s' % ext for ext in extensions])
+    parser = pep8.get_parser('flake8', '%s (%s)' % (__version__, details))
+    for opt in ('--repeat', '--testsuite', '--doctest'):
+        try:
+            parser.remove_option(opt)
+        except ValueError:
+            pass
+    parser.add_option('--exit-zero', action='store_true',
+                      help="exit with code 0 even if there are errors")
+    for parser_hook in parser_hooks:
+        parser_hook(parser)
+    parser.add_option('--install-hook', default=False, action='store_true',
+                      help='Install the appropriate hook for this '
+                      'repository.', dest='install_hook')
+    return parser, options_hooks
+
+
+class StyleGuide(pep8.StyleGuide):
+    # Backward compatibility pep8 <= 1.4.2
+    checker_class = pep8.Checker
+
+    def input_file(self, filename, lines=None, expected=None, line_offset=0):
+        """Run all checks on a Python source file."""
+        if self.options.verbose:
+            print('checking %s' % filename)
+        fchecker = self.checker_class(
+            filename, lines=lines, options=self.options)
+        # Any "# flake8: noqa" line?
+        if any(_flake8_noqa(line) for line in fchecker.lines):
+            return 0
+        return fchecker.check_all(expected=expected, line_offset=line_offset)
+
+
+def get_style_guide(**kwargs):
+    """Parse the options and configure the checker."""
+    kwargs['parser'], options_hooks = get_parser()
+    styleguide = StyleGuide(**kwargs)
+    options = styleguide.options
+    for options_hook in options_hooks:
+        options_hook(options)
+    return styleguide

File flake8/hooks.py

View file
  • Ignore whitespace
+# -*- coding: utf-8 -*-
+from __future__ import with_statement
 import os
 import sys
-from flake8.util import (_initpep8, pep8style, skip_file, get_parser,
-                         ConfigParser)
 from subprocess import Popen, PIPE
+try:
+    from configparser import ConfigParser
+except ImportError:   # Python 2
+    from ConfigParser import ConfigParser
+
+from flake8.engine import get_parser, get_style_guide
+from flake8.main import DEFAULT_CONFIG
 
 
 def git_hook(complexity=-1, strict=False, ignore=None, lazy=False):
-    from flake8.main import check_file
-    _initpep8()
-    if ignore:
-        pep8style.options.ignore = ignore
-
-    warnings = 0
-
     gitcmd = "git diff-index --cached --name-only HEAD"
     if lazy:
         gitcmd = gitcmd.replace('--cached ', '')
 
     _, files_modified, _ = run(gitcmd)
-    for filename in files_modified:
-        ext = os.path.splitext(filename)[-1]
-        if ext != '.py':
-            continue
-        if not os.path.exists(filename):
-            continue
-        warnings += check_file(path=filename, ignore=ignore,
-                               complexity=complexity)
+
+    flake8_style = get_style_guide(
+        config_file=DEFAULT_CONFIG, ignore=ignore, max_complexity=complexity)
+    report = flake8_style.check_files(files_modified)
 
     if strict:
-        return warnings
+        return report.total_errors
 
     return 0
 
 
 def hg_hook(ui, repo, **kwargs):
-    from flake8.main import check_file
     complexity = ui.config('flake8', 'complexity', default=-1)
+    strict = ui.configbool('flake8', 'strict', default=True)
     config = ui.config('flake8', 'config', default=True)
-    _initpep8(config_file=config)
-    warnings = 0
+    if config is True:
+        config = DEFAULT_CONFIG
 
-    for file_ in _get_files(repo, **kwargs):
-        warnings += check_file(file_, complexity)
+    paths = _get_files(repo, **kwargs)
 
-    strict = ui.configbool('flake8', 'strict', default=True)
+    flake8_style = get_style_guide(
+        config_file=config, max_complexity=complexity)
+    report = flake8_style.check_files(paths)
 
     if strict:
-        return warnings
+        return report.total_errors
 
     return 0
 
 
 def run(command):
     p = Popen(command.split(), stdout=PIPE, stderr=PIPE)
-    p.wait()
-    return (p.returncode, [line.strip() for line in p.stdout.readlines()],
-            [line.strip() for line in p.stderr.readlines()])
+    (stdout, stderr) = p.communicate()
+    return (p.returncode, [line.strip() for line in stdout.splitlines()],
+            [line.strip() for line in stderr.splitlines()])
 
 
 def _get_files(repo, **kwargs):
             if file_ in seen or not os.path.exists(file_):
                 continue
             seen.add(file_)
-            if not file_.endswith('.py'):
-                continue
-            if skip_file(file_):
-                continue
-            yield file_
+            if file_.endswith('.py'):
+                yield file_
 
 
 def find_vcs():

File flake8/main.py

View file
  • Ignore whitespace
+# -*- coding: utf-8 -*-
 import os
 import sys
-import pep8
-import pyflakes.api
-import pyflakes.checker
-import select
-from flake8 import mccabe
-from flake8.util import _initpep8, skip_file, get_parser, Flake8Reporter
 
-pep8style = None
+import setuptools
+
+from flake8.engine import get_style_guide
 
 if sys.platform.startswith('win'):
-    pep8.DEFAULT_CONFIG = os.path.expanduser(r'~\.flake8')
+    DEFAULT_CONFIG = os.path.expanduser(r'~\.flake8')
 else:
-    pep8.DEFAULT_CONFIG = os.path.join(
+    DEFAULT_CONFIG = os.path.join(
         os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'),
         'flake8'
     )
 
-PROJECT_CONFIG = ['.flake8']
-PROJECT_CONFIG.extend(pep8.PROJECT_CONFIG)
-pep8.PROJECT_CONFIG = tuple(PROJECT_CONFIG)
-
 
 def main():
-    global pep8style
-    # parse out our flags so pep8 doesn't get confused
-    parser = get_parser()
+    """Parse options and run checks on Python source."""
+    # Prepare
+    flake8_style = get_style_guide(parse_argv=True, config_file=DEFAULT_CONFIG)
+    options = flake8_style.options
 
-    # We then have to re-parse argv to make sure pep8 is properly initialized
-    pep8style = pep8.StyleGuide(parse_argv=True, config_file=True,
-                                parser=parser)
-    opts = pep8style.options
-
-    if opts.install_hook:
+    if options.install_hook:
         from flake8.hooks import install_hook
         install_hook()
 
-    warnings = 0
-    stdin = None
+    # Run the checkers
+    report = flake8_style.check_files()
 
-    complexity = opts.max_complexity
-    builtins = set(opts.builtins.split(','))
-    if builtins:
-        orig_builtins = set(pyflakes.checker._MAGIC_GLOBALS)
-        pyflakes.checker._MAGIC_GLOBALS = orig_builtins | builtins
+    # Print the final report
+    options = flake8_style.options
+    if options.statistics:
+        report.print_statistics()
+    if options.benchmark:
+        report.print_benchmark()
+    if report.total_errors:
+        if options.count:
+            sys.stderr.write(str(report.total_errors) + '\n')
+        if not options.exit_zero:
+            raise SystemExit(1)
 
-    # This is needed so we can ignore some items
-    pyflakes_reporter = Flake8Reporter(opts.ignore)
 
-    if pep8style.paths and opts.filename is not None:
-        for path in _get_python_files(pep8style.paths):
-            if path == '-':
-                if stdin is None:
-                    stdin = read_stdin()
-                warnings += check_code(stdin, opts.ignore, complexity)
-            else:
-                warnings += check_file(path, opts.ignore, complexity,
-                                       pyflakes_reporter)
-    else:
-        stdin = read_stdin()
-        warnings += check_code(stdin, opts.ignore, complexity,
-                               pyflakes_reporter)
+def check_file(path, ignore=(), complexity=-1):
+    flake8_style = get_style_guide(
+        config_file=DEFAULT_CONFIG, ignore=ignore, max_complexity=complexity)
+    return flake8_style.input_file(path)
 
-    if opts.exit_zero:
-        raise SystemExit(0)
 
-    raise SystemExit(warnings > 0)
+def check_code(code, ignore=(), complexity=-1):
+    flake8_style = get_style_guide(
+        config_file=DEFAULT_CONFIG, ignore=ignore, max_complexity=complexity)
+    return flake8_style.input_file('-', lines=code.splitlines())
 
 
-def check_file(path, ignore=(), complexity=-1, reporter=None):
-    if pep8style.excluded(path):
-        return 0
-    warnings = pyflakes.api.checkPath(path, reporter)
-    warnings -= reporter.ignored_warnings
-    warnings += pep8style.input_file(path)
-    if complexity > -1:
-        warnings += mccabe.get_module_complexity(path, complexity)
-    return warnings
+class Flake8Command(setuptools.Command):
+    description = "Run flake8 on modules registered in setuptools"
+    user_options = []
 
+    def initialize_options(self):
+        pass
 
-def check_code(code, ignore=(), complexity=-1, reporter=None):
-    warnings = pyflakes.api.check(code, '<stdin>', reporter)
-    warnings -= reporter.ignored_warnings
-    warnings += pep8style.input_file('-', lines=code.split('\n'))
-    if complexity > -1:
-        warnings += mccabe.get_code_complexity(code, complexity)
-    return warnings
+    def finalize_options(self):
+        pass
 
+    def distribution_files(self):
+        if self.distribution.packages:
+            for package in self.distribution.packages:
+                yield package.replace(".", os.path.sep)
 
-def read_stdin():
-    # wait for 1 second on the stdin fd
-    reads, __, __ = select.select([sys.stdin], [], [], 1.)
-    if reads == []:
-        print('input not specified')
-        raise SystemExit(1)
+        if self.distribution.py_modules:
+            for filename in self.distribution.py_modules:
+                yield "%s.py" % filename
 
-    return sys.stdin.read()
-
-
-try:
-    from setuptools import Command
-except ImportError:
-    Flake8Command = None
-else:
-    class Flake8Command(Command):
-        description = "Run flake8 on modules registered in setuptools"
-        user_options = []
-
-        def initialize_options(self):
-            pass
-
-        def finalize_options(self):
-            pass
-
-        def distribution_files(self):
-            if self.distribution.packages:
-                for package in self.distribution.packages:
-                    yield package.replace(".", os.path.sep)
-
-            if self.distribution.py_modules:
-                for filename in self.distribution.py_modules:
-                    yield "%s.py" % filename
-
-        def run(self):
-            _initpep8()
-
-            # _get_python_files can produce the same file several
-            # times, if one of its paths is a parent of another. Keep
-            # a set of checked files to de-duplicate.
-            checked = set()
-
-            warnings = 0
-            for path in _get_python_files(self.distribution_files()):
-                if path not in checked:
-                    warnings += check_file(path)
-                checked.add(path)
-
-            raise SystemExit(warnings > 0)
-
-
-def _get_python_files(paths):
-    for path in paths:
-        if os.path.isdir(path):
-            for dirpath, dirnames, filenames in os.walk(path):
-                if pep8style.excluded(dirpath):
-                    dirnames[:] = []
-                    continue
-                for filename in filenames:
-                    if not filename.endswith('.py'):
-                        continue
-                    fullpath = os.path.join(dirpath, filename)
-                    if not skip_file(fullpath) or pep8style.excluded(fullpath):
-                        yield fullpath
-
-        else:
-            if not skip_file(path) or pep8style.excluded(path):
-                yield path
+    def run(self):
+        flake8_style = get_style_guide(config_file=DEFAULT_CONFIG)
+        paths = self.distribution_files()
+        report = flake8_style.check_files(paths)
+        raise SystemExit(report.total_errors > 0)

File flake8/mccabe.py

  • Ignore whitespace
-""" Meager code path measurement tool.
-    Ned Batchelder
-    http://nedbatchelder.com/blog/200803/python_code_complexity_microtool.html
-    MIT License.
-"""
-try:
-    from compiler import parse      # NOQA
-    iter_child_nodes = None         # NOQA
-except ImportError:
-    from ast import parse, iter_child_nodes     # NOQA
-
-import optparse
-import sys
-from flake8.util import skip_warning
-from collections import defaultdict
-
-WARNING_CODE = "W901"
-
-
-class ASTVisitor:
-
-    VERBOSE = 0
-
-    def __init__(self):
-        self.node = None
-        self._cache = {}
-
-    def default(self, node, *args):
-        if hasattr(node, 'getChildNodes'):
-            children = node.getChildNodes()
-        else:
-            children = iter_child_nodes(node)
-
-        for child in children:
-            self.dispatch(child, *args)
-
-    def dispatch(self, node, *args):
-        self.node = node
-        klass = node.__class__
-        meth = self._cache.get(klass)
-        if meth is None:
-            className = klass.__name__
-            meth = getattr(self.visitor, 'visit' + className, self.default)
-            self._cache[klass] = meth
-
-        return meth(node, *args)
-
-    def preorder(self, tree, visitor, *args):
-        """Do preorder walk of tree using visitor"""
-        self.visitor = visitor
-        visitor.visit = self.dispatch
-        self.dispatch(tree, *args)  # XXX *args make sense?
-
-
-class PathNode:
-    def __init__(self, name, look="circle"):
-        self.name = name
-        self.look = look
-
-    def to_dot(self):
-        print('node [shape=%s,label="%s"] %d;' % (
-            self.look, self.name, self.dot_id()))
-
-    def dot_id(self):
-        return id(self)
-
-
-class PathGraph:
-    def __init__(self, name, entity, lineno):
-        self.name = name
-        self.entity = entity
-        self.lineno = lineno
-        self.nodes = defaultdict(list)
-
-    def connect(self, n1, n2):
-        self.nodes[n1].append(n2)
-
-    def to_dot(self):
-        print('subgraph {')
-        for node in self.nodes:
-            node.to_dot()
-        for node, nexts in self.nodes.items():
-            for next in nexts:
-                print('%s -- %s;' % (node.dot_id(), next.dot_id()))
-        print('}')
-
-    def complexity(self):
-        """ Return the McCabe complexity for the graph.
-            V-E+2
-        """
-        num_edges = sum([len(n) for n in self.nodes.values()])
-        num_nodes = len(self.nodes)
-        return num_edges - num_nodes + 2
-
-
-class PathGraphingAstVisitor(ASTVisitor):
-    """ A visitor for a parsed Abstract Syntax Tree which finds executable
-        statements.
-    """
-
-    def __init__(self):
-        ASTVisitor.__init__(self)
-        self.classname = ""
-        self.graphs = {}
-        self.reset()
-
-    def reset(self):
-        self.graph = None
-        self.tail = None
-
-    def visitFunction(self, node):
-
-        if self.classname:
-            entity = '%s%s' % (self.classname, node.name)
-        else:
-            entity = node.name
-
-        name = '%d:1: %r' % (node.lineno, entity)
-
-        if self.graph is not None:
-            # closure
-            pathnode = self.appendPathNode(name)
-            self.tail = pathnode
-            self.default(node)
-            bottom = PathNode("", look='point')
-            self.graph.connect(self.tail, bottom)
-            self.graph.connect(pathnode, bottom)
-            self.tail = bottom
-        else:
-            self.graph = PathGraph(name, entity, node.lineno)
-            pathnode = PathNode(name)
-            self.tail = pathnode
-            self.default(node)
-            self.graphs["%s%s" % (self.classname, node.name)] = self.graph
-            self.reset()
-
-    visitFunctionDef = visitFunction
-
-    def visitClass(self, node):
-        old_classname = self.classname
-        self.classname += node.name + "."
-        self.default(node)
-        self.classname = old_classname
-
-    def appendPathNode(self, name):
-        if not self.tail:
-            return
-        pathnode = PathNode(name)
-        self.graph.connect(self.tail, pathnode)
-        self.tail = pathnode
-        return pathnode
-
-    def visitSimpleStatement(self, node):
-        if node.lineno is None:
-            lineno = 0
-        else:
-            lineno = node.lineno
-        name = "Stmt %d" % lineno
-        self.appendPathNode(name)
-
-    visitAssert = visitAssign = visitAssTuple = visitPrint = \
-        visitPrintnl = visitRaise = visitSubscript = visitDecorators = \
-        visitPass = visitDiscard = visitGlobal = visitReturn = \
-        visitSimpleStatement
-
-    def visitLoop(self, node):
-        name = "Loop %d" % node.lineno
-
-        if self.graph is None:
-            # global loop
-            self.graph = PathGraph(name, name, node.lineno)
-            pathnode = PathNode(name)
-            self.tail = pathnode
-            self.default(node)
-            self.graphs["%s%s" % (self.classname, name)] = self.graph
-            self.reset()
-        else:
-            pathnode = self.appendPathNode(name)
-            self.tail = pathnode
-            self.default(node.body)
-            bottom = PathNode("", look='point')
-            self.graph.connect(self.tail, bottom)
-            self.graph.connect(pathnode, bottom)
-            self.tail = bottom
-
-        # TODO: else clause in node.else_
-
-    visitFor = visitWhile = visitLoop
-
-    def visitIf(self, node):
-        name = "If %d" % node.lineno
-        pathnode = self.appendPathNode(name)
-        if not pathnode:
-            return  # TODO: figure out what to do with if's outside def's.
-        loose_ends = []
-        for t, n in node.tests:
-            self.tail = pathnode
-            self.default(n)
-            loose_ends.append(self.tail)
-        if node.else_:
-            self.tail = pathnode
-            self.default(node.else_)
-            loose_ends.append(self.tail)
-        else:
-            loose_ends.append(pathnode)
-        bottom = PathNode("", look='point')
-        for le in loose_ends:
-            self.graph.connect(le, bottom)
-        self.tail = bottom
-
-    # TODO: visitTryExcept
-    # TODO: visitTryFinally
-    # TODO: visitWith
-
-    # XXX todo: determine which ones can add to the complexity
-    # py2
-    # TODO: visitStmt
-    # TODO: visitAssName
-    # TODO: visitCallFunc
-    # TODO: visitConst
-
-    # py3
-    # TODO: visitStore
-    # TODO: visitCall
-    # TODO: visitLoad
-    # TODO: visitNum
-    # TODO: visitarguments
-    # TODO: visitExpr
-
-
-def get_code_complexity(code, min=7, filename='stdin'):
-    complex = []
-    try:
-        ast = parse(code)
-    except (AttributeError, SyntaxError):
-        e = sys.exc_info()[1]
-        sys.stderr.write("Unable to parse %s: %s\n" % (filename, e))
-        return 0
-
-    visitor = PathGraphingAstVisitor()
-    visitor.preorder(ast, visitor)
-    for graph in visitor.graphs.values():
-        if graph is None:
-            # ?
-            continue
-        if graph.complexity() >= min:
-            graph.filename = filename
-            if not skip_warning(graph):
-                msg = '%s:%d:1: %s %r is too complex (%d)' % (
-                    filename,
-                    graph.lineno,
-                    WARNING_CODE,
-                    graph.entity,
-                    graph.complexity(),
-                )
-                complex.append(msg)
-
-    if len(complex) == 0:
-        return 0
-
-    print('\n'.join(complex))
-    return len(complex)
-
-
-def get_module_complexity(module_path, min=7):
-    """Returns the complexity of a module"""
-    code = open(module_path, "rU").read() + '\n\n'
-    return get_code_complexity(code, min, filename=module_path)
-
-
-def main(argv):
-    opar = optparse.OptionParser()
-    opar.add_option("-d", "--dot", dest="dot",
-                    help="output a graphviz dot file", action="store_true")
-    opar.add_option("-m", "--min", dest="min",
-                    help="minimum complexity for output", type="int",
-                    default=2)
-
-    options, args = opar.parse_args(argv)
-
-    text = open(args[0], "rU").read() + '\n\n'
-    ast = parse(text)
-    visitor = PathGraphingAstVisitor()
-    visitor.preorder(ast, visitor)
-
-    if options.dot:
-        print('graph {')
-        for graph in visitor.graphs.values():
-            if graph.complexity() >= options.min:
-                graph.to_dot()
-        print('}')
-    else:
-        for graph in visitor.graphs.values():
-            if graph.complexity() >= options.min:
-                print(graph.name, graph.complexity())
-
-
-if __name__ == '__main__':
-    main(sys.argv[1:])

File flake8/run.py

View file
  • Ignore whitespace
 """
 Implementation of the command-line I{flake8} tool.
 """
-from flake8.hooks import git_hook, hg_hook  # noqa
+from flake8.hooks import git_hook, hg_hook                      # noqa
+from flake8.main import check_code, check_file, Flake8Command   # noqa
 from flake8.main import main
-from flake8.main import (check_code, check_file, get_parser,  # noqa
-                         Flake8Command)  # noqa
 
 
 if __name__ == '__main__':

File flake8/tests/test_flakes.py

View file
  • Ignore whitespace
+# -*- coding: utf-8 -*-
+import sys
+
 from unittest import TestCase
 from pyflakes.api import check
 
 
-code = """
+class FlakesTestReporter(object):
+    def __init__(self):
+        self.messages = []
+        self.flakes = self.messages.append
+
+    def unexpectedError(self, filename, msg):
+        self.flakes('[unexpectedError] %s: %s' % (filename, msg))
+
+    def syntaxError(self, filename, msg, lineno, offset, text):
+        self.flakes('[syntaxError] %s:%d: %s' % (filename, lineno, msg))
+
+
+code0 = """
+try:
+    pass
+except ValueError, err:
+    print(err)
+"""
+
+code1 = """
 try:
     pass
 except ValueError as err:
 class TestFlake(TestCase):
 
     def test_exception(self):
-        for c in (code, code2, code3):
-            warnings = check(code, '(stdin)')
+        codes = [code1, code2, code3]
+        if sys.version_info < (2, 6):
+            codes[0] = code0
+        elif sys.version_info < (3,):
+            codes.insert(0, code0)
+        for code in codes:
+            reporter = FlakesTestReporter()
+            warnings = check(code, '(stdin)', reporter)
+            self.assertFalse(reporter.messages)
             self.assertEqual(warnings, 0)
 
     def test_from_import_exception_in_scope(self):
-        warnings = check(code_from_import_exception, '(stdin)')
+        reporter = FlakesTestReporter()
+        warnings = check(code_from_import_exception, '(stdin)', reporter)
+        self.assertFalse(reporter.messages)
         self.assertEqual(warnings, 0)
 
     def test_import_exception_in_scope(self):
-        warnings = check(code_import_exception, '(stdin)')
+        reporter = FlakesTestReporter()
+        warnings = check(code_import_exception, '(stdin)', reporter)
+        self.assertFalse(reporter.messages)
         self.assertEqual(warnings, 0)

File flake8/tests/test_mccabe.py

  • Ignore whitespace
-import unittest
-import sys
-try:
-    from StringIO import StringIO
-except ImportError:
-    from io import StringIO     # NOQA
-
-from flake8.mccabe import get_code_complexity
-
-
-_GLOBAL = """\
-
-for i in range(10):
-    pass
-
-def a():
-    def b():
-        def c():
-            pass
-        c()
-    b()
-
-"""
-
-
-class McCabeTest(unittest.TestCase):
-
-    def setUp(self):
-        self.old = sys.stdout
-        self.out = sys.stdout = StringIO()
-
-    def tearDown(self):
-        sys.sdtout = self.old
-
-    def test_sample(self):
-        self.assertEqual(get_code_complexity(_GLOBAL, 1), 2)
-        self.out.seek(0)
-        res = self.out.read().strip().split('\n')
-        wanted = ["stdin:5:1: W901 'a' is too complex (4)",
-                  "stdin:2:1: W901 'Loop 2' is too complex (2)"]
-        self.assertEqual(res, wanted)

File flake8/util.py

View file
  • Ignore whitespace
-from __future__ import with_statement
-import re
-import os
-import sys
-from io import StringIO
-import pep8
-import pyflakes
-from pyflakes import reporter, messages
+# -*- coding: utf-8 -*-
 
 try:
-    # Python 2
-    from ConfigParser import ConfigParser
-except ImportError:
-    # Python 3
-    from configparser import ConfigParser
+    import ast
+    iter_child_nodes = ast.iter_child_nodes
+except ImportError:   # Python 2.5
+    import _ast as ast
 
-pep8style = None
+    if 'decorator_list' not in ast.ClassDef._fields:
+        # Patch the missing attribute 'decorator_list'
+        ast.ClassDef.decorator_list = ()
+        ast.FunctionDef.decorator_list = property(lambda s: s.decorators)
 
+    def iter_child_nodes(node):
+        """
+        Yield all direct child nodes of *node*, that is, all fields that
+        are nodes and all items of fields that are lists of nodes.
+        """
+        if not node._fields:
+            return
+        for name in node._fields:
+            field = getattr(node, name, None)
+            if isinstance(field, ast.AST):
+                yield field
+            elif isinstance(field, list):
+                for item in field:
+                    if isinstance(item, ast.AST):
+                        yield item
 
-def get_parser():
-    """Create a custom OptionParser"""
-    from flake8 import __version__
-    parser = pep8.get_parser()
 
-    def version(option, opt, value, parser):
-        parser.print_usage()
-        parser.print_version()
-        sys.exit(0)
+class OrderedSet(list):
+    """List without duplicates."""
+    __slots__ = ()
 
-    parser.version = '{0} (pep8: {1}, pyflakes: {2})'.format(
-        __version__, pep8.__version__, pyflakes.__version__)
-    parser.remove_option('--version')
-    parser.add_option('--builtins', default='', dest='builtins',
-                      help="append builtin functions to pyflakes' "
-                           "_MAGIC_BUILTINS")
-    parser.add_option('--exit-zero', action='store_true', default=False,
-                      help='Exit with status 0 even if there are errors')
-    parser.add_option('--max-complexity', default=-1, action='store',
-                      type='int', help='McCabe complexity threshold')
-    parser.add_option('--install-hook', default=False, action='store_true',
-                      help='Install the appropriate hook for this '
-                      'repository.', dest='install_hook')
-    # don't overlap with pep8's verbose option
-    parser.add_option('-V', '--version', action='callback',
-                      callback=version,
-                      help='Print the version info for flake8')
-    parser.prog = os.path.basename(sys.argv[0])
-    return parser
-
-
-def skip_warning(warning, ignore=[]):
-    # XXX quick dirty hack, just need to keep the line in the warning
-    if not hasattr(warning, 'message') or ignore is None:
-        # McCabe's warnings cannot be skipped afaik, and they're all strings.
-        # And we'll get a TypeError otherwise
-        return False
-    if warning.message.split()[0] in ignore:
-        return True
-    if not os.path.isfile(warning.filename):
-        return False
-
-    # XXX should cache the file in memory
-    with open(warning.filename) as f:
-        line = f.readlines()[warning.lineno - 1]
-
-    return skip_line(line)
-
-
-def skip_line(line):
-    def _noqa(line):
-        return line.strip().lower().endswith('# noqa')
-    skip = _noqa(line)
-    if not skip:
-        i = line.rfind(' #')
-        skip = _noqa(line[:i]) if i > 0 else False
-    return skip
-
-
-_NOQA = re.compile(r'flake8[:=]\s*noqa', re.I | re.M)
-
-
-def skip_file(path, source=None):
-    """Returns True if this header is found in path
-
-    # flake8: noqa
-    """
-    if os.path.isfile(path):
-        f = open(path)
-    elif source:
-        f = StringIO(source)
-    else:
-        return False
-
-    try:
-        content = f.read()
-    finally:
-        f.close()
-    return _NOQA.search(content) is not None
-
-
-def _initpep8(config_file=True):
-    # default pep8 setup
-    global pep8style
-    import pep8
-    if pep8style is None:
-        pep8style = pep8.StyleGuide(config_file=config_file)
-    pep8style.options.physical_checks = pep8.find_checks('physical_line')
-    pep8style.options.logical_checks = pep8.find_checks('logical_line')
-    pep8style.options.counters = dict.fromkeys(pep8.BENCHMARK_KEYS, 0)
-    pep8style.options.messages = {}
-    if not pep8style.options.max_line_length:
-        pep8style.options.max_line_length = 79
-    pep8style.args = []
-    return pep8style
-
-
-error_mapping = {
-    'W402': (messages.UnusedImport,),
-    'W403': (messages.ImportShadowedByLoopVar,),
-    'W404': (messages.ImportStarUsed,),
-    'W405': (messages.LateFutureImport,),
-    'W801': (messages.RedefinedWhileUnused,
-             messages.RedefinedInListComp,),
-    'W802': (messages.UndefinedName,),
-    'W803': (messages.UndefinedExport,),
-    'W804': (messages.UndefinedLocal,
-             messages.UnusedVariable,),
-    'W805': (messages.DuplicateArgument,),
-    'W806': (messages.Redefined,),
-}
-
-
-class Flake8Reporter(reporter.Reporter):
-    """Our own instance of a Reporter so that we can silence some messages."""
-    class_mapping = dict((k, c) for (c, v) in error_mapping.items() for k in v)
-
-    def __init__(self, ignore=None):
-        super(Flake8Reporter, self).__init__(sys.stdout, sys.stderr)
-        self.ignore = ignore or []
-        self.ignored_warnings = 0
-
-    def flake(self, message):
-        classes = [error_mapping[i] for i in self.ignore if i in error_mapping]
-
-        if (any(isinstance(message, c) for c in classes) or
-                skip_warning(message)):
-            self.ignored_warnings += 1
-            return
-        m = self.to_str(message)
-        i = m.rfind(':') + 1
-        message = '{0} {1}{2}'.format(
-            m[:i], self.class_mapping[message.__class__], m[i:]
-        )
-
-        super(Flake8Reporter, self).flake(message)
-
-    def to_str(self, message):
-        try:
-            return unicode(message)
-        except NameError:
-            return str(message)
+    def add(self, value):
+        if value not in self:
+            self.append(value)

File setup.py

View file
  • Ignore whitespace
-import sys
-import os
+# -*- coding: utf-8 -*-
+from __future__ import with_statement
+from setuptools import setup
 
-ispy3 = sys.version_info[0] == 3
-iswin = os.name == 'nt'
 
-kwargs = {}
-scripts = ["flake8/flake8"]
-if ispy3:
-    from distutils.core import setup    # NOQA
-    if iswin:
-        scripts.append("scripts/flake8.cmd")
-else:
-    try:
-        from setuptools import setup    # NOQA
-        kwargs = {
-            'entry_points': {
-                'distutils.commands': ['flake8 = flake8.main:Flake8Command'],
-                'console_scripts': ['flake8 = flake8.main:main']
-            },
-            'tests_require': ['nose'],
-            'test_suite': 'nose.collector',
-        }
-    except ImportError:
-        from distutils.core import setup   # NOQA
-        if iswin:
-            scripts.append("scripts/flake8.cmd")
+def get_version(fname='flake8/__init__.py'):
+    with open(fname) as f:
+        for line in f:
+            if line.startswith('__version__'):
+                return eval(line.split('=')[-1])
 
-from flake8 import __version__
 
-README = open('README.rst').read()
+def get_long_description():
+    descr = []
+    for fname in ('README.rst', 'CHANGES.rst'):
+        with open(fname) as f:
+            descr.append(f.read())
+    return '\n\n'.join(descr)
+
 
 setup(
     name="flake8",
     license="MIT",
-    version=__version__,
-    description="code checking using pep8 and pyflakes",
+    version=get_version(),
+    description="the modular source code checker: pep8, pyflakes and co",
+    long_description=get_long_description(),
     author="Tarek Ziade",
     author_email="tarek@ziade.org",
     maintainer="Ian Cordasco",
     maintainer_email="graffatcolmingov@gmail.com",
     url="http://bitbucket.org/tarek/flake8",
     packages=["flake8", "flake8.tests"],
-    scripts=scripts,
-    install_requires=["pyflakes==0.6.1",  "pep8==1.4.2"],
-    long_description=README,
+    install_requires=[
+        "setuptools",
+        "pyflakes >= 0.6.1",
+        "pep8 >= 1.4.3",
+        "mccabe >= 0.2",
+    ],
+    entry_points={
+        'distutils.commands': ['flake8 = flake8.main:Flake8Command'],
+        'console_scripts': ['flake8 = flake8.main:main'],
+        'flake8.extension': [
+            'F = flake8._pyflakes:FlakesChecker',
+        ],
+    },
     classifiers=[
         "Environment :: Console",
         "Intended Audience :: Developers",
         "License :: OSI Approved :: MIT License",
         "Programming Language :: Python",
-        "Topic :: Software Development",
-        "Topic :: Utilities",
+        "Programming Language :: Python :: 2",
+        "Programming Language :: Python :: 3",
+        "Topic :: Software Development :: Libraries :: Python Modules",
+        "Topic :: Software Development :: Quality Assurance",
     ],
-    **kwargs
+    tests_require=['nose'],
+    test_suite='nose.collector',
 )