This commit is contained in:
Ian Cordasco 2013-02-22 23:18:15 -05:00
parent 50e3ce9c78
commit 257eae684e
12 changed files with 691 additions and 1 deletions

130
docs/Makefile Normal file
View file

@ -0,0 +1,130 @@
# 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."

34
docs/api.rst Normal file
View file

@ -0,0 +1,34 @@
.. 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

17
docs/buildout.rst Normal file
View file

@ -0,0 +1,17 @@
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

238
docs/conf.py Normal file
View file

@ -0,0 +1,238 @@
# -*- 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, 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.
# 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 = []

28
docs/config.rst Normal file
View file

@ -0,0 +1,28 @@
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 codes in the table below).

79
docs/index.rst Normal file
View file

@ -0,0 +1,79 @@
======
Flake8
======
Flake8 is a wrapper around these tools:
- PyFlakes
- pep8
- Ned Batchelder's McCabe script
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 contain this line are skipped::
# flake8: noqa
- 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: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 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 complexity of a function is higher than the value. By default it's
deactivated::
$ 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: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.
See https://en.wikipedia.org/wiki/Cyclomatic_complexity.
Documentation
=============
.. toctree::
api
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

21
docs/setuptools.rst Normal file
View file

@ -0,0 +1,21 @@
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

56
docs/vcs.rst Normal file
View file

@ -0,0 +1,56 @@
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.

49
docs/warnings.rst Normal file
View file

@ -0,0 +1,49 @@
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 |
+------+--------------------------------------------------------------------+

View file

@ -32,6 +32,9 @@ def _register_extensions():
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))
@ -67,7 +70,8 @@ class StyleGuide(pep8.StyleGuide):
def get_style_guide(**kwargs):
"""Parse the options and configure the checker."""
"""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

View file

@ -13,6 +13,18 @@ from flake8.main import DEFAULT_CONFIG
def git_hook(complexity=-1, strict=False, ignore=None, lazy=False):
"""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 ', '')
@ -30,6 +42,11 @@ def git_hook(complexity=-1, strict=False, ignore=None, lazy=False):
def hg_hook(ui, repo, **kwargs):
"""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)

View file

@ -42,18 +42,35 @@ def main():
def check_file(path, ignore=(), complexity=-1):
"""Checks a file using pep8 and pyflakes by default and mccabe
optionally.
: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)
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())
class Flake8Command(setuptools.Command):
"""The :class:`Flake8Command` class is used by setuptools to perform
checks on registered modules.
"""
description = "Run flake8 on modules registered in setuptools"
user_options = []