a
    NPYC                    @   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 zddlmZ ddlmZ W n ey   ddlmZ Y n0 dZd	Zd
Zz<ejdkrejdZn ejedpejddZW n ey   dZY n0 dZejejedZ dZ!dddZ"dZ#e$g dZ%e$ej&dg e% Z'e$g dZ(e$g dZ)e)*g dZ+e$g dZ,e$dZ-e$e	j.e	j/gZ/e/*e	j0e	j1gZ2e2*e	j3e	j4gZ5g dZ6e7dZ8e7d Z9e7d!Z:e7d"Z;e7d#Z<e7d$Z=e7d%Z>e7d&Z?e7d'Z@e7d(ZAe7d)d*e' ZBe7d+ZCe7d,ZDe7d-ZEe	Fd.gjGHdd/ d.kZId0d1 ZJd2d3 ZKd4d5 ZLd6d7 ZMd8d9 ZNd:d; 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`da Zbdbdc Zcddde Zddfdg Zedhdi Zfejgdjk rdkdl Zhe7dmjiZjejkjlZmndndl ZhenjjZjdodp Zme7dqejojpZqdrds Zrdtdu ZsddwdxZtejufdydzZvdd|d}Zwd~d ZxeIrexfddZxi i i dZydd ZzdddZ{dd Z|e|  G dd de}Z~G dd de}ZG dd deZG dd deZG dd deZG dd de}ZdefddZdd ZdddZdddZdd Zedkre  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	testsuiteO   z+%(path)s:%(row)d:%(col)d: %(code)s %(text)sz%%(path)s:%(row)d: [%(code)s] %(text)s)defaultZpylinti   )FalseNoneTrueprint)>>***+-)r   r   /z//r   r   )^&|z<<r   %)z**=z*=z/=z//=z+=z-=z!=<><>z%=z^=z&=z|===z<=z>=z<<=z>>==z 	)directoriesfileslogical lines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*)r   z'(?:[^,\s])(\s*)(?:[-+*/|!<=>%&^]+)(\s*)z
\blambda\bz*^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@.*$z#
   c                 C   s:   t | d}t|D ]\}}||kr|df  S q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.9/site-packages/pep8.pytabs_or_spaces   s    r.   c                 C   s*   t | d}d|v r&|ddfS dS )zFor 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    r1   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    




r9   c                 C   s0   ||kr,|   }|sdS || kr,t| dfS dS )zTrailing 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 fileNr5   )r'   linesline_numbertotal_linesZstripped_last_liner,   r,   r-   trailing_blank_lines   s    r=   c                 C   s   |   }t|}||krt|s| }t|dkr8|sPt|dkrp|d dkrpt|t|d  |d k rpdS t|drzt|d	}W n ty   Y n0 ||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))r6   r7   noqasplithasattrrB   UnicodeError)r'   max_line_length	multilinelinelengthZchunksr,   r,   r-   maximum_line_length   s*    


rK   c                 c   s   |dk r|sdS | dr&|rdV  nf|dks:|rJ|dkrJdd| fV  nB|  dr|rv|s||k st|sd	V  n|dkrd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 decoratorr>   r   zE303 too many blank lines (%d))def zclass rM   )r   z#E301 expected 1 blank line, found 0z%E302 expected 2 blank lines, found %d)
startswithDOCSTRING_REGEXr$   )logical_lineblank_linesindent_levelr;   blank_beforeprevious_logicalprevious_indent_levelr,   r,   r-   rR      s    

rR   c                 c   s   | }t |D ]n}| }| }| }||d krJ|d d| fV  q||d  dkr|dv rfdnd}|d||f fV  q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E202ZE203z%s whitespace before '%s'N)EXTRANEOUS_WHITESPACE_REGEXfinditerr%   stripstart)rQ   rI   r$   textr+   foundcoder,   r,   r-   extraneous_whitespace  s    ra   c                 c   s   t | D ]|}| \}}d|v r4|ddfV  nt|dkrP|ddfV  d|v rj|ddfV  q
t|dkr
|ddfV  q
dS )	zAvoid 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 keywordr>   zE273 tab after keywordz"E271 multiple spaces after keywordN)KEYWORD_REGEXr[   groupsr]   r7   rQ   r$   beforeZafterr,   r,   r-   whitespace_around_keywords2  s    	rf   c                 c   s   | }t t|d D ]}|| }|dv r||d  tvr|d| }|dkrv|d|dkrv|d|dk rvq|dkr||d  d	krq|d
| fV  qdS )zEach 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:[]{rX   )z"E231 missing whitespace after '%s')ranger7   
WHITESPACEcountrfind)rQ   rI   r0   r+   re   r,   r,   r-   missing_whitespaceI  s    rp   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rd|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   rL   zE11%d %szE11%d %s (comment)   r"   z%indentation is not a multiple of fourrg   r>   zexpected an indented blockzunexpected indentationN)endswith)rQ   rU   r(   rS   rV   cZtmplZindent_expectr,   r,   r-   indentationc  s    
rt   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rtd|d d    |D ]\}}}}}|
|d | k }|r|d | }
| o|tv}|r|}|dkr(td|   t|| ||
< |tjkoJ|dv }t|| D ]*}||
 ||  }||v }|rX qqX|| 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ur|dfV  n|sT|	rt||
 dkrt|rj|sj|dfV  |||< n|du r|d ||< np||t	fv rn`|dkrd} nB|| rd} n2|s|| rd} n|||< |dkrd} nd} |d|  fV  ||
 rZ|tj
tjfvrZ|| sZ|d ||< d||d < |dkrtd||d f  n|tjtjfv sv|dv rt	||d < n\|s|
s|s|dkrd||d d < n.|dkr||d d  r|| |
 |tjkrn|dv rn|d7 }|d |d t||kr*|g  || |
 ||
  d7  < |dkr>td ||d || f  n|d!v r>|dkr>| p|d }!|  t|D ]}"||" |!krd||"< qt|D ]}#|#|!kr||#= q||d d= |d8 }|r
d||| < t|
ddD ]&}$||$ r||$  d8  <  q>qt||d ksTJ |d |vrn|||d < |d |d k}|r||
 ||d | < q|	rt||d kr|d |d d f}%|rd"}&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   r>   r"   r@   Nrg   r/   )rq   )rq      FrL   z>>> rq   z... z]})z6E124 closing bracket does not match visual indentationz+E133 closing bracket is missing indentationTz7E128 continuation line under-indented for visual indentru   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if([{z.bracket depth %s seen, col %s, visual min = %s)]}zE129 visually indented linezE125 continuation linez(%s with same indent as next logical line)rr   r   r6   NEWLINEexpand_indenttokenizeOPreversedgetstrNLCOMMENTSTRINGisspaceappendr7   poprl   list)'rQ   tokensrS   hang_closingr(   rC   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_typer^   r]   endrI   newlineZclose_bracketZopen_rowZhangZhanging_indenterrorZprev_indentdZindidxposr`   r,   r,   r-   continued_indentation  s    















 








r   c                 c   s   |d \}}}}}t dt|D ]}|| \}}}	}
}|tjkr|dv r|	|kr|tjksb|dv r|dk s~||d  d dkrt|s|d| fV  |}|}|
}q 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([rY   r>   classzE211 whitespace before '%s'N)rl   r7   r~   r   NAMEkeyword	iskeyword)rQ   r   	prev_type	prev_text__prev_endr0   r   r^   r]   r   r,   r,   r-   whitespace_before_parametersI  s,    
r   c                 c   s   t | D ]|}| \}}d|v r4|ddfV  nt|dkrP|ddfV  d|v rj|ddfV  q
t|dkr
|ddfV  q
dS )	zAvoid 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 operatorr>   zE224 tab after operatorz#E222 multiple spaces after operatorN)OPERATOR_REGEXr[   rc   r]   r7   rd   r,   r,   r-   whitespace_around_operatori  s    	r   c                 c   s  d}d}t j}d }}|D ]\}}}	}
}|tv r4q|dv rF|d7 }n|dkrV|d8 }|r|	|kr|dur|d s|d dfV  d}nz|d	kr|d
v rnh|du s|d r|dfV  nH|dkrd\}}|dkrd\}}n|tvrd\}}|d d||f fV  d}n|t jkr|dur|dkr,|r,nP|tv r<d}n@|tv rn|t jkr^|dv r|n
|tvr|d}n|tv r|d}|du r||	|kf}n|r|	|kr|dfV  d}|}|}|
}q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"   rk   Tz'E225 missing whitespace around operatorr   )r   r   r   )ZE226Z
arithmeticr   )ZE228Zmodulo)ZE227zbitwise or shiftz(%s missing whitespace around %s operatorr   rY   )r~   r   SKIP_COMMENTSARITHMETIC_OPWS_NEEDED_OPERATORSUNARY_OPERATORSKEYWORDSWS_OPTIONAL_OPERATORS)rQ   r   r   Z
need_spacer   r   r   r   r^   r]   r   rI   r`   Zoptyper,   r,   r-   "missing_whitespace_around_operator  sh    






r   c                 c   s^   | }t |D ]J}| d }d| v rB|d| d  fV  q|d| d  fV  qdS )zAvoid 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_REGEXr[   r]   r%   )rQ   rI   mr_   r,   r,   r-   whitespace_around_comma  s    	r   c                 c   s   d}d}d}d}|  d}d}|D ]\}}	}
}}|tjkr<q"|rVd}|
|krV||fV  |tjkr|	dkrr|d7 }nl|	dkr|d8 }nZ|r|	d	kr|dkrd
}n@|r|	dkr|dkrd}n&|r|	dkr|sd
}|
|kr||fV  |sd}|}q"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"   rk   rg   TrX   r   )rO   r~   r   r   )rQ   r   r   Zno_spacer   Zannotated_func_argZin_defmessager   r^   r]   r   rI   r,   r,   r-   (whitespace_around_named_parameter_equals  s:    






r   c                 c   s  d}|D ]\}}}}}|t jkr|d|d   }|rf|d |d krf|d |d d k rf|dfV  |d\}	}
}|	dvo|	d	dd pd	}|r|s|dd tv 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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   r>   z.E261 at least two spaces before inline commentrW   z#:r?   z*E262 inline comment should start with '# '!z)E265 block comment should start with '# 'z+E266 too many leading '#' for block comment)r~   r   r\   	partitionlstriprm   r   )rQ   r   r   r   r^   r]   r   rI   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| v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
    import rX   r@   ;Nz!E401 multiple imports on one line)rO   find)rQ   rI   r_   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rd	V  nJt fd
d|D rjdS | r|ddrd|d< qd|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v r| dd  } | r4| d dv r4| dd  } | oN| d dkpN| d dkS )Nr   ZuUbBr"   ZrR"'r,   rI   r,   r,   r-   is_string_literall  s
    z8module_imports_on_top_of_file.<locals>.is_string_literal)tryexceptelsefinallyNr   zfrom Zseen_non_importsF)r   z+E402 module level import not at top of filec                 3   s   | ]}  |V  qd S NrO   ).0kwr   r,   r-   	<genexpr>      z0module_imports_on_top_of_file.<locals>.<genexpr>Zseen_docstringT)rO   r   any)rQ   rS   checker_staterC   r   Zallowed_try_keywordsr,   r   r-   module_imports_on_top_of_file[  s&    

r   c                 c   sB  | }t |d }|d}d|  k r.|k rn n|d| }|d|dkr|d|dkr|d	|d
krt|}|r|d|   }|dd dkrt|dd  rdV  q|	drdV  n
|dfV  |d|d }q|d}d|k r>||k r |dfV  n
|dfV  |d|d }q 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"   rg   r@   Nrj   }rh   ri   r   rk   r   )r   z1E731 do not assign a lambda expression, use a defrN   )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)
r7   r   rn   LAMBDA_REGEXsearchr]   r6   isidentifierr\   rO   )rQ   rI   Z	last_charr_   re   Z	lambda_kwr,   r,   r-   compound_statements  s4    

$





r   c                 c   s   d } }}d}d}|D ]\}}}	}
}|t jkr4d}|	d |krV|rV|rV|sV|dfV  |
d |kr|ddr|
d t| d d	 f}nd}|
d  }}n|	d }|t jkr|d
v r|d	7 }q|dv r|d	8 }q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 brackets
\r@   r"   rz   r{   )r~   r   r6   rr   r7   
splitlinesr   )rQ   r   Z
prev_startr   r   r   Z	backslashr   r^   r]   r   rI   r,   r,   r-   explicit_line_join  s&    



r   c           
      c   s|   dd }d}d}|D ]b\}}}}}	|t jkr.qd|v s>d|v rN|t jkrNd}q|||rj|rj|sj|dfV  |dv }d}q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v o|dvS )N)andorz()[]{},:.;@=%)r~   r   )r   r^   r,   r,   r-   is_binary_operator  s    z8break_around_binary_operator.<locals>.is_binary_operatorFTr2   r3   z&W503 line break before binary operatorz([{,;N)r~   r   r   )
rQ   r   r   Z
line_breakZunary_contextr   r^   r]   r   rI   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v rXd	}n2d
}|dkrh|pt|dkot| }|d|rd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"   rL   r>   r   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%   r]   )rQ   rC   r$   Z	singletonZsamemsgr`   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"   r>   inz+E713 test for membership should be 'not in'z0E714 test for object identity should be 'is not'N)COMPARE_NEGATIVE_REGEXr   r]   r%   )rQ   r$   r   r,   r,   r-   comparison_negative6  s    

r   c                 c   sF   t | }|rB|sB|d}|r4t|r4|tv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   
SINGLETONSr]   )rQ   rC   r$   instr,   r,   r-   comparison_typeK  s    

r   c                 c   s$   |  d}|dkr |s |dfV  dS )zThe {}.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(r@   z'W601 .has_key() is deprecated, use 'in'Nr   )rQ   rC   r   r,   r,   r-   python_3000_has_keyb  s    
r   c                 c   s.   t | }|r*t| s*| d dfV  dS )zWhen 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   )rQ   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':
    r   r@   z!W603 '<>' is deprecated, use '!='Nr   rQ   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`
    `r@   z+W604 backticks are deprecated, use 'repr()'Nr   r   r,   r,   r-   python_3000_backticks  s    
r   )rL   c                 C   s6   t | d}| W  d   S 1 s(0    Y  dS )Read the source code.ZrUN)open	readlines)filenamefr,   r,   r-   r     s    r   z[a-zA-Z_]\w*$c                    s   zht | dJ}t|j\ }t| dd} fdd|D |  W  d   W S 1 s\0    Y  W nP tttfy   t | dd}| W  d    Y S 1 s0    Y  Y n0 dS )	r   rbT)line_bufferingc                    s   g | ]}|  qS r,   )rB   )r   lZcodingr,   r-   
<listcomp>  r   zreadlines.<locals>.<listcomp>Nzlatin-1)encoding)	r   r~   detect_encodingreadliner   r   LookupErrorSyntaxErrorrF   )r   r   r:   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| vrt | t |   S d}| D ]4}|dkrB|d d d }q$|dkrT|d7 }q$ qZq$|S )zReturn 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   ru   rW   r"   )r7   r   )rI   resultr+   r,   r,   r-   r}     s    
r}   c                 C   sb   |  | d d }t| d }| dd dv r>|d7 }|d8 }| d| d||   | |d  S )zReplace contents with 'xxx' to prevent syntax matching.

    >>> mute_string('"abc"')
    '"xxx"'
    >>> mute_string("'''abc'''")
    "'''xxx'''"
    >>> mute_string("r'abc'")
    "r'xxx'"
    r@   r"   N)z"""z'''r>   x)r0   r7   )r^   r]   r   r,   r,   r-   mute_string  s    r  .c           	         s   i }d }}|   D ]}|r6|dd dkr|d8 }q|dd dkrt|}dd | D \}}|| t|||  q|dd dkr|d	d d
dd }|dd dkr|dd }t ||< qt fdd|	 D S )z&Return a dictionary of matching lines.Nr"   r   rL   z@@ c                 S   s   g | ]}t |pd qS )1)int)r   gr,   r,   r-   r     r   zparse_udiff.<locals>.<listcomp>z+++rq   r/   r   r>   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$   rc   updaterl   rD   setdictitems)	diffr  r  rvr  r   rI   Z
hunk_matchr   r,   r  r-   parse_udiff  s&    
r  c                 C   sd   | sg S t | tr| S g }| dD ]:}| }d|v rNtjtj||}||	d q$|S )zQParse a comma-separated list of paths.

    Return a list of absolute paths.
    rX   r   )

isinstancer   rD   r\   r  r  abspathr  r   r6   )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 r   r   )r   patternr   r,   r-   r     r   z!filename_match.<locals>.<genexpr>)r   )r   r  r
   r,   r   r-   r    s    r  c                 C   s,   | d t v p*| d | d d d   dkS )Nr   rq   rL   r"   z\
)r|   r   )tokenr,   r,   r-   _is_eol_token  s    r"  c                 C   s&   || p$| d t jko$| d | d kS )Nr   r"   rq   )r~   r   )r!  Z
_eol_tokenr,   r,   r-   r"    s    )r'   rQ   treec                 C   s6   t jdkr$dd t| j D S t| d S d S )N)rL   rL   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	signature
parametersvaluesZ
getargspec)functionr,   r,   r-   _get_parameters&  s
    
r+  c                 C   s   dd }t | rVt| }|r|d dv r|du rBt| jp>d}|| |d || n2t | rt| jdd dd	gkr|| d	|d dS )
zRegister a new check object.c                 S   sB   | t | v 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'   rQ   Nr   r>   selfr#  )r'  
isfunctionr+  ERRORCODE_REGEXfindall__doc__Zisclass__init__)r.  r/  r1  r0  r,   r,   r-   register_check0  s    

r8  c                  C   s.   t t} t | t jD ]\}}t| qdS )zwRegister all globally visible functions.

    The first argument name is either 'physical_line' or 'logical_line'.
    N)r'  Z	getmoduler8  Z
getmembersr3  )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 u rt |j}n|rJ d | _|j| _|j| _|j| _|j	| _	d| _
|j| _|j| _|| _i | _|d u r~d| _|pxg | _nz|dkrd| _t d| _n\|d u rzt|| _W q ty   t d d \}}d|j|f | _g | _Y q0 n|| _| jrpt| jd d }|dv rp|d	kr@| jd d
d  | jd< n0| jd d d dkrp| jd dd  | jd< |pz|j| _| jj| _d S )NFr   r   Tr>   z%s: %sr   )     r=  r"   rL   u   ï»¿)
StyleGuideoptions	_io_errorphysical_checks_physical_checkslogical_checks_logical_checks
ast_checks_ast_checksrG   rH   r   r   r   _checker_statesr:   r  r   r   IOErrorr   exc_info__name__ordreportr   report_error)	r2  r   r:   r?  rL  kwargsexc_typeexcZord0r,   r,   r-   r7  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.Nr>   r"   rL   )r"   r   r   zE901 %s: %s)r   rI  r7   r0  rM  rJ  report_invalid_syntax)r2  rO  rP  r*   r,   r,   r-   rQ  z  s    
zChecker.report_invalid_syntaxc                 C   sR   | j | jkrdS | j| j  }|  j d7  _ | jdu rN|dd tv rN|d | _|S )z(Get the next line from the input buffer.r   r"   Nr   )r;   r<   r:   r(   rm   )r2  rI   r,   r,   r-   r     s    
zChecker.readlinec                 C   s&   g }|D ]}| t| | q|| S )zRun a check plugin.)r   getattr)r2  r.  argument_namesZ	argumentsr%  r,   r,   r-   	run_check  s    zChecker.run_checkc                 C   s   d|v r| j |i | _dS )z9 Prepares a custom state for the specific checker plugin.r   N)rG  
setdefaultr   )r2  r%  rS  r,   r,   r-   init_checker_state  s    zChecker.init_checker_statec                 C   sp   || _ | jD ]^\}}}| || | ||}|dur|\}}| | j||| |dd dkr|d | _qdS )z,Run all physical checks on a raw input line.Nrq   ZE101r   )r'   rB  rV  rT  rM  r;   r(   )r2  rI   r%  r.  rS  r  r*   r^   r,   r,   r-   check_physical  s    zChecker.check_physicalc                 C   s$  g }g }d}d } }}| j D ]\}}}	}
}|tv r6q|sDd|	fg}|tjkrZ|| q|tjkrlt|}|r|	\}}||kr| j|d  |d  }|dks|dvr|dvrd| }n||kr||| | }|| |t|7 }|||
f |
\}}qd	|| _
|otd	|| _|S )	z!Build a logical line from tokens.r   Nr"   rX   z{[(rY   rW   r   )r   SKIP_TOKENSr~   r   r   r   r  r:   r7   r  rQ   rC   )r2  ZlogicalZcommentsrJ   prev_rowprev_colmappingr   r^   r]   r   rI   	start_row	start_colr   r,   r,   r-   build_tokens_line  s>    






zChecker.build_tokens_linec                 C   sJ  | j   |  }|sdS |d d \}}| j|d  }t|d| | _| j| jk r^| j| _| jdkr~t	| j
dd   | jD ]\}}}| jdkrt	d|  | || | ||pdD ]^\}}	t|ts|D ]\}
}||
kr qq|d |d | |
 f}| |d |d |	| qq| j
r:| j| _| j
| _d| _g | _dS )	z:Build a line from tokens and run all logical checks on it.Nr   r"   r>   P   rq   z   r,   )rL  increment_logical_liner^  r:   r}   rS   rT   rR   r   r   rQ   r6   rD  rV  rT  r  tuplerM  rV   rU   r   )r2  r[  r\  r]  Z
start_liner%  r.  rS  r*   r^   Ztoken_offsetr   r,   r,   r-   check_logical  s6    


zChecker.check_logicalc           
   
   C   s   zt d| jddt}W n  tttfy:   |   Y S 0 | jD ]T\}}}||| j	}|
 D ]4\}}}}	| jrt| j|d  s`| ||||	 q`qBdS )z,Build the file's AST and run all AST checks.r   execr"   N)compiler  r:   PyCF_ONLY_AST
ValueErrorr   	TypeErrorrQ  rF  r   runrC   rM  )
r2  r#  r%  clsr   Zcheckerlinenor*   r^   r.  r,   r,   r-   	check_ast  s    zChecker.check_astc              	   c   s   | j r| ddd| j  t t| j}z8|D ].}|d d | jkrL W dS | | |V  q.W n  ttj	fy   | 
  Y n0 dS )z=Tokenize the file, run physical line checks and yield tokens.r"   r   zE902 %sr>   N)r@  rM  r   r~   generate_tokensr   r<   maybe_check_physicalr   
TokenErrorrQ  )r2  Ztokengenr!  r,   r,   r-   rl    s    
zChecker.generate_tokensc                 C   s   t |r| |d  n||d tjkrd|d v rt|d rBdS d| _|d d | _|d ddd D ] }| |d  |  jd7  _qld	| _dS )
z@If appropriate (based on token), check current physical line(s).rq   r   r2   r"   NTr>   r@   F)r"  rW  r~   r   rC   rH   r;   rD   )r2  r!  rI   r,   r,   r-   rm    s    zChecker.maybe_check_physicalr   c                 C   s4  | j | j| j|| t| j| _| jr0|   d| _d| _	d | _
| _d| _g | _d | _| _d}|  D ]}| j| |dd \}}| jdkr
|d d |d d krd|d d pd|d d f }nd|d d  }td	|d d |tj|d  |f  |tjkr>|d
v r*|d7 }n|dv r|d8 }ql|sl|tv r|tjkrh|   d| _n0t| jdkr|  jd7  _| jd= n|   qltrl|tjkrlt| jdkrlt|}|d|d< |d d |d d t|d  f|d< t|g| _|   ql| jr*| | jd  |   | j  S )z!Run all checks on the input file.r   Nr   r>   rL   z[%s:%s]r"   zl.%szl.%s	%s	%s	%rrz   rY   r   r@   ) rL  	init_filer   r:   r7   r<   rF  rk  r;   r(   rS   rV   rU   r   rR   rT   rl  r   r   r   r~   tok_namer   r|   rb  COMMENT_WITH_NLr   r   r6   ra  rW  get_file_results)r2  expectedline_offsetr   r!  r   r^   r   r,   r,   r-   	check_all"  s\    "






(
zChecker.check_all)NNNN)Nr   )rJ  
__module____qualname__r6  r7  rQ  r   rT  rV  rW  r^  rb  rk  rl  rm  ru  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r2  r?  r,   r,   r-   r7  \  s    zBaseReport.__init__c                 C   s   t   | _dS )zStart the timer.N)time_start_timer2  r,   r,   r-   r]   e  s    zBaseReport.startc                 C   s   t   | j | _dS )zStop the timer.N)r  r  r}  r  r,   r,   r-   stopi  s    zBaseReport.stopc                 C   sN   || _ || _|pd| _|| _d| _| jd  d7  < | jd  t|7  < dS )Signal a new file.r,   r   r   r"   r!   N)r   r:   rs  rt  file_errorsr  r7   r2  r   r:   rs  rt  r,   r,   r-   ro  m  s    
zBaseReport.init_filec                 C   s   | j d  d7  < dS )zSignal a new logical line.r    r"   N)r  r  r,   r,   r-   r`  w  s    z!BaseReport.increment_logical_linec                 C   s   |dd }|  |rdS || jv r8| j|  d7  < nd| j|< |dd | j|< || jv rbdS | jrx| jsxt| j |  jd7  _|  jd7  _|S )&Report an error, according to options.Nrq   r"      )	r|  r  r  rs  print_filenamer  r   r   r~  r2  r;   r*   r^   r.  r`   r,   r,   r-   r   {  s    




zBaseReport.errorc                 C   s   | j S )z6Return the count of errors and warnings for this file.)r  r  r,   r,   r-   rr    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,   )rO   r  r   keyprefixr2  r,   r-   r     s   z(BaseReport.get_count.<locals>.<listcomp>)sumr  r2  r  r,   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)rO   r  r  r  r  r,   r-   r     s   z-BaseReport.get_statistics.<locals>.<listcomp>)sortedr  r  r,   r  r-   get_statistics  s    zBaseReport.get_statisticsc                 C   s   |  |D ]}t| q
dS )z9Print overall statistics (number of errors and warnings).N)r  r   )r2  r  rI   r,   r,   r-   print_statistics  s    zBaseReport.print_statisticsc                 C   sL   t d| jdf  | jrH| jD ](}t d| j| | j || j| f  qdS )zPrint benchmark numbers.z	%-7.2f %szseconds elapsedz%-7d %s per second (%d total)N)r   r}  rz  r  )r2  r  r,   r,   r-   print_benchmark  s    
zBaseReport.print_benchmarkN)r   )r   )r   )rJ  rv  rw  r6  r  r7  r]   r  ro  r`  r   rr  r  r  r  r  r,   r,   r,   r-   rx  W  s   	



rx  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)rJ  rv  rw  r6  r  r,   r,   r,   r-   r    s   r  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 r   )superr  r7  REPORT_FORMATr   formatlower_fmtrepeat_repeatZshow_source_show_sourceZ	show_pep8
_show_pep8r  	__class__r,   r-   r7    s    zStandardReport.__init__c                    s   g | _ tt| ||||S )r  )_deferred_printr  r  ro  r  r  r,   r-   ro    s    
zStandardReport.init_filec                    sR   t t| ||||}|rN| j| dks.| jrN| j||||dd |jf |S )r  r"   r  N)r  r  r   r  r  r  r   r6  r  r  r,   r-   r     s    zStandardReport.errorc              	   C   s   | j   | 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|rtd|   tj  q| jS )	z<Print the result and return the overall count for this file.r"   )r  r   colr`   r^   r   z\SrW   Nr   z    )r  sortr   r  r   rt  r  r7   r:   r6   resubr  r\   r   stdoutflushr  )r2  r;   r*   r`   r^   docrI   r,   r,   r-   rr    s"    


zStandardReport.get_file_results)	rJ  rv  rw  r6  r7  ro  r   rr  __classcell__r,   r,   r  r-   r    s
   	r  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 r   )r  r  r7  selected_lines	_selectedr  r  r,   r-   r7    s    zDiffReport.__init__c                    s*   || j | j vrd S tt| ||||S r   )r  r   r  r  r   )r2  r;   r*   r^   r.  r  r,   r-   r     s    zDiffReport.error)rJ  rv  rw  r6  r7  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   sH  | dt| _| dd}| dd}| dd }t|i |}|rHd n
|dd }t||||\}| _|r|j| d|v r|d | _| j	| _
|| _|js|jrtnt|_t|jpd|_|js|js|js|jstrttd|_n|jrd	nt|j|_td d  |_| j|_| d
|_| d|_| d|_|   d S )Nchecker_class
parse_argvFconfig_fileparserr  r,   rX   )r   r'   rQ   r#  )r   r;  r  r  r   process_optionsr  __dict__r  
input_filerunnerr?  reporterquietrx  r  ra  selectr   r   doctestDEFAULT_IGNORErD   BENCHMARK_KEYSry  r{  
get_checksrA  rC  rE  init_report)	r2  r0  rN  r  r  r  Zoptions_dictarglistr?  r,   r,   r-   r7    sB    

zStyleGuide.__init__Nc                 C   s   |p
| j j| j | j _| j jS )zInitialize the report instance.)r?  r  rL  )r2  r  r,   r,   r-   r  "  s    zStyleGuide.init_reportc                 C   s   |du r| j }| jj}| j}|  z8|D ].}tj|rF| | q*| 	|s*|| q*W n t
yv   td Y n0 |  |S )zRun all checks on the paths.Nz... stopped)r  r?  rL  r  r]   r  r  isdir	input_direxcludedKeyboardInterruptr   r  )r2  r  rL  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)r:   r?  )rs  rt  )r?  r   r   r  ru  )r2  r   r:   rs  rt  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}t	|D ]\}}}|r\t
d|  |d  d7  < t|D ]}	| |	|rt||	 qtt|D ],}
t|
|r| |
|s|tj||
 qqBdS )z9Check all files in this directory and all subdirectories.r   r   z
directory r   r"   N)r6   r  r?  rL  r  r   r   r  r  walkr   r  remover  r  r  )r2  dirnamer  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  )r2  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 )zCheck 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.
        rq   c                 3   s   | ]}|  V  qd S r   r   )r   sr`   r,   r-   r   m  s   z)StyleGuide.ignore_code.<locals>.<genexpr>F)r7   r   r?  r  rO   r   )r2  r`   r,   r  r-   r{  f  s    zStyleGuide.ignore_codec                    sR   g }t |  D ]8\}}|\}}t fdd|D r||j||f qt|S )zGet 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 r   )r{  )r   r`   r  r,   r-   r   |  r   z(StyleGuide.get_checks.<locals>.<genexpr>)r,  r  r   r   rJ  r  )r2  Zargument_nameZchecksr.  attrsr/  r0  r,   r  r-   r  s  s    zStyleGuide.get_checks)N)N)NNr   )N)rJ  rv  rw  r6  r7  r  r  r  r  r  r{  r  r,   r,   r,   r-   r>    s   %



r>  c                 C   s  t | |dd}g d|_|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d%d& |jd'dd(d& |jd)dd*d& |jd+dd,d& |jd-d.d/td0d1 |jd2dd3d& |jd4d5d6d7d |jd8dd9d& |d:}tj	t
rp|jd;d<d=d> |jd?dd@d& |jdAddBd& |S )CNz%prog [options] input ...)progversionZusage)r  r   r  r   zmax-line-lengthzhang-closingrn   r  r  z	show-pep8zshow-source
statisticsr   z-vz	--verboser   rn   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  r
   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|  }|r|	 fddtD r }| jrtd   qtj \ }qZ|rtj|r| jrtd|  |	| |j}||rtdd |jD }	|g \}
}||D ]}|dd	|jvr2td
|  q
| jdkrVtd||||f  |d	d}|	| }|dv r|||}nF|dkr|||}|dkrt||}n|dv sJ |||}t|
|| q
|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 r   )r  r  r  )r   fnr  r,   r-   r     r   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	  rn   stringr  )r  r  )r)  F)r   configr  curdirUSER_CONFIGr  isfiler   r   r  r  commonprefixPROJECT_CONFIGrD   r  Zhas_sectionr  option_list
parse_argsr?  replacer  r   Zgetintr  Z
getbooleansetattrr  r   )r?  r0  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  sZ    





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stdd tD rdg}n
|d t||| |}|o|jdkot|_t|j|_t|j|_t|j|_t|j|_|jrBt|_t }t||j|d |_t|j}||fS )zProcess 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ConfigurationzThe 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 locationr  Nr   Fr  c                 s   s   | ]}t j|V  qd S r   )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  r  _parse_multi_optionsr   r  r  r  r   r  r  r  r  r  )r  r  r  r  r%   r?  r0  r   r,   r,   r-   r    sH    



r  rX   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,   )r\   r  r,   r,   r-   r   A  r   z(_parse_multi_options.<locals>.<listcomp>N)rD   )r?  Zsplit_tokenr,   r,   r-   r  6  s    
r  c                  C   s   t d ddl} z| | jdd  W n ty:   Y n0 tdd}|j}|jsX|jrnddl	m
} ||}n| }|jr|  |jr|  |jr|js|  |jr|jrt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  r   z_main.<locals>.<lambda>T)r  )	run_testsr2   r"   )warningswarnsignalSIGPIPEAttributeErrorr>  r?  r  r   Ztestsuite.supportr  r  r  r  Z	benchmarkr  r  Zprint_resultsr~  rn   r   stderrwriter   r  )r   Z	pep8styler?  r  rL  r,   r,   r-   _mainF  s0    	

r  __main__)Nr  )T)N)NFNN)rX   )r6  Z
__future__r   r  r   r  r  r'  r   r~   r  Zoptparser   r   Zconfigparserr   ior   ImportErrorZConfigParser__version__r  r  platformr  
expanduserr  r  getenvr  r  __file__r  r  r  re  	frozensetr   kwlistr   r   r   unionr   r   rm   r   r|   INDENTDEDENTrX  r   
ERRORTOKENr   r  rd  r#   r   r   r4  rP   rZ   r   r   r   r   rb   r   r   r  rl  r   sendrq  r.   r1   r9   r=   rK   rR   ra   rf   rp   rt   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  r   Ir   rC   r}   r  r  r  r  r  r"  r,  r+  r8  r:  objectr;  rx  r  r  r  r>  r  r  r  r  r  rJ  r,   r,   r,   r-   <module>   s  














&%  H \1)29''"



	

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