Commits

Anonymous committed 7357e5d Merge

Merged tarek/flake8 into default

Comments (0)

Files changed (26)

+CHANGES
+=======
+
+2.0.0 - 2013-02-xx
+------------------
+
+- Pyflakes errors are now prefixed by an ``F`` instead of an ``E``
+- McCabe complexity warnings are now prefixed by a ``C`` instead of a ``W``
+- Flake8 now supports extensions through entry points
+- Due to the above support, we now **require** setuptools
+- We now have `documentation <https://flake8.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-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
 - Miki Tebeka
 - David Cramer
 - Peter Teichman
+- Ian Cordasco
 - Oleg Broytman
 - Marc Labbé
 - Bruno Miguel Custódio
+- Florent Xicluna
 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.
-
+include *.rst
 include CONTRIBUTORS.txt
-include README
 include LICENSE
 recursive-include scripts flake8.*
 
 - PyFlakes
 - pep8
-- Ned's McCabe script
+- Ned Batchelder'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
 ==========
 
+::
+
+    pip install flake8
+
 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.
 
 
-Mercurial hook
-==============
+.. _links:
 
-To use the Mercurial hook on any *commit* or *qrefresh*, change your .hg/rc file
-like this::
+Links
+=====
 
-    [hooks]
-    commit = python:flake8.run.hg_hook
-    qrefresh = python:flake8.run.hg_hook
+* `flake8 documentation <http://flake8.readthedocs.org/en/latest/>`_
 
-    [flake8]
-    strict = 0
-    complexity = 12
-
-
-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.
-
-*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.
-
-Git hook
-========
-
-To use the Git hook on any *commit*, add a **pre-commit** file in the
-*.git/hooks* directory containing::
-
-    #!/usr/bin/python
-    import sys
-    from flake8.run import git_hook
-
-    COMPLEXITY = 10
-    STRICT = False
-
-    if __name__ == '__main__':
-        sys.exit(git_hook(complexity=COMPLEXITY, strict=STRICT, ignore='E501'))
-
-
-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
-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.
-
-*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.
-
-
-Buildout integration
-=====================
-
-In order to use Flake8 inside a buildout, edit your buildout.cfg and add this::
-
-    [buildout]
-
-    parts +=
-        ...
-        flake8
-
-    [flake8]
-    recipe = zc.recipe.egg
-    eggs = flake8
-           ${buildout:eggs}
-    entry-points =
-        flake8=flake8.run:main
-
-
-setuptools 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
-setup_requires::
-
-    setup(
-        name="project",
-        packages=["project"],
-
-        setup_requires=[
-            "flake8"
-        ]
-    )
-
-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::
-
-    $ python setup.py flake8
-
-
-
-Original projects
-=================
-
-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
-- 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.
-
-pep8:
-
-- E101: indentation contains mixed spaces and tabs
-- E111: indentation is not a multiple of four
-- E112: expected an indented block
-- E113: unexpected indentation
-- 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()'
-
-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
-
-McCabe:
-
-- W901: '<function_name>' is too complex ('<complexity_level>')
-
-CHANGES
-=======
-
-2.0.0 - 2013-01-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-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
-
-
+* `pep8 documentation <http://pep8.readthedocs.org/en/latest/>`_
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS    =
+SPHINXBUILD   = sphinx-build
+PAPER         =
+BUILDDIR      = _build
+
+# Internal variables.
+PAPEROPT_a4     = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+
+.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
+
+help:
+	@echo "Please use \`make <target>' where <target> is one of"
+	@echo "  html       to make standalone HTML files"
+	@echo "  dirhtml    to make HTML files named index.html in directories"
+	@echo "  singlehtml to make a single large HTML file"
+	@echo "  pickle     to make pickle files"
+	@echo "  json       to make JSON files"
+	@echo "  htmlhelp   to make HTML files and a HTML help project"
+	@echo "  qthelp     to make HTML files and a qthelp project"
+	@echo "  devhelp    to make HTML files and a Devhelp project"
+	@echo "  epub       to make an epub"
+	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+	@echo "  latexpdf   to make LaTeX files and run them through pdflatex"
+	@echo "  text       to make text files"
+	@echo "  man        to make manual pages"
+	@echo "  changes    to make an overview of all changed/added/deprecated items"
+	@echo "  linkcheck  to check all external links for integrity"
+	@echo "  doctest    to run all doctests embedded in the documentation (if enabled)"
+
+clean:
+	-rm -rf $(BUILDDIR)/*
+
+html:
+	$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
+	@echo
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
+
+dirhtml:
+	$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
+	@echo
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
+
+singlehtml:
+	$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
+	@echo
+	@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
+
+pickle:
+	$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
+	@echo
+	@echo "Build finished; now you can process the pickle files."
+
+json:
+	$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
+	@echo
+	@echo "Build finished; now you can process the JSON files."
+
+htmlhelp:
+	$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
+	@echo
+	@echo "Build finished; now you can run HTML Help Workshop with the" \
+	      ".hhp project file in $(BUILDDIR)/htmlhelp."
+
+qthelp:
+	$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
+	@echo
+	@echo "Build finished; now you can run "qcollectiongenerator" with the" \
+	      ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
+	@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Raclette.qhcp"
+	@echo "To view the help file:"
+	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Raclette.qhc"
+
+devhelp:
+	$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
+	@echo
+	@echo "Build finished."
+	@echo "To view the help file:"
+	@echo "# mkdir -p $$HOME/.local/share/devhelp/Raclette"
+	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Raclette"
+	@echo "# devhelp"
+
+epub:
+	$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
+	@echo
+	@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
+
+latex:
+	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+	@echo
+	@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
+	@echo "Run \`make' in that directory to run these through (pdf)latex" \
+	      "(use \`make latexpdf' here to do that automatically)."
+
+latexpdf:
+	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+	@echo "Running LaTeX files through pdflatex..."
+	make -C $(BUILDDIR)/latex all-pdf
+	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+text:
+	$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
+	@echo
+	@echo "Build finished. The text files are in $(BUILDDIR)/text."
+
+man:
+	$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
+	@echo
+	@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
+
+changes:
+	$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
+	@echo
+	@echo "The overview file is in $(BUILDDIR)/changes."
+
+linkcheck:
+	$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
+	@echo
+	@echo "Link check complete; look for any errors in the above output " \
+	      "or in $(BUILDDIR)/linkcheck/output.txt."
+
+doctest:
+	$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
+	@echo "Testing of doctests in the sources finished, look at the " \
+	      "results in $(BUILDDIR)/doctest/output.txt."
+==========
+Flake8 API
+==========
+
+.. module:: flake8
+
+flake8.engine
+=============
+
+.. autofunction:: flake8.engine.get_parser
+
+.. autofunction:: flake8.engine.get_style_guide
+
+flake8.hooks
+============
+
+.. autofunction:: flake8.hooks.git_hook
+
+.. autofunction:: flake8.hooks.hg_hook
+
+flake8.main
+===========
+
+.. autofunction:: flake8.main.main
+
+.. autofunction:: flake8.main.check_file
+
+.. autofunction:: flake8.main.check_code
+
+.. autoclass:: flake8.main.Flake8Command
+
+flake8.util
+===========
+
+For AST checkers, this module has the ``iter_child_nodes`` function and
+handles compatibility for all versions of Python between 2.5 and 3.3. The
+function was added to the ``ast`` module in Python 2.6 but is redefined in the
+case where the user is running Python 2.5

docs/buildout.rst

+Buildout integration
+=====================
+
+In order to use Flake8 inside a buildout, edit your buildout.cfg and add this::
+
+    [buildout]
+
+    parts +=
+        ...
+        flake8
+
+    [flake8]
+    recipe = zc.recipe.egg
+    eggs = flake8
+           ${buildout:eggs}
+    entry-points =
+        flake8=flake8.main:main
+# -*- coding: utf-8 -*-
+#
+# This file is execfile()d with the current directory set to its
+# containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys
+import os
+
+# This environment variable makes decorators not decorate functions, so their
+# signatures in the generated documentation are still correct
+os.environ['GENERATING_DOCUMENTATION'] = "flake8"
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+sys.path.insert(0, os.path.abspath('..'))
+import flake8
+
+# -- General configuration ----------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = ['sphinx.ext.autodoc']
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'flake8'
+copyright = u'2012-2013 - Tarek Ziade, Ian Cordasco, Florent Xicluna'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = flake8.__version__
+# The full version, including alpha/beta/rc tags.
+release = version
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = ['_build']
+
+# The reST default role (used for this markup: `text`) to use for
+# all documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+# pygments_style = 'flask_theme_support.FlaskyStyle'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+
+# -- Options for HTML output --------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages.  See the documentation for
+# a list of builtin themes.
+html_theme = 'nature'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further.  For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents.  If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar.  Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+#html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = False
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+#html_show_sphinx = False
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it.  The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'flake8_doc'
+
+
+# -- Options for LaTeX output -------------------------------------------------
+
+# The paper size ('letter' or 'a4').
+#latex_paper_size = 'letter'
+
+# The font size ('10pt', '11pt' or '12pt').
+#latex_font_size = '10pt'
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title,
+#  author, documentclass [howto/manual]).
+latex_documents = [
+    ('index', 'flake8.tex', u'flake8 Documentation',
+     u'Tarek Ziade', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Additional stuff for the LaTeX preamble.
+#latex_preamble = ''
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output -------------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+    ('index', 'flake8', u'flake8 Documentation',
+     [u'Tarek Ziade', u'Ian Cordasco', u'Florent Xicluna'], 1)
+]
+
+# If true, show URL addresses after external links.
+#man_show_urls = False
+
+
+# -- Options for Texinfo output -----------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+#  dir menu entry, description, category)
+texinfo_documents = [
+    ('index', 'flake8', u'flake8 Documentation', u'Tarek Ziade',
+     'flake8', 'Code checking using pep8, pyflakes and mccabe',
+     'Miscellaneous'),
+]
+
+# Documents to append as an appendix to all manuals.
+texinfo_appendices = []
+Configuration
+=============
+
+The behaviour may be configured at two levels.
+
+Global
+------
+
+The user settings are read from the ``~/.config/flake8`` file.
+Example::
+
+  [flake8]
+  ignore = E226,E302,E41
+  max-line-length = 160
+
+Per-Project
+-----------
+
+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.
+
+Default
+-------
+
+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 the :ref:`warning and error codes <error-codes>`).

docs/extensions.rst

+Writing an Extension for Flake8
+===============================
+
+Since Flake8 is now adding support for extensions, we require ``setuptools`` 
+so we can manage extensions through entry points. If you are making an 
+existing tool compatible with Flake8 but do not already require 
+``setuptools``, you should probably add it to your list of requirements. Next, 
+you'll need to edit your ``setup.py`` file so that upon installation, your 
+extension is registered. If you define a class called ``PackageEntryClass`` 
+then this would look something like the following::
+
+
+    setup(
+        # ...
+        entry_points={
+            'flake8.extension': ['P10 = package.PackageEntryClass'],
+        }
+        # ...
+    )
+
+We used ``P10`` here, but in reality, you should check to prevent as much 
+future overlap as possible with other extensions. ``W`` and ``E`` followed by 
+three digits should be considered entirely reserved for pep8. ``F`` should be 
+considered reserved for Pyflakes and ``C`` for McCabe. Also, in anticipation 
+of possible pylint integration, ``W`` and ``E`` followed by four digits should 
+be considered reserved. We have no way of checking for those though, so while 
+we ask you not use them, we can not (currently) prevent you from doing so.
+
+A Real Example: McCabe
+----------------------
+
+Below is an example from mccabe_ for how to write your ``setup.py`` file for 
+your Flake8 extension.
+
+.. code-block:: python
+
+    # https://github.com/florentx/mccabe/blob/master/setup.py
+    # -*- coding: utf-8 -*-
+    from __future__ import with_statement
+    from setuptools import setup
+
+
+    def get_version(fname='mccabe.py'):
+        with open(fname) as f:
+            for line in f:
+                if line.startswith('__version__'):
+                    return eval(line.split('=')[-1])
+
+
+    def get_long_description():
+        descr = []
+        for fname in ('README.rst',):
+            with open(fname) as f:
+                descr.append(f.read())
+        return '\n\n'.join(descr)
+
+
+    setup(
+        name='mccabe',
+        version=get_version(),
+        description="McCabe checker, plugin for flake8",
+        long_description=get_long_description(),
+        keywords='flake8 mccabe',
+        author='Tarek Ziade',
+        author_email='tarek@ziade.org',
+        maintainer='Florent Xicluna',
+        maintainer_email='florent.xicluna@gmail.com',
+        url='https://github.com/florentx/mccabe',
+        license='Expat license',
+        py_modules=['mccabe'],
+        zip_safe=False,
+        install_requires=[
+            'setuptools',
+        ],
+        entry_points={
+            'flake8.extension': [
+                'C90 = mccabe:McCabeChecker',
+            ],
+        },
+        classifiers=[
+            'Development Status :: 3 - Alpha',
+            'Environment :: Console',
+            'Intended Audience :: Developers',
+            'License :: OSI Approved :: MIT License',
+            'Operating System :: OS Independent',
+            'Programming Language :: Python',
+            'Programming Language :: Python :: 2',
+            'Programming Language :: Python :: 3',
+            'Topic :: Software Development :: Libraries :: Python Modules',
+            'Topic :: Software Development :: Quality Assurance',
+        ],
+    )
+
+In ``mccabe.py`` you can see that extra options are added to the parser when 
+flake8 registers the extensions:
+
+.. code-block:: python
+
+    # https://github.com/florentx/mccabe/blob/e88be51e0c6c2bd1b87d7a44b7e71b78fdc53959/mccabe.py#L225
+    class McCabeChecker(object):
+        """McCabe cyclomatic complexity checker."""
+        name = 'mccabe'
+        version = __version__
+        _code = 'C901'
+        _error_tmpl = "C901 %r is too complex (%d)"
+        max_complexity = 0
+
+        def __init__(self, tree, filename):
+            self.tree = tree
+
+        @classmethod
+        def add_options(cls, parser):
+            parser.add_option('--max-complexity', default=-1, action='store',
+                              type='int', help="McCabe complexity threshold")
+            parser.config_options.append('max-complexity')
+
+        @classmethod
+        def parse_options(cls, options):
+            cls.max_complexity = options.max_complexity
+
+        def run(self):
+            if self.max_complexity < 0:
+                return
+            visitor = PathGraphingAstVisitor()
+            visitor.preorder(self.tree, visitor)
+            for graph in visitor.graphs.values():
+                if graph.complexity() >= self.max_complexity:
+                    text = self._error_tmpl % (graph.entity, graph.complexity())
+                    yield graph.lineno, 0, text, type(self)
+
+Since that is the defined entry point in the above ``setup.py``, flake8 finds 
+it and uses it to register the extension.
+
+.. links
+.. _mccabe: https://github.com/florentx/mccabe
+.. _PyPI: https://pypi.python.org/pypi/
+.. include:: ../README.rst
+   :end-before: _links:
+
+Documentation
+=============
+
+.. toctree::
+
+    api
+    extensions
+    config
+    vcs
+    buildout
+    setuptools
+    warnings
+
+Original Projects
+=================
+
+Flake8 is just a glue project, all the merits go to the creators of the original
+projects:
+
+- pep8: https://github.com/jcrocholl/pep8
+- PyFlakes: https://launchpad.net/pyflakes
+- McCabe: http://nedbatchelder.com/blog/200803/python_code_complexity_microtool.html
+
+.. include:: ../CHANGES.rst

docs/setuptools.rst

+Setuptools 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
+setup_requires::
+
+    setup(
+        name="project",
+        packages=["project"],
+
+        setup_requires=[
+            "flake8"
+        ]
+    )
+
+Running ``python setup.py flake8`` on the command line will check the
+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
+VCS Hooks
+=========
+
+Mercurial hook
+--------------
+
+To use the Mercurial hook on any *commit* or *qrefresh*, change your .hg/hgrc
+file like this::
+
+    [hooks]
+    commit = python:flake8.run.hg_hook
+    qrefresh = python:flake8.run.hg_hook
+
+    [flake8]
+    strict = 0
+    complexity = 12
+
+
+If *strict* option is set to **1**, any warning will block the commit. When
+*strict* is set to **0**, warnings are just printed to the standard output.
+
+*complexity* defines the maximum McCabe complexity allowed before a warning
+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
+--------
+
+To use the Git hook on any *commit*, add a **pre-commit** file in the
+*.git/hooks* directory containing::
+
+    #!/usr/bin/python
+    import sys
+    from flake8.run import git_hook
+
+    COMPLEXITY = 10
+    STRICT = False
+
+    if __name__ == '__main__':
+        sys.exit(git_hook(complexity=COMPLEXITY, strict=STRICT, ignore='E501'))
+
+
+If *strict* option is set to **True**, any warning will block the commit. When
+*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 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
+index.
+
+Also, make sure the file is executable and adapt the shebang line so it
+points to your Python interpreter.

docs/warnings.rst

+.. _error-codes:
+
+Warning / Error codes
+=====================
+
+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.
+
+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:
+
+- ``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>`_
+
+
+The original PyFlakes does not provide error codes.  Flake8 patches the
+PyFlakes messages to add the following codes:
+
++------+--------------------------------------------------------------------+
+| 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              |
++------+--------------------------------------------------------------------+

flake8/__init__.py

File contents unchanged.

flake8/_pyflakes.py

+# -*- 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__
+# -*- 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():
+    """This returns an instance of optparse.OptionParser with all the
+    extensions registered and options set. This wraps ``pep8.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. This returns a sub-class 
+    of ``pep8.StyleGuide``."""
+    kwargs['parser'], options_hooks = get_parser()
+    styleguide = StyleGuide(**kwargs)
+    options = styleguide.options
+    for options_hook in options_hooks:
+        options_hook(options)
+    return styleguide
+# -*- 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
-
+    """This is the function used by the git hook.
+    
+    :param int complexity: (optional), any value > 0 enables complexity
+        checking with mccabe
+    :param bool strict: (optional), if True, this returns the total number of
+        errors which will cause the hook to fail
+    :param str ignore: (optional), a comma-separated list of errors and
+        warnings to ignore
+    :param bool lazy: (optional), allows for the instances where you don't add
+        the files to the index before running a commit, e.g., git commit -a
+    :returns: total number of errors if strict is True, otherwise 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
+    """This is the function executed directly by Mercurial as part of the
+    hook. This is never called directly by the user, so the parameters are
+    undocumented. If you would like to learn more about them, please feel free
+    to read the official Mercurial documentation.
+    """
     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():
+# -*- 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, read_config,
-                         Flake8Reporter)
 
-pep8style = None
+import setuptools
+
+from flake8.engine import get_style_guide
+
+if sys.platform.startswith('win'):
+    DEFAULT_CONFIG = os.path.expanduser(r'~\.flake8')
+else:
+    DEFAULT_CONFIG = os.path.join(
+        os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'),
+        'flake8'
+    )
 
 
 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()
 
-    read_config(opts, parser)
+    # Run the checkers
+    report = flake8_style.check_files()
 
-    warnings = 0
-    stdin = None
+    # 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)
 
-    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
 
-    # This is needed so we can ignore some items
-    pyflakes_reporter = Flake8Reporter(opts.ignore)
+def check_file(path, ignore=(), complexity=-1):
+    """Checks a file using pep8 and pyflakes by default and mccabe 
+    optionally.
 
-    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)
+    :param str path: path to the file to be checked
+    :param tuple ignore: (optional), error and warning codes to be ignored
+    :param int complexity: (optional), enables the mccabe check for values > 0
+    """
+    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)
+def check_code(code, ignore=(), complexity=-1):
+    """Checks code using pep8 and pyflakes by default and mccabe optionally.
 
+    :param str code: code to be checked
+    :param tuple ignore: (optional), error and warning codes to be ignored
+    :param int complexity: (optional), enables the mccabe check for values > 0
+    """
+    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 += pep8style.input_file(path)
-    if complexity > -1:
-        warnings += mccabe.get_module_complexity(path, complexity)
-    return warnings
 
+class Flake8Command(setuptools.Command):
+    """The :class:`Flake8Command` class is used by setuptools to perform
+    checks on registered modules.
+    """
 
-def check_code(code, ignore=(), complexity=-1, reporter=None):
-    warnings = pyflakes.api.check(code, '<stdin>', reporter)
-    warnings += pep8style.input_file('-', lines=code.split('\n'))
-    if complexity > -1:
-        warnings += mccabe.get_code_complexity(code, complexity)
-    return warnings
+    description = "Run flake8 on modules registered in setuptools"
+    user_options = []
 
+    def initialize_options(self):
+        pass
 
-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)
+    def finalize_options(self):
+        pass
 
-    return sys.stdin.read()
+    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
 
-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)

flake8/mccabe.py

-""" 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:])
 """
 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
 
 
<