pep8.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  1. #!/usr/bin/env python
  2. # pep8.py - Check Python source code formatting, according to PEP 8
  3. # Copyright (C) 2006 Johann C. Rocholl <johann@rocholl.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person
  6. # obtaining a copy of this software and associated documentation files
  7. # (the "Software"), to deal in the Software without restriction,
  8. # including without limitation the rights to use, copy, modify, merge,
  9. # publish, distribute, sublicense, and/or sell copies of the Software,
  10. # and to permit persons to whom the Software is furnished to do so,
  11. # subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be
  14. # included in all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  20. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  21. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. # SOFTWARE.
  24. r"""
  25. Check Python source code formatting, according to PEP 8:
  26. http://www.python.org/dev/peps/pep-0008/
  27. For usage and a list of options, try this:
  28. $ python pep8.py -h
  29. This program and its regression test suite live here:
  30. http://github.com/jcrocholl/pep8
  31. Groups of errors and warnings:
  32. E errors
  33. W warnings
  34. 100 indentation
  35. 200 whitespace
  36. 300 blank lines
  37. 400 imports
  38. 500 line length
  39. 600 deprecation
  40. 700 statements
  41. 900 syntax error
  42. You can add checks to this program by writing plugins. Each plugin is
  43. a simple function that is called for each line of source code, either
  44. physical or logical.
  45. Physical line:
  46. - Raw line of text from the input file.
  47. Logical line:
  48. - Multi-line statements converted to a single line.
  49. - Stripped left and right.
  50. - Contents of strings replaced with 'xxx' of same length.
  51. - Comments removed.
  52. The check function requests physical or logical lines by the name of
  53. the first argument:
  54. def maximum_line_length(physical_line)
  55. def extraneous_whitespace(logical_line)
  56. def blank_lines(logical_line, blank_lines, indent_level, line_number)
  57. The last example above demonstrates how check plugins can request
  58. additional information with extra arguments. All attributes of the
  59. Checker object are available. Some examples:
  60. lines: a list of the raw lines from the input file
  61. tokens: the tokens that contribute to this logical line
  62. line_number: line number in the input file
  63. blank_lines: blank lines before this one
  64. indent_char: first indentation character in this file (' ' or '\t')
  65. indent_level: indentation (with tabs expanded to multiples of 8)
  66. previous_indent_level: indentation on previous line
  67. previous_logical: previous logical line
  68. The docstring of each check function shall be the relevant part of
  69. text from PEP 8. It is printed if the user enables --show-pep8.
  70. Several docstrings contain examples directly from the PEP 8 document.
  71. Okay: spam(ham[1], {eggs: 2})
  72. E201: spam( ham[1], {eggs: 2})
  73. These examples are verified automatically when pep8.py is run with the
  74. --doctest option. You can add examples for your own check functions.
  75. The format is simple: "Okay" or error/warning code followed by colon
  76. and space, the rest of the line is example source code. If you put 'r'
  77. before the docstring, you can use \n for newline, \t for tab and \s
  78. for space.
  79. """
  80. __version__ = '1.3.3'
  81. import os
  82. import sys
  83. import re
  84. import time
  85. import inspect
  86. import keyword
  87. import tokenize
  88. from optparse import OptionParser
  89. from fnmatch import fnmatch
  90. try:
  91. from configparser import RawConfigParser
  92. from io import TextIOWrapper
  93. except ImportError:
  94. from ConfigParser import RawConfigParser
  95. DEFAULT_EXCLUDE = '.svn,CVS,.bzr,.hg,.git'
  96. DEFAULT_IGNORE = 'E24'
  97. if sys.platform == 'win32':
  98. DEFAULT_CONFIG = os.path.expanduser(r'~\.pep8')
  99. else:
  100. DEFAULT_CONFIG = os.path.join(os.getenv('XDG_CONFIG_HOME') or
  101. os.path.expanduser('~/.config'), 'pep8')
  102. MAX_LINE_LENGTH = 79
  103. REPORT_FORMAT = {
  104. 'default': '%(path)s:%(row)d:%(col)d: %(code)s %(text)s',
  105. 'pylint': '%(path)s:%(row)d: [%(code)s] %(text)s',
  106. }
  107. SINGLETONS = frozenset(['False', 'None', 'True'])
  108. KEYWORDS = frozenset(keyword.kwlist + ['print']) - SINGLETONS
  109. BINARY_OPERATORS = frozenset([
  110. '**=', '*=', '+=', '-=', '!=', '<>',
  111. '%=', '^=', '&=', '|=', '==', '/=', '//=', '<=', '>=', '<<=', '>>=',
  112. '%', '^', '&', '|', '=', '/', '//', '<', '>', '<<'])
  113. UNARY_OPERATORS = frozenset(['>>', '**', '*', '+', '-'])
  114. OPERATORS = BINARY_OPERATORS | UNARY_OPERATORS
  115. WHITESPACE = frozenset(' \t')
  116. SKIP_TOKENS = frozenset([tokenize.COMMENT, tokenize.NL, tokenize.NEWLINE,
  117. tokenize.INDENT, tokenize.DEDENT])
  118. BENCHMARK_KEYS = ['directories', 'files', 'logical lines', 'physical lines']
  119. INDENT_REGEX = re.compile(r'([ \t]*)')
  120. RAISE_COMMA_REGEX = re.compile(r'raise\s+\w+\s*(,)')
  121. RERAISE_COMMA_REGEX = re.compile(r'raise\s+\w+\s*,\s*\w+\s*,\s*\w+')
  122. SELFTEST_REGEX = re.compile(r'(Okay|[EW]\d{3}):\s(.*)')
  123. ERRORCODE_REGEX = re.compile(r'[EW]\d{3}')
  124. DOCSTRING_REGEX = re.compile(r'u?r?["\']')
  125. EXTRANEOUS_WHITESPACE_REGEX = re.compile(r'[[({] | []}),;:]')
  126. WHITESPACE_AFTER_COMMA_REGEX = re.compile(r'[,;:]\s*(?: |\t)')
  127. COMPARE_SINGLETON_REGEX = re.compile(r'([=!]=)\s*(None|False|True)')
  128. COMPARE_TYPE_REGEX = re.compile(r'([=!]=|is|is\s+not)\s*type(?:s\.(\w+)Type'
  129. r'|\(\s*(\(\s*\)|[^)]*[^ )])\s*\))')
  130. KEYWORD_REGEX = re.compile(r'(?:[^\s])(\s*)\b(?:%s)\b(\s*)' %
  131. r'|'.join(KEYWORDS))
  132. OPERATOR_REGEX = re.compile(r'(?:[^\s])(\s*)(?:[-+*/|!<=>%&^]+)(\s*)')
  133. LAMBDA_REGEX = re.compile(r'\blambda\b')
  134. HUNK_REGEX = re.compile(r'^@@ -\d+,\d+ \+(\d+),(\d+) @@.*$')
  135. # Work around Python < 2.6 behaviour, which does not generate NL after
  136. # a comment which is on a line by itself.
  137. COMMENT_WITH_NL = tokenize.generate_tokens(['#\n'].pop).send(None)[1] == '#\n'
  138. ##############################################################################
  139. # Plugins (check functions) for physical lines
  140. ##############################################################################
  141. def tabs_or_spaces(physical_line, indent_char):
  142. r"""
  143. Never mix tabs and spaces.
  144. The most popular way of indenting Python is with spaces only. The
  145. second-most popular way is with tabs only. Code indented with a mixture
  146. of tabs and spaces should be converted to using spaces exclusively. When
  147. invoking the Python command line interpreter with the -t option, it issues
  148. warnings about code that illegally mixes tabs and spaces. When using -tt
  149. these warnings become errors. These options are highly recommended!
  150. Okay: if a == 0:\n a = 1\n b = 1
  151. E101: if a == 0:\n a = 1\n\tb = 1
  152. """
  153. indent = INDENT_REGEX.match(physical_line).group(1)
  154. for offset, char in enumerate(indent):
  155. if char != indent_char:
  156. return offset, "E101 indentation contains mixed spaces and tabs"
  157. def tabs_obsolete(physical_line):
  158. r"""
  159. For new projects, spaces-only are strongly recommended over tabs. Most
  160. editors have features that make this easy to do.
  161. Okay: if True:\n return
  162. W191: if True:\n\treturn
  163. """
  164. indent = INDENT_REGEX.match(physical_line).group(1)
  165. if '\t' in indent:
  166. return indent.index('\t'), "W191 indentation contains tabs"
  167. def trailing_whitespace(physical_line):
  168. r"""
  169. JCR: Trailing whitespace is superfluous.
  170. FBM: Except when it occurs as part of a blank line (i.e. the line is
  171. nothing but whitespace). According to Python docs[1] a line with only
  172. whitespace is considered a blank line, and is to be ignored. However,
  173. matching a blank line to its indentation level avoids mistakenly
  174. terminating a multi-line statement (e.g. class declaration) when
  175. pasting code into the standard Python interpreter.
  176. [1] http://docs.python.org/reference/lexical_analysis.html#blank-lines
  177. The warning returned varies on whether the line itself is blank, for easier
  178. filtering for those who want to indent their blank lines.
  179. Okay: spam(1)
  180. W291: spam(1)\s
  181. W293: class Foo(object):\n \n bang = 12
  182. """
  183. physical_line = physical_line.rstrip('\n') # chr(10), newline
  184. physical_line = physical_line.rstrip('\r') # chr(13), carriage return
  185. physical_line = physical_line.rstrip('\x0c') # chr(12), form feed, ^L
  186. stripped = physical_line.rstrip(' \t\v')
  187. if physical_line != stripped:
  188. if stripped:
  189. return len(stripped), "W291 trailing whitespace"
  190. else:
  191. return 0, "W293 blank line contains whitespace"
  192. def trailing_blank_lines(physical_line, lines, line_number):
  193. r"""
  194. JCR: Trailing blank lines are superfluous.
  195. Okay: spam(1)
  196. W391: spam(1)\n
  197. """
  198. if not physical_line.rstrip() and line_number == len(lines):
  199. return 0, "W391 blank line at end of file"
  200. def missing_newline(physical_line):
  201. """
  202. JCR: The last line should have a newline.
  203. Reports warning W292.
  204. """
  205. if physical_line.rstrip() == physical_line:
  206. return len(physical_line), "W292 no newline at end of file"
  207. def maximum_line_length(physical_line, max_line_length):
  208. """
  209. Limit all lines to a maximum of 79 characters.
  210. There are still many devices around that are limited to 80 character
  211. lines; plus, limiting windows to 80 characters makes it possible to have
  212. several windows side-by-side. The default wrapping on such devices looks
  213. ugly. Therefore, please limit all lines to a maximum of 79 characters.
  214. For flowing long blocks of text (docstrings or comments), limiting the
  215. length to 72 characters is recommended.
  216. Reports error E501.
  217. """
  218. line = physical_line.rstrip()
  219. length = len(line)
  220. if length > max_line_length:
  221. if hasattr(line, 'decode'): # Python 2
  222. # The line could contain multi-byte characters
  223. try:
  224. length = len(line.decode('utf-8'))
  225. except UnicodeError:
  226. pass
  227. if length > max_line_length:
  228. return (max_line_length, "E501 line too long "
  229. "(%d > %d characters)" % (length, max_line_length))
  230. ##############################################################################
  231. # Plugins (check functions) for logical lines
  232. ##############################################################################
  233. def blank_lines(logical_line, blank_lines, indent_level, line_number,
  234. previous_logical, previous_indent_level):
  235. r"""
  236. Separate top-level function and class definitions with two blank lines.
  237. Method definitions inside a class are separated by a single blank line.
  238. Extra blank lines may be used (sparingly) to separate groups of related
  239. functions. Blank lines may be omitted between a bunch of related
  240. one-liners (e.g. a set of dummy implementations).
  241. Use blank lines in functions, sparingly, to indicate logical sections.
  242. Okay: def a():\n pass\n\n\ndef b():\n pass
  243. Okay: def a():\n pass\n\n\n# Foo\n# Bar\n\ndef b():\n pass
  244. E301: class Foo:\n b = 0\n def bar():\n pass
  245. E302: def a():\n pass\n\ndef b(n):\n pass
  246. E303: def a():\n pass\n\n\n\ndef b(n):\n pass
  247. E303: def a():\n\n\n\n pass
  248. E304: @decorator\n\ndef a():\n pass
  249. """
  250. if line_number == 1:
  251. return # Don't expect blank lines before the first line
  252. if previous_logical.startswith('@'):
  253. if blank_lines:
  254. yield 0, "E304 blank lines found after function decorator"
  255. elif blank_lines > 2 or (indent_level and blank_lines == 2):
  256. yield 0, "E303 too many blank lines (%d)" % blank_lines
  257. elif logical_line.startswith(('def ', 'class ', '@')):
  258. if indent_level:
  259. if not (blank_lines or previous_indent_level < indent_level or
  260. DOCSTRING_REGEX.match(previous_logical)):
  261. yield 0, "E301 expected 1 blank line, found 0"
  262. elif blank_lines != 2:
  263. yield 0, "E302 expected 2 blank lines, found %d" % blank_lines
  264. def extraneous_whitespace(logical_line):
  265. """
  266. Avoid extraneous whitespace in the following situations:
  267. - Immediately inside parentheses, brackets or braces.
  268. - Immediately before a comma, semicolon, or colon.
  269. Okay: spam(ham[1], {eggs: 2})
  270. E201: spam( ham[1], {eggs: 2})
  271. E201: spam(ham[ 1], {eggs: 2})
  272. E201: spam(ham[1], { eggs: 2})
  273. E202: spam(ham[1], {eggs: 2} )
  274. E202: spam(ham[1 ], {eggs: 2})
  275. E202: spam(ham[1], {eggs: 2 })
  276. E203: if x == 4: print x, y; x, y = y , x
  277. E203: if x == 4: print x, y ; x, y = y, x
  278. E203: if x == 4 : print x, y; x, y = y, x
  279. """
  280. line = logical_line
  281. for match in EXTRANEOUS_WHITESPACE_REGEX.finditer(line):
  282. text = match.group()
  283. char = text.strip()
  284. found = match.start()
  285. if text == char + ' ':
  286. # assert char in '([{'
  287. yield found + 1, "E201 whitespace after '%s'" % char
  288. elif line[found - 1] != ',':
  289. code = ('E202' if char in '}])' else 'E203') # if char in ',;:'
  290. yield found, "%s whitespace before '%s'" % (code, char)
  291. def whitespace_around_keywords(logical_line):
  292. r"""
  293. Avoid extraneous whitespace around keywords.
  294. Okay: True and False
  295. E271: True and False
  296. E272: True and False
  297. E273: True and\tFalse
  298. E274: True\tand False
  299. """
  300. for match in KEYWORD_REGEX.finditer(logical_line):
  301. before, after = match.groups()
  302. if '\t' in before:
  303. yield match.start(1), "E274 tab before keyword"
  304. elif len(before) > 1:
  305. yield match.start(1), "E272 multiple spaces before keyword"
  306. if '\t' in after:
  307. yield match.start(2), "E273 tab after keyword"
  308. elif len(after) > 1:
  309. yield match.start(2), "E271 multiple spaces after keyword"
  310. def missing_whitespace(logical_line):
  311. """
  312. JCR: Each comma, semicolon or colon should be followed by whitespace.
  313. Okay: [a, b]
  314. Okay: (3,)
  315. Okay: a[1:4]
  316. Okay: a[:4]
  317. Okay: a[1:]
  318. Okay: a[1:4:2]
  319. E231: ['a','b']
  320. E231: foo(bar,baz)
  321. """
  322. line = logical_line
  323. for index in range(len(line) - 1):
  324. char = line[index]
  325. if char in ',;:' and line[index + 1] not in WHITESPACE:
  326. before = line[:index]
  327. if char == ':' and before.count('[') > before.count(']'):
  328. continue # Slice syntax, no space required
  329. if char == ',' and line[index + 1] == ')':
  330. continue # Allow tuple with only one element: (3,)
  331. yield index, "E231 missing whitespace after '%s'" % char
  332. def indentation(logical_line, previous_logical, indent_char,
  333. indent_level, previous_indent_level):
  334. r"""
  335. Use 4 spaces per indentation level.
  336. For really old code that you don't want to mess up, you can continue to
  337. use 8-space tabs.
  338. Okay: a = 1
  339. Okay: if a == 0:\n a = 1
  340. E111: a = 1
  341. Okay: for item in items:\n pass
  342. E112: for item in items:\npass
  343. Okay: a = 1\nb = 2
  344. E113: a = 1\n b = 2
  345. """
  346. if indent_char == ' ' and indent_level % 4:
  347. yield 0, "E111 indentation is not a multiple of four"
  348. indent_expect = previous_logical.endswith(':')
  349. if indent_expect and indent_level <= previous_indent_level:
  350. yield 0, "E112 expected an indented block"
  351. if indent_level > previous_indent_level and not indent_expect:
  352. yield 0, "E113 unexpected indentation"
  353. def continuation_line_indentation(logical_line, tokens, indent_level, verbose):
  354. r"""
  355. Continuation lines should align wrapped elements either vertically using
  356. Python's implicit line joining inside parentheses, brackets and braces, or
  357. using a hanging indent.
  358. When using a hanging indent the following considerations should be applied:
  359. - there should be no arguments on the first line, and
  360. - further indentation should be used to clearly distinguish itself as a
  361. continuation line.
  362. Okay: a = (\n)
  363. E123: a = (\n )
  364. Okay: a = (\n 42)
  365. E121: a = (\n 42)
  366. E122: a = (\n42)
  367. E123: a = (\n 42\n )
  368. E124: a = (24,\n 42\n)
  369. E125: if (a or\n b):\n pass
  370. E126: a = (\n 42)
  371. E127: a = (24,\n 42)
  372. E128: a = (24,\n 42)
  373. """
  374. first_row = tokens[0][2][0]
  375. nrows = 1 + tokens[-1][2][0] - first_row
  376. if nrows == 1:
  377. return
  378. # indent_next tells us whether the next block is indented; assuming
  379. # that it is indented by 4 spaces, then we should not allow 4-space
  380. # indents on the final continuation line; in turn, some other
  381. # indents are allowed to have an extra 4 spaces.
  382. indent_next = logical_line.endswith(':')
  383. row = depth = 0
  384. # remember how many brackets were opened on each line
  385. parens = [0] * nrows
  386. # relative indents of physical lines
  387. rel_indent = [0] * nrows
  388. # visual indents
  389. indent = [indent_level]
  390. indent_chances = {}
  391. last_indent = (0, 0)
  392. if verbose >= 3:
  393. print(">>> " + tokens[0][4].rstrip())
  394. for token_type, text, start, end, line in tokens:
  395. newline = row < start[0] - first_row
  396. if newline:
  397. row = start[0] - first_row
  398. newline = (not last_token_multiline and
  399. token_type not in (tokenize.NL, tokenize.NEWLINE))
  400. if newline:
  401. # this is the beginning of a continuation line.
  402. last_indent = start
  403. if verbose >= 3:
  404. print("... " + line.rstrip())
  405. # record the initial indent.
  406. rel_indent[row] = start[1] - indent_level
  407. if depth:
  408. # a bracket expression in a continuation line.
  409. # find the line that it was opened on
  410. for open_row in range(row - 1, -1, -1):
  411. if parens[open_row]:
  412. break
  413. else:
  414. # an unbracketed continuation line (ie, backslash)
  415. open_row = 0
  416. hang = rel_indent[row] - rel_indent[open_row]
  417. visual_indent = indent_chances.get(start[1])
  418. if token_type == tokenize.OP and text in ']})':
  419. # this line starts with a closing bracket
  420. if indent[depth]:
  421. if start[1] != indent[depth]:
  422. yield (start, 'E124 closing bracket does not match '
  423. 'visual indentation')
  424. elif hang:
  425. yield (start, 'E123 closing bracket does not match '
  426. 'indentation of opening bracket\'s line')
  427. elif visual_indent is True:
  428. # visual indent is verified
  429. if not indent[depth]:
  430. indent[depth] = start[1]
  431. elif visual_indent in (text, str):
  432. # ignore token lined up with matching one from a previous line
  433. pass
  434. elif indent[depth] and start[1] < indent[depth]:
  435. # visual indent is broken
  436. yield (start, 'E128 continuation line '
  437. 'under-indented for visual indent')
  438. elif hang == 4 or (indent_next and rel_indent[row] == 8):
  439. # hanging indent is verified
  440. pass
  441. else:
  442. # indent is broken
  443. if hang <= 0:
  444. error = 'E122', 'missing indentation or outdented'
  445. elif indent[depth]:
  446. error = 'E127', 'over-indented for visual indent'
  447. elif hang % 4:
  448. error = 'E121', 'indentation is not a multiple of four'
  449. else:
  450. error = 'E126', 'over-indented for hanging indent'
  451. yield start, "%s continuation line %s" % error
  452. # look for visual indenting
  453. if parens[row] and token_type != tokenize.NL and not indent[depth]:
  454. indent[depth] = start[1]
  455. indent_chances[start[1]] = True
  456. if verbose >= 4:
  457. print("bracket depth %s indent to %s" % (depth, start[1]))
  458. # deal with implicit string concatenation
  459. elif token_type == tokenize.STRING or text in ('u', 'ur', 'b', 'br'):
  460. indent_chances[start[1]] = str
  461. # keep track of bracket depth
  462. if token_type == tokenize.OP:
  463. if text in '([{':
  464. depth += 1
  465. indent.append(0)
  466. parens[row] += 1
  467. if verbose >= 4:
  468. print("bracket depth %s seen, col %s, visual min = %s" %
  469. (depth, start[1], indent[depth]))
  470. elif text in ')]}' and depth > 0:
  471. # parent indents should not be more than this one
  472. prev_indent = indent.pop() or last_indent[1]
  473. for d in range(depth):
  474. if indent[d] > prev_indent:
  475. indent[d] = 0
  476. for ind in list(indent_chances):
  477. if ind >= prev_indent:
  478. del indent_chances[ind]
  479. depth -= 1
  480. if depth:
  481. indent_chances[indent[depth]] = True
  482. for idx in range(row, -1, -1):
  483. if parens[idx]:
  484. parens[idx] -= 1
  485. break
  486. assert len(indent) == depth + 1
  487. if start[1] not in indent_chances:
  488. # allow to line up tokens
  489. indent_chances[start[1]] = text
  490. last_token_multiline = (start[0] != end[0])
  491. if indent_next and rel_indent[-1] == 4:
  492. yield (last_indent, "E125 continuation line does not distinguish "
  493. "itself from next logical line")
  494. def whitespace_before_parameters(logical_line, tokens):
  495. """
  496. Avoid extraneous whitespace in the following situations:
  497. - Immediately before the open parenthesis that starts the argument
  498. list of a function call.
  499. - Immediately before the open parenthesis that starts an indexing or
  500. slicing.
  501. Okay: spam(1)
  502. E211: spam (1)
  503. Okay: dict['key'] = list[index]
  504. E211: dict ['key'] = list[index]
  505. E211: dict['key'] = list [index]
  506. """
  507. prev_type = tokens[0][0]
  508. prev_text = tokens[0][1]
  509. prev_end = tokens[0][3]
  510. for index in range(1, len(tokens)):
  511. token_type, text, start, end, line = tokens[index]
  512. if (token_type == tokenize.OP and
  513. text in '([' and
  514. start != prev_end and
  515. (prev_type == tokenize.NAME or prev_text in '}])') and
  516. # Syntax "class A (B):" is allowed, but avoid it
  517. (index < 2 or tokens[index - 2][1] != 'class') and
  518. # Allow "return (a.foo for a in range(5))"
  519. not keyword.iskeyword(prev_text)):
  520. yield prev_end, "E211 whitespace before '%s'" % text
  521. prev_type = token_type
  522. prev_text = text
  523. prev_end = end
  524. def whitespace_around_operator(logical_line):
  525. r"""
  526. Avoid extraneous whitespace in the following situations:
  527. - More than one space around an assignment (or other) operator to
  528. align it with another.
  529. Okay: a = 12 + 3
  530. E221: a = 4 + 5
  531. E222: a = 4 + 5
  532. E223: a = 4\t+ 5
  533. E224: a = 4 +\t5
  534. """
  535. for match in OPERATOR_REGEX.finditer(logical_line):
  536. before, after = match.groups()
  537. if '\t' in before:
  538. yield match.start(1), "E223 tab before operator"
  539. elif len(before) > 1:
  540. yield match.start(1), "E221 multiple spaces before operator"
  541. if '\t' in after:
  542. yield match.start(2), "E224 tab after operator"
  543. elif len(after) > 1:
  544. yield match.start(2), "E222 multiple spaces after operator"
  545. def missing_whitespace_around_operator(logical_line, tokens):
  546. r"""
  547. - Always surround these binary operators with a single space on
  548. either side: assignment (=), augmented assignment (+=, -= etc.),
  549. comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not),
  550. Booleans (and, or, not).
  551. - Use spaces around arithmetic operators.
  552. Okay: i = i + 1
  553. Okay: submitted += 1
  554. Okay: x = x * 2 - 1
  555. Okay: hypot2 = x * x + y * y
  556. Okay: c = (a + b) * (a - b)
  557. Okay: foo(bar, key='word', *args, **kwargs)
  558. Okay: baz(**kwargs)
  559. Okay: negative = -1
  560. Okay: spam(-1)
  561. Okay: alpha[:-i]
  562. Okay: if not -5 < x < +5:\n pass
  563. Okay: lambda *args, **kw: (args, kw)
  564. E225: i=i+1
  565. E225: submitted +=1
  566. E225: x = x*2 - 1
  567. E225: hypot2 = x*x + y*y
  568. E225: c = (a+b) * (a-b)
  569. E225: c = alpha -4
  570. E225: z = x **y
  571. """
  572. parens = 0
  573. need_space = False
  574. prev_type = tokenize.OP
  575. prev_text = prev_end = None
  576. for token_type, text, start, end, line in tokens:
  577. if token_type in (tokenize.NL, tokenize.NEWLINE, tokenize.ERRORTOKEN):
  578. # ERRORTOKEN is triggered by backticks in Python 3000
  579. continue
  580. if text in ('(', 'lambda'):
  581. parens += 1
  582. elif text == ')':
  583. parens -= 1
  584. if need_space:
  585. if start != prev_end:
  586. need_space = False
  587. elif text == '>' and prev_text in ('<', '-'):
  588. # Tolerate the "<>" operator, even if running Python 3
  589. # Deal with Python 3's annotated return value "->"
  590. pass
  591. else:
  592. yield prev_end, "E225 missing whitespace around operator"
  593. need_space = False
  594. elif token_type == tokenize.OP and prev_end is not None:
  595. if text == '=' and parens:
  596. # Allow keyword args or defaults: foo(bar=None).
  597. pass
  598. elif text in BINARY_OPERATORS:
  599. need_space = True
  600. elif text in UNARY_OPERATORS:
  601. # Allow unary operators: -123, -x, +1.
  602. # Allow argument unpacking: foo(*args, **kwargs).
  603. if prev_type == tokenize.OP:
  604. if prev_text in '}])':
  605. need_space = True
  606. elif prev_type == tokenize.NAME:
  607. if prev_text not in KEYWORDS:
  608. need_space = True
  609. elif prev_type not in SKIP_TOKENS:
  610. need_space = True
  611. if need_space and start == prev_end:
  612. yield prev_end, "E225 missing whitespace around operator"
  613. need_space = False
  614. prev_type = token_type
  615. prev_text = text
  616. prev_end = end
  617. def whitespace_around_comma(logical_line):
  618. r"""
  619. Avoid extraneous whitespace in the following situations:
  620. - More than one space around an assignment (or other) operator to
  621. align it with another.
  622. Note: these checks are disabled by default
  623. Okay: a = (1, 2)
  624. E241: a = (1, 2)
  625. E242: a = (1,\t2)
  626. """
  627. line = logical_line
  628. for m in WHITESPACE_AFTER_COMMA_REGEX.finditer(line):
  629. found = m.start() + 1
  630. if '\t' in m.group():
  631. yield found, "E242 tab after '%s'" % m.group()[0]
  632. else:
  633. yield found, "E241 multiple spaces after '%s'" % m.group()[0]
  634. def whitespace_around_named_parameter_equals(logical_line, tokens):
  635. """
  636. Don't use spaces around the '=' sign when used to indicate a
  637. keyword argument or a default parameter value.
  638. Okay: def complex(real, imag=0.0):
  639. Okay: return magic(r=real, i=imag)
  640. Okay: boolean(a == b)
  641. Okay: boolean(a != b)
  642. Okay: boolean(a <= b)
  643. Okay: boolean(a >= b)
  644. E251: def complex(real, imag = 0.0):
  645. E251: return magic(r = real, i = imag)
  646. """
  647. parens = 0
  648. no_space = False
  649. prev_end = None
  650. for token_type, text, start, end, line in tokens:
  651. if no_space:
  652. no_space = False
  653. if start != prev_end:
  654. yield (prev_end,
  655. "E251 no spaces around keyword / parameter equals")
  656. elif token_type == tokenize.OP:
  657. if text == '(':
  658. parens += 1
  659. elif text == ')':
  660. parens -= 1
  661. elif parens and text == '=':
  662. no_space = True
  663. if start != prev_end:
  664. yield (prev_end,
  665. "E251 no spaces around keyword / parameter equals")
  666. prev_end = end
  667. def whitespace_before_inline_comment(logical_line, tokens):
  668. """
  669. Separate inline comments by at least two spaces.
  670. An inline comment is a comment on the same line as a statement. Inline
  671. comments should be separated by at least two spaces from the statement.
  672. They should start with a # and a single space.
  673. Okay: x = x + 1 # Increment x
  674. Okay: x = x + 1 # Increment x
  675. E261: x = x + 1 # Increment x
  676. E262: x = x + 1 #Increment x
  677. E262: x = x + 1 # Increment x
  678. """
  679. prev_end = (0, 0)
  680. for token_type, text, start, end, line in tokens:
  681. if token_type == tokenize.COMMENT:
  682. if not line[:start[1]].strip():
  683. continue
  684. if prev_end[0] == start[0] and start[1] < prev_end[1] + 2:
  685. yield (prev_end,
  686. "E261 at least two spaces before inline comment")
  687. if text.startswith('# ') or not text.startswith('# '):
  688. yield start, "E262 inline comment should start with '# '"
  689. elif token_type != tokenize.NL:
  690. prev_end = end
  691. def imports_on_separate_lines(logical_line):
  692. r"""
  693. Imports should usually be on separate lines.
  694. Okay: import os\nimport sys
  695. E401: import sys, os
  696. Okay: from subprocess import Popen, PIPE
  697. Okay: from myclas import MyClass
  698. Okay: from foo.bar.yourclass import YourClass
  699. Okay: import myclass
  700. Okay: import foo.bar.yourclass
  701. """
  702. line = logical_line
  703. if line.startswith('import '):
  704. found = line.find(',')
  705. if -1 < found:
  706. yield found, "E401 multiple imports on one line"
  707. def compound_statements(logical_line):
  708. r"""
  709. Compound statements (multiple statements on the same line) are
  710. generally discouraged.
  711. While sometimes it's okay to put an if/for/while with a small body
  712. on the same line, never do this for multi-clause statements. Also
  713. avoid folding such long lines!
  714. Okay: if foo == 'blah':\n do_blah_thing()
  715. Okay: do_one()
  716. Okay: do_two()
  717. Okay: do_three()
  718. E701: if foo == 'blah': do_blah_thing()
  719. E701: for x in lst: total += x
  720. E701: while t < 10: t = delay()
  721. E701: if foo == 'blah': do_blah_thing()
  722. E701: else: do_non_blah_thing()
  723. E701: try: something()
  724. E701: finally: cleanup()
  725. E701: if foo == 'blah': one(); two(); three()
  726. E702: do_one(); do_two(); do_three()
  727. """
  728. line = logical_line
  729. found = line.find(':')
  730. if -1 < found < len(line) - 1:
  731. before = line[:found]
  732. if (before.count('{') <= before.count('}') and # {'a': 1} (dict)
  733. before.count('[') <= before.count(']') and # [1:2] (slice)
  734. before.count('(') <= before.count(')') and # (Python 3 annotation)
  735. not LAMBDA_REGEX.search(before)): # lambda x: x
  736. yield found, "E701 multiple statements on one line (colon)"
  737. found = line.find(';')
  738. if -1 < found:
  739. yield found, "E702 multiple statements on one line (semicolon)"
  740. def explicit_line_join(logical_line, tokens):
  741. r"""
  742. Avoid explicit line join between brackets.
  743. The preferred way of wrapping long lines is by using Python's implied line
  744. continuation inside parentheses, brackets and braces. Long lines can be
  745. broken over multiple lines by wrapping expressions in parentheses. These
  746. should be used in preference to using a backslash for line continuation.
  747. E502: aaa = [123, \\n 123]
  748. E502: aaa = ("bbb " \\n "ccc")
  749. Okay: aaa = [123,\n 123]
  750. Okay: aaa = ("bbb "\n "ccc")
  751. Okay: aaa = "bbb " \\n "ccc"
  752. """
  753. prev_start = prev_end = parens = 0
  754. for token_type, text, start, end, line in tokens:
  755. if start[0] != prev_start and parens and backslash:
  756. yield backslash, "E502 the backslash is redundant between brackets"
  757. if end[0] != prev_end:
  758. if line.rstrip('\r\n').endswith('\\'):
  759. backslash = (end[0], len(line.splitlines()[-1]) - 1)
  760. else:
  761. backslash = None
  762. prev_start = prev_end = end[0]
  763. else:
  764. prev_start = start[0]
  765. if token_type == tokenize.OP:
  766. if text in '([{':
  767. parens += 1
  768. elif text in ')]}':
  769. parens -= 1
  770. def comparison_to_singleton(logical_line):
  771. """
  772. Comparisons to singletons like None should always be done
  773. with "is" or "is not", never the equality operators.
  774. Okay: if arg is not None:
  775. E711: if arg != None:
  776. E712: if arg == True:
  777. Also, beware of writing if x when you really mean if x is not None --
  778. e.g. when testing whether a variable or argument that defaults to None was
  779. set to some other value. The other value might have a type (such as a
  780. container) that could be false in a boolean context!
  781. """
  782. match = COMPARE_SINGLETON_REGEX.search(logical_line)
  783. if match:
  784. same = (match.group(1) == '==')
  785. singleton = match.group(2)
  786. msg = "'if cond is %s:'" % (('' if same else 'not ') + singleton)
  787. if singleton in ('None',):
  788. code = 'E711'
  789. else:
  790. code = 'E712'
  791. nonzero = ((singleton == 'True' and same) or
  792. (singleton == 'False' and not same))
  793. msg += " or 'if %scond:'" % ('' if nonzero else 'not ')
  794. yield match.start(1), ("%s comparison to %s should be %s" %
  795. (code, singleton, msg))
  796. def comparison_type(logical_line):
  797. """
  798. Object type comparisons should always use isinstance() instead of
  799. comparing types directly.
  800. Okay: if isinstance(obj, int):
  801. E721: if type(obj) is type(1):
  802. When checking if an object is a string, keep in mind that it might be a
  803. unicode string too! In Python 2.3, str and unicode have a common base
  804. class, basestring, so you can do:
  805. Okay: if isinstance(obj, basestring):
  806. Okay: if type(a1) is type(b1):
  807. """
  808. match = COMPARE_TYPE_REGEX.search(logical_line)
  809. if match:
  810. inst = match.group(3)
  811. if inst and isidentifier(inst) and inst not in SINGLETONS:
  812. return # Allow comparison for types which are not obvious
  813. yield match.start(1), "E721 do not compare types, use 'isinstance()'"
  814. def python_3000_has_key(logical_line):
  815. r"""
  816. The {}.has_key() method will be removed in the future version of
  817. Python. Use the 'in' operation instead.
  818. Okay: if "alph" in d:\n print d["alph"]
  819. W601: assert d.has_key('alph')
  820. """
  821. pos = logical_line.find('.has_key(')
  822. if pos > -1:
  823. yield pos, "W601 .has_key() is deprecated, use 'in'"
  824. def python_3000_raise_comma(logical_line):
  825. """
  826. When raising an exception, use "raise ValueError('message')"
  827. instead of the older form "raise ValueError, 'message'".
  828. The paren-using form is preferred because when the exception arguments
  829. are long or include string formatting, you don't need to use line
  830. continuation characters thanks to the containing parentheses. The older
  831. form will be removed in Python 3000.
  832. Okay: raise DummyError("Message")
  833. W602: raise DummyError, "Message"
  834. """
  835. match = RAISE_COMMA_REGEX.match(logical_line)
  836. if match and not RERAISE_COMMA_REGEX.match(logical_line):
  837. yield match.start(1), "W602 deprecated form of raising exception"
  838. def python_3000_not_equal(logical_line):
  839. """
  840. != can also be written <>, but this is an obsolete usage kept for
  841. backwards compatibility only. New code should always use !=.
  842. The older syntax is removed in Python 3000.
  843. Okay: if a != 'no':
  844. W603: if a <> 'no':
  845. """
  846. pos = logical_line.find('<>')
  847. if pos > -1:
  848. yield pos, "W603 '<>' is deprecated, use '!='"
  849. def python_3000_backticks(logical_line):
  850. """
  851. Backticks are removed in Python 3000.
  852. Use repr() instead.
  853. Okay: val = repr(1 + 2)
  854. W604: val = `1 + 2`
  855. """
  856. pos = logical_line.find('`')
  857. if pos > -1:
  858. yield pos, "W604 backticks are deprecated, use 'repr()'"
  859. ##############################################################################
  860. # Helper functions
  861. ##############################################################################
  862. if '' == ''.encode():
  863. # Python 2: implicit encoding.
  864. def readlines(filename):
  865. f = open(filename)
  866. try:
  867. return f.readlines()
  868. finally:
  869. f.close()
  870. isidentifier = re.compile(r'[a-zA-Z_]\w*').match
  871. stdin_get_value = sys.stdin.read
  872. else:
  873. # Python 3
  874. def readlines(filename):
  875. f = open(filename, 'rb')
  876. try:
  877. coding, lines = tokenize.detect_encoding(f.readline)
  878. f = TextIOWrapper(f, coding, line_buffering=True)
  879. return [l.decode(coding) for l in lines] + f.readlines()
  880. except (LookupError, SyntaxError, UnicodeError):
  881. f.close()
  882. # Fall back if files are improperly declared
  883. f = open(filename, encoding='latin-1')
  884. return f.readlines()
  885. finally:
  886. f.close()
  887. isidentifier = str.isidentifier
  888. stdin_get_value = TextIOWrapper(sys.stdin.buffer, errors='ignore').read
  889. readlines.__doc__ = " Read the source code."
  890. def expand_indent(line):
  891. r"""
  892. Return the amount of indentation.
  893. Tabs are expanded to the next multiple of 8.
  894. >>> expand_indent(' ')
  895. 4
  896. >>> expand_indent('\t')
  897. 8
  898. >>> expand_indent(' \t')
  899. 8
  900. >>> expand_indent(' \t')
  901. 8
  902. >>> expand_indent(' \t')
  903. 16
  904. """
  905. if '\t' not in line:
  906. return len(line) - len(line.lstrip())
  907. result = 0
  908. for char in line:
  909. if char == '\t':
  910. result = result // 8 * 8 + 8
  911. elif char == ' ':
  912. result += 1
  913. else:
  914. break
  915. return result
  916. def mute_string(text):
  917. """
  918. Replace contents with 'xxx' to prevent syntax matching.
  919. >>> mute_string('"abc"')
  920. '"xxx"'
  921. >>> mute_string("'''abc'''")
  922. "'''xxx'''"
  923. >>> mute_string("r'abc'")
  924. "r'xxx'"
  925. """
  926. # String modifiers (e.g. u or r)
  927. start = text.index(text[-1]) + 1
  928. end = len(text) - 1
  929. # Triple quotes
  930. if text[-3:] in ('"""', "'''"):
  931. start += 2
  932. end -= 2
  933. return text[:start] + 'x' * (end - start) + text[end:]
  934. def parse_udiff(diff, patterns=None, parent='.'):
  935. rv = {}
  936. path = nrows = None
  937. for line in diff.splitlines():
  938. if nrows:
  939. if line[:1] != '-':
  940. nrows -= 1
  941. continue
  942. if line[:3] == '@@ ':
  943. row, nrows = [int(g) for g in HUNK_REGEX.match(line).groups()]
  944. rv[path].update(range(row, row + nrows))
  945. elif line[:3] == '+++':
  946. path = line[4:].split('\t', 1)[0]
  947. if path[:2] == 'b/':
  948. path = path[2:]
  949. rv[path] = set()
  950. return dict([(os.path.join(parent, path), rows)
  951. for (path, rows) in rv.items()
  952. if rows and filename_match(path, patterns)])
  953. def filename_match(filename, patterns, default=True):
  954. """
  955. Check if patterns contains a pattern that matches filename.
  956. If patterns is unspecified, this always returns True.
  957. """
  958. if not patterns:
  959. return default
  960. return any(fnmatch(filename, pattern) for pattern in patterns)
  961. ##############################################################################
  962. # Framework to run all checks
  963. ##############################################################################
  964. def find_checks(argument_name):
  965. """
  966. Find all globally visible functions where the first argument name
  967. starts with argument_name.
  968. """
  969. for name, function in globals().items():
  970. if not inspect.isfunction(function):
  971. continue
  972. args = inspect.getargspec(function)[0]
  973. if args and args[0].startswith(argument_name):
  974. codes = ERRORCODE_REGEX.findall(function.__doc__ or '')
  975. yield name, codes, function, args
  976. class Checker(object):
  977. """
  978. Load a Python source file, tokenize it, check coding style.
  979. """
  980. def __init__(self, filename, lines=None,
  981. options=None, report=None, **kwargs):
  982. if options is None:
  983. options = StyleGuide(kwargs).options
  984. else:
  985. assert not kwargs
  986. self._io_error = None
  987. self._physical_checks = options.physical_checks
  988. self._logical_checks = options.logical_checks
  989. self.max_line_length = options.max_line_length
  990. self.verbose = options.verbose
  991. self.filename = filename
  992. if filename is None:
  993. self.filename = 'stdin'
  994. self.lines = lines or []
  995. elif lines is None:
  996. try:
  997. self.lines = readlines(filename)
  998. except IOError:
  999. exc_type, exc = sys.exc_info()[:2]
  1000. self._io_error = '%s: %s' % (exc_type.__name__, exc)
  1001. self.lines = []
  1002. else:
  1003. self.lines = lines
  1004. self.report = report or options.report
  1005. self.report_error = self.report.error
  1006. def readline(self):
  1007. """
  1008. Get the next line from the input buffer.
  1009. """
  1010. self.line_number += 1
  1011. if self.line_number > len(self.lines):
  1012. return ''
  1013. return self.lines[self.line_number - 1]
  1014. def readline_check_physical(self):
  1015. """
  1016. Check and return the next physical line. This method can be
  1017. used to feed tokenize.generate_tokens.
  1018. """
  1019. line = self.readline()
  1020. if line:
  1021. self.check_physical(line)
  1022. return line
  1023. def run_check(self, check, argument_names):
  1024. """
  1025. Run a check plugin.
  1026. """
  1027. arguments = []
  1028. for name in argument_names:
  1029. arguments.append(getattr(self, name))
  1030. return check(*arguments)
  1031. def check_physical(self, line):
  1032. """
  1033. Run all physical checks on a raw input line.
  1034. """
  1035. self.physical_line = line
  1036. if self.indent_char is None and line[:1] in WHITESPACE:
  1037. self.indent_char = line[0]
  1038. for name, check, argument_names in self._physical_checks:
  1039. result = self.run_check(check, argument_names)
  1040. if result is not None:
  1041. offset, text = result
  1042. self.report_error(self.line_number, offset, text, check)
  1043. def build_tokens_line(self):
  1044. """
  1045. Build a logical line from tokens.
  1046. """
  1047. self.mapping = []
  1048. logical = []
  1049. length = 0
  1050. previous = None
  1051. for token in self.tokens:
  1052. token_type, text = token[0:2]
  1053. if token_type in SKIP_TOKENS:
  1054. continue
  1055. if token_type == tokenize.STRING:
  1056. text = mute_string(text)
  1057. if previous:
  1058. end_row, end = previous[3]
  1059. start_row, start = token[2]
  1060. if end_row != start_row: # different row
  1061. prev_text = self.lines[end_row - 1][end - 1]
  1062. if prev_text == ',' or (prev_text not in '{[('
  1063. and text not in '}])'):
  1064. logical.append(' ')
  1065. length += 1
  1066. elif end != start: # different column
  1067. fill = self.lines[end_row - 1][end:start]
  1068. logical.append(fill)
  1069. length += len(fill)
  1070. self.mapping.append((length, token))
  1071. logical.append(text)
  1072. length += len(text)
  1073. previous = token
  1074. self.logical_line = ''.join(logical)
  1075. assert self.logical_line.strip() == self.logical_line
  1076. def check_logical(self):
  1077. """
  1078. Build a line from tokens and run all logical checks on it.
  1079. """
  1080. self.build_tokens_line()
  1081. self.report.increment_logical_line()
  1082. first_line = self.lines[self.mapping[0][1][2][0] - 1]
  1083. indent = first_line[:self.mapping[0][1][2][1]]
  1084. self.previous_indent_level = self.indent_level
  1085. self.indent_level = expand_indent(indent)
  1086. if self.verbose >= 2:
  1087. print(self.logical_line[:80].rstrip())
  1088. for name, check, argument_names in self._logical_checks:
  1089. if self.verbose >= 4:
  1090. print(' ' + name)
  1091. for result in self.run_check(check, argument_names):
  1092. offset, text = result
  1093. if isinstance(offset, tuple):
  1094. orig_number, orig_offset = offset
  1095. else:
  1096. for token_offset, token in self.mapping:
  1097. if offset >= token_offset:
  1098. orig_number = token[2][0]
  1099. orig_offset = (token[2][1] + offset - token_offset)
  1100. self.report_error(orig_number, orig_offset, text, check)
  1101. self.previous_logical = self.logical_line
  1102. def generate_tokens(self):
  1103. if self._io_error:
  1104. self.report_error(1, 0, 'E902 %s' % self._io_error, readlines)
  1105. tokengen = tokenize.generate_tokens(self.readline_check_physical)
  1106. try:
  1107. for token in tokengen:
  1108. yield token
  1109. except (SyntaxError, tokenize.TokenError):
  1110. exc_type, exc = sys.exc_info()[:2]
  1111. offset = exc.args[1]
  1112. if len(offset) > 2:
  1113. offset = offset[1:3]
  1114. self.report_error(offset[0], offset[1],
  1115. 'E901 %s: %s' % (exc_type.__name__, exc.args[0]),
  1116. self.generate_tokens)
  1117. generate_tokens.__doc__ = " Check if the syntax is valid."
  1118. def check_all(self, expected=None, line_offset=0):
  1119. """
  1120. Run all checks on the input file.
  1121. """
  1122. self.report.init_file(self.filename, self.lines, expected, line_offset)
  1123. self.line_number = 0
  1124. self.indent_char = None
  1125. self.indent_level = 0
  1126. self.previous_logical = ''
  1127. self.tokens = []
  1128. self.blank_lines = blank_lines_before_comment = 0
  1129. parens = 0
  1130. for token in self.generate_tokens():
  1131. self.tokens.append(token)
  1132. token_type, text = token[0:2]
  1133. if self.verbose >= 3:
  1134. if token[2][0] == token[3][0]:
  1135. pos = '[%s:%s]' % (token[2][1] or '', token[3][1])
  1136. else:
  1137. pos = 'l.%s' % token[3][0]
  1138. print('l.%s\t%s\t%s\t%r' %
  1139. (token[2][0], pos, tokenize.tok_name[token[0]], text))
  1140. if token_type == tokenize.OP:
  1141. if text in '([{':
  1142. parens += 1
  1143. elif text in '}])':
  1144. parens -= 1
  1145. elif not parens:
  1146. if token_type == tokenize.NEWLINE:
  1147. if self.blank_lines < blank_lines_before_comment:
  1148. self.blank_lines = blank_lines_before_comment
  1149. self.check_logical()
  1150. self.tokens = []
  1151. self.blank_lines = blank_lines_before_comment = 0
  1152. elif token_type == tokenize.NL:
  1153. if len(self.tokens) == 1:
  1154. # The physical line contains only this token.
  1155. self.blank_lines += 1
  1156. self.tokens = []
  1157. elif token_type == tokenize.COMMENT and len(self.tokens) == 1:
  1158. if blank_lines_before_comment < self.blank_lines:
  1159. blank_lines_before_comment = self.blank_lines
  1160. self.blank_lines = 0
  1161. if COMMENT_WITH_NL:
  1162. # The comment also ends a physical line
  1163. self.tokens = []
  1164. return self.report.get_file_results()
  1165. class BaseReport(object):
  1166. """Collect the results of the checks."""
  1167. print_filename = False
  1168. def __init__(self, options):
  1169. self._benchmark_keys = options.benchmark_keys
  1170. self._ignore_code = options.ignore_code
  1171. # Results
  1172. self.elapsed = 0
  1173. self.total_errors = 0
  1174. self.counters = dict.fromkeys(self._benchmark_keys, 0)
  1175. self.messages = {}
  1176. def start(self):
  1177. """Start the timer."""
  1178. self._start_time = time.time()
  1179. def stop(self):
  1180. """Stop the timer."""
  1181. self.elapsed = time.time() - self._start_time
  1182. def init_file(self, filename, lines, expected, line_offset):
  1183. """Signal a new file."""
  1184. self.filename = filename
  1185. self.lines = lines
  1186. self.expected = expected or ()
  1187. self.line_offset = line_offset
  1188. self.file_errors = 0
  1189. self.counters['files'] += 1
  1190. self.counters['physical lines'] += len(lines)
  1191. def increment_logical_line(self):
  1192. """Signal a new logical line."""
  1193. self.counters['logical lines'] += 1
  1194. def error(self, line_number, offset, text, check):
  1195. """Report an error, according to options."""
  1196. code = text[:4]
  1197. if self._ignore_code(code):
  1198. return
  1199. if code in self.counters:
  1200. self.counters[code] += 1
  1201. else:
  1202. self.counters[code] = 1
  1203. self.messages[code] = text[5:]
  1204. # Don't care about expected errors or warnings
  1205. if code in self.expected:
  1206. return
  1207. if self.print_filename and not self.file_errors:
  1208. print(self.filename)
  1209. self.file_errors += 1
  1210. self.total_errors += 1
  1211. return code
  1212. def get_file_results(self):
  1213. """Return the count of errors and warnings for this file."""
  1214. return self.file_errors
  1215. def get_count(self, prefix=''):
  1216. """Return the total count of errors and warnings."""
  1217. return sum([self.counters[key]
  1218. for key in self.messages if key.startswith(prefix)])
  1219. def get_statistics(self, prefix=''):
  1220. """
  1221. Get statistics for message codes that start with the prefix.
  1222. prefix='' matches all errors and warnings
  1223. prefix='E' matches all errors
  1224. prefix='W' matches all warnings
  1225. prefix='E4' matches all errors that have to do with imports
  1226. """
  1227. return ['%-7s %s %s' % (self.counters[key], key, self.messages[key])
  1228. for key in sorted(self.messages) if key.startswith(prefix)]
  1229. def print_statistics(self, prefix=''):
  1230. """Print overall statistics (number of errors and warnings)."""
  1231. for line in self.get_statistics(prefix):
  1232. print(line)
  1233. def print_benchmark(self):
  1234. """Print benchmark numbers."""
  1235. print('%-7.2f %s' % (self.elapsed, 'seconds elapsed'))
  1236. if self.elapsed:
  1237. for key in self._benchmark_keys:
  1238. print('%-7d %s per second (%d total)' %
  1239. (self.counters[key] / self.elapsed, key,
  1240. self.counters[key]))
  1241. class FileReport(BaseReport):
  1242. print_filename = True
  1243. class StandardReport(BaseReport):
  1244. """Collect and print the results of the checks."""
  1245. def __init__(self, options):
  1246. super(StandardReport, self).__init__(options)
  1247. self._fmt = REPORT_FORMAT.get(options.format.lower(),
  1248. options.format)
  1249. self._repeat = options.repeat
  1250. self._show_source = options.show_source
  1251. self._show_pep8 = options.show_pep8
  1252. def error(self, line_number, offset, text, check):
  1253. """
  1254. Report an error, according to options.
  1255. """
  1256. code = super(StandardReport, self).error(line_number, offset,
  1257. text, check)
  1258. if code and (self.counters[code] == 1 or self._repeat):
  1259. print(self._fmt % {
  1260. 'path': self.filename,
  1261. 'row': self.line_offset + line_number, 'col': offset + 1,
  1262. 'code': code, 'text': text[5:],
  1263. })
  1264. if self._show_source:
  1265. if line_number > len(self.lines):
  1266. line = ''
  1267. else:
  1268. line = self.lines[line_number - 1]
  1269. print(line.rstrip())
  1270. print(' ' * offset + '^')
  1271. if self._show_pep8:
  1272. print(check.__doc__.lstrip('\n').rstrip())
  1273. return code
  1274. class DiffReport(StandardReport):
  1275. """Collect and print the results for the changed lines only."""
  1276. def __init__(self, options):
  1277. super(DiffReport, self).__init__(options)
  1278. self._selected = options.selected_lines
  1279. def error(self, line_number, offset, text, check):
  1280. if line_number not in self._selected[self.filename]:
  1281. return
  1282. return super(DiffReport, self).error(line_number, offset, text, check)
  1283. class TestReport(StandardReport):
  1284. """Collect the results for the tests."""
  1285. def __init__(self, options):
  1286. options.benchmark_keys += ['test cases', 'failed tests']
  1287. super(TestReport, self).__init__(options)
  1288. self._verbose = options.verbose
  1289. def get_file_results(self):
  1290. # Check if the expected errors were found
  1291. label = '%s:%s:1' % (self.filename, self.line_offset)
  1292. codes = sorted(self.expected)
  1293. for code in codes:
  1294. if not self.counters.get(code):
  1295. self.file_errors += 1
  1296. self.total_errors += 1
  1297. print('%s: error %s not found' % (label, code))
  1298. if self._verbose and not self.file_errors:
  1299. print('%s: passed (%s)' %
  1300. (label, ' '.join(codes) or 'Okay'))
  1301. self.counters['test cases'] += 1
  1302. if self.file_errors:
  1303. self.counters['failed tests'] += 1
  1304. # Reset counters
  1305. for key in set(self.counters) - set(self._benchmark_keys):
  1306. del self.counters[key]
  1307. self.messages = {}
  1308. return self.file_errors
  1309. def print_results(self):
  1310. results = ("%(physical lines)d lines tested: %(files)d files, "
  1311. "%(test cases)d test cases%%s." % self.counters)
  1312. if self.total_errors:
  1313. print(results % ", %s failures" % self.total_errors)
  1314. else:
  1315. print(results % "")
  1316. print("Test failed." if self.total_errors else "Test passed.")
  1317. class StyleGuide(object):
  1318. """Initialize a PEP-8 instance with few options."""
  1319. def __init__(self, *args, **kwargs):
  1320. # build options from the command line
  1321. parse_argv = kwargs.pop('parse_argv', False)
  1322. config_file = kwargs.pop('config_file', None)
  1323. options, self.paths = process_options(parse_argv=parse_argv,
  1324. config_file=config_file)
  1325. if args or kwargs:
  1326. # build options from dict
  1327. options_dict = dict(*args, **kwargs)
  1328. options.__dict__.update(options_dict)
  1329. if 'paths' in options_dict:
  1330. self.paths = options_dict['paths']
  1331. self.runner = self.input_file
  1332. self.options = options
  1333. if not options.reporter:
  1334. options.reporter = BaseReport if options.quiet else StandardReport
  1335. for index, value in enumerate(options.exclude):
  1336. options.exclude[index] = value.rstrip('/')
  1337. # Ignore all checks which are not explicitly selected
  1338. options.select = tuple(options.select or ())
  1339. options.ignore = tuple(options.ignore or options.select and ('',))
  1340. options.benchmark_keys = BENCHMARK_KEYS[:]
  1341. options.ignore_code = self.ignore_code
  1342. options.physical_checks = self.get_checks('physical_line')
  1343. options.logical_checks = self.get_checks('logical_line')
  1344. self.init_report()
  1345. def init_report(self, reporter=None):
  1346. """Initialize the report instance."""
  1347. self.options.report = (reporter or self.options.reporter)(self.options)
  1348. return self.options.report
  1349. def check_files(self, paths=None):
  1350. """Run all checks on the paths."""
  1351. if paths is None:
  1352. paths = self.paths
  1353. report = self.options.report
  1354. runner = self.runner
  1355. report.start()
  1356. for path in paths:
  1357. if os.path.isdir(path):
  1358. self.input_dir(path)
  1359. elif not self.excluded(path):
  1360. runner(path)
  1361. report.stop()
  1362. return report
  1363. def input_file(self, filename, lines=None, expected=None, line_offset=0):
  1364. """Run all checks on a Python source file."""
  1365. if self.options.verbose:
  1366. print('checking %s' % filename)
  1367. fchecker = Checker(filename, lines=lines, options=self.options)
  1368. return fchecker.check_all(expected=expected, line_offset=line_offset)
  1369. def input_dir(self, dirname):
  1370. """Check all files in this directory and all subdirectories."""
  1371. dirname = dirname.rstrip('/')
  1372. if self.excluded(dirname):
  1373. return 0
  1374. counters = self.options.report.counters
  1375. verbose = self.options.verbose
  1376. filepatterns = self.options.filename
  1377. runner = self.runner
  1378. for root, dirs, files in os.walk(dirname):
  1379. if verbose:
  1380. print('directory ' + root)
  1381. counters['directories'] += 1
  1382. for subdir in sorted(dirs):
  1383. if self.excluded(subdir):
  1384. dirs.remove(subdir)
  1385. for filename in sorted(files):
  1386. # contain a pattern that matches?
  1387. if ((filename_match(filename, filepatterns) and
  1388. not self.excluded(filename))):
  1389. runner(os.path.join(root, filename))
  1390. def excluded(self, filename):
  1391. """
  1392. Check if options.exclude contains a pattern that matches filename.
  1393. """
  1394. basename = os.path.basename(filename)
  1395. return filename_match(basename, self.options.exclude, default=False)
  1396. def ignore_code(self, code):
  1397. """
  1398. Check if the error code should be ignored.
  1399. If 'options.select' contains a prefix of the error code,
  1400. return False. Else, if 'options.ignore' contains a prefix of
  1401. the error code, return True.
  1402. """
  1403. return (code.startswith(self.options.ignore) and
  1404. not code.startswith(self.options.select))
  1405. def get_checks(self, argument_name):
  1406. """
  1407. Find all globally visible functions where the first argument name
  1408. starts with argument_name and which contain selected tests.
  1409. """
  1410. checks = []
  1411. for name, codes, function, args in find_checks(argument_name):
  1412. if any(not (code and self.ignore_code(code)) for code in codes):
  1413. checks.append((name, function, args))
  1414. return sorted(checks)
  1415. def init_tests(pep8style):
  1416. """
  1417. Initialize testing framework.
  1418. A test file can provide many tests. Each test starts with a
  1419. declaration. This declaration is a single line starting with '#:'.
  1420. It declares codes of expected failures, separated by spaces or 'Okay'
  1421. if no failure is expected.
  1422. If the file does not contain such declaration, it should pass all
  1423. tests. If the declaration is empty, following lines are not checked,
  1424. until next declaration.
  1425. Examples:
  1426. * Only E224 and W701 are expected: #: E224 W701
  1427. * Following example is conform: #: Okay
  1428. * Don't check these lines: #:
  1429. """
  1430. report = pep8style.init_report(TestReport)
  1431. runner = pep8style.input_file
  1432. def run_tests(filename):
  1433. """Run all the tests from a file."""
  1434. lines = readlines(filename) + ['#:\n']
  1435. line_offset = 0
  1436. codes = ['Okay']
  1437. testcase = []
  1438. count_files = report.counters['files']
  1439. for index, line in enumerate(lines):
  1440. if not line.startswith('#:'):
  1441. if codes:
  1442. # Collect the lines of the test case
  1443. testcase.append(line)
  1444. continue
  1445. if codes and index:
  1446. codes = [c for c in codes if c != 'Okay']
  1447. # Run the checker
  1448. runner(filename, testcase, expected=codes,
  1449. line_offset=line_offset)
  1450. # output the real line numbers
  1451. line_offset = index + 1
  1452. # configure the expected errors
  1453. codes = line.split()[1:]
  1454. # empty the test case buffer
  1455. del testcase[:]
  1456. report.counters['files'] = count_files + 1
  1457. return report.counters['failed tests']
  1458. pep8style.runner = run_tests
  1459. def selftest(options):
  1460. """
  1461. Test all check functions with test cases in docstrings.
  1462. """
  1463. count_failed = count_all = 0
  1464. report = BaseReport(options)
  1465. counters = report.counters
  1466. checks = options.physical_checks + options.logical_checks
  1467. for name, check, argument_names in checks:
  1468. for line in check.__doc__.splitlines():
  1469. line = line.lstrip()
  1470. match = SELFTEST_REGEX.match(line)
  1471. if match is None:
  1472. continue
  1473. code, source = match.groups()
  1474. checker = Checker(None, options=options, report=report)
  1475. for part in source.split(r'\n'):
  1476. part = part.replace(r'\t', '\t')
  1477. part = part.replace(r'\s', ' ')
  1478. checker.lines.append(part + '\n')
  1479. checker.check_all()
  1480. error = None
  1481. if code == 'Okay':
  1482. if len(counters) > len(options.benchmark_keys):
  1483. codes = [key for key in counters
  1484. if key not in options.benchmark_keys]
  1485. error = "incorrectly found %s" % ', '.join(codes)
  1486. elif not counters.get(code):
  1487. error = "failed to find %s" % code
  1488. # Keep showing errors for multiple tests
  1489. for key in set(counters) - set(options.benchmark_keys):
  1490. del counters[key]
  1491. report.messages = {}
  1492. count_all += 1
  1493. if not error:
  1494. if options.verbose:
  1495. print("%s: %s" % (code, source))
  1496. else:
  1497. count_failed += 1
  1498. print("%s: %s:" % (__file__, error))
  1499. for line in checker.lines:
  1500. print(line.rstrip())
  1501. return count_failed, count_all
  1502. def read_config(options, args, arglist, parser):
  1503. """Read both user configuration and local configuration."""
  1504. config = RawConfigParser()
  1505. user_conf = options.config
  1506. if user_conf and os.path.isfile(user_conf):
  1507. if options.verbose:
  1508. print('user configuration: %s' % user_conf)
  1509. config.read(user_conf)
  1510. parent = tail = args and os.path.abspath(os.path.commonprefix(args))
  1511. while tail:
  1512. local_conf = os.path.join(parent, '.pep8')
  1513. if os.path.isfile(local_conf):
  1514. if options.verbose:
  1515. print('local configuration: %s' % local_conf)
  1516. config.read(local_conf)
  1517. break
  1518. parent, tail = os.path.split(parent)
  1519. if config.has_section('pep8'):
  1520. option_list = dict([(o.dest, o.type or o.action)
  1521. for o in parser.option_list])
  1522. # First, read the default values
  1523. new_options, _ = parser.parse_args([])
  1524. # Second, parse the configuration
  1525. for opt in config.options('pep8'):
  1526. if options.verbose > 1:
  1527. print(' %s = %s' % (opt, config.get('pep8', opt)))
  1528. if opt.replace('_', '-') not in parser.config_options:
  1529. print('Unknown option: \'%s\'\n not in [%s]' %
  1530. (opt, ' '.join(parser.config_options)))
  1531. sys.exit(1)
  1532. normalized_opt = opt.replace('-', '_')
  1533. opt_type = option_list[normalized_opt]
  1534. if opt_type in ('int', 'count'):
  1535. value = config.getint('pep8', opt)
  1536. elif opt_type == 'string':
  1537. value = config.get('pep8', opt)
  1538. else:
  1539. assert opt_type in ('store_true', 'store_false')
  1540. value = config.getboolean('pep8', opt)
  1541. setattr(new_options, normalized_opt, value)
  1542. # Third, overwrite with the command-line options
  1543. options, _ = parser.parse_args(arglist, values=new_options)
  1544. return options
  1545. def process_options(arglist=None, parse_argv=False, config_file=None):
  1546. """Process options passed either via arglist or via command line args."""
  1547. if not arglist and not parse_argv:
  1548. # Don't read the command line if the module is used as a library.
  1549. arglist = []
  1550. if config_file is True:
  1551. config_file = DEFAULT_CONFIG
  1552. parser = OptionParser(version=__version__,
  1553. usage="%prog [options] input ...")
  1554. parser.config_options = [
  1555. 'exclude', 'filename', 'select', 'ignore', 'max-line-length', 'count',
  1556. 'format', 'quiet', 'show-pep8', 'show-source', 'statistics', 'verbose']
  1557. parser.add_option('-v', '--verbose', default=0, action='count',
  1558. help="print status messages, or debug with -vv")
  1559. parser.add_option('-q', '--quiet', default=0, action='count',
  1560. help="report only file names, or nothing with -qq")
  1561. parser.add_option('-r', '--repeat', default=True, action='store_true',
  1562. help="(obsolete) show all occurrences of the same error")
  1563. parser.add_option('--first', action='store_false', dest='repeat',
  1564. help="show first occurrence of each error")
  1565. parser.add_option('--exclude', metavar='patterns', default=DEFAULT_EXCLUDE,
  1566. help="exclude files or directories which match these "
  1567. "comma separated patterns (default: %default)")
  1568. parser.add_option('--filename', metavar='patterns', default='*.py',
  1569. help="when parsing directories, only check filenames "
  1570. "matching these comma separated patterns "
  1571. "(default: %default)")
  1572. parser.add_option('--select', metavar='errors', default='',
  1573. help="select errors and warnings (e.g. E,W6)")
  1574. parser.add_option('--ignore', metavar='errors', default='',
  1575. help="skip errors and warnings (e.g. E4,W)")
  1576. parser.add_option('--show-source', action='store_true',
  1577. help="show source code for each error")
  1578. parser.add_option('--show-pep8', action='store_true',
  1579. help="show text of PEP 8 for each error "
  1580. "(implies --first)")
  1581. parser.add_option('--statistics', action='store_true',
  1582. help="count errors and warnings")
  1583. parser.add_option('--count', action='store_true',
  1584. help="print total number of errors and warnings "
  1585. "to standard error and set exit code to 1 if "
  1586. "total is not null")
  1587. parser.add_option('--max-line-length', type='int', metavar='n',
  1588. default=MAX_LINE_LENGTH,
  1589. help="set maximum allowed line length "
  1590. "(default: %default)")
  1591. parser.add_option('--format', metavar='format', default='default',
  1592. help="set the error format [default|pylint|<custom>]")
  1593. parser.add_option('--diff', action='store_true',
  1594. help="report only lines changed according to the "
  1595. "unified diff received on STDIN")
  1596. group = parser.add_option_group("Testing Options")
  1597. group.add_option('--testsuite', metavar='dir',
  1598. help="run regression tests from dir")
  1599. group.add_option('--doctest', action='store_true',
  1600. help="run doctest on myself")
  1601. group.add_option('--benchmark', action='store_true',
  1602. help="measure processing speed")
  1603. group = parser.add_option_group("Configuration", description=(
  1604. "The project options are read from the [pep8] section of the .pep8 "
  1605. "file located in any parent folder of the path(s) being processed. "
  1606. "Allowed options are: %s." % ', '.join(parser.config_options)))
  1607. group.add_option('--config', metavar='path', default=config_file,
  1608. help="config file location (default: %default)")
  1609. options, args = parser.parse_args(arglist)
  1610. options.reporter = None
  1611. if options.testsuite:
  1612. args.append(options.testsuite)
  1613. elif not options.doctest:
  1614. if parse_argv and not args:
  1615. if os.path.exists('.pep8') or options.diff:
  1616. args = ['.']
  1617. else:
  1618. parser.error('input not specified')
  1619. options = read_config(options, args, arglist, parser)
  1620. options.reporter = parse_argv and options.quiet == 1 and FileReport
  1621. if options.filename:
  1622. options.filename = options.filename.split(',')
  1623. options.exclude = options.exclude.split(',')
  1624. if options.select:
  1625. options.select = options.select.split(',')
  1626. if options.ignore:
  1627. options.ignore = options.ignore.split(',')
  1628. elif not (options.select or
  1629. options.testsuite or options.doctest) and DEFAULT_IGNORE:
  1630. # The default choice: ignore controversial checks
  1631. # (for doctest and testsuite, all checks are required)
  1632. options.ignore = DEFAULT_IGNORE.split(',')
  1633. if options.diff:
  1634. options.reporter = DiffReport
  1635. stdin = stdin_get_value()
  1636. options.selected_lines = parse_udiff(stdin, options.filename, args[0])
  1637. args = sorted(options.selected_lines)
  1638. return options, args
  1639. def _main():
  1640. """Parse options and run checks on Python source."""
  1641. pep8style = StyleGuide(parse_argv=True, config_file=True)
  1642. options = pep8style.options
  1643. if options.doctest:
  1644. import doctest
  1645. fail_d, done_d = doctest.testmod(report=False, verbose=options.verbose)
  1646. fail_s, done_s = selftest(options)
  1647. count_failed = fail_s + fail_d
  1648. if not options.quiet:
  1649. count_passed = done_d + done_s - count_failed
  1650. print("%d passed and %d failed." % (count_passed, count_failed))
  1651. print("Test failed." if count_failed else "Test passed.")
  1652. if count_failed:
  1653. sys.exit(1)
  1654. if options.testsuite:
  1655. init_tests(pep8style)
  1656. report = pep8style.check_files()
  1657. if options.statistics:
  1658. report.print_statistics()
  1659. if options.benchmark:
  1660. report.print_benchmark()
  1661. if options.testsuite and not options.quiet:
  1662. report.print_results()
  1663. if report.total_errors:
  1664. if options.count:
  1665. sys.stderr.write(str(report.total_errors) + '\n')
  1666. sys.exit(1)
  1667. if __name__ == '__main__':
  1668. _main()