B
    NPïY¾C ã               @   s  d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZ ddlmZ yddlmZ ddlmZ W n  ek
r¤   ddlmZ Y nX dZd	Zd
Zy<ejdkrÌej d¡Zn ej e d¡pæej d¡d¡ZW n ek
r   dZY nX dZej ej e¡d¡Z dZ!dddœZ"dZ#e$dddgƒZ%e$ej&dg ƒe% Z'e$dddddgƒZ(e$ddd d!ddgƒZ)e) *d"d#d$d%dd&g¡Z+e$d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:gƒZ,e$d;ƒZ-e$e	j.e	j/gƒZ/e/ *e	j0e	j1g¡Z2e2 *e	j3e	j4g¡Z5d<d=d>d?gZ6e 7d@¡Z8e 7dA¡Z9e 7dB¡Z:e 7dC¡Z;e 7dD¡Z<e 7dE¡Z=e 7dF¡Z>e 7dG¡Z?e 7dH¡Z@e 7dI¡ZAe 7dJd$ e'¡ ¡ZBe 7dK¡ZCe 7dL¡ZDe 7dM¡ZEe	 FdNgjG¡ Hd¡dO dNkZIdPdQ„ ZJdRdS„ ZKdTdU„ ZLdVdW„ ZMdXdY„ ZNdZd[„ ZOd\d]„ ZPd^d_„ ZQd`da„ ZRdbdc„ ZSddde„ ZTdfdg„ ZUdhdi„ ZVdjdk„ ZWdldm„ ZXdndo„ ZYdpdq„ ZZdrds„ Z[dtdu„ Z\dvdw„ Z]dxdy„ Z^dzd{„ Z_d|d}„ Z`d~d„ Zad€d„ Zbd‚dƒ„ Zcd„d…„ Zdd†d‡„ Zedˆd‰„ ZfejgdŠk rÐd‹dŒ„ Zhe 7d¡jiZjejkjlZmndŽdŒ„ ZhenjjZjdd„ Zme 7d‘ejo¡jpZqd’d“„ Zrd”d•„ ZsdÁd—d˜„Ztejufd™dš„ZvdÂdœd„ZwdždŸ„ ZxeIrBexfd dŸ„Zxi i i d¡œZyd¢d£„ ZzdÃd¤d¥„Z{d¦d§„ Z|e|ƒ  G d¨d©„ d©e}ƒZ~G dªd«„ d«e}ƒZG d¬d­„ d­eƒZ€G d®d¯„ d¯eƒZG d°d±„ d±eƒZ‚G d²d³„ d³e}ƒZƒdefd´dµ„Z„d¶d·„ Z…dÄd¹dº„Z†dÅd¼d½„Z‡d¾d¿„ Zˆe‰dÀkreˆƒ  dS )Æa~  
Check Python source code formatting, according to PEP 8.

For usage and a list of options, try this:
$ python pep8.py -h

This program and its regression test suite live here:
https://github.com/pycqa/pep8

Groups of errors and warnings:
E errors
W warnings
100 indentation
200 whitespace
300 blank lines
400 imports
500 line length
600 deprecation
700 statements
900 syntax error
é    )Úwith_statementN)ÚOptionParser)Úfnmatch)ÚRawConfigParser)ÚTextIOWrapperz1.7.1z'.svn,CVS,.bzr,.hg,.git,__pycache__,.toxzE121,E123,E126,E226,E24,E704Zwin32z~\.pep8ZXDG_CONFIG_HOMEz	~/.configZpep8)z	setup.cfgztox.iniz.pep8Ú	testsuiteéO   z+%(path)s:%(row)d:%(col)d: %(code)s %(text)sz%%(path)s:%(row)d: [%(code)s] %(text)s)ÚdefaultZpylinti   ÚFalseÚNoneÚTrueÚprintz>>z**Ú*ú+ú-ú/z//ú^ú&ú|z<<ú%z**=z*=z/=z//=z+=z-=z!=z<>ú<ú>z%=z^=z&=z|=z==z<=z>=z<<=z>>=ú=z 	ÚdirectoriesÚfileszlogical lineszphysical linesz([ \t]*)zraise\s+\w+\s*,zraise\s+\w+\s*,.*,\s*\w+\s*$z\b[A-Z]\d{3}\bz	u?r?["\']z[[({] | []}),;:]z[,;:]\s*(?:  |\t)z?(\bNone|\bFalse|\bTrue)?\s*([=!]=)\s*(?(1)|(None|False|True))\bz!\b(not)\s+[^][)(}{ ]+\s+(in|is)\szE(?:[=!]=|is(?:\s+not)?)\s*type(?:s.\w+Type|\s*\(\s*([^)]*[^ )])\s*\))z(\s*)\b(?:%s)\b(\s*)z'(?:[^,\s])(\s*)(?:[-+*/|!<=>%&^]+)(\s*)z
\blambda\bz*^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@.*$z#
é   c             C   s:   t  | ¡ d¡}x$t|ƒD ]\}}||kr|dfS qW dS )aI  Never mix tabs and spaces.

    The most popular way of indenting Python is with spaces only.  The
    second-most popular way is with tabs only.  Code indented with a mixture
    of tabs and spaces should be converted to using spaces exclusively.  When
    invoking the Python command line interpreter with the -t option, it issues
    warnings about code that illegally mixes tabs and spaces.  When using -tt
    these warnings become errors.  These options are highly recommended!

    Okay: if a == 0:\n        a = 1\n        b = 1
    E101: if a == 0:\n        a = 1\n\tb = 1
    r   z/E101 indentation contains mixed spaces and tabsN)ÚINDENT_REGEXÚmatchÚgroupÚ	enumerate)Úphysical_lineÚindent_charÚindentÚoffsetÚchar© r%   ú#lib/python3.7/site-packages/pep8.pyÚtabs_or_spaces„   s    r'   c             C   s*   t  | ¡ d¡}d|kr&| d¡dfS dS )zƒFor new projects, spaces-only are strongly recommended over tabs.

    Okay: if True:\n    return
    W191: if True:\n\treturn
    r   ú	zW191 indentation contains tabsN)r   r   r   Úindex)r    r"   r%   r%   r&   Útabs_obsolete—   s    r*   c             C   sH   |   d¡} |   d¡} |   d¡} |   d¡}| |krD|r@t|ƒdfS dS dS )a  Trailing whitespace is superfluous.

    The warning returned varies on whether the line itself is blank, for easier
    filtering for those who want to indent their blank lines.

    Okay: spam(1)\n#
    W291: spam(1) \n#
    W293: class Foo(object):\n    \n    bang = 12
    Ú
úúz 	zW291 trailing whitespace)r   z#W293 blank line contains whitespaceN)ÚrstripÚlen)r    Ústrippedr%   r%   r&   Útrailing_whitespace¢   s    




r1   c             C   s0   ||kr,|   ¡ }|sdS || kr,t| ƒdfS dS )z—Trailing blank lines are superfluous.

    Okay: spam(1)
    W391: spam(1)\n

    However the last line should end with a new line (warning W292).
    )r   zW391 blank line at end of filezW292 no newline at end of fileN)r.   r/   )r    ÚlinesÚline_numberÚtotal_linesZstripped_last_liner%   r%   r&   Útrailing_blank_lines·   s    r5   c             C   s¾   |   ¡ }t|ƒ}||krºt|ƒsº| ¡ }t|ƒdkr8|sPt|ƒdkrp|d dkrpt|ƒt|d ƒ |d k rpdS t|dƒr¢yt| d	¡ƒ}W n tk
r    Y nX ||krº|d
||f fS dS )aô  Limit all lines to a maximum of 79 characters.

    There are still many devices around that are limited to 80 character
    lines; plus, limiting windows to 80 characters makes it possible to have
    several windows side-by-side.  The default wrapping on such devices looks
    ugly.  Therefore, please limit all lines to a maximum of 79 characters.
    For flowing long blocks of text (docstrings or comments), limiting the
    length to 72 characters is recommended.

    Reports error E501.
    r   é   r   ú#éÿÿÿÿé   NÚdecodezutf-8z'E501 line too long (%d > %d characters))r.   r/   ÚnoqaÚsplitÚhasattrr:   ÚUnicodeError)r    Úmax_line_lengthÚ	multilineÚlineÚlengthZchunksr%   r%   r&   Úmaximum_line_lengthÇ   s     
rC   c             c   s   |dk r|sdS |  d¡r&|rŒdV  nf|dks:|rJ|dkrJdd| fV  nB|   d¡rŒ|rv|sŒ||k sŒt |¡sŒd	V  n|dkrŒdd
| fV  dS )a"  Separate top-level function and class definitions with two blank lines.

    Method definitions inside a class are separated by a single blank line.

    Extra blank lines may be used (sparingly) to separate groups of related
    functions.  Blank lines may be omitted between a bunch of related
    one-liners (e.g. a set of dummy implementations).

    Use blank lines in functions, sparingly, to indicate logical sections.

    Okay: def a():\n    pass\n\n\ndef b():\n    pass
    Okay: def a():\n    pass\n\n\n# Foo\n# Bar\n\ndef b():\n    pass

    E301: class Foo:\n    b = 0\n    def bar():\n        pass
    E302: def a():\n    pass\n\ndef b(n):\n    pass
    E303: def a():\n    pass\n\n\n\ndef b(n):\n    pass
    E303: def a():\n\n\n\n    pass
    E304: @decorator\n\ndef a():\n    pass
    é   Nú@)r   z/E304 blank lines found after function decoratorr6   r   zE303 too many blank lines (%d))zdef zclass rE   )r   z#E301 expected 1 blank line, found 0z%E302 expected 2 blank lines, found %d)Ú
startswithÚDOCSTRING_REGEXr   )Úlogical_lineÚblank_linesÚindent_levelr3   Úblank_beforeÚprevious_logicalÚprevious_indent_levelr%   r%   r&   rI   í   s    


rI   c             c   s†   | }x|t  |¡D ]n}| ¡ }| ¡ }| ¡ }||d krL|d d| fV  q||d  dkr|dkrhdnd}|d||f fV  qW d	S )
aH  Avoid extraneous whitespace.

    Avoid extraneous whitespace in these situations:
    - Immediately inside parentheses, brackets or braces.
    - Immediately before a comma, semicolon, or colon.

    Okay: spam(ham[1], {eggs: 2})
    E201: spam( ham[1], {eggs: 2})
    E201: spam(ham[ 1], {eggs: 2})
    E201: spam(ham[1], { eggs: 2})
    E202: spam(ham[1], {eggs: 2} )
    E202: spam(ham[1 ], {eggs: 2})
    E202: spam(ham[1], {eggs: 2 })

    E203: if x == 4: print x, y; x, y = y , x
    E203: if x == 4: print x, y ; x, y = y, x
    E203: if x == 4 : print x, y; x, y = y, x
    ú r   zE201 whitespace after '%s'ú,z}])ZE202ZE203z%s whitespace before '%s'N)ÚEXTRANEOUS_WHITESPACE_REGEXÚfinditerr   ÚstripÚstart)rH   rA   r   Útextr$   ÚfoundÚcoder%   r%   r&   Úextraneous_whitespace  s    rW   c             c   s   xŠt  | ¡D ]|}| ¡ \}}d|kr6| d¡dfV  nt|ƒdkrR| d¡dfV  d|krl| d¡dfV  qt|ƒdkr| d¡dfV  qW dS )	z³Avoid extraneous whitespace around keywords.

    Okay: True and False
    E271: True and  False
    E272: True  and False
    E273: True and\tFalse
    E274: True\tand False
    r(   r   zE274 tab before keywordz#E272 multiple spaces before keywordr6   zE273 tab after keywordz"E271 multiple spaces after keywordN)ÚKEYWORD_REGEXrQ   ÚgroupsrS   r/   )rH   r   ÚbeforeÚafterr%   r%   r&   Úwhitespace_around_keywords2  s    	r\   c             c   s¨   | }xžt t|ƒd ƒD ]Š}|| }|dkr||d  tkr|d|… }|dkrx| d¡| d¡krx| d¡| d¡k rxq|dkr’||d  d	kr’q|d
| fV  qW dS )zëEach comma, semicolon or colon should be followed by whitespace.

    Okay: [a, b]
    Okay: (3,)
    Okay: a[1:4]
    Okay: a[:4]
    Okay: a[1:]
    Okay: a[1:4:2]
    E231: ['a','b']
    E231: foo(bar,baz)
    E231: [{'a':'b'}]
    r   z,;:Nú:ú[ú]Ú{rO   ú)z"E231 missing whitespace after '%s')Úranger/   Ú
WHITESPACEÚcountÚrfind)rH   rA   r)   r$   rZ   r%   r%   r&   Úmissing_whitespaceI  s    rf   c             c   sŠ   | rdnd}| rdnd}|d r6d|d| df fV  |  d¡}|rd||krdd|d	| d
f fV  n"|s†||kr†d|d| df fV  dS )aª  Use 4 spaces per indentation level.

    For really old code that you don't want to mess up, you can continue to
    use 8-space tabs.

    Okay: a = 1
    Okay: if a == 0:\n    a = 1
    E111:   a = 1
    E114:   # a = 1

    Okay: for item in items:\n    pass
    E112: for item in items:\npass
    E115: for item in items:\n# Hi\n    pass

    Okay: a = 1\nb = 2
    E113: a = 1\n    b = 2
    E116: a = 1\n    # b = 2
    r   rD   zE11%d %szE11%d %s (comment)é   r   z%indentation is not a multiple of fourr]   r6   zexpected an indented blockzunexpected indentationN)Úendswith)rH   rL   r!   rJ   rM   ÚcZtmplZindent_expectr%   r%   r&   Úindentationc  s    
rj   c       '      c   sô  |d d d }d|d d d  | }|s4|dkr8dS |   d¡}	d }
}|dkrVdnd	}dg| }dg| }dgg}dg}i }|d d }d}d
}|d g}|dkr¾td|d d  ¡  ƒ xä|D ]Ú\}}}}}|
|d | k }|r|d | }
| o|tk}|r |}|dkr,td| ¡  ƒ t|ƒ| ||
< |tjkoN|dk}x6t|| ƒD ]&}||
 ||  }||k}|r^P q^W || rž||| k}| o¼|dko¼| |d ¡}|rî|| rî|d || kr |dfV  n|r|s|r |dfV  nô|| r>|d || k r>|dk	r |dfV  nÂ|sX|	rx||
 dkrx|rn|sn|dfV  |||< nˆ|dkr|d ||< np||t	fkr n`|dkr°d} nB|| rÀd} n2|sÖ|| rÖd} n|||< |dkrîd} nd} |d|  fV  ||
 r^|tj
tjfkr^|| s^|d ||< d||d < |dkrätd||d f ƒ n†|tjtjfksz|dkrˆt	||d < n\|s¶|
s¶|s¶|dkr¶d||d d < n.|dkrä||d d…  ¡ rä||  |
¡ |tjkrz|dkrr|d7 }| d¡ | d¡ t|ƒ|kr.| g ¡ ||  |
¡ ||
  d7  < |dkrJtd ||d || f ƒ nØ|d!krJ|dkrJ| ¡ p–|d }!| ¡  x(t|ƒD ]}"||" |!krªd||"< qªW x"t|ƒD ]}#|#|!krÔ||#= qÔW ||d d…= |d8 }|rd||| < x2t|
ddƒD ]"}$||$ r$||$  d8  < P q$W t|ƒ|d ks`t‚|d |krz|||d < |d |d k}|rÆ||
 ||d | < qÆW |	rðt|ƒ|d krð|d |d d f}%|rÞd"}&nd#}&|%d$|& fV  dS )%a2  Continuation lines indentation.

    Continuation lines should align wrapped elements either vertically
    using Python's implicit line joining inside parentheses, brackets
    and braces, or using a hanging indent.

    When using a hanging indent these considerations should be applied:
    - there should be no arguments on the first line, and
    - further indentation should be used to clearly distinguish itself as a
      continuation line.

    Okay: a = (\n)
    E123: a = (\n    )

    Okay: a = (\n    42)
    E121: a = (\n   42)
    E122: a = (\n42)
    E123: a = (\n    42\n    )
    E124: a = (24,\n     42\n)
    E125: if (\n    b):\n    pass
    E126: a = (\n        42)
    E127: a = (24,\n      42)
    E128: a = (24,\n    42)
    E129: if (a or\n    b):\n    pass
    E131: a = (\n    42\n 24)
    r   r6   r   r8   Nr]   r(   )rg   )rg   é   FrD   z>>> rg   z... z]})z6E124 closing bracket does not match visual indentationz+E133 closing bracket is missing indentationTz7E128 continuation line under-indented for visual indentrk   zIE123 closing bracket does not match indentation of opening bracket's line)ZE122z missing indentation or outdented)ZE127zover-indented for visual indent)ZE131zunaligned for hanging indent)ZE126z over-indented for hanging indent)ZE121z!under-indented for hanging indentz%s continuation line %szbracket depth %s indent to %s)ÚuZurÚbÚbrÚifz([{z.bracket depth %s seen, col %s, visual min = %sz)]}zE129 visually indented linezE125 continuation linez(%s with same indent as next logical line)rh   r   r.   ÚNEWLINEÚexpand_indentÚtokenizeÚOPÚreversedÚgetÚstrÚNLÚCOMMENTÚSTRINGÚisspaceÚappendr/   Úpoprb   ÚlistÚAssertionError)'rH   ÚtokensrJ   Úhang_closingr!   r;   ÚverboseZ	first_rowÚnrowsZindent_nextÚrowZdepthZvalid_hangsÚparensZ
rel_indentZ	open_rowsZhangsZindent_chancesZlast_indentZvisual_indentZlast_token_multiliner"   Ú
token_typerT   rS   ÚendrA   ÚnewlineZclose_bracketZopen_rowZhangZhanging_indentÚerrorZprev_indentÚdZindÚidxÚposrV   r%   r%   r&   Úcontinued_indentation‚  sò    
















 






rŒ   c             c   s¬   |d \}}}}}x”t dt|ƒƒD ]‚}|| \}}}	}
}|tjkr˜|dkr˜|	|kr˜|tjksd|dkr˜|dk s€||d  d dkr˜t |¡s˜|d| fV  |}|}|
}q"W dS )	a”  Avoid extraneous whitespace.

    Avoid extraneous whitespace in the following situations:
    - before the open parenthesis that starts the argument list of a
      function call.
    - before the open parenthesis that starts an indexing or slicing.

    Okay: spam(1)
    E211: spam (1)

    Okay: dict['key'] = list[index]
    E211: dict ['key'] = list[index]
    E211: dict['key'] = list [index]
    r   r   z([z}])r6   ÚclasszE211 whitespace before '%s'N)rb   r/   rr   rs   ÚNAMEÚkeywordÚ	iskeyword)rH   r   Ú	prev_typeÚ	prev_textÚ__Úprev_endr)   r…   rT   rS   r†   r%   r%   r&   Úwhitespace_before_parametersI  s    

r•   c             c   s   xŠt  | ¡D ]|}| ¡ \}}d|kr6| d¡dfV  nt|ƒdkrR| d¡dfV  d|krl| d¡dfV  qt|ƒdkr| d¡dfV  qW dS )	zžAvoid extraneous whitespace around an operator.

    Okay: a = 12 + 3
    E221: a = 4  + 5
    E222: a = 4 +  5
    E223: a = 4\t+ 5
    E224: a = 4 +\t5
    r(   r   zE223 tab before operatorz$E221 multiple spaces before operatorr6   zE224 tab after operatorz#E222 multiple spaces after operatorN)ÚOPERATOR_REGEXrQ   rY   rS   r/   )rH   r   rZ   r[   r%   r%   r&   Úwhitespace_around_operatori  s    	r—   c             c   sÌ  d}d}t j}d }}x®|D ]¤\}}}	}
}|tkr8q|dkrJ|d7 }n|dkrZ|d8 }|r
|	|krŒ|dk	r†|d s†|d dfV  d}n||d	krž|d
kržnj|dks®|d rº|dfV  nJ|dkrd\}}|dkrÞd\}}n|tkrîd\}}|d d||f fV  d}n®|t jkr¸|dk	r¸|dkr2|r2nP|tkrBd}n@|tkrt|t jkrd|dkr‚n
|tkr‚d}n|tkr‚d}|dkrš||	|kf}n|r¸|	|kr¸|dfV  d}|}|}|
}qW dS )aA  Surround operators with a single space on either side.

    - Always surround these binary operators with a single space on
      either side: assignment (=), augmented assignment (+=, -= etc.),
      comparisons (==, <, >, !=, <=, >=, in, not in, is, is not),
      Booleans (and, or, not).

    - If operators with different priorities are used, consider adding
      whitespace around the operators with the lowest priorities.

    Okay: i = i + 1
    Okay: submitted += 1
    Okay: x = x * 2 - 1
    Okay: hypot2 = x * x + y * y
    Okay: c = (a + b) * (a - b)
    Okay: foo(bar, key='word', *args, **kwargs)
    Okay: alpha[:-i]

    E225: i=i+1
    E225: submitted +=1
    E225: x = x /2 - 1
    E225: z = x **y
    E226: c = (a+b) * (a-b)
    E226: hypot2 = x*x + y*y
    E227: c = a|b
    E228: msg = fmt%(errno, errmsg)
    r   FN)ú(Úlambdar   ra   Tz'E225 missing whitespace around operatorr   )r   r   z**)ZE226Z
arithmeticr   )ZE228Zmodulo)ZE227zbitwise or shiftz(%s missing whitespace around %s operatorr   z}]))rr   rs   ÚSKIP_COMMENTSÚARITHMETIC_OPÚWS_NEEDED_OPERATORSÚUNARY_OPERATORSÚKEYWORDSÚWS_OPTIONAL_OPERATORS)rH   r   r„   Z
need_spacer‘   r’   r”   r…   rT   rS   r†   rA   rV   Zoptyper%   r%   r&   Ú"missing_whitespace_around_operator€  sb    








r    c             c   sb   | }xXt  |¡D ]J}| ¡ d }d| ¡ krD|d| ¡ d  fV  q|d| ¡ d  fV  qW dS )z¬Avoid extraneous whitespace after a comma or a colon.

    Note: these checks are disabled by default

    Okay: a = (1, 2)
    E241: a = (1,  2)
    E242: a = (1,\t2)
    r   r(   zE242 tab after '%s'r   zE241 multiple spaces after '%s'N)ÚWHITESPACE_AFTER_COMMA_REGEXrQ   rS   r   )rH   rA   ÚmrU   r%   r%   r&   Úwhitespace_around_commaÜ  s    	r£   c             c   sô   d}d}d}d}|   d¡}d}xÐ|D ]È\}}	}
}}|tjkr>q$|rXd}|
|krX||fV  |tjkrè|	dkrt|d7 }nl|	dkr†|d8 }nZ|r |	d	kr |dkr d
}n@|rº|	dkrº|dkrºd}n&|rà|	dkrà|sàd
}|
|krà||fV  |sèd}|}q$W dS )aã  Don't use spaces around the '=' sign in function arguments.

    Don't use spaces around the '=' sign when used to indicate a
    keyword argument or a default parameter value.

    Okay: def complex(real, imag=0.0):
    Okay: return magic(r=real, i=imag)
    Okay: boolean(a == b)
    Okay: boolean(a != b)
    Okay: boolean(a <= b)
    Okay: boolean(a >= b)
    Okay: def foo(arg: int = 42):

    E251: def complex(real, imag = 0.0):
    E251: return magic(r = real, i = imag)
    r   FNÚdefz8E251 unexpected spaces around keyword / parameter equalsr˜   r   ra   r]   TrO   r   )rF   rr   rw   rs   )rH   r   r„   Zno_spacer”   Zannotated_func_argZin_defÚmessager…   rT   rS   r†   rA   r%   r%   r&   Ú(whitespace_around_named_parameter_equalsî  s:    






r¦   c             c   s  d}x|D ]ú\}}}}}|t jkrø|d|d …  ¡ }|rj|d |d krj|d |d d k rj|dfV  | d¡\}	}
}|	dko–|	 d	¡dd… p–d	}|r¼|s°|dd… tkrö|d
fV  n:|rö|dksÔ|d dkrö|d	krè|dfV  n|rö|dfV  q|t jkr|}qW dS )a{  Separate inline comments by at least two spaces.

    An inline comment is a comment on the same line as a statement.  Inline
    comments should be separated by at least two spaces from the statement.
    They should start with a # and a single space.

    Each line of a block comment starts with a # and a single space
    (unless it is indented text inside the comment).

    Okay: x = x + 1  # Increment x
    Okay: x = x + 1    # Increment x
    Okay: # Block comment
    E261: x = x + 1 # Increment x
    E262: x = x + 1  #Increment x
    E262: x = x + 1  #  Increment x
    E265: #Block comment
    E266: ### Block comment
    )r   r   Nr   r   r6   z.E261 at least two spaces before inline commentrN   z#:r7   z*E262 inline comment should start with '# 'ú!z)E265 block comment should start with '# 'z+E266 too many leading '#' for block comment)rr   rx   rR   Ú	partitionÚlstriprc   rw   )rH   r   r”   r…   rT   rS   r†   rA   Zinline_commentZsymbolZspÚcommentZ
bad_prefixr%   r%   r&   Úwhitespace_before_comment  s(    
$
r«   c             c   s>   | }|  d¡r:| d¡}d|k r:d|d|… kr:|dfV  dS )a,  Imports should usually be on separate lines.

    Okay: import os\nimport sys
    E401: import sys, os

    Okay: from subprocess import Popen, PIPE
    Okay: from myclas import MyClass
    Okay: from foo.bar.yourclass import YourClass
    Okay: import myclass
    Okay: import foo.bar.yourclass
    zimport rO   r8   ú;Nz!E401 multiple imports on one line)rF   Úfind)rH   rA   rU   r%   r%   r&   Úimports_on_separate_linesH  s
    

r®   c             #   sž   dd„ }d}|rdS | sdS |r$dS | ‰ ˆ   d¡s<ˆ   d¡rP| dd¡ršd	V  nJt‡ fd
d„|D ƒƒrjdS |ˆ ƒr’| dd¡rˆd|d< qšd|d< nd|d< dS )a]  Imports are always put at the top of the file, just after any module
    comments and docstrings, and before module globals and constants.

    Okay: import os
    Okay: # this is a comment\nimport os
    Okay: '''this is a module docstring'''\nimport os
    Okay: r'''this is a module docstring'''\nimport os
    Okay: try:\n    import x\nexcept:\n    pass\nelse:\n    pass\nimport y
    Okay: try:\n    import x\nexcept:\n    pass\nfinally:\n    pass\nimport y
    E402: a=1\nimport os
    E402: 'One string'\n"Two string"\nimport os
    E402: a=1\nfrom sys import x

    Okay: if x:\n    import os
    c             S   sP   | d dkr| dd … } | r4| d dkr4| dd … } | oN| d dkpN| d dkS )Nr   ZuUbBr   ZrRú"ú'r%   )rA   r%   r%   r&   Úis_string_literall  s
    z8module_imports_on_top_of_file.<locals>.is_string_literal)ÚtryÚexceptÚelseÚfinallyNzimport zfrom Zseen_non_importsF)r   z+E402 module level import not at top of filec             3   s   | ]}ˆ   |¡V  qd S )N)rF   )Ú.0Úkw)rA   r%   r&   ú	<genexpr>  s    z0module_imports_on_top_of_file.<locals>.<genexpr>Zseen_docstringT)rF   ru   Úany)rH   rJ   Úchecker_stater;   r±   Zallowed_try_keywordsr%   )rA   r&   Úmodule_imports_on_top_of_file[  s&    

r»   c             c   sJ  | }t |ƒd }| d¡}xÞd|  k r0|k røn nÄ|d|… }| d¡| d¡kræ| d¡| d¡kræ| d	¡| d
¡kræt |¡}|rÊ|d| ¡ …  ¡ }|dd… dkrÈt|dd…  ¡ ƒrÈdV  P | 	d¡rÜdV  n
|dfV  | d|d ¡}qW | d¡}x@d|k rD||k r&|dfV  n
|dfV  | d|d ¡}qW dS )aš  Compound statements (on the same line) are generally discouraged.

    While sometimes it's okay to put an if/for/while with a small body
    on the same line, never do this for multi-clause statements.
    Also avoid folding such long lines!

    Always use a def statement instead of an assignment statement that
    binds a lambda expression directly to a name.

    Okay: if foo == 'blah':\n    do_blah_thing()
    Okay: do_one()
    Okay: do_two()
    Okay: do_three()

    E701: if foo == 'blah': do_blah_thing()
    E701: for x in lst: total += x
    E701: while t < 10: t = delay()
    E701: if foo == 'blah': do_blah_thing()
    E701: else: do_non_blah_thing()
    E701: try: something()
    E701: finally: cleanup()
    E701: if foo == 'blah': one(); two(); three()
    E702: do_one(); do_two(); do_three()
    E703: do_four();  # useless semicolon
    E704: def f(x): return 2*x
    E731: f = lambda x: 2*x
    r   r]   r8   Nr`   Ú}r^   r_   r˜   ra   r   )r   z1E731 do not assign a lambda expression, use a defzdef )r   z*E704 multiple statements on one line (def)z,E701 multiple statements on one line (colon)r¬   z0E702 multiple statements on one line (semicolon)z$E703 statement ends with a semicolon)
r/   r­   rd   ÚLAMBDA_REGEXÚsearchrS   r.   ÚisidentifierrR   rF   )rH   rA   Z	last_charrU   rZ   Z	lambda_kwr%   r%   r&   Úcompound_statements  s0    

$




rÀ   c             c   sà   d } }}d}d}xÆ|D ]¾\}}}	}
}|t jkr6d}|	d |krX|rX|rX|sX|dfV  |
d |kr¤| d¡ d¡r’|
d t| ¡ d ƒd	 f}nd}|
d  }}n|	d }|t jkr|d
krÈ|d	7 }q|dkr|d	8 }qW dS )a?  Avoid explicit line join between brackets.

    The preferred way of wrapping long lines is by using Python's implied line
    continuation inside parentheses, brackets and braces.  Long lines can be
    broken over multiple lines by wrapping expressions in parentheses.  These
    should be used in preference to using a backslash for line continuation.

    E502: aaa = [123, \\n       123]
    E502: aaa = ("bbb " \\n       "ccc")

    Okay: aaa = [123,\n       123]
    Okay: aaa = ("bbb "\n       "ccc")
    Okay: aaa = "bbb " \\n    "ccc"
    Okay: aaa = 123  # \\
    r   FNTz0E502 the backslash is redundant between bracketsz
ú\r8   r   z([{z)]})rr   rx   r.   rh   r/   Ú
splitlinesrs   )rH   r   Z
prev_startr”   r„   rª   Z	backslashr…   rT   rS   r†   rA   r%   r%   r&   Úexplicit_line_joinÆ  s&    



rÃ   c       
      c   s€   dd„ }d}d}xj|D ]b\}}}}}	|t jkr0qd|ks@d|krP|t jkrPd}q|||ƒrl|rl|sl|dfV  |dk}d}qW d	S )
a™  
    Avoid breaks before binary operators.

    The preferred place to break around a binary operator is after the
    operator, not before it.

    W503: (width == 0\n + height == 0)
    W503: (width == 0\n and height == 0)

    Okay: (width == 0 +\n height == 0)
    Okay: foo(\n    -x)
    Okay: foo(x\n    [])
    Okay: x = '''\n''' + ''
    Okay: foo(x,\n    -y)
    Okay: foo(x,  # comment\n    -y)
    c             S   s   | t jks|dko|dkS )N)ÚandÚorz()[]{},:.;@=%)rr   rs   )r…   rT   r%   r%   r&   Úis_binary_operatorþ  s    z8break_around_binary_operator.<locals>.is_binary_operatorFTr+   r,   z&W503 line break before binary operatorz([{,;N)rr   rx   ry   )
rH   r   rÆ   Z
line_breakZunary_contextr…   rT   rS   r†   rA   r%   r%   r&   Úbreak_around_binary_operatorí  s    

rÇ   c             c   s¨   | ot  | ¡}|r¤| d¡p&| d¡}| d¡dk}d|r@dnd|  }|dkrXd	}n2d
}|dkrh|pt|dkot| }|d|r‚dnd 7 }| d¡d|||f fV  dS )aX  Comparison to singletons should use "is" or "is not".

    Comparisons to singletons like None should always be done
    with "is" or "is not", never the equality operators.

    Okay: if arg is not None:
    E711: if arg != None:
    E711: if None == arg:
    E712: if arg == True:
    E712: if False == arg:

    Also, beware of writing if x when you really mean if x is not None --
    e.g. when testing whether a variable or argument that defaults to None was
    set to some other value.  The other value might have a type (such as a
    container) that could be false in a boolean context!
    r   rD   r6   z==z'if cond is %s:'Ú znot )r   ZE711ZE712r   r
   z or 'if %scond:'z %s comparison to %s should be %sN)ÚCOMPARE_SINGLETON_REGEXr¾   r   rS   )rH   r;   r   Z	singletonZsameÚmsgrV   Znonzeror%   r%   r&   Úcomparison_to_singleton  s    
rË   c             c   s@   t  | ¡}|r<| d¡}| d¡dkr2|dfV  n
|dfV  dS )aG  Negative comparison should be done using "not in" and "is not".

    Okay: if x not in y:\n    pass
    Okay: assert (X in Y or X is Z)
    Okay: if not (X in Y):\n    pass
    Okay: zz = x is not y
    E713: Z = not X in Y
    E713: if not X.B in Y:\n    pass
    E714: if not X is Y:\n    pass
    E714: Z = not X.B is Y
    r   r6   Úinz+E713 test for membership should be 'not in'z0E714 test for object identity should be 'is not'N)ÚCOMPARE_NEGATIVE_REGEXr¾   rS   r   )rH   r   r‹   r%   r%   r&   Úcomparison_negative6  s    

rÎ   c             c   sF   t  | ¡}|rB|sB| d¡}|r4t|ƒr4|tkr4dS | ¡ dfV  dS )a²  Object type comparisons should always use isinstance().

    Do not compare types directly.

    Okay: if isinstance(obj, int):
    E721: if type(obj) is type(1):

    When checking if an object is a string, keep in mind that it might be a
    unicode string too! In Python 2.3, str and unicode have a common base
    class, basestring, so you can do:

    Okay: if isinstance(obj, basestring):
    Okay: if type(a1) is type(b1):
    r   Nz-E721 do not compare types, use 'isinstance()')ÚCOMPARE_TYPE_REGEXr¾   r   r¿   Ú
SINGLETONSrS   )rH   r;   r   Zinstr%   r%   r&   Úcomparison_typeK  s    

rÑ   c             c   s$   |   d¡}|dkr |s |dfV  dS )zžThe {}.has_key() method is removed in Python 3: use the 'in' operator.

    Okay: if "alph" in d:\n    print d["alph"]
    W601: assert d.has_key('alph')
    z	.has_key(r8   z'W601 .has_key() is deprecated, use 'in'N)r­   )rH   r;   r‹   r%   r%   r&   Úpython_3000_has_keyb  s    
rÒ   c             c   s.   t  | ¡}|r*t | ¡s*| ¡ d dfV  dS )z»When raising an exception, use "raise ValueError('message')".

    The older form is removed in Python 3.

    Okay: raise DummyError("Message")
    W602: raise DummyError, "Message"
    r   z)W602 deprecated form of raising exceptionN)ÚRAISE_COMMA_REGEXr   ÚRERAISE_COMMA_REGEXr†   )rH   r   r%   r%   r&   Úpython_3000_raise_commam  s    
rÕ   c             c   s    |   d¡}|dkr|dfV  dS )zNew code should always use != instead of <>.

    The older syntax is removed in Python 3.

    Okay: if a != 'no':
    W603: if a <> 'no':
    z<>r8   z!W603 '<>' is deprecated, use '!='N)r­   )rH   r‹   r%   r%   r&   Úpython_3000_not_equalz  s    
rÖ   c             c   s    |   d¡}|dkr|dfV  dS )zpBackticks are removed in Python 3: use repr() instead.

    Okay: val = repr(1 + 2)
    W604: val = `1 + 2`
    ú`r8   z+W604 backticks are deprecated, use 'repr()'N)r­   )rH   r‹   r%   r%   r&   Úpython_3000_backticks‡  s    
rØ   )rD   c          	   C   s   t | dƒ
}| ¡ S Q R X dS )zRead the source code.ZrUN)ÚopenÚ	readlines)ÚfilenameÚfr%   r%   r&   rÚ   ™  s    rÚ   z[a-zA-Z_]\w*$c                sŠ   yNt | dƒ:}t |j¡\‰ }t|ˆ dd}‡ fdd„|D ƒ| ¡  S Q R X W n6 tttfk
r„   t | dd
}| ¡ S Q R X Y nX dS )	zRead the source code.ÚrbT)Úline_bufferingc                s   g | ]}|  ˆ ¡‘qS r%   )r:   )r¶   Úl)Úcodingr%   r&   ú
<listcomp>§  s    zreadlines.<locals>.<listcomp>Nzlatin-1)Úencoding)	rÙ   rr   Údetect_encodingÚreadliner   rÚ   ÚLookupErrorÚSyntaxErrorr>   )rÛ   rÜ   r2   r%   )rà   r&   rÚ   ¡  s    $c               C   s   t tjjdd ¡ S )NÚignore)Úerrors)r   ÚsysÚstdinÚbufferÚreadr%   r%   r%   r&   Ústdin_get_value®  s    rí   z# no(?:qa|pep8)\bc             C   s`   d| krt | ƒt |  ¡ ƒ S d}x:| D ]2}|dkrD|d d d }q&|dkrV|d7 }q&P q&W |S )zóReturn the amount of indentation.

    Tabs are expanded to the next multiple of 8.

    >>> expand_indent('    ')
    4
    >>> expand_indent('\t')
    8
    >>> expand_indent('       \t')
    8
    >>> expand_indent('        \t')
    16
    r(   r   rk   rN   r   )r/   r©   )rA   Úresultr$   r%   r%   r&   rq   ³  s    

rq   c             C   sb   |   | d ¡d }t| ƒd }| dd… dkr>|d7 }|d8 }| d|… d||   | |d…  S )zÂReplace contents with 'xxx' to prevent syntax matching.

    >>> mute_string('"abc"')
    '"xxx"'
    >>> mute_string("'''abc'''")
    "'''xxx'''"
    >>> mute_string("r'abc'")
    "r'xxx'"
    r8   r   éýÿÿÿN)z"""z'''r6   Úx)r)   r/   )rT   rS   r†   r%   r%   r&   Úmute_stringÎ  s    rñ   Ú.c       	         sð   i }d }}xÆ|   ¡ D ]º}|r8|dd… dkr|d8 }q|dd… dkr‚t |¡}dd„ | ¡ D ƒ\}}||  t||| ƒ¡ q|dd… dkr|d	d…  d
d¡d }|dd… dkrÆ|dd… }tƒ ||< qW t‡ ‡fdd„| 	¡ D ƒƒS )z&Return a dictionary of matching lines.Nr   r   rD   z@@ c             S   s   g | ]}t |pd ƒ‘qS )Ú1)Úint)r¶   Úgr%   r%   r&   rá   ï  s    zparse_udiff.<locals>.<listcomp>z+++rg   r(   r   r6   zb/c                s0   g | ](\}}|rt |ˆƒrtj ˆ |¡|f‘qS r%   )Úfilename_matchÚosÚpathÚjoin)r¶   rø   Zrows)ÚparentÚpatternsr%   r&   rá   ö  s   )
rÂ   Ú
HUNK_REGEXr   rY   Úupdaterb   r<   ÚsetÚdictÚitems)	Údiffrû   rú   Úrvrø   r‚   rA   Z
hunk_matchrƒ   r%   )rú   rû   r&   Úparse_udiffâ  s$    
r  c             C   sh   | sg S t | tƒr| S g }xH|  d¡D ]:}| ¡ }d|krPtj tj ||¡¡}| | 	d¡¡ q&W |S )zQParse a comma-separated list of paths.

    Return a list of absolute paths.
    rO   r   )
Ú
isinstancer}   r<   rR   r÷   rø   Úabspathrù   r{   r.   )Úvaluerú   Úpathsrø   r%   r%   r&   Únormalize_pathsû  s    
r  Tc                s   |s|S t ‡ fdd„|D ƒƒS )z{Check if patterns contains a pattern that matches filename.

    If patterns is unspecified, this always returns True.
    c             3   s   | ]}t ˆ |ƒV  qd S )N)r   )r¶   Úpattern)rÛ   r%   r&   r¸     s    z!filename_match.<locals>.<genexpr>)r¹   )rÛ   rû   r	   r%   )rÛ   r&   rö     s    rö   c             C   s,   | d t kp*| d | d d d …  ¡ dkS )Nr   rg   rD   r   z\
)rp   r©   )Útokenr%   r%   r&   Ú_is_eol_token  s    r  c             C   s&   || ƒp$| d t jko$| d | d kS )Nr   r   rg   )rr   rx   )r
  Z
_eol_tokenr%   r%   r&   r    s    )r    rH   Útreec             C   s6   t jdkr$dd„ t | ¡j ¡ D ƒS t | ¡d S d S )N)rD   rD   c             S   s   g | ]}|j |jkr|j‘qS r%   )ÚkindZPOSITIONAL_OR_KEYWORDÚname)r¶   Z	parameterr%   r%   r&   rá   (  s   z#_get_parameters.<locals>.<listcomp>r   )ré   Úversion_infoÚinspectZ	signatureZ
parametersÚvaluesZ
getargspec)Úfunctionr%   r%   r&   Ú_get_parameters&  s    
r  c             C   sŒ   dd„ }t  | ¡rVt| ƒ}|rˆ|d dkrˆ|dkrBt | jp>d¡}|| |d ||ƒ n2t  | ¡rˆt| jƒdd… dd	gkrˆ|| d	|dƒ dS )
zRegister a new check object.c             S   sB   | t | kr(t | |  d  |p"g ¡ n|p0dg|ft | | < d S )Nr   rÈ   )Ú_checksÚextend)Úcheckr  ÚcodesÚargsr%   r%   r&   Ú
_add_check2  s    z"register_check.<locals>._add_checkr   )r    rH   NrÈ   r6   Úselfr  )r  Ú
isfunctionr  ÚERRORCODE_REGEXÚfindallÚ__doc__ZisclassÚ__init__)r  r  r  r  r%   r%   r&   Úregister_check0  s    

r   c              C   s2   t  t¡} x"t  | t j¡D ]\}}t|ƒ qW dS )zwRegister all globally visible functions.

    The first argument name is either 'physical_line' or 'logical_line'.
    N)r  Z	getmoduler   Z
getmembersr  )Úmodr  r  r%   r%   r&   Úinit_checks_registryB  s    
r"  c               @   st   e Zd ZdZddd„Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zddd„ZdS )ÚCheckerz;Load a Python source file, tokenize it, check coding style.Nc       	      K   sŽ  |d krt |ƒj}n|rt‚d | _|j| _|j| _|j| _	|j
| _
d| _|j| _|j| _|| _i | _|d kr~d| _|pxg | _n||dkrœd| _tƒ  d¡| _n^|d krôyt|ƒ| _W qú tk
rð   t ¡ d d… \}}d|j|f | _g | _Y qúX n|| _| jrrt| jd d ƒ}|dkrr|d	krB| jd d
d … | jd< n0| jd d d… dkrr| jd dd … | jd< |p||j| _| jj| _d S )NFrê   r   Tr6   z%s: %sr   )éï   iÿþ  iÿþ  r   rD   u   Ã¯Â»Â¿)Ú
StyleGuideÚoptionsr~   Ú	_io_errorÚphysical_checksÚ_physical_checksÚlogical_checksÚ_logical_checksÚ
ast_checksÚ_ast_checksr?   r@   r€   r   rÛ   Ú_checker_statesr2   rí   rÂ   rÚ   ÚIOErrorré   Úexc_infoÚ__name__ÚordÚreportrˆ   Úreport_error)	r  rÛ   r2   r&  r3  ÚkwargsÚexc_typeÚexcZord0r%   r%   r&   r  P  sH    

zChecker.__init__c             C   s|   t  ¡ dd… \}}t|jƒdkrF|jd }t|ƒdkrJ|dd… }nd}|  |d |d p^dd|j|jd f | j¡ dS )zCheck if the syntax is valid.Nr6   r   rD   )r   r   r   zE901 %s: %s)ré   r0  r/   r  r4  r1  Úreport_invalid_syntax)r  r6  r7  r#   r%   r%   r&   r8  z  s    
zChecker.report_invalid_syntaxc             C   sR   | j | jkrdS | j| j  }|  j d7  _ | jdkrN|dd… tkrN|d | _|S )z(Get the next line from the input buffer.rÈ   r   Nr   )r3   r4   r2   r!   rc   )r  rA   r%   r%   r&   rä   ‡  s    
zChecker.readlinec             C   s*   g }x|D ]}|  t| |ƒ¡ q
W ||Ž S )zRun a check plugin.)r{   Úgetattr)r  r  Úargument_namesZ	argumentsr  r%   r%   r&   Ú	run_check‘  s    
zChecker.run_checkc             C   s   d|kr| j  |i ¡| _dS )z9 Prepares a custom state for the specific checker plugin.rº   N)r.  Ú
setdefaultrº   )r  r  r:  r%   r%   r&   Úinit_checker_state˜  s    zChecker.init_checker_statec             C   st   || _ xh| jD ]^\}}}|  ||¡ |  ||¡}|dk	r|\}}|  | j|||¡ |dd… dkr|d | _qW dS )z,Run all physical checks on a raw input line.Nrg   ZE101r   )r    r)  r=  r;  r4  r3   r!   )r  rA   r  r  r:  rî   r#   rT   r%   r%   r&   Úcheck_physical  s    zChecker.check_physicalc             C   s(  g }g }d}d } }}xè| j D ]Þ\}}}	}
}|tkr8q |sFd|	fg}|tjkr\| |¡ q |tjkrnt|ƒ}|rÒ|	\}}||krº| j|d  |d  }|dks°|dkrÒ|dkrÒd| }n||krÒ|||… | }| |¡ |t|ƒ7 }| ||
f¡ |
\}}q W d 	|¡| _
|o td 	|¡ƒ| _|S )	z!Build a logical line from tokens.r   Nr   rO   z{[(z}])rN   rÈ   )r   ÚSKIP_TOKENSrr   rx   r{   ry   rñ   r2   r/   rù   rH   r;   )r  ZlogicalZcommentsrB   Úprev_rowÚprev_colÚmappingr…   rT   rS   r†   rA   Ú	start_rowÚ	start_colr’   r%   r%   r&   Úbuild_tokens_line©  s<    





zChecker.build_tokens_linec             C   sT  | j  ¡  |  ¡ }|sdS |d d \}}| j|d  }t|d|… ƒ| _| j| jk r^| j| _| jdkr~t	| j
dd…  ¡ ƒ x¬| jD ]¢\}}}| jdkr¦t	d| ƒ |  ||¡ xt|  ||¡pÂdD ]`\}}	t|tƒsx|D ]\}
}||
krÞP qÞW |d |d | |
 f}|  |d |d |	|¡ qÄW q†W | j
rD| j| _| j
| _d| _g | _dS )	z:Build a line from tokens and run all logical checks on it.Nr   r   r6   éP   rg   z   r%   )r3  Úincrement_logical_linerE  r2   rq   rJ   rK   rI   r   r   rH   r.   r+  r=  r;  r  Útupler4  rM   rL   r   )r  rB  rC  rD  Z
start_liner  r  r:  r#   rT   Ztoken_offsetr‹   r%   r%   r&   Úcheck_logicalÊ  s6    


 zChecker.check_logicalc       
   
   C   s¢   yt d | j¡ddtƒ}W n tttfk
r8   |  ¡ S X xb| jD ]X\}}}||| j	ƒ}x@| 
¡ D ]4\}}}}	| jr†t| j|d  ƒsb|  ||||	¡ qbW qBW dS )z,Build the file's AST and run all AST checks.rÈ   Úexecr   N)Úcompilerù   r2   ÚPyCF_ONLY_ASTÚ
ValueErrorræ   Ú	TypeErrorr8  r-  rÛ   Úrunr;   r4  )
r  r  r  Úclsr“   ZcheckerÚlinenor#   rT   r  r%   r%   r&   Ú	check_astê  s    
zChecker.check_astc          	   c   sˆ   | j r|  ddd| j  t¡ t | j¡}y8x2|D ]*}|d d | jkrJdS |  |¡ |V  q0W W n" ttj	fk
r‚   |  
¡  Y nX dS )z=Tokenize the file, run physical line checks and yield tokens.r   r   zE902 %sr6   N)r'  r4  rÚ   rr   Úgenerate_tokensrä   r4   Úmaybe_check_physicalræ   Ú
TokenErrorr8  )r  Ztokengenr
  r%   r%   r&   rS  ö  s    

zChecker.generate_tokensc             C   sœ   t |ƒr|  |d ¡ n€|d tjkr˜d|d kr˜t|d ƒrBdS d| _|d d | _x:|d  d¡dd… D ] }|  |d ¡ |  jd7  _qnW d	| _dS )
z@If appropriate (based on token), check current physical line(s).rg   r   r+   r   NTr6   r8   F)r  r>  rr   ry   r;   r@   r3   r<   )r  r
  rA   r%   r%   r&   rT    s    zChecker.maybe_check_physicalr   c             C   s:  | j  | j| j||¡ t| jƒ| _| jr0|  ¡  d| _d| _	d | _
| _d| _g | _d | _| _d}x¨|  ¡ D ]š}| j |¡ |dd… \}}| jdkr|d d |d d krØd|d d pÆd|d d f }nd|d d  }td	|d d |tj|d  |f ƒ |tjkrB|d
kr.|d7 }n|dkr|d8 }qp|sp|tkrž|tjkrl|  ¡  d| _n0t| jƒdkr”|  jd7  _| jd= n|  ¡  qptrp|tjkrpt| jƒdkrpt|ƒ}| d¡|d< |d d |d d t|d ƒ f|d< t|ƒg| _|  ¡  qpW | jr0|  | jd ¡ |  ¡  | j  ¡ S )z!Run all checks on the input file.r   NrÈ   r6   rD   z[%s:%s]r   zl.%szl.%s	%s	%s	%rz([{z}])z
r8   ) r3  Ú	init_filerÛ   r2   r/   r4   r-  rR  r3   r!   rJ   rM   rL   r   rI   rK   rS  r{   r   r   rr   Útok_namers   rp   rI  ÚCOMMENT_WITH_NLrx   r}   r.   rH  r>  Úget_file_results)r  ÚexpectedÚline_offsetr„   r
  r…   rT   r‹   r%   r%   r&   Ú	check_all"  sZ    ""






(zChecker.check_all)NNNN)Nr   )r1  Ú
__module__Ú__qualname__r  r  r8  rä   r;  r=  r>  rE  rI  rR  rS  rT  r\  r%   r%   r%   r&   r#  M  s    
)
! r#  c               @   sr   e Zd ZdZdZdd„ Zdd„ Zdd„ Zd	d
„ Zdd„ Z	dd„ Z
dd„ Zddd„Zddd„Zddd„Zdd„ ZdS )Ú
BaseReportz"Collect the results of the checks.Fc             C   s6   |j | _|j| _d| _d| _t | jd¡| _i | _	d S )Nr   )
Úbenchmark_keysÚ_benchmark_keysÚignore_codeÚ_ignore_codeÚelapsedÚtotal_errorsrÿ   ÚfromkeysÚcountersÚmessages)r  r&  r%   r%   r&   r  \  s    zBaseReport.__init__c             C   s   t   ¡ | _dS )zStart the timer.N)ÚtimeÚ_start_time)r  r%   r%   r&   rS   e  s    zBaseReport.startc             C   s   t   ¡ | j | _dS )zStop the timer.N)ri  rj  rd  )r  r%   r%   r&   Ústopi  s    zBaseReport.stopc             C   sN   || _ || _|pd| _|| _d| _| jd  d7  < | jd  t|ƒ7  < dS )zSignal a new file.r%   r   r   r   zphysical linesN)rÛ   r2   rZ  r[  Úfile_errorsrg  r/   )r  rÛ   r2   rZ  r[  r%   r%   r&   rV  m  s    
zBaseReport.init_filec             C   s   | j d  d7  < dS )zSignal a new logical line.zlogical linesr   N)rg  )r  r%   r%   r&   rG  w  s    z!BaseReport.increment_logical_linec             C   s˜   |dd… }|   |¡rdS || jkr8| j|  d7  < nd| j|< |dd… | j|< || jkrbdS | jrx| jsxt| jƒ |  jd7  _|  jd7  _|S )z&Report an error, according to options.Nrg   r   é   )	rc  rg  rh  rZ  Úprint_filenamerl  r   rÛ   re  )r  r3   r#   rT   r  rV   r%   r%   r&   rˆ   {  s    




zBaseReport.errorc             C   s   | j S )z6Return the count of errors and warnings for this file.)rl  )r  r%   r%   r&   rY  Ž  s    zBaseReport.get_file_resultsrÈ   c                s   t ‡ ‡fdd„ˆjD ƒƒS )z.Return the total count of errors and warnings.c                s    g | ]}|  ˆ ¡rˆj| ‘qS r%   )rF   rg  )r¶   Úkey)Úprefixr  r%   r&   rá   ”  s   z(BaseReport.get_count.<locals>.<listcomp>)Úsumrh  )r  rp  r%   )rp  r  r&   Ú	get_count’  s    zBaseReport.get_countc                s   ‡ ‡fdd„t ˆjƒD ƒS )a
  Get statistics for message codes that start with the prefix.

        prefix='' matches all errors and warnings
        prefix='E' matches all errors
        prefix='W' matches all warnings
        prefix='E4' matches all errors that have to do with imports
        c                s0   g | ](}|  ˆ ¡rd ˆj| |ˆj| f ‘qS )z
%-7s %s %s)rF   rg  rh  )r¶   ro  )rp  r  r%   r&   rá   Ÿ  s   z-BaseReport.get_statistics.<locals>.<listcomp>)Úsortedrh  )r  rp  r%   )rp  r  r&   Úget_statistics—  s    zBaseReport.get_statisticsc             C   s    x|   |¡D ]}t|ƒ qW dS )z9Print overall statistics (number of errors and warnings).N)rt  r   )r  rp  rA   r%   r%   r&   Úprint_statistics¢  s    zBaseReport.print_statisticsc             C   sP   t d| jdf ƒ | jrLx2| jD ](}t d| j| | j || j| f ƒ q W dS )zPrint benchmark numbers.z	%-7.2f %szseconds elapsedz%-7d %s per second (%d total)N)r   rd  ra  rg  )r  ro  r%   r%   r&   Úprint_benchmark§  s    zBaseReport.print_benchmarkN)rÈ   )rÈ   )rÈ   )r1  r]  r^  r  rn  r  rS   rk  rV  rG  rˆ   rY  rr  rt  ru  rv  r%   r%   r%   r&   r_  W  s   	



r_  c               @   s   e Zd ZdZdZdS )Ú
FileReportz?Collect the results of the checks and print only the filenames.TN)r1  r]  r^  r  rn  r%   r%   r%   r&   rw  ±  s   rw  c                   s@   e Zd ZdZ‡ fdd„Z‡ fdd„Z‡ fdd„Zdd	„ Z‡  ZS )
ÚStandardReportz,Collect and print the results of the checks.c                sB   t t| ƒ |¡ t |j ¡ |j¡| _|j| _	|j
| _|j| _d S )N)Úsuperrx  r  ÚREPORT_FORMATru   ÚformatÚlowerÚ_fmtÚrepeatÚ_repeatZshow_sourceÚ_show_sourceZ	show_pep8Ú
_show_pep8)r  r&  )Ú	__class__r%   r&   r  ¹  s    
zStandardReport.__init__c                s   g | _ tt| ƒ ||||¡S )zSignal a new file.)Ú_deferred_printry  rx  rV  )r  rÛ   r2   rZ  r[  )r‚  r%   r&   rV  Á  s    
zStandardReport.init_filec                sR   t t| ƒ ||||¡}|rN| j| dks.| jrN| j ||||dd… |jf¡ |S )z&Report an error, according to options.r   rm  N)ry  rx  rˆ   rg  r  rƒ  r{   r  )r  r3   r#   rT   r  rV   )r‚  r%   r&   rˆ   Ç  s    zStandardReport.errorc          	   C   sÆ   | j  ¡  x´| j D ]ª\}}}}}t| j| j| j| |d ||dœ ƒ | jr˜|t| jƒkr`d}n| j|d  }t| 	¡ ƒ tt
 dd|d|… ¡d ƒ | jr²|r²td| ¡  ƒ tj ¡  qW | jS )	z<Print the result and return the overall count for this file.r   )rø   rƒ   ÚcolrV   rT   rÈ   z\SrN   Nr   z    )rƒ  Úsortr   r}  rÛ   r[  r€  r/   r2   r.   ÚreÚsubr  rR   ré   ÚstdoutÚflushrl  )r  r3   r#   rV   rT   ÚdocrA   r%   r%   r&   rY  Ð  s     

zStandardReport.get_file_results)	r1  r]  r^  r  r  rV  rˆ   rY  Ú__classcell__r%   r%   )r‚  r&   rx  ¶  s
   	rx  c                   s,   e Zd ZdZ‡ fdd„Z‡ fdd„Z‡  ZS )Ú
DiffReportz9Collect and print the results for the changed lines only.c                s   t t| ƒ |¡ |j| _d S )N)ry  rŒ  r  Úselected_linesÚ	_selected)r  r&  )r‚  r%   r&   r  ð  s    zDiffReport.__init__c                s*   || j | j krd S tt| ƒ ||||¡S )N)rŽ  rÛ   ry  rŒ  rˆ   )r  r3   r#   rT   r  )r‚  r%   r&   rˆ   ô  s    zDiffReport.error)r1  r]  r^  r  r  rˆ   r‹  r%   r%   )r‚  r&   rŒ  í  s   rŒ  c               @   sX   e Zd ZdZdd„ Zddd„Zddd„Zdd
d„Zdd„ Zddd„Z	dd„ Z
dd„ ZdS )r%  z-Initialize a PEP-8 instance with few options.c       	      O   sD  |  dt¡| _|  dd¡}|  dd¡}|  dd ¡}t||Ž}|rDd n
| dd ¡}t||||ƒ\}| _|r†|j |¡ d|kr†|d | _| j	| _
|| _|jsª|jr¤tnt|_t|jp´dƒ|_|jsè|jsè|jsè|jsètrètt d¡ƒ|_n|jròd	nt|jƒ|_td d … |_| j|_|  d
¡|_|  d¡|_|  d¡|_|  ¡  d S )NÚchecker_classÚ
parse_argvFÚconfig_fileÚparserr  r%   rO   )rÈ   r    rH   r  )r|   r#  r  rÿ   ru   Úprocess_optionsr  Ú__dict__rý   Ú
input_fileÚrunnerr&  ÚreporterÚquietr_  rx  rH  Úselectrç   r   ÚdoctestÚDEFAULT_IGNOREr<   ÚBENCHMARK_KEYSr`  rb  Ú
get_checksr(  r*  r,  Úinit_report)	r  r  r5  r  r‘  r’  Zoptions_dictÚarglistr&  r%   r%   r&   r  ý  s6    

zStyleGuide.__init__Nc             C   s   |p
| j j| j ƒ| j _| j jS )zInitialize the report instance.)r&  r—  r3  )r  r—  r%   r%   r&   rž  "  s    zStyleGuide.init_reportc             C   sŠ   |dkr| j }| jj}| j}| ¡  y<x6|D ].}tj |¡rH|  |¡ q,|  	|¡s,||ƒ q,W W n t
k
r|   tdƒ Y nX | ¡  |S )zRun all checks on the paths.Nz... stopped)r  r&  r3  r–  rS   r÷   rø   ÚisdirÚ	input_dirÚexcludedÚKeyboardInterruptr   rk  )r  r  r3  r–  rø   r%   r%   r&   Úcheck_files'  s    

zStyleGuide.check_filesr   c             C   s4   | j jrtd| ƒ | j||| j d}|j||dS )z'Run all checks on a Python source file.zchecking %s)r2   r&  )rZ  r[  )r&  r   r   r  r\  )r  rÛ   r2   rZ  r[  Zfcheckerr%   r%   r&   r•  9  s
    zStyleGuide.input_filec             C   sØ   |  d¡}|  |¡rdS | jjj}| jj}| jj}| j}xšt 	|¡D ]Œ\}}}|r^t
d| ƒ |d  d7  < x&t|ƒD ]}	|  |	|¡rx| |	¡ qxW x8t|ƒD ],}
t|
|ƒr |  |
|¡s |tj ||
¡ƒ q W qDW dS )z9Check all files in this directory and all subdirectories.r   r   z
directory r   r   N)r.   r¢  r&  r3  rg  r   rÛ   r–  r÷   Úwalkr   rs  Úremoverö   rø   rù   )r  Údirnamerg  r   Zfilepatternsr–  ÚrootÚdirsr   ZsubdirrÛ   r%   r%   r&   r¡  A  s$    



zStyleGuide.input_dirc             C   sV   | j jsdS tj |¡}t|| j jƒr*dS |r<tj ||¡}tj |¡}t|| j jƒS )z|Check if the file should be excluded.

        Check if 'options.exclude' contains a pattern that matches filename.
        FT)r&  Úexcluder÷   rø   Úbasenamerö   rù   r  )r  rÛ   rú   r«  r%   r%   r&   r¢  W  s    zStyleGuide.excludedc                sH   t ˆ ƒdk r*t‡ fdd„| jjD ƒƒr*dS ˆ  | jj¡oFˆ  | jj¡ S )zàCheck if the error code should be ignored.

        If 'options.select' contains a prefix of the error code,
        return False.  Else, if 'options.ignore' contains a prefix of
        the error code, return True.
        rg   c             3   s   | ]}|  ˆ ¡V  qd S )N)rF   )r¶   Ús)rV   r%   r&   r¸   m  s   z)StyleGuide.ignore_code.<locals>.<genexpr>F)r/   r¹   r&  r™  rF   rç   )r  rV   r%   )rV   r&   rb  f  s
    zStyleGuide.ignore_codec                sV   g }xHt |  ¡ D ]8\}}|\}}t‡ fdd„|D ƒƒr| |j||f¡ qW t|ƒS )z½Get all the checks for this category.

        Find all globally visible functions where the first argument name
        starts with argument_name and which contain selected tests.
        c             3   s   | ]}|oˆ   |¡ V  qd S )N)rb  )r¶   rV   )r  r%   r&   r¸   |  s    z(StyleGuide.get_checks.<locals>.<genexpr>)r  r   r¹   r{   r1  rs  )r  Zargument_nameZchecksr  Zattrsr  r  r%   )r  r&   r  s  s    zStyleGuide.get_checks)N)N)NNr   )N)r1  r]  r^  r  r  rž  r¤  r•  r¡  r¢  rb  r  r%   r%   r%   r&   r%  ú  s   %



r%  c             C   sš  t | |dd}ddddddd	d
dddddg|_|jdddd	dd |jdddd	dd |jdddddd |jdddd d! |jd"d#td$d% |jd&d#d'd(d% |jd)d*d+d,d% |jd-d*d+d.t d% |jd/dd0d1 |jd2dd3d1 |jd4dd5d1 |jd6dd7d1 |jd8d9d:td;d< |jd=dd>d1 |jd?d
d@dAd% |jdBddCd1 | dD¡}tj 	t
¡r†|jdEdFdGdH |jdIddJd1 |jdKddLd1 |S )MNz%prog [options] input ...)ÚprogÚversionZusagerª  rÛ   r™  rç   zmax-line-lengthzhang-closingrd   r{  r˜  z	show-pep8zshow-sourceÚ
statisticsr   z-vz	--verboser   z(print status messages, or debug with -vv)r	   ÚactionÚhelpz-qz--quietz+report only file names, or nothing with -qqz-rz--repeatTÚ
store_truez1(obsolete) show all occurrences of the same errorz--firstÚstore_falser~  z#show first occurrence of each error)r°  Údestr±  z	--excluderû   z[exclude files or directories which match these comma separated patterns (default: %default))Úmetavarr	   r±  z
--filenamez*.pyzjwhen parsing directories, only check filenames matching these comma separated patterns (default: %default)z--selectrè   rÈ   z&select errors and warnings (e.g. E,W6)z--ignorez2skip errors and warnings (e.g. E4,W) (default: %s)z--show-sourcezshow source code for each error)r°  r±  z--show-pep8z3show text of PEP 8 for each error (implies --first)z--statisticszcount errors and warningsz--countzgprint total number of errors and warnings to standard error and set exit code to 1 if total is not nullz--max-line-lengthrô   Únz3set maximum allowed line length (default: %default))Útyperµ  r	   r±  z--hang-closingzNhang closing bracket instead of matching indentation of opening bracket's linez--formatr	   z.set the error format [default|pylint|<custom>]z--diffzSreport changes only within line number ranges in the unified diff received on STDINzTesting Optionsz--testsuiteÚdirzrun regression tests from dir)rµ  r±  z	--doctestzrun doctest on myselfz--benchmarkzmeasure processing speed)r   Úconfig_optionsÚ
add_optionÚDEFAULT_EXCLUDEr›  ÚMAX_LINE_LENGTHÚadd_option_groupr÷   rø   ÚexistsÚTESTSUITE_PATH)r­  r®  r’  r   r%   r%   r&   Ú
get_parser  s`    










rÀ  c                s  t ƒ }| j}tj}tr>tj t¡r>| jr4tdt ƒ | 	t¡ |oTtj 
tj |¡¡ ‰ }xH|r¢| 	‡ fdd„tD ƒ¡rˆ }| jrŽtdˆ  ƒ P tj ˆ ¡\‰ }q\W |rÐtj |¡rÐ| jrÆtd| ƒ | 	|¡ |j}| |¡ròtdd„ |jD ƒƒ}	| g ¡\}
}xÚ| |¡D ]Ì}| dd	¡|jkr8td
| ƒ q| jdkr\td|| ||¡f ƒ | d	d¡}|	| }|dkrˆ| ||¡}nF|dkr´| ||¡}|dkrÎt||ƒ}n|dksÂt‚| ||¡}t|
||ƒ qW |j||
d\} }d | _| _| S )ao  Read and parse configurations

    If a config file is specified on the command line with the "--config"
    option, then only it is used for configuration.

    Otherwise, the user configuration (~/.config/pep8) and any local
    configurations in the current directory or above will be merged together
    (in that order) using the read method of ConfigParser.
    zuser configuration: %sc             3   s   | ]}t j ˆ |¡V  qd S )N)r÷   rø   rù   )r¶   Úfn)rú   r%   r&   r¸   Õ  s    zread_config.<locals>.<genexpr>zlocal configuration: in %szcli configuration: %sc             S   s   g | ]}|j |jp|jf‘qS r%   )r´  r·  r°  )r¶   Úor%   r%   r&   rá   ã  s   zread_config.<locals>.<listcomp>Ú_r   z  unknown option '%s' ignoredr   z	  %s = %s)rô   rd   Ústringrª  )r²  r³  )r  F)r   Úconfigr÷   ÚcurdirÚUSER_CONFIGrø   Úisfiler   r   rì   r  ÚcommonprefixÚPROJECT_CONFIGr<   r­  Zhas_sectionrÿ   Úoption_listÚ
parse_argsr&  Úreplacer¹  ru   Zgetintr  r~   Z
getbooleanÚsetattrrš  r   )r&  r  rŸ  r’  rÅ  Zcli_confZ	local_dirÚtailZpep8_sectionrË  Znew_optionsr“   ZoptZnormalized_optZopt_typer  r%   )rú   r&   Úread_config¾  sX    





rÐ  Fc             C   sJ  |s
t ƒ }| d¡sF|jdd|jd |j¡f d}|jdd|dd | sR|sRg } | | ¡\}}d	|_| 	d
d¡r€| 
|j¡ n`| 	dd¡sà|r¾|s¾|js¬tdd„ tD ƒƒr´dg}n
| d¡ t||| |ƒ}|oÜ|jdkoÜt|_t|jƒ|_t|jƒ|_t|jƒ|_t|jƒ|_|jrBt|_tƒ }t||j|d ƒ|_t|jƒ}||fS )zÓProcess options passed either via arglist or via command line args.

    Passing in the ``config_file`` parameter allows other tools, such as flake8
    to specify their own options to be processed in pep8.
    z--configZConfigurationz³The project options are read from the [%s] section of the tox.ini file or the setup.cfg file located in any parent folder of the path(s) being processed.  Allowed options are: %s.z, )Zdescriptionrø   zuser config file location)rµ  r	   r±  Nr   Frš  c             s   s   | ]}t j |¡V  qd S )N)r÷   rø   r¾  )r¶   r  r%   r%   r&   r¸      s   z"process_options.<locals>.<genexpr>rò   zinput not specifiedr   r   )rÀ  Z
has_optionr½  r­  rù   r¹  rº  rÌ  r—  Zensure_valuer{   r   r  r¹   rÊ  rˆ   rÐ  r˜  rw  Ú_parse_multi_optionsrÛ   r  rª  r™  rç   rŒ  rí   r  r  rs  )rŸ  r  r‘  r’  r   r&  r  rê   r%   r%   r&   r“    s@    




r“  rO   c             C   s    | rdd„ |   |¡D ƒS | S dS )zgSplit and strip and discard empties.

    Turns the following:

    A,
    B,

    into ["A", "B"]
    c             S   s   g | ]}|  ¡ r|  ¡ ‘qS r%   )rR   )r¶   rÂ  r%   r%   r&   rá   A  s    z(_parse_multi_options.<locals>.<listcomp>N)r<   )r&  Zsplit_tokenr%   r%   r&   rÑ  6  s    
rÑ  c              C   sØ   t  d¡ ddl} y|  | jdd„ ¡ W n tk
r<   Y nX tdd}|j}|jsZ|jrpddl	m
} ||ƒ}n| ¡ }|jr†| ¡  |jr”| ¡  |jr¨|js¨| ¡  |jrÔ|jrÊtj t|jƒd	 ¡ t d
¡ dS )zwParse options and run checks on Python source.

    Warn of deprecation and advise users to switch to pycodestyle.
    zÐ

pep8 has been renamed to pycodestyle (GitHub issue #466)
Use of the pep8 tool will be removed in a future release.
Please install and use `pycodestyle` instead.

$ pip install pycodestyle
$ pycodestyle ...
r   Nc             S   s
   t  d¡S )Nr   )ré   Úexit)ZsignumÚframer%   r%   r&   Ú<lambda>X  s    z_main.<locals>.<lambda>T)r  )Ú	run_testsr+   r   )ÚwarningsÚwarnÚsignalÚSIGPIPEÚAttributeErrorr%  r&  rš  r   Ztestsuite.supportrÕ  r¤  r¯  ru  Z	benchmarkrv  r˜  Zprint_resultsre  rd   ré   ÚstderrÚwriterv   rÒ  )rØ  Z	pep8styler&  rÕ  r3  r%   r%   r&   Ú_mainF  s.    

rÝ  Ú__main__)Nrò   )T)N)NFNN)rO   )Šr  Z
__future__r   r÷   ré   r†  ri  r  r   rr   rÖ  Zoptparser   r   Zconfigparserr   Úior   ÚImportErrorZConfigParserÚ__version__r»  r›  Úplatformrø   Ú
expanduserrÇ  rù   ÚgetenvrÊ  r§  Ú__file__r¿  r¼  rz  rL  Ú	frozensetrÐ   Úkwlistrž   r   r›   ÚunionrŸ   rœ   rc   rw   rp   ÚINDENTÚDEDENTr?  rx   Ú
ERRORTOKENrš   rœ  rK  r   rÓ   rÔ   r  rG   rP   r¡   rÉ   rÍ   rÏ   rX   r–   r½   rü   rS  r|   ÚsendrX  r'   r*   r1   r5   rC   rI   rW   r\   rf   rj   rŒ   r•   r—   r    r£   r¦   r«   r®   r»   rÀ   rÃ   rÇ   rË   rÎ   rÑ   rÒ   rÕ   rÖ   rØ   r  rÚ   r   r¿   rê   rì   rí   rv   ÚIr¾   r;   rq   rñ   r  rÆ  r  rö   r  r  r  r   r"  Úobjectr#  r_  rw  rx  rŒ  r%  rÀ  rÐ  r“  rÑ  rÝ  r1  r%   r%   r%   r&   Ú<module>/   s  















&%  H \1)29''"



	

  Z7 =E 
2
.
