PageRenderTime 70ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/python/helpers/pydev/third_party/pep8/autopep8.py

http://github.com/JetBrains/intellij-community
Python | 3827 lines | 3787 code | 5 blank | 35 comment | 7 complexity | 2d5b239baef85c8d2be553f23f1cd584 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, MPL-2.0-no-copyleft-exception, MIT, EPL-1.0, AGPL-1.0
  1. #!/usr/bin/env python
  2. # Copyright (C) 2010-2011 Hideo Hattori
  3. # Copyright (C) 2011-2013 Hideo Hattori, Steven Myint
  4. # Copyright (C) 2013-2016 Hideo Hattori, Steven Myint, Bill Wendling
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining
  7. # a copy of this software and associated documentation files (the
  8. # "Software"), to deal in the Software without restriction, including
  9. # without limitation the rights to use, copy, modify, merge, publish,
  10. # distribute, sublicense, and/or sell copies of the Software, and to
  11. # permit persons to whom the Software is furnished to do so, subject to
  12. # the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be
  15. # included in all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  20. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  21. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  22. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  23. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. # SOFTWARE.
  25. """Automatically formats Python code to conform to the PEP 8 style guide.
  26. Fixes that only need be done once can be added by adding a function of the form
  27. "fix_<code>(source)" to this module. They should return the fixed source code.
  28. These fixes are picked up by apply_global_fixes().
  29. Fixes that depend on pycodestyle should be added as methods to FixPEP8. See the
  30. class documentation for more information.
  31. """
  32. from __future__ import absolute_import
  33. from __future__ import division
  34. from __future__ import print_function
  35. from __future__ import unicode_literals
  36. import codecs
  37. import collections
  38. import copy
  39. import difflib
  40. import fnmatch
  41. import inspect
  42. import io
  43. import keyword
  44. import locale
  45. import os
  46. import re
  47. import signal
  48. import sys
  49. import textwrap
  50. import token
  51. import tokenize
  52. import pycodestyle
  53. def check_lib2to3():
  54. try:
  55. import lib2to3
  56. except ImportError:
  57. sys.path.append(os.path.join(os.path.dirname(__file__), 'lib2to3'))
  58. import lib2to3
  59. try:
  60. unicode
  61. except NameError:
  62. unicode = str
  63. __version__ = '1.3'
  64. CR = '\r'
  65. LF = '\n'
  66. CRLF = '\r\n'
  67. PYTHON_SHEBANG_REGEX = re.compile(r'^#!.*\bpython[23]?\b\s*$')
  68. LAMBDA_REGEX = re.compile(r'([\w.]+)\s=\slambda\s*([\(\)\w,\s.]*):')
  69. COMPARE_NEGATIVE_REGEX = re.compile(r'\b(not)\s+([^][)(}{]+)\s+(in|is)\s')
  70. BARE_EXCEPT_REGEX = re.compile(r'except\s*:')
  71. STARTSWITH_DEF_REGEX = re.compile(r'^(async\s+def|def)\s.*\):')
  72. # For generating line shortening candidates.
  73. SHORTEN_OPERATOR_GROUPS = frozenset([
  74. frozenset([',']),
  75. frozenset(['%']),
  76. frozenset([',', '(', '[', '{']),
  77. frozenset(['%', '(', '[', '{']),
  78. frozenset([',', '(', '[', '{', '%', '+', '-', '*', '/', '//']),
  79. frozenset(['%', '+', '-', '*', '/', '//']),
  80. ])
  81. DEFAULT_IGNORE = 'E24,W503'
  82. DEFAULT_INDENT_SIZE = 4
  83. # W602 is handled separately due to the need to avoid "with_traceback".
  84. CODE_TO_2TO3 = {
  85. 'E231': ['ws_comma'],
  86. 'E721': ['idioms'],
  87. 'W601': ['has_key'],
  88. 'W603': ['ne'],
  89. 'W604': ['repr'],
  90. 'W690': ['apply',
  91. 'except',
  92. 'exitfunc',
  93. 'numliterals',
  94. 'operator',
  95. 'paren',
  96. 'reduce',
  97. 'renames',
  98. 'standarderror',
  99. 'sys_exc',
  100. 'throw',
  101. 'tuple_params',
  102. 'xreadlines']}
  103. if sys.platform == 'win32': # pragma: no cover
  104. DEFAULT_CONFIG = os.path.expanduser(r'~\.pep8')
  105. else:
  106. DEFAULT_CONFIG = os.path.join(os.getenv('XDG_CONFIG_HOME') or
  107. os.path.expanduser('~/.config'), 'pep8')
  108. PROJECT_CONFIG = ('setup.cfg', 'tox.ini', '.pep8')
  109. MAX_PYTHON_FILE_DETECTION_BYTES = 1024
  110. def open_with_encoding(filename,
  111. encoding=None, mode='r', limit_byte_check=-1):
  112. """Return opened file with a specific encoding."""
  113. if not encoding:
  114. encoding = detect_encoding(filename, limit_byte_check=limit_byte_check)
  115. return io.open(filename, mode=mode, encoding=encoding,
  116. newline='') # Preserve line endings
  117. def detect_encoding(filename, limit_byte_check=-1):
  118. """Return file encoding."""
  119. try:
  120. with open(filename, 'rb') as input_file:
  121. from lib2to3.pgen2 import tokenize as lib2to3_tokenize
  122. encoding = lib2to3_tokenize.detect_encoding(input_file.readline)[0]
  123. with open_with_encoding(filename, encoding) as test_file:
  124. test_file.read(limit_byte_check)
  125. return encoding
  126. except (LookupError, SyntaxError, UnicodeDecodeError):
  127. return 'latin-1'
  128. def readlines_from_file(filename):
  129. """Return contents of file."""
  130. with open_with_encoding(filename) as input_file:
  131. return input_file.readlines()
  132. def extended_blank_lines(logical_line,
  133. blank_lines,
  134. blank_before,
  135. indent_level,
  136. previous_logical):
  137. """Check for missing blank lines after class declaration."""
  138. if previous_logical.startswith('def '):
  139. if blank_lines and pycodestyle.DOCSTRING_REGEX.match(logical_line):
  140. yield (0, 'E303 too many blank lines ({0})'.format(blank_lines))
  141. elif pycodestyle.DOCSTRING_REGEX.match(previous_logical):
  142. # Missing blank line between class docstring and method declaration.
  143. if (
  144. indent_level and
  145. not blank_lines and
  146. not blank_before and
  147. logical_line.startswith(('def ')) and
  148. '(self' in logical_line
  149. ):
  150. yield (0, 'E301 expected 1 blank line, found 0')
  151. pycodestyle.register_check(extended_blank_lines)
  152. def continued_indentation(logical_line, tokens, indent_level, indent_char,
  153. noqa):
  154. """Override pycodestyle's function to provide indentation information."""
  155. first_row = tokens[0][2][0]
  156. nrows = 1 + tokens[-1][2][0] - first_row
  157. if noqa or nrows == 1:
  158. return
  159. # indent_next tells us whether the next block is indented. Assuming
  160. # that it is indented by 4 spaces, then we should not allow 4-space
  161. # indents on the final continuation line. In turn, some other
  162. # indents are allowed to have an extra 4 spaces.
  163. indent_next = logical_line.endswith(':')
  164. row = depth = 0
  165. valid_hangs = (
  166. (DEFAULT_INDENT_SIZE,)
  167. if indent_char != '\t' else (DEFAULT_INDENT_SIZE,
  168. 2 * DEFAULT_INDENT_SIZE)
  169. )
  170. # Remember how many brackets were opened on each line.
  171. parens = [0] * nrows
  172. # Relative indents of physical lines.
  173. rel_indent = [0] * nrows
  174. # For each depth, collect a list of opening rows.
  175. open_rows = [[0]]
  176. # For each depth, memorize the hanging indentation.
  177. hangs = [None]
  178. # Visual indents.
  179. indent_chances = {}
  180. last_indent = tokens[0][2]
  181. indent = [last_indent[1]]
  182. last_token_multiline = None
  183. line = None
  184. last_line = ''
  185. last_line_begins_with_multiline = False
  186. for token_type, text, start, end, line in tokens:
  187. newline = row < start[0] - first_row
  188. if newline:
  189. row = start[0] - first_row
  190. newline = (not last_token_multiline and
  191. token_type not in (tokenize.NL, tokenize.NEWLINE))
  192. last_line_begins_with_multiline = last_token_multiline
  193. if newline:
  194. # This is the beginning of a continuation line.
  195. last_indent = start
  196. # Record the initial indent.
  197. rel_indent[row] = pycodestyle.expand_indent(line) - indent_level
  198. # Identify closing bracket.
  199. close_bracket = (token_type == tokenize.OP and text in ']})')
  200. # Is the indent relative to an opening bracket line?
  201. for open_row in reversed(open_rows[depth]):
  202. hang = rel_indent[row] - rel_indent[open_row]
  203. hanging_indent = hang in valid_hangs
  204. if hanging_indent:
  205. break
  206. if hangs[depth]:
  207. hanging_indent = (hang == hangs[depth])
  208. visual_indent = (not close_bracket and hang > 0 and
  209. indent_chances.get(start[1]))
  210. if close_bracket and indent[depth]:
  211. # Closing bracket for visual indent.
  212. if start[1] != indent[depth]:
  213. yield (start, 'E124 {0}'.format(indent[depth]))
  214. elif close_bracket and not hang:
  215. pass
  216. elif indent[depth] and start[1] < indent[depth]:
  217. # Visual indent is broken.
  218. yield (start, 'E128 {0}'.format(indent[depth]))
  219. elif (hanging_indent or
  220. (indent_next and
  221. rel_indent[row] == 2 * DEFAULT_INDENT_SIZE)):
  222. # Hanging indent is verified.
  223. if close_bracket:
  224. yield (start, 'E123 {0}'.format(indent_level +
  225. rel_indent[open_row]))
  226. hangs[depth] = hang
  227. elif visual_indent is True:
  228. # Visual indent is verified.
  229. indent[depth] = start[1]
  230. elif visual_indent in (text, unicode):
  231. # Ignore token lined up with matching one from a previous line.
  232. pass
  233. else:
  234. one_indented = (indent_level + rel_indent[open_row] +
  235. DEFAULT_INDENT_SIZE)
  236. # Indent is broken.
  237. if hang <= 0:
  238. error = ('E122', one_indented)
  239. elif indent[depth]:
  240. error = ('E127', indent[depth])
  241. elif not close_bracket and hangs[depth]:
  242. error = ('E131', one_indented)
  243. elif hang > DEFAULT_INDENT_SIZE:
  244. error = ('E126', one_indented)
  245. else:
  246. hangs[depth] = hang
  247. error = ('E121', one_indented)
  248. yield (start, '{0} {1}'.format(*error))
  249. # Look for visual indenting.
  250. if (
  251. parens[row] and
  252. token_type not in (tokenize.NL, tokenize.COMMENT) and
  253. not indent[depth]
  254. ):
  255. indent[depth] = start[1]
  256. indent_chances[start[1]] = True
  257. # Deal with implicit string concatenation.
  258. elif (token_type in (tokenize.STRING, tokenize.COMMENT) or
  259. text in ('u', 'ur', 'b', 'br')):
  260. indent_chances[start[1]] = unicode
  261. # Special case for the "if" statement because len("if (") is equal to
  262. # 4.
  263. elif not indent_chances and not row and not depth and text == 'if':
  264. indent_chances[end[1] + 1] = True
  265. elif text == ':' and line[end[1]:].isspace():
  266. open_rows[depth].append(row)
  267. # Keep track of bracket depth.
  268. if token_type == tokenize.OP:
  269. if text in '([{':
  270. depth += 1
  271. indent.append(0)
  272. hangs.append(None)
  273. if len(open_rows) == depth:
  274. open_rows.append([])
  275. open_rows[depth].append(row)
  276. parens[row] += 1
  277. elif text in ')]}' and depth > 0:
  278. # Parent indents should not be more than this one.
  279. prev_indent = indent.pop() or last_indent[1]
  280. hangs.pop()
  281. for d in range(depth):
  282. if indent[d] > prev_indent:
  283. indent[d] = 0
  284. for ind in list(indent_chances):
  285. if ind >= prev_indent:
  286. del indent_chances[ind]
  287. del open_rows[depth + 1:]
  288. depth -= 1
  289. if depth:
  290. indent_chances[indent[depth]] = True
  291. for idx in range(row, -1, -1):
  292. if parens[idx]:
  293. parens[idx] -= 1
  294. break
  295. assert len(indent) == depth + 1
  296. if (
  297. start[1] not in indent_chances and
  298. # This is for purposes of speeding up E121 (GitHub #90).
  299. not last_line.rstrip().endswith(',')
  300. ):
  301. # Allow to line up tokens.
  302. indent_chances[start[1]] = text
  303. last_token_multiline = (start[0] != end[0])
  304. if last_token_multiline:
  305. rel_indent[end[0] - first_row] = rel_indent[row]
  306. last_line = line
  307. if (
  308. indent_next and
  309. not last_line_begins_with_multiline and
  310. pycodestyle.expand_indent(line) == indent_level + DEFAULT_INDENT_SIZE
  311. ):
  312. pos = (start[0], indent[0] + 4)
  313. desired_indent = indent_level + 2 * DEFAULT_INDENT_SIZE
  314. if visual_indent:
  315. yield (pos, 'E129 {0}'.format(desired_indent))
  316. else:
  317. yield (pos, 'E125 {0}'.format(desired_indent))
  318. del pycodestyle._checks['logical_line'][pycodestyle.continued_indentation]
  319. pycodestyle.register_check(continued_indentation)
  320. class FixPEP8(object):
  321. """Fix invalid code.
  322. Fixer methods are prefixed "fix_". The _fix_source() method looks for these
  323. automatically.
  324. The fixer method can take either one or two arguments (in addition to
  325. self). The first argument is "result", which is the error information from
  326. pycodestyle. The second argument, "logical", is required only for
  327. logical-line fixes.
  328. The fixer method can return the list of modified lines or None. An empty
  329. list would mean that no changes were made. None would mean that only the
  330. line reported in the pycodestyle error was modified. Note that the modified
  331. line numbers that are returned are indexed at 1. This typically would
  332. correspond with the line number reported in the pycodestyle error
  333. information.
  334. [fixed method list]
  335. - e111,e114,e115,e116
  336. - e121,e122,e123,e124,e125,e126,e127,e128,e129
  337. - e201,e202,e203
  338. - e211
  339. - e221,e222,e223,e224,e225
  340. - e231
  341. - e251
  342. - e261,e262
  343. - e271,e272,e273,e274
  344. - e301,e302,e303,e304,e306
  345. - e401
  346. - e502
  347. - e701,e702,e703,e704
  348. - e711,e712,e713,e714
  349. - e722
  350. - e731
  351. - w291
  352. - w503
  353. """
  354. def __init__(self, filename,
  355. options,
  356. contents=None,
  357. long_line_ignore_cache=None):
  358. self.filename = filename
  359. if contents is None:
  360. self.source = readlines_from_file(filename)
  361. else:
  362. sio = io.StringIO(contents)
  363. self.source = sio.readlines()
  364. self.options = options
  365. self.indent_word = _get_indentword(''.join(self.source))
  366. self.long_line_ignore_cache = (
  367. set() if long_line_ignore_cache is None
  368. else long_line_ignore_cache)
  369. # Many fixers are the same even though pycodestyle categorizes them
  370. # differently.
  371. self.fix_e115 = self.fix_e112
  372. self.fix_e116 = self.fix_e113
  373. self.fix_e121 = self._fix_reindent
  374. self.fix_e122 = self._fix_reindent
  375. self.fix_e123 = self._fix_reindent
  376. self.fix_e124 = self._fix_reindent
  377. self.fix_e126 = self._fix_reindent
  378. self.fix_e127 = self._fix_reindent
  379. self.fix_e128 = self._fix_reindent
  380. self.fix_e129 = self._fix_reindent
  381. self.fix_e202 = self.fix_e201
  382. self.fix_e203 = self.fix_e201
  383. self.fix_e211 = self.fix_e201
  384. self.fix_e221 = self.fix_e271
  385. self.fix_e222 = self.fix_e271
  386. self.fix_e223 = self.fix_e271
  387. self.fix_e226 = self.fix_e225
  388. self.fix_e227 = self.fix_e225
  389. self.fix_e228 = self.fix_e225
  390. self.fix_e241 = self.fix_e271
  391. self.fix_e242 = self.fix_e224
  392. self.fix_e261 = self.fix_e262
  393. self.fix_e272 = self.fix_e271
  394. self.fix_e273 = self.fix_e271
  395. self.fix_e274 = self.fix_e271
  396. self.fix_e306 = self.fix_e301
  397. self.fix_e501 = (
  398. self.fix_long_line_logically if
  399. options and (options.aggressive >= 2 or options.experimental) else
  400. self.fix_long_line_physically)
  401. self.fix_e703 = self.fix_e702
  402. self.fix_w293 = self.fix_w291
  403. def _fix_source(self, results):
  404. try:
  405. (logical_start, logical_end) = _find_logical(self.source)
  406. logical_support = True
  407. except (SyntaxError, tokenize.TokenError): # pragma: no cover
  408. logical_support = False
  409. completed_lines = set()
  410. for result in sorted(results, key=_priority_key):
  411. if result['line'] in completed_lines:
  412. continue
  413. fixed_methodname = 'fix_' + result['id'].lower()
  414. if hasattr(self, fixed_methodname):
  415. fix = getattr(self, fixed_methodname)
  416. line_index = result['line'] - 1
  417. original_line = self.source[line_index]
  418. is_logical_fix = len(_get_parameters(fix)) > 2
  419. if is_logical_fix:
  420. logical = None
  421. if logical_support:
  422. logical = _get_logical(self.source,
  423. result,
  424. logical_start,
  425. logical_end)
  426. if logical and set(range(
  427. logical[0][0] + 1,
  428. logical[1][0] + 1)).intersection(
  429. completed_lines):
  430. continue
  431. modified_lines = fix(result, logical)
  432. else:
  433. modified_lines = fix(result)
  434. if modified_lines is None:
  435. # Force logical fixes to report what they modified.
  436. assert not is_logical_fix
  437. if self.source[line_index] == original_line:
  438. modified_lines = []
  439. if modified_lines:
  440. completed_lines.update(modified_lines)
  441. elif modified_lines == []: # Empty list means no fix
  442. if self.options.verbose >= 2:
  443. print(
  444. '---> Not fixing {error} on line {line}'.format(
  445. error=result['id'], line=result['line']),
  446. file=sys.stderr)
  447. else: # We assume one-line fix when None.
  448. completed_lines.add(result['line'])
  449. else:
  450. if self.options.verbose >= 3:
  451. print(
  452. "---> '{0}' is not defined.".format(fixed_methodname),
  453. file=sys.stderr)
  454. info = result['info'].strip()
  455. print('---> {0}:{1}:{2}:{3}'.format(self.filename,
  456. result['line'],
  457. result['column'],
  458. info),
  459. file=sys.stderr)
  460. def fix(self):
  461. """Return a version of the source code with PEP 8 violations fixed."""
  462. pep8_options = {
  463. 'ignore': self.options.ignore,
  464. 'select': self.options.select,
  465. 'max_line_length': self.options.max_line_length,
  466. }
  467. results = _execute_pep8(pep8_options, self.source)
  468. if self.options.verbose:
  469. progress = {}
  470. for r in results:
  471. if r['id'] not in progress:
  472. progress[r['id']] = set()
  473. progress[r['id']].add(r['line'])
  474. print('---> {n} issue(s) to fix {progress}'.format(
  475. n=len(results), progress=progress), file=sys.stderr)
  476. if self.options.line_range:
  477. start, end = self.options.line_range
  478. results = [r for r in results
  479. if start <= r['line'] <= end]
  480. self._fix_source(filter_results(source=''.join(self.source),
  481. results=results,
  482. aggressive=self.options.aggressive))
  483. if self.options.line_range:
  484. # If number of lines has changed then change line_range.
  485. count = sum(sline.count('\n')
  486. for sline in self.source[start - 1:end])
  487. self.options.line_range[1] = start + count - 1
  488. return ''.join(self.source)
  489. def _fix_reindent(self, result):
  490. """Fix a badly indented line.
  491. This is done by adding or removing from its initial indent only.
  492. """
  493. num_indent_spaces = int(result['info'].split()[1])
  494. line_index = result['line'] - 1
  495. target = self.source[line_index]
  496. self.source[line_index] = ' ' * num_indent_spaces + target.lstrip()
  497. def fix_e112(self, result):
  498. """Fix under-indented comments."""
  499. line_index = result['line'] - 1
  500. target = self.source[line_index]
  501. if not target.lstrip().startswith('#'):
  502. # Don't screw with invalid syntax.
  503. return []
  504. self.source[line_index] = self.indent_word + target
  505. def fix_e113(self, result):
  506. """Fix over-indented comments."""
  507. line_index = result['line'] - 1
  508. target = self.source[line_index]
  509. indent = _get_indentation(target)
  510. stripped = target.lstrip()
  511. if not stripped.startswith('#'):
  512. # Don't screw with invalid syntax.
  513. return []
  514. self.source[line_index] = indent[1:] + stripped
  515. def fix_e125(self, result):
  516. """Fix indentation undistinguish from the next logical line."""
  517. num_indent_spaces = int(result['info'].split()[1])
  518. line_index = result['line'] - 1
  519. target = self.source[line_index]
  520. spaces_to_add = num_indent_spaces - len(_get_indentation(target))
  521. indent = len(_get_indentation(target))
  522. modified_lines = []
  523. while len(_get_indentation(self.source[line_index])) >= indent:
  524. self.source[line_index] = (' ' * spaces_to_add +
  525. self.source[line_index])
  526. modified_lines.append(1 + line_index) # Line indexed at 1.
  527. line_index -= 1
  528. return modified_lines
  529. def fix_e131(self, result):
  530. """Fix indentation undistinguish from the next logical line."""
  531. num_indent_spaces = int(result['info'].split()[1])
  532. line_index = result['line'] - 1
  533. target = self.source[line_index]
  534. spaces_to_add = num_indent_spaces - len(_get_indentation(target))
  535. if spaces_to_add >= 0:
  536. self.source[line_index] = (' ' * spaces_to_add +
  537. self.source[line_index])
  538. else:
  539. offset = abs(spaces_to_add)
  540. self.source[line_index] = self.source[line_index][offset:]
  541. def fix_e201(self, result):
  542. """Remove extraneous whitespace."""
  543. line_index = result['line'] - 1
  544. target = self.source[line_index]
  545. offset = result['column'] - 1
  546. fixed = fix_whitespace(target,
  547. offset=offset,
  548. replacement='')
  549. self.source[line_index] = fixed
  550. def fix_e224(self, result):
  551. """Remove extraneous whitespace around operator."""
  552. target = self.source[result['line'] - 1]
  553. offset = result['column'] - 1
  554. fixed = target[:offset] + target[offset:].replace('\t', ' ')
  555. self.source[result['line'] - 1] = fixed
  556. def fix_e225(self, result):
  557. """Fix missing whitespace around operator."""
  558. target = self.source[result['line'] - 1]
  559. offset = result['column'] - 1
  560. fixed = target[:offset] + ' ' + target[offset:]
  561. # Only proceed if non-whitespace characters match.
  562. # And make sure we don't break the indentation.
  563. if (
  564. fixed.replace(' ', '') == target.replace(' ', '') and
  565. _get_indentation(fixed) == _get_indentation(target)
  566. ):
  567. self.source[result['line'] - 1] = fixed
  568. else:
  569. return []
  570. def fix_e231(self, result):
  571. """Add missing whitespace."""
  572. line_index = result['line'] - 1
  573. target = self.source[line_index]
  574. offset = result['column']
  575. fixed = target[:offset].rstrip() + ' ' + target[offset:].lstrip()
  576. self.source[line_index] = fixed
  577. def fix_e251(self, result):
  578. """Remove whitespace around parameter '=' sign."""
  579. line_index = result['line'] - 1
  580. target = self.source[line_index]
  581. # This is necessary since pycodestyle sometimes reports columns that
  582. # goes past the end of the physical line. This happens in cases like,
  583. # foo(bar\n=None)
  584. c = min(result['column'] - 1,
  585. len(target) - 1)
  586. if target[c].strip():
  587. fixed = target
  588. else:
  589. fixed = target[:c].rstrip() + target[c:].lstrip()
  590. # There could be an escaped newline
  591. #
  592. # def foo(a=\
  593. # 1)
  594. if fixed.endswith(('=\\\n', '=\\\r\n', '=\\\r')):
  595. self.source[line_index] = fixed.rstrip('\n\r \t\\')
  596. self.source[line_index + 1] = self.source[line_index + 1].lstrip()
  597. return [line_index + 1, line_index + 2] # Line indexed at 1
  598. self.source[result['line'] - 1] = fixed
  599. def fix_e262(self, result):
  600. """Fix spacing after comment hash."""
  601. target = self.source[result['line'] - 1]
  602. offset = result['column']
  603. code = target[:offset].rstrip(' \t#')
  604. comment = target[offset:].lstrip(' \t#')
  605. fixed = code + (' # ' + comment if comment.strip() else '\n')
  606. self.source[result['line'] - 1] = fixed
  607. def fix_e271(self, result):
  608. """Fix extraneous whitespace around keywords."""
  609. line_index = result['line'] - 1
  610. target = self.source[line_index]
  611. offset = result['column'] - 1
  612. fixed = fix_whitespace(target,
  613. offset=offset,
  614. replacement=' ')
  615. if fixed == target:
  616. return []
  617. else:
  618. self.source[line_index] = fixed
  619. def fix_e301(self, result):
  620. """Add missing blank line."""
  621. cr = '\n'
  622. self.source[result['line'] - 1] = cr + self.source[result['line'] - 1]
  623. def fix_e302(self, result):
  624. """Add missing 2 blank lines."""
  625. add_linenum = 2 - int(result['info'].split()[-1])
  626. cr = '\n' * add_linenum
  627. self.source[result['line'] - 1] = cr + self.source[result['line'] - 1]
  628. def fix_e303(self, result):
  629. """Remove extra blank lines."""
  630. delete_linenum = int(result['info'].split('(')[1].split(')')[0]) - 2
  631. delete_linenum = max(1, delete_linenum)
  632. # We need to count because pycodestyle reports an offset line number if
  633. # there are comments.
  634. cnt = 0
  635. line = result['line'] - 2
  636. modified_lines = []
  637. while cnt < delete_linenum and line >= 0:
  638. if not self.source[line].strip():
  639. self.source[line] = ''
  640. modified_lines.append(1 + line) # Line indexed at 1
  641. cnt += 1
  642. line -= 1
  643. return modified_lines
  644. def fix_e304(self, result):
  645. """Remove blank line following function decorator."""
  646. line = result['line'] - 2
  647. if not self.source[line].strip():
  648. self.source[line] = ''
  649. def fix_e305(self, result):
  650. """Add missing 2 blank lines after end of function or class."""
  651. cr = '\n'
  652. # check comment line
  653. offset = result['line'] - 2
  654. while True:
  655. if offset < 0:
  656. break
  657. line = self.source[offset].lstrip()
  658. if len(line) == 0:
  659. break
  660. if line[0] != '#':
  661. break
  662. offset -= 1
  663. offset += 1
  664. self.source[offset] = cr + self.source[offset]
  665. def fix_e401(self, result):
  666. """Put imports on separate lines."""
  667. line_index = result['line'] - 1
  668. target = self.source[line_index]
  669. offset = result['column'] - 1
  670. if not target.lstrip().startswith('import'):
  671. return []
  672. indentation = re.split(pattern=r'\bimport\b',
  673. string=target, maxsplit=1)[0]
  674. fixed = (target[:offset].rstrip('\t ,') + '\n' +
  675. indentation + 'import ' + target[offset:].lstrip('\t ,'))
  676. self.source[line_index] = fixed
  677. def fix_long_line_logically(self, result, logical):
  678. """Try to make lines fit within --max-line-length characters."""
  679. if (
  680. not logical or
  681. len(logical[2]) == 1 or
  682. self.source[result['line'] - 1].lstrip().startswith('#')
  683. ):
  684. return self.fix_long_line_physically(result)
  685. start_line_index = logical[0][0]
  686. end_line_index = logical[1][0]
  687. logical_lines = logical[2]
  688. previous_line = get_item(self.source, start_line_index - 1, default='')
  689. next_line = get_item(self.source, end_line_index + 1, default='')
  690. single_line = join_logical_line(''.join(logical_lines))
  691. try:
  692. fixed = self.fix_long_line(
  693. target=single_line,
  694. previous_line=previous_line,
  695. next_line=next_line,
  696. original=''.join(logical_lines))
  697. except (SyntaxError, tokenize.TokenError):
  698. return self.fix_long_line_physically(result)
  699. if fixed:
  700. for line_index in range(start_line_index, end_line_index + 1):
  701. self.source[line_index] = ''
  702. self.source[start_line_index] = fixed
  703. return range(start_line_index + 1, end_line_index + 1)
  704. else:
  705. return []
  706. def fix_long_line_physically(self, result):
  707. """Try to make lines fit within --max-line-length characters."""
  708. line_index = result['line'] - 1
  709. target = self.source[line_index]
  710. previous_line = get_item(self.source, line_index - 1, default='')
  711. next_line = get_item(self.source, line_index + 1, default='')
  712. try:
  713. fixed = self.fix_long_line(
  714. target=target,
  715. previous_line=previous_line,
  716. next_line=next_line,
  717. original=target)
  718. except (SyntaxError, tokenize.TokenError):
  719. return []
  720. if fixed:
  721. self.source[line_index] = fixed
  722. return [line_index + 1]
  723. else:
  724. return []
  725. def fix_long_line(self, target, previous_line,
  726. next_line, original):
  727. cache_entry = (target, previous_line, next_line)
  728. if cache_entry in self.long_line_ignore_cache:
  729. return []
  730. if target.lstrip().startswith('#'):
  731. # Wrap commented lines.
  732. return shorten_comment(
  733. line=target,
  734. max_line_length=self.options.max_line_length,
  735. last_comment=not next_line.lstrip().startswith('#'))
  736. fixed = get_fixed_long_line(
  737. target=target,
  738. previous_line=previous_line,
  739. original=original,
  740. indent_word=self.indent_word,
  741. max_line_length=self.options.max_line_length,
  742. aggressive=self.options.aggressive,
  743. experimental=self.options.experimental,
  744. verbose=self.options.verbose)
  745. if fixed and not code_almost_equal(original, fixed):
  746. return fixed
  747. else:
  748. self.long_line_ignore_cache.add(cache_entry)
  749. return None
  750. def fix_e502(self, result):
  751. """Remove extraneous escape of newline."""
  752. (line_index, _, target) = get_index_offset_contents(result,
  753. self.source)
  754. self.source[line_index] = target.rstrip('\n\r \t\\') + '\n'
  755. def fix_e701(self, result):
  756. """Put colon-separated compound statement on separate lines."""
  757. line_index = result['line'] - 1
  758. target = self.source[line_index]
  759. c = result['column']
  760. fixed_source = (target[:c] + '\n' +
  761. _get_indentation(target) + self.indent_word +
  762. target[c:].lstrip('\n\r \t\\'))
  763. self.source[result['line'] - 1] = fixed_source
  764. return [result['line'], result['line'] + 1]
  765. def fix_e702(self, result, logical):
  766. """Put semicolon-separated compound statement on separate lines."""
  767. if not logical:
  768. return [] # pragma: no cover
  769. logical_lines = logical[2]
  770. line_index = result['line'] - 1
  771. target = self.source[line_index]
  772. if target.rstrip().endswith('\\'):
  773. # Normalize '1; \\\n2' into '1; 2'.
  774. self.source[line_index] = target.rstrip('\n \r\t\\')
  775. self.source[line_index + 1] = self.source[line_index + 1].lstrip()
  776. return [line_index + 1, line_index + 2]
  777. if target.rstrip().endswith(';'):
  778. self.source[line_index] = target.rstrip('\n \r\t;') + '\n'
  779. return [line_index + 1]
  780. offset = result['column'] - 1
  781. first = target[:offset].rstrip(';').rstrip()
  782. second = (_get_indentation(logical_lines[0]) +
  783. target[offset:].lstrip(';').lstrip())
  784. # Find inline comment.
  785. inline_comment = None
  786. if target[offset:].lstrip(';').lstrip()[:2] == '# ':
  787. inline_comment = target[offset:].lstrip(';')
  788. if inline_comment:
  789. self.source[line_index] = first + inline_comment
  790. else:
  791. self.source[line_index] = first + '\n' + second
  792. return [line_index + 1]
  793. def fix_e704(self, result):
  794. """Fix multiple statements on one line def"""
  795. (line_index, _, target) = get_index_offset_contents(result,
  796. self.source)
  797. match = STARTSWITH_DEF_REGEX.match(target)
  798. if match:
  799. self.source[line_index] = '{0}\n{1}{2}'.format(
  800. match.group(0),
  801. _get_indentation(target) + self.indent_word,
  802. target[match.end(0):].lstrip())
  803. def fix_e711(self, result):
  804. """Fix comparison with None."""
  805. (line_index, offset, target) = get_index_offset_contents(result,
  806. self.source)
  807. right_offset = offset + 2
  808. if right_offset >= len(target):
  809. return []
  810. left = target[:offset].rstrip()
  811. center = target[offset:right_offset]
  812. right = target[right_offset:].lstrip()
  813. if not right.startswith('None'):
  814. return []
  815. if center.strip() == '==':
  816. new_center = 'is'
  817. elif center.strip() == '!=':
  818. new_center = 'is not'
  819. else:
  820. return []
  821. self.source[line_index] = ' '.join([left, new_center, right])
  822. def fix_e712(self, result):
  823. """Fix (trivial case of) comparison with boolean."""
  824. (line_index, offset, target) = get_index_offset_contents(result,
  825. self.source)
  826. # Handle very easy "not" special cases.
  827. if re.match(r'^\s*if [\w.]+ == False:$', target):
  828. self.source[line_index] = re.sub(r'if ([\w.]+) == False:',
  829. r'if not \1:', target, count=1)
  830. elif re.match(r'^\s*if [\w.]+ != True:$', target):
  831. self.source[line_index] = re.sub(r'if ([\w.]+) != True:',
  832. r'if not \1:', target, count=1)
  833. else:
  834. right_offset = offset + 2
  835. if right_offset >= len(target):
  836. return []
  837. left = target[:offset].rstrip()
  838. center = target[offset:right_offset]
  839. right = target[right_offset:].lstrip()
  840. # Handle simple cases only.
  841. new_right = None
  842. if center.strip() == '==':
  843. if re.match(r'\bTrue\b', right):
  844. new_right = re.sub(r'\bTrue\b *', '', right, count=1)
  845. elif center.strip() == '!=':
  846. if re.match(r'\bFalse\b', right):
  847. new_right = re.sub(r'\bFalse\b *', '', right, count=1)
  848. if new_right is None:
  849. return []
  850. if new_right[0].isalnum():
  851. new_right = ' ' + new_right
  852. self.source[line_index] = left + new_right
  853. def fix_e713(self, result):
  854. """Fix (trivial case of) non-membership check."""
  855. (line_index, _, target) = get_index_offset_contents(result,
  856. self.source)
  857. match = COMPARE_NEGATIVE_REGEX.search(target)
  858. if match:
  859. if match.group(3) == 'in':
  860. pos_start = match.start(1)
  861. self.source[line_index] = '{0}{1} {2} {3} {4}'.format(
  862. target[:pos_start], match.group(2), match.group(1),
  863. match.group(3), target[match.end():])
  864. def fix_e714(self, result):
  865. """Fix object identity should be 'is not' case."""
  866. (line_index, _, target) = get_index_offset_contents(result,
  867. self.source)
  868. match = COMPARE_NEGATIVE_REGEX.search(target)
  869. if match:
  870. if match.group(3) == 'is':
  871. pos_start = match.start(1)
  872. self.source[line_index] = '{0}{1} {2} {3} {4}'.format(
  873. target[:pos_start], match.group(2), match.group(3),
  874. match.group(1), target[match.end():])
  875. def fix_e722(self, result):
  876. """fix bare except"""
  877. (line_index, _, target) = get_index_offset_contents(result,
  878. self.source)
  879. if BARE_EXCEPT_REGEX.search(target):
  880. self.source[line_index] = '{0}{1}'.format(
  881. target[:result['column'] - 1], "except Exception:")
  882. def fix_e731(self, result):
  883. """Fix do not assign a lambda expression check."""
  884. (line_index, _, target) = get_index_offset_contents(result,
  885. self.source)
  886. match = LAMBDA_REGEX.search(target)
  887. if match:
  888. end = match.end()
  889. self.source[line_index] = '{0}def {1}({2}): return {3}'.format(
  890. target[:match.start(0)], match.group(1), match.group(2),
  891. target[end:].lstrip())
  892. def fix_w291(self, result):
  893. """Remove trailing whitespace."""
  894. fixed_line = self.source[result['line'] - 1].rstrip()
  895. self.source[result['line'] - 1] = fixed_line + '\n'
  896. def fix_w391(self, _):
  897. """Remove trailing blank lines."""
  898. blank_count = 0
  899. for line in reversed(self.source):
  900. line = line.rstrip()
  901. if line:
  902. break
  903. else:
  904. blank_count += 1
  905. original_length = len(self.source)
  906. self.source = self.source[:original_length - blank_count]
  907. return range(1, 1 + original_length)
  908. def fix_w503(self, result):
  909. (line_index, _, target) = get_index_offset_contents(result,
  910. self.source)
  911. one_string_token = target.split()[0]
  912. try:
  913. ts = generate_tokens(one_string_token)
  914. except tokenize.TokenError:
  915. return
  916. if not _is_binary_operator(ts[0][0], one_string_token):
  917. return
  918. i = target.index(one_string_token)
  919. self.source[line_index] = '{0}{1}'.format(
  920. target[:i], target[i + len(one_string_token):])
  921. nl = find_newline(self.source[line_index - 1:line_index])
  922. before_line = self.source[line_index - 1]
  923. bl = before_line.index(nl)
  924. self.source[line_index - 1] = '{0} {1}{2}'.format(
  925. before_line[:bl], one_string_token,
  926. before_line[bl:])
  927. def get_index_offset_contents(result, source):
  928. """Return (line_index, column_offset, line_contents)."""
  929. line_index = result['line'] - 1
  930. return (line_index,
  931. result['column'] - 1,
  932. source[line_index])
  933. def get_fixed_long_line(target, previous_line, original,
  934. indent_word=' ', max_line_length=79,
  935. aggressive=False, experimental=False, verbose=False):
  936. """Break up long line and return result.
  937. Do this by generating multiple reformatted candidates and then
  938. ranking the candidates to heuristically select the best option.
  939. """
  940. indent = _get_indentation(target)
  941. source = target[len(indent):]
  942. assert source.lstrip() == source
  943. # Check for partial multiline.
  944. tokens = list(generate_tokens(source))
  945. candidates = shorten_line(
  946. tokens, source, indent,
  947. indent_word,
  948. max_line_length,
  949. aggressive=aggressive,
  950. experimental=experimental,
  951. previous_line=previous_line)
  952. # Also sort alphabetically as a tie breaker (for determinism).
  953. candidates = sorted(
  954. sorted(set(candidates).union([target, original])),
  955. key=lambda x: line_shortening_rank(
  956. x,
  957. indent_word,
  958. max_line_length,
  959. experimental=experimental))
  960. if verbose >= 4:
  961. print(('-' * 79 + '\n').join([''] + candidates + ['']),
  962. file=wrap_output(sys.stderr, 'utf-8'))
  963. if candidates:
  964. best_candidate = candidates[0]
  965. # Don't allow things to get longer.
  966. if longest_line_length(best_candidate) > longest_line_length(original):
  967. return None
  968. else:
  969. return best_candidate
  970. def longest_line_length(code):
  971. """Return length of longest line."""
  972. return max(len(line) for line in code.splitlines())
  973. def join_logical_line(logical_line):
  974. """Return single line based on logical line input."""
  975. indentation = _get_indentation(logical_line)
  976. return indentation + untokenize_without_newlines(
  977. generate_tokens(logical_line.lstrip())) + '\n'
  978. def untokenize_without_newlines(tokens):
  979. """Return source code based on tokens."""
  980. text = ''
  981. last_row = 0
  982. last_column = -1
  983. for t in tokens:
  984. token_string = t[1]
  985. (start_row, start_column) = t[2]
  986. (end_row, end_column) = t[3]
  987. if start_row > last_row:
  988. last_column = 0
  989. if (
  990. (start_column > last_column or token_string == '\n') and
  991. not text.endswith(' ')
  992. ):
  993. text += ' '
  994. if token_string != '\n':
  995. text += token_string
  996. last_row = end_row
  997. last_column = end_column
  998. return text.rstrip()
  999. def _find_logical(source_lines):
  1000. # Make a variable which is the index of all the starts of lines.
  1001. logical_start = []
  1002. logical_end = []
  1003. last_newline = True
  1004. parens = 0
  1005. for t in generate_tokens(''.join(source_lines)):
  1006. if t[0] in [tokenize.COMMENT, tokenize.DEDENT,
  1007. tokenize.INDENT, tokenize.NL,
  1008. tokenize.ENDMARKER]:
  1009. continue
  1010. if not parens and t[0] in [tokenize.NEWLINE, tokenize.SEMI]:
  1011. last_newline = True
  1012. logical_end.append((t[3][0] - 1, t[2][1]))
  1013. continue
  1014. if last_newline and not parens:
  1015. logical_start.append((t[2][0] - 1, t[2][1]))
  1016. last_newline = False
  1017. if t[0] == tokenize.OP:
  1018. if t[1] in '([{':
  1019. parens += 1
  1020. elif t[1] in '}])':
  1021. parens -= 1
  1022. return (logical_start, logical_end)
  1023. def _get_logical(source_lines, result, logical_start, logical_end):
  1024. """Return the logical line corresponding to the result.
  1025. Assumes input is already E702-clean.
  1026. """
  1027. row = result['line'] - 1
  1028. col = result['column'] - 1
  1029. ls = None
  1030. le = None
  1031. for i in range(0, len(logical_start), 1):
  1032. assert logical_end
  1033. x = logical_end[i]
  1034. if x[0] > row or (x[0] == row and x[1] > col):
  1035. le = x
  1036. ls = logical_start[i]
  1037. break
  1038. if ls is None:
  1039. return None
  1040. original = source_lines[ls[0]:le[0] + 1]
  1041. return ls, le, original
  1042. def get_item(items, index, default=None):
  1043. if 0 <= index < len(items):
  1044. return items[index]
  1045. else:
  1046. return default
  1047. def reindent(source, indent_size):
  1048. """Reindent all lines."""
  1049. reindenter = Reindenter(source)
  1050. return reindenter.run(indent_size)
  1051. def code_almost_equal(a, b):
  1052. """Return True if code is similar.
  1053. Ignore whitespace when comparing specific line.
  1054. """
  1055. split_a = split_and_strip_non_empty_lines(a)
  1056. split_b = split_and_strip_non_empty_lines(b)
  1057. if len(split_a) != len(split_b):
  1058. return False
  1059. for (index, _) in enumerate(split_a):
  1060. if ''.join(split_a[index].split()) != ''.join(split_b[index].split()):
  1061. return False
  1062. return True
  1063. def split_and_strip_non_empty_lines(text):
  1064. """Return lines split by newline.
  1065. Ignore empty lines.
  1066. """
  1067. return [line.strip() for line in text.splitlines() if line.strip()]
  1068. def fix_e265(source, aggressive=False): # pylint: disable=unused-argument
  1069. """Format block comments."""
  1070. if '#' not in source:
  1071. # Optimization.
  1072. return source
  1073. ignored_line_numbers = multiline_string_lines(
  1074. source,
  1075. include_docstrings=True) | set(commented_out_code_lines(source))
  1076. fixed_lines = []
  1077. sio = io.StringIO(source)
  1078. for (line_number, line) in enumerate(sio.readlines(), start=1):
  1079. if (
  1080. line.lstrip().startswith('#') and
  1081. line_number not in ignored_line_numbers and
  1082. not pycodestyle.noqa(line)
  1083. ):
  1084. indentation = _get_indentation(line)
  1085. line = line.lstrip()
  1086. # Normalize beginning if not a shebang.
  1087. if len(line) > 1:
  1088. pos = next((index for index, c in enumerate(line)
  1089. if c != '#'))
  1090. if (
  1091. # Leave multiple spaces like '# ' alone.
  1092. (line[:pos].count('#') > 1 or line[1].isalnum()) and
  1093. # Leave stylistic outlined blocks alone.
  1094. not line.rstrip().endswith('#')
  1095. ):
  1096. line = '# ' + line.lstrip('# \t')
  1097. fixed_lines.append(indentation + line)
  1098. else:
  1099. fixed_lines.append(line)
  1100. return ''.join(fixed_lines)
  1101. def refactor(source, fixer_names, ignore=None, filename=''):
  1102. """Return refactored code using lib2to3.
  1103. Skip if ignore string is produced in the refactored code.
  1104. """
  1105. check_lib2to3()
  1106. from lib2to3 import pgen2
  1107. try:
  1108. new_text = refactor_with_2to3(source,
  1109. fixer_names=fixer_names,
  1110. filename=filename)
  1111. except (pgen2.parse.ParseError,
  1112. SyntaxError,
  1113. UnicodeDecodeError,
  1114. UnicodeEncodeError):
  1115. return source
  1116. if ignore:
  1117. if ignore in new_text and ignore not in source:
  1118. return source
  1119. return new_text
  1120. def code_to_2to3(select, ignore):
  1121. fixes = set()
  1122. for code, fix in CODE_TO_2TO3.items():
  1123. if code_match(code, select=select, ignore=ignore):
  1124. fixes |= set(fix)
  1125. return fixes
  1126. def fix_2to3(source,
  1127. aggressive=True, select=None, ignore=None, filename=''):
  1128. """Fix various deprecated code (via lib2to3)."""
  1129. if not aggressive:
  1130. return source
  1131. select = select or []
  1132. ignore = ignore or []
  1133. return refactor(source,
  1134. code_to_2to3(select=select,
  1135. ignore=ignore),
  1136. filename=filename)
  1137. def fix_w602(source, aggressive=True):
  1138. """Fix deprecated form of raising exception."""
  1139. if not aggressive:
  1140. return source
  1141. return refactor(source, ['raise'],
  1142. ignore='with_traceback')
  1143. def find_newline(source):
  1144. """Return type of newline used in source.
  1145. Input is a list of lines.
  1146. """
  1147. assert not isinstance(source, unicode)
  1148. counter = collections.defaultdict(int)
  1149. for line in source:
  1150. if line.endswith(CRLF):
  1151. counter[CRLF] += 1
  1152. elif line.endswith(CR):
  1153. counter[CR] += 1
  1154. elif line.endswith(LF):
  1155. counter[LF] += 1
  1156. return (sorted(counter, key=counter.get, reverse=True) or [LF])[0]
  1157. def _get_indentword(source):
  1158. """Return indentation type."""
  1159. indent_word = ' ' # Default in case source has no indentation
  1160. try:
  1161. for t in generate_tokens(source):
  1162. if t[0] == token.INDENT:
  1163. indent_word = t[1]
  1164. break
  1165. except (SyntaxError, tokenize.TokenError):
  1166. pass
  1167. return indent_word
  1168. def _get_indentation(line):
  1169. """Return leading whitespace."""
  1170. if line.strip():
  1171. non_whitespace_index = len(line) - len(line.lstrip())
  1172. return line[:non_whitespace_index]
  1173. else:
  1174. return ''
  1175. def get_diff_text(old, new, filename):
  1176. """Return text of unified diff between old and new."""
  1177. newline = '\n'
  1178. diff = difflib.unified_diff(
  1179. old, new,
  1180. 'original/' + filename,
  1181. 'fixed/' + filename,
  1182. lineterm=newline)
  1183. text = ''
  1184. for line in diff:
  1185. text += line
  1186. # Work around missing newline (http://bugs.python.org/issue2142).
  1187. if text and not line.endswith(newline):
  1188. text += newline + r'\ No newline at end of file' + newline
  1189. return text
  1190. def _priority_key(pep8_result):
  1191. """Key for sorting PEP8 results.
  1192. Global fixes should be done first. This is important for things like
  1193. indentation.
  1194. """
  1195. priority = [
  1196. # Fix multiline colon-based before semicolon based.
  1197. 'e701',
  1198. # Break multiline statements early.
  1199. 'e702',
  1200. # Things that make lines longer.
  1201. 'e225', 'e231',
  1202. # Remove extraneous whitespace before breaking lines.
  1203. 'e201',
  1204. # Shorten whitespace in comment before resorting to wrapping.
  1205. 'e262'
  1206. ]
  1207. middle_index = 10000
  1208. lowest_priority = [
  1209. # We need to shorten lines last since the logical fixer can get in a
  1210. # loop, which causes us to exit early.
  1211. 'e501'
  1212. ]
  1213. key = pep8_result['id'].lower()
  1214. try:
  1215. return priority.index(key)
  1216. except ValueError:
  1217. try:
  1218. return middle_index + lowest_priority.index(key) + 1
  1219. except ValueError:
  1220. return middle_index
  1221. def shorten_line(tokens, source, indentation, indent_word, max_line_length,
  1222. aggressive=False, experimental=False, previous_line=''):
  1223. """Separate line at OPERATOR.
  1224. Multiple candidates will be yielded.
  1225. """
  1226. for candidate in _shorten_line(tokens=tokens,
  1227. source=source,
  1228. indentation=indentation,
  1229. indent_word=indent_word,
  1230. aggressive=aggressive,
  1231. previous_line=previous_line):
  1232. yield candidate
  1233. if aggressive:
  1234. for key_token_strings in SHORTEN_OPERATOR_GROUPS:
  1235. shortened = _shorten_line_at_tokens(
  1236. tokens=tokens,
  1237. source=source,
  1238. indentation=indentation,
  1239. indent_word=indent_word,
  1240. key_token_strings=key_token_strings,
  1241. aggressive=aggressive)
  1242. if shortened is not None and shortened != source:
  1243. yield shortened
  1244. if experimental:
  1245. for shortened in _shorten_line_at_tokens_new(
  1246. tokens=tokens,
  1247. source=source,
  1248. indentation=indentation,
  1249. max_line_length=max_line_length):
  1250. yield shortened
  1251. def _shorten_line(tokens, source, indentation, indent_word,
  1252. aggressive=False, previous_line=''):
  1253. """Separate line at OPERATOR.
  1254. The input is expected to be free of newlines except for inside multiline
  1255. strings and at the end.
  1256. Multiple candidates will be yielded.
  1257. """
  1258. for (token_type,
  1259. token_string,
  1260. start_offset,
  1261. end_offset) in token_offsets(tokens):
  1262. if (
  1263. token_type == tokenize.COMMENT and
  1264. not is_probably_part_of_multiline(previous_line) and
  1265. not is_probably_part_of_multiline(source) and
  1266. not source[start_offset + 1:].strip().lower().startswith(
  1267. ('noqa', 'pragma:', 'pylint:'))
  1268. ):
  1269. # Move inline comments to previous line.
  1270. first = source[:start_offset]
  1271. second = source[start_offset:]
  1272. yield (indentation + second.strip() + '\n' +
  1273. indentation + first.strip() + '\n')
  1274. elif token_type == token.OP and token_string != '=':
  1275. # Don't break on '=' after keyword as this violates PEP 8.
  1276. assert token_type != token.INDENT
  1277. first = source[:end_offset]
  1278. second_indent = indentation
  1279. if first.rstrip().endswith('('):
  1280. second_indent += indent_word
  1281. elif '(' in first:
  1282. second_indent += ' ' * (1 + first.find('('))
  1283. else:
  1284. second_indent += indent_word
  1285. second = (second_indent + source[end_offset:].lstrip())
  1286. if (
  1287. not second.strip() or
  1288. second.lstrip().startswith('#')
  1289. ):
  1290. continue
  1291. # Do not begin a line with a comma
  1292. if second.lstrip().startswith(','):
  1293. continue
  1294. # Do end a line with a dot
  1295. if first.rstrip().endswith('.'):
  1296. continue
  1297. if token_string in '+-*/':
  1298. fixed = first + ' \\' + '\n' + second
  1299. else:
  1300. fixed = first + '\n' + second
  1301. # Only fix if syntax is okay.
  1302. if check_syntax(normalize_multiline(fixed)
  1303. if aggressive else fixed):
  1304. yield indentation + fixed
  1305. def _is_binary_operator(token_type, text):
  1306. return ((token_type == tokenize.OP or text in ['and', 'or']) and
  1307. text not in '()[]{},:.;@=%~')
  1308. # A convenient way to handle tokens.
  1309. Token = collections.namedtuple('Token', ['token_type', 'token_string',
  1310. 'spos', 'epos', 'line'])
  1311. class ReformattedLines(object):
  1312. """The reflowed lines of atoms.
  1313. Each part of the line is represented as an "atom." They can be moved
  1314. around when need be to get the optimal formatting.
  1315. """
  1316. ###########################################################################
  1317. # Private Classes
  1318. class _Indent(object):
  1319. """Represent an indentation in the atom stream."""
  1320. def __init__(self, indent_amt):
  1321. self._indent_amt = indent_amt
  1322. def emit(self):
  1323. return ' ' * self._indent_amt
  1324. @property
  1325. def size(self):
  1326. return self._indent_amt
  1327. class _Space(object):
  1328. """Represent a space in the atom stream."""
  1329. def emit(self):
  1330. return ' '
  1331. @property
  1332. def size(self):
  1333. return 1
  1334. class _LineBreak(object):
  1335. """Represent a line break in the atom stream."""
  1336. def emit(self):
  1337. return '\n'
  1338. @property
  1339. def size(self):
  1340. return 0
  1341. def __init__(self, max_line_length):
  1342. self._max_line_length = max_line_length
  1343. self._lines = []
  1344. self._bracket_depth = 0
  1345. self._prev_item = None
  1346. self._prev_prev_item = None
  1347. def __repr__(self):
  1348. return self.emit()
  1349. ###########################################################################
  1350. # Public Methods
  1351. def add(self, obj, indent_amt, break_after_open_bracket):
  1352. if isinstance(obj, Atom):
  1353. self._add_item(obj, indent_amt)
  1354. return
  1355. self._add_container(obj, indent_amt, break_after_open_bracket)
  1356. def add_comment(self, item):
  1357. num_spaces = 2
  1358. if len(self._lines) > 1:
  1359. if isinstance(self._lines[-1], self._Space):
  1360. num_spaces -= 1
  1361. if len(self._lines) > 2:
  1362. if isinstance(self._lines[-2], self._Space):
  1363. num_spaces -= 1
  1364. while num_spaces > 0:
  1365. self._lines.append(self._Space())
  1366. num_spaces -= 1
  1367. self._lines.append(item)
  1368. def add_indent(self, indent_amt):
  1369. self._lines.append(self._Indent(indent_amt))
  1370. def add_line_break(self, indent):
  1371. self._lines.append(self._LineBreak())
  1372. self.add_indent(len(indent))
  1373. def add_line_break_at(self, index, indent_amt):
  1374. self._lines.insert(index, self._LineBreak())
  1375. self._lines.insert(index + 1, self._Indent(indent_amt))
  1376. def add_space_if_needed(self, curr_text, equal=False):
  1377. if (
  1378. not self._lines or isinstance(
  1379. self._lines[-1], (self._LineBreak, self._Indent, self._Space))
  1380. ):
  1381. return
  1382. prev_text = unicode(self._prev_item)
  1383. prev_prev_text = (
  1384. unicode(self._prev_prev_item) if self._prev_prev_item else '')
  1385. if (
  1386. # The previous item was a keyword or identifier and the current
  1387. # item isn't an operator that doesn't require a space.
  1388. ((self._prev_item.is_keyword or self._prev_item.is_string or
  1389. self._prev_item.is_name or self._prev_item.is_number) and
  1390. (curr_text[0] not in '([{.,:}])' or
  1391. (curr_text[0] == '=' and equal))) or
  1392. # Don't place spaces around a '.', unless it's in an 'import'
  1393. # statement.
  1394. ((prev_prev_text != 'from' and prev_text[-1] != '.' and
  1395. curr_text != 'import') and
  1396. # Don't place a space before a colon.
  1397. curr_text[0] != ':' and
  1398. # Don't split up ending brackets by spaces.
  1399. ((prev_text[-1] in '}])' and curr_text[0] not in '.,}])') or
  1400. # Put a space after a colon or comma.
  1401. prev_text[-1] in ':,' or
  1402. # Put space around '=' if asked to.
  1403. (equal and prev_text == '=') or
  1404. # Put spaces around non-unary arithmetic operators.
  1405. ((self._prev_prev_item and
  1406. (prev_text not in '+-' and
  1407. (self._prev_prev_item.is_name or
  1408. self._prev_prev_item.is_number or
  1409. self._prev_prev_item.is_string)) and
  1410. prev_text in ('+', '-', '%', '*', '/', '//', '**', 'in')))))
  1411. ):
  1412. self._lines.append(self._Space())
  1413. def previous_item(self):
  1414. """Return the previous non-whitespace item."""
  1415. return self._prev_item
  1416. def fits_on_current_line(self, item_extent):
  1417. return self.current_size() + item_extent <= self._max_line_length
  1418. def current_size(self):
  1419. """The size of the current line minus the indentation."""
  1420. size = 0
  1421. for item in reversed(self._lines):
  1422. size += item.size
  1423. if isinstance(item, self._LineBreak):
  1424. break
  1425. return size
  1426. def line_empty(self):
  1427. return (self._lines and
  1428. isinstance(self._lines[-1],
  1429. (self._LineBreak, self._Indent)))
  1430. def emit(self):
  1431. string = ''
  1432. for item in self._lines:
  1433. if isinstance(item, self._LineBreak):
  1434. string = string.rstrip()
  1435. string += item.emit()
  1436. return string.rstrip() + '\n'
  1437. ###########################################################################
  1438. # Private Methods
  1439. def _add_item(self, item, indent_amt):
  1440. """Add an item to the line.
  1441. Reflow the line to get the best formatting after the item is
  1442. inserted. The bracket depth indicates if the item is being
  1443. inserted inside of a container or not.
  1444. """
  1445. if self._prev_item and self._prev_item.is_string and item.is_string:
  1446. # Place consecutive string literals on separate lines.
  1447. self._lines.append(self._LineBreak())
  1448. self._lines.append(self._Indent(indent_amt))
  1449. item_text = unicode(item)
  1450. if self._lines and self._bracket_depth:
  1451. # Adding the item into a container.
  1452. self._prevent_default_initializer_splitting(item, indent_amt)
  1453. if item_text in '.,)]}':
  1454. self._split_after_delimiter(item, indent_amt)
  1455. elif self._lines and not self.line_empty():
  1456. # Adding the item outside of a container.
  1457. if self.fits_on_current_line(len(item_text)):
  1458. self._enforce_space(item)
  1459. else:
  1460. # Line break for the new item.
  1461. self._lines.append(self._LineBreak())
  1462. self._lines.append(self._Indent(indent_amt))
  1463. self._lines.append(item)
  1464. self._prev_item, self._prev_prev_item = item, self._prev_item
  1465. if item_text in '([{':
  1466. self._bracket_depth += 1
  1467. elif item_text in '}])':
  1468. self._bracket_depth -= 1
  1469. assert self._bracket_depth >= 0
  1470. def _add_container(self, container, indent_amt, break_after_open_bracket):
  1471. actual_indent = indent_amt + 1
  1472. if (
  1473. unicode(self._prev_item) != '=' and
  1474. not self.line_empty() and
  1475. not self.fits_on_current_line(
  1476. container.size + self._bracket_depth + 2)
  1477. ):
  1478. if unicode(container)[0] == '(' and self._prev_item.is_name:
  1479. # Don't split before the opening bracket of a call.
  1480. break_after_open_bracket = True
  1481. actual_indent = indent_amt + 4
  1482. elif (
  1483. break_after_open_bracket or
  1484. unicode(self._prev_item) not in '([{'
  1485. ):
  1486. # If the container doesn't fit on the current line and the
  1487. # current line isn't empty, place the container on the next
  1488. # line.
  1489. self._lines.append(self._LineBreak())
  1490. self._lines.append(self._Indent(indent_amt))
  1491. break_after_open_bracket = False
  1492. else:
  1493. actual_indent = self.current_size() + 1
  1494. break_after_open_bracket = False
  1495. if isinstance(container, (ListComprehension, IfExpression)):
  1496. actual_indent = indent_amt
  1497. # Increase the continued indentation only if recursing on a
  1498. # container.
  1499. container.reflow(self, ' ' * actual_indent,
  1500. break_after_open_bracket=break_after_open_bracket)
  1501. def _prevent_default_initializer_splitting(self, item, indent_amt):
  1502. """Prevent splitting between a default initializer.
  1503. When there is a default initializer, it's best to keep it all on
  1504. the same line. It's nicer and more readable, even if it goes
  1505. over the maximum allowable line length. This goes back along the
  1506. current line to determine if we have a default initializer, and,
  1507. if so, to remove extraneous whitespaces and add a line
  1508. break/indent before it if needed.
  1509. """
  1510. if unicode(item) == '=':
  1511. # This is the assignment in the initializer. Just remove spaces for
  1512. # now.
  1513. self._delete_whitespace()
  1514. return
  1515. if (not self._prev_item or not self._prev_prev_item or
  1516. unicode(self._prev_item) != '='):
  1517. return
  1518. self._delete_whitespace()
  1519. prev_prev_index = self._lines.index(self._prev_prev_item)
  1520. if (
  1521. isinstance(self._lines[prev_prev_index - 1], self._Indent) or
  1522. self.fits_on_current_line(item.size + 1)
  1523. ):
  1524. # The default initializer is already the only item on this line.
  1525. # Don't insert a newline here.
  1526. return
  1527. # Replace the space with a newline/indent combo.
  1528. if isinstance(self._lines[prev_prev_index - 1], self._Space):
  1529. del self._lines[prev_prev_index - 1]
  1530. self.add_line_break_at(self._lines.index(self._prev_prev_item),
  1531. indent_amt)
  1532. def _split_after_delimiter(self, item, indent_amt):
  1533. """Split the line only after a delimiter."""
  1534. self._delete_whitespace()
  1535. if self.fits_on_current_line(item.size):
  1536. return
  1537. last_space = None
  1538. for item in reversed(self._lines):
  1539. if (
  1540. last_space and
  1541. (not isinstance(item, Atom) or not item.is_colon)
  1542. ):
  1543. break
  1544. else:
  1545. last_space = None
  1546. if isinstance(item, self._Space):
  1547. last_space = item
  1548. if isinstance(item, (self._LineBreak, self._Indent)):
  1549. return
  1550. if not last_space:
  1551. return
  1552. self.add_line_break_at(self._lines.index(last_space), indent_amt)
  1553. def _enforce_space(self, item):
  1554. """Enforce a space in certain situations.
  1555. There are cases where we will want a space where normally we
  1556. wouldn't put one. This just enforces the addition of a space.
  1557. """
  1558. if isinstance(self._lines[-1],
  1559. (self._Space, self._LineBreak, self._Indent)):
  1560. return
  1561. if not self._prev_item:
  1562. return
  1563. item_text = unicode(item)
  1564. prev_text = unicode(self._prev_item)
  1565. # Prefer a space around a '.' in an import statement, and between the
  1566. # 'import' and '('.
  1567. if (
  1568. (item_text == '.' and prev_text == 'from') or
  1569. (item_text == 'import' and prev_text == '.') or
  1570. (item_text == '(' and prev_text == 'import')
  1571. ):
  1572. self._lines.append(self._Space())
  1573. def _delete_whitespace(self):
  1574. """Delete all whitespace from the end of the line."""
  1575. while isinstance(self._lines[-1], (self._Space, self._LineBreak,
  1576. self._Indent)):
  1577. del self._lines[-1]
  1578. class Atom(object):
  1579. """The smallest unbreakable unit that can be reflowed."""
  1580. def __init__(self, atom):
  1581. self._atom = atom
  1582. def __repr__(self):
  1583. return self._atom.token_string
  1584. def __len__(self):
  1585. return self.size
  1586. def reflow(
  1587. self, reflowed_lines, continued_indent, extent,
  1588. break_after_open_bracket=False,
  1589. is_list_comp_or_if_expr=False,
  1590. next_is_dot=False
  1591. ):
  1592. if self._atom.token_type == tokenize.COMMENT:
  1593. reflowed_lines.add_comment(self)
  1594. return
  1595. total_size = extent if extent else self.size
  1596. if self._atom.token_string not in ',:([{}])':
  1597. # Some atoms will need an extra 1-sized space token after them.
  1598. total_size += 1
  1599. prev_item = reflowed_lines.previous_item()
  1600. if (
  1601. not is_list_comp_or_if_expr and
  1602. not reflowed_lines.fits_on_current_line(total_size) and
  1603. not (next_is_dot and
  1604. reflowed_lines.fits_on_current_line(self.size + 1)) and
  1605. not reflowed_lines.line_empty() and
  1606. not self.is_colon and
  1607. not (prev_item and prev_item.is_name and
  1608. unicode(self) == '(')
  1609. ):
  1610. # Start a new line if there is already something on the line and
  1611. # adding this atom would make it go over the max line length.
  1612. reflowed_lines.add_line_break(continued_indent)
  1613. else:
  1614. reflowed_lines.add_space_if_needed(unicode(self))
  1615. reflowed_lines.add(self, len(continued_indent),
  1616. break_after_open_bracket)
  1617. def emit(self):
  1618. return self.__repr__()
  1619. @property
  1620. def is_keyword(self):
  1621. return keyword.iskeyword(self._atom.token_string)
  1622. @property
  1623. def is_string(self):
  1624. return self._atom.token_type == tokenize.STRING
  1625. @property
  1626. def is_name(self):
  1627. return self._atom.token_type == tokenize.NAME
  1628. @property
  1629. def is_number(self):
  1630. return self._atom.token_type == tokenize.NUMBER
  1631. @property
  1632. def is_comma(self):
  1633. return self._atom.token_string == ','
  1634. @property
  1635. def is_colon(self):
  1636. return self._atom.token_string == ':'
  1637. @property
  1638. def size(self):
  1639. return len(self._atom.token_string)
  1640. class Container(object):
  1641. """Base class for all container types."""
  1642. def __init__(self, items):
  1643. self._items = items
  1644. def __repr__(self):
  1645. string = ''
  1646. last_was_keyword = False
  1647. for item in self._items:
  1648. if item.is_comma:
  1649. string += ', '
  1650. elif item.is_colon:
  1651. string += ': '
  1652. else:
  1653. item_string = unicode(item)
  1654. if (
  1655. string and
  1656. (last_was_keyword or
  1657. (not string.endswith(tuple('([{,.:}]) ')) and
  1658. not item_string.startswith(tuple('([{,.:}])'))))
  1659. ):
  1660. string += ' '
  1661. string += item_string
  1662. last_was_keyword = item.is_keyword
  1663. return string
  1664. def __iter__(self):
  1665. for element in self._items:
  1666. yield element
  1667. def __getitem__(self, idx):
  1668. return self._items[idx]
  1669. def reflow(self, reflowed_lines, continued_indent,
  1670. break_after_open_bracket=False):
  1671. last_was_container = False
  1672. for (index, item) in enumerate(self._items):
  1673. next_item = get_item(self._items, index + 1)
  1674. if isinstance(item, Atom):
  1675. is_list_comp_or_if_expr = (
  1676. isinstance(self, (ListComprehension, IfExpression)))
  1677. item.reflow(reflowed_lines, continued_indent,
  1678. self._get_extent(index),
  1679. is_list_comp_or_if_expr=is_list_comp_or_if_expr,
  1680. next_is_dot=(next_item and
  1681. unicode(next_item) == '.'))
  1682. if last_was_container and item.is_comma:
  1683. reflowed_lines.add_line_break(continued_indent)
  1684. last_was_container = False
  1685. else: # isinstance(item, Container)
  1686. reflowed_lines.add(item, len(continued_indent),
  1687. break_after_open_bracket)
  1688. last_was_container = not isinstance(item, (ListComprehension,
  1689. IfExpression))
  1690. if (
  1691. break_after_open_bracket and index == 0 and
  1692. # Prefer to keep empty containers together instead of
  1693. # separating them.
  1694. unicode(item) == self.open_bracket and
  1695. (not next_item or unicode(next_item) != self.close_bracket) and
  1696. (len(self._items) != 3 or not isinstance(next_item, Atom))
  1697. ):
  1698. reflowed_lines.add_line_break(continued_indent)
  1699. break_after_open_bracket = False
  1700. else:
  1701. next_next_item = get_item(self._items, index + 2)
  1702. if (
  1703. unicode(item) not in ['.', '%', 'in'] and
  1704. next_item and not isinstance(next_item, Container) and
  1705. unicode(next_item) != ':' and
  1706. next_next_item and (not isinstance(next_next_item, Atom) or
  1707. unicode(next_item) == 'not') and
  1708. not reflowed_lines.line_empty() and
  1709. not reflowed_lines.fits_on_current_line(
  1710. self._get_extent(index + 1) + 2)
  1711. ):
  1712. reflowed_lines.add_line_break(continued_indent)
  1713. def _get_extent(self, index):
  1714. """The extent of the full element.
  1715. E.g., the length of a function call or keyword.
  1716. """
  1717. extent = 0
  1718. prev_item = get_item(self._items, index - 1)
  1719. seen_dot = prev_item and unicode(prev_item) == '.'
  1720. while index < len(self._items):
  1721. item = get_item(self._items, index)
  1722. index += 1
  1723. if isinstance(item, (ListComprehension, IfExpression)):
  1724. break
  1725. if isinstance(item, Container):
  1726. if prev_item and prev_item.is_name:
  1727. if seen_dot:
  1728. extent += 1
  1729. else:
  1730. extent += item.size
  1731. prev_item = item
  1732. continue
  1733. elif (unicode(item) not in ['.', '=', ':', 'not'] and
  1734. not item.is_name and not item.is_string):
  1735. break
  1736. if unicode(item) == '.':
  1737. seen_dot = True
  1738. extent += item.size
  1739. prev_item = item
  1740. return extent
  1741. @property
  1742. def is_string(self):
  1743. return False
  1744. @property
  1745. def size(self):
  1746. return len(self.__repr__())
  1747. @property
  1748. def is_keyword(self):
  1749. return False
  1750. @property
  1751. def is_name(self):
  1752. return False
  1753. @property
  1754. def is_comma(self):
  1755. return False
  1756. @property
  1757. def is_colon(self):
  1758. return False
  1759. @property
  1760. def open_bracket(self):
  1761. return None
  1762. @property
  1763. def close_bracket(self):
  1764. return None
  1765. class Tuple(Container):
  1766. """A high-level representation of a tuple."""
  1767. @property
  1768. def open_bracket(self):
  1769. return '('
  1770. @property
  1771. def close_bracket(self):
  1772. return ')'
  1773. class List(Container):
  1774. """A high-level representation of a list."""
  1775. @property
  1776. def open_bracket(self):
  1777. return '['
  1778. @property
  1779. def close_bracket(self):
  1780. return ']'
  1781. class DictOrSet(Container):
  1782. """A high-level representation of a dictionary or set."""
  1783. @property
  1784. def open_bracket(self):
  1785. return '{'
  1786. @property
  1787. def close_bracket(self):
  1788. return '}'
  1789. class ListComprehension(Container):
  1790. """A high-level representation of a list comprehension."""
  1791. @property
  1792. def size(self):
  1793. length = 0
  1794. for item in self._items:
  1795. if isinstance(item, IfExpression):
  1796. break
  1797. length += item.size
  1798. return length
  1799. class IfExpression(Container):
  1800. """A high-level representation of an if-expression."""
  1801. def _parse_container(tokens, index, for_or_if=None):
  1802. """Parse a high-level container, such as a list, tuple, etc."""
  1803. # Store the opening bracket.
  1804. items = [Atom(Token(*tokens[index]))]
  1805. index += 1
  1806. num_tokens = len(tokens)
  1807. while index < num_tokens:
  1808. tok = Token(*tokens[index])
  1809. if tok.token_string in ',)]}':
  1810. # First check if we're at the end of a list comprehension or
  1811. # if-expression. Don't add the ending token as part of the list
  1812. # comprehension or if-expression, because they aren't part of those
  1813. # constructs.
  1814. if for_or_if == 'for':
  1815. return (ListComprehension(items), index - 1)
  1816. elif for_or_if == 'if':
  1817. return (IfExpression(items), index - 1)
  1818. # We've reached the end of a container.
  1819. items.append(Atom(tok))
  1820. # If not, then we are at the end of a container.
  1821. if tok.token_string == ')':
  1822. # The end of a tuple.
  1823. return (Tuple(items), index)
  1824. elif tok.token_string == ']':
  1825. # The end of a list.
  1826. return (List(items), index)
  1827. elif tok.token_string == '}':
  1828. # The end of a dictionary or set.
  1829. return (DictOrSet(items), index)
  1830. elif tok.token_string in '([{':
  1831. # A sub-container is being defined.
  1832. (container, index) = _parse_container(tokens, index)
  1833. items.append(container)
  1834. elif tok.token_string == 'for':
  1835. (container, index) = _parse_container(tokens, index, 'for')
  1836. items.append(container)
  1837. elif tok.token_string == 'if':
  1838. (container, index) = _parse_container(tokens, index, 'if')
  1839. items.append(container)
  1840. else:
  1841. items.append(Atom(tok))
  1842. index += 1
  1843. return (None, None)
  1844. def _parse_tokens(tokens):
  1845. """Parse the tokens.
  1846. This converts the tokens into a form where we can manipulate them
  1847. more easily.
  1848. """
  1849. index = 0
  1850. parsed_tokens = []
  1851. num_tokens = len(tokens)
  1852. while index < num_tokens:
  1853. tok = Token(*tokens[index])
  1854. assert tok.token_type != token.INDENT
  1855. if tok.token_type == tokenize.NEWLINE:
  1856. # There's only one newline and it's at the end.
  1857. break
  1858. if tok.token_string in '([{':
  1859. (container, index) = _parse_container(tokens, index)
  1860. if not container:
  1861. return None
  1862. parsed_tokens.append(container)
  1863. else:
  1864. parsed_tokens.append(Atom(tok))
  1865. index += 1
  1866. return parsed_tokens
  1867. def _reflow_lines(parsed_tokens, indentation, max_line_length,
  1868. start_on_prefix_line):
  1869. """Reflow the lines so that it looks nice."""
  1870. if unicode(parsed_tokens[0]) == 'def':
  1871. # A function definition gets indented a bit more.
  1872. continued_indent = indentation + ' ' * 2 * DEFAULT_INDENT_SIZE
  1873. else:
  1874. continued_indent = indentation + ' ' * DEFAULT_INDENT_SIZE
  1875. break_after_open_bracket = not start_on_prefix_line
  1876. lines = ReformattedLines(max_line_length)
  1877. lines.add_indent(len(indentation.lstrip('\r\n')))
  1878. if not start_on_prefix_line:
  1879. # If splitting after the opening bracket will cause the first element
  1880. # to be aligned weirdly, don't try it.
  1881. first_token = get_item(parsed_tokens, 0)
  1882. second_token = get_item(parsed_tokens, 1)
  1883. if (
  1884. first_token and second_token and
  1885. unicode(second_token)[0] == '(' and
  1886. len(indentation) + len(first_token) + 1 == len(continued_indent)
  1887. ):
  1888. return None
  1889. for item in parsed_tokens:
  1890. lines.add_space_if_needed(unicode(item), equal=True)
  1891. save_continued_indent = continued_indent
  1892. if start_on_prefix_line and isinstance(item, Container):
  1893. start_on_prefix_line = False
  1894. continued_indent = ' ' * (lines.current_size() + 1)
  1895. item.reflow(lines, continued_indent, break_after_open_bracket)
  1896. continued_indent = save_continued_indent
  1897. return lines.emit()
  1898. def _shorten_line_at_tokens_new(tokens, source, indentation,
  1899. max_line_length):
  1900. """Shorten the line taking its length into account.
  1901. The input is expected to be free of newlines except for inside
  1902. multiline strings and at the end.
  1903. """
  1904. # Yield the original source so to see if it's a better choice than the
  1905. # shortened candidate lines we generate here.
  1906. yield indentation + source
  1907. parsed_tokens = _parse_tokens(tokens)
  1908. if parsed_tokens:
  1909. # Perform two reflows. The first one starts on the same line as the
  1910. # prefix. The second starts on the line after the prefix.
  1911. fixed = _reflow_lines(parsed_tokens, indentation, max_line_length,
  1912. start_on_prefix_line=True)
  1913. if fixed and check_syntax(normalize_multiline(fixed.lstrip())):
  1914. yield fixed
  1915. fixed = _reflow_lines(parsed_tokens, indentation, max_line_length,
  1916. start_on_prefix_line=False)
  1917. if fixed and check_syntax(normalize_multiline(fixed.lstrip())):
  1918. yield fixed
  1919. def _shorten_line_at_tokens(tokens, source, indentation, indent_word,
  1920. key_token_strings, aggressive):
  1921. """Separate line by breaking at tokens in key_token_strings.
  1922. The input is expected to be free of newlines except for inside
  1923. multiline strings and at the end.
  1924. """
  1925. offsets = []
  1926. for (index, _t) in enumerate(token_offsets(tokens)):
  1927. (token_type,
  1928. token_string,
  1929. start_offset,
  1930. end_offset) = _t
  1931. assert token_type != token.INDENT
  1932. if token_string in key_token_strings:
  1933. # Do not break in containers with zero or one items.
  1934. unwanted_next_token = {
  1935. '(': ')',
  1936. '[': ']',
  1937. '{': '}'}.get(token_string)
  1938. if unwanted_next_token:
  1939. if (
  1940. get_item(tokens,
  1941. index + 1,
  1942. default=[None, None])[1] == unwanted_next_token or
  1943. get_item(tokens,
  1944. index + 2,
  1945. default=[None, None])[1] == unwanted_next_token
  1946. ):
  1947. continue
  1948. if (
  1949. index > 2 and token_string == '(' and
  1950. tokens[index - 1][1] in ',(%['
  1951. ):
  1952. # Don't split after a tuple start, or before a tuple start if
  1953. # the tuple is in a list.
  1954. continue
  1955. if end_offset < len(source) - 1:
  1956. # Don't split right before newline.
  1957. offsets.append(end_offset)
  1958. else:
  1959. # Break at adjacent strings. These were probably meant to be on
  1960. # separate lines in the first place.
  1961. previous_token = get_item(tokens, index - 1)
  1962. if (
  1963. token_type == tokenize.STRING and
  1964. previous_token and previous_token[0] == tokenize.STRING
  1965. ):
  1966. offsets.append(start_offset)
  1967. current_indent = None
  1968. fixed = None
  1969. for line in split_at_offsets(source, offsets):
  1970. if fixed:
  1971. fixed += '\n' + current_indent + line
  1972. for symbol in '([{':
  1973. if line.endswith(symbol):
  1974. current_indent += indent_word
  1975. else:
  1976. # First line.
  1977. fixed = line
  1978. assert not current_indent
  1979. current_indent = indent_word
  1980. assert fixed is not None
  1981. if check_syntax(normalize_multiline(fixed)
  1982. if aggressive > 1 else fixed):
  1983. return indentation + fixed
  1984. else:
  1985. return None
  1986. def token_offsets(tokens):
  1987. """Yield tokens and offsets."""
  1988. end_offset = 0
  1989. previous_end_row = 0
  1990. previous_end_column = 0
  1991. for t in tokens:
  1992. token_type = t[0]
  1993. token_string = t[1]
  1994. (start_row, start_column) = t[2]
  1995. (end_row, end_column) = t[3]
  1996. # Account for the whitespace between tokens.
  1997. end_offset += start_column
  1998. if previous_end_row == start_row:
  1999. end_offset -= previous_end_column
  2000. # Record the start offset of the token.
  2001. start_offset = end_offset
  2002. # Account for the length of the token itself.
  2003. end_offset += len(token_string)
  2004. yield (token_type,
  2005. token_string,
  2006. start_offset,
  2007. end_offset)
  2008. previous_end_row = end_row
  2009. previous_end_column = end_column
  2010. def normalize_multiline(line):
  2011. """Normalize multiline-related code that will cause syntax error.
  2012. This is for purposes of checking syntax.
  2013. """
  2014. if line.startswith('def ') and line.rstrip().endswith(':'):
  2015. return line + ' pass'
  2016. elif line.startswith('return '):
  2017. return 'def _(): ' + line
  2018. elif line.startswith('@'):
  2019. return line + 'def _(): pass'
  2020. elif line.startswith('class '):
  2021. return line + ' pass'
  2022. elif line.startswith(('if ', 'elif ', 'for ', 'while ')):
  2023. return line + ' pass'
  2024. else:
  2025. return line
  2026. def fix_whitespace(line, offset, replacement):
  2027. """Replace whitespace at offset and return fixed line."""
  2028. # Replace escaped newlines too
  2029. left = line[:offset].rstrip('\n\r \t\\')
  2030. right = line[offset:].lstrip('\n\r \t\\')
  2031. if right.startswith('#'):
  2032. return line
  2033. else:
  2034. return left + replacement + right
  2035. def _execute_pep8(pep8_options, source):
  2036. """Execute pycodestyle via python method calls."""
  2037. class QuietReport(pycodestyle.BaseReport):
  2038. """Version of checker that does not print."""
  2039. def __init__(self, options):
  2040. super(QuietReport, self).__init__(options)
  2041. self.__full_error_results = []
  2042. def error(self, line_number, offset, text, check):
  2043. """Collect errors."""
  2044. code = super(QuietReport, self).error(line_number,
  2045. offset,
  2046. text,
  2047. check)
  2048. if code:
  2049. self.__full_error_results.append(
  2050. {'id': code,
  2051. 'line': line_number,
  2052. 'column': offset + 1,
  2053. 'info': text})
  2054. def full_error_results(self):
  2055. """Return error results in detail.
  2056. Results are in the form of a list of dictionaries. Each
  2057. dictionary contains 'id', 'line', 'column', and 'info'.
  2058. """
  2059. return self.__full_error_results
  2060. checker = pycodestyle.Checker('', lines=source, reporter=QuietReport,
  2061. **pep8_options)
  2062. checker.check_all()
  2063. return checker.report.full_error_results()
  2064. def _remove_leading_and_normalize(line):
  2065. return line.lstrip().rstrip(CR + LF) + '\n'
  2066. class Reindenter(object):
  2067. """Reindents badly-indented code to uniformly use four-space indentation.
  2068. Released to the public domain, by Tim Peters, 03 October 2000.
  2069. """
  2070. def __init__(self, input_text):
  2071. sio = io.StringIO(input_text)
  2072. source_lines = sio.readlines()
  2073. self.string_content_line_numbers = multiline_string_lines(input_text)
  2074. # File lines, rstripped & tab-expanded. Dummy at start is so
  2075. # that we can use tokenize's 1-based line numbering easily.
  2076. # Note that a line is all-blank iff it is a newline.
  2077. self.lines = []
  2078. for line_number, line in enumerate(source_lines, start=1):
  2079. # Do not modify if inside a multiline string.
  2080. if line_number in self.string_content_line_numbers:
  2081. self.lines.append(line)
  2082. else:
  2083. # Only expand leading tabs.
  2084. self.lines.append(_get_indentation(line).expandtabs() +
  2085. _remove_leading_and_normalize(line))
  2086. self.lines.insert(0, None)
  2087. self.index = 1 # index into self.lines of next line
  2088. self.input_text = input_text
  2089. def run(self, indent_size=DEFAULT_INDENT_SIZE):
  2090. """Fix indentation and return modified line numbers.
  2091. Line numbers are indexed at 1.
  2092. """
  2093. if indent_size < 1:
  2094. return self.input_text
  2095. try:
  2096. stats = _reindent_stats(tokenize.generate_tokens(self.getline))
  2097. except (SyntaxError, tokenize.TokenError):
  2098. return self.input_text
  2099. # Remove trailing empty lines.
  2100. lines = self.lines
  2101. # Sentinel.
  2102. stats.append((len(lines), 0))
  2103. # Map count of leading spaces to # we want.
  2104. have2want = {}
  2105. # Program after transformation.
  2106. after = []
  2107. # Copy over initial empty lines -- there's nothing to do until
  2108. # we see a line with *something* on it.
  2109. i = stats[0][0]
  2110. after.extend(lines[1:i])
  2111. for i in range(len(stats) - 1):
  2112. thisstmt, thislevel = stats[i]
  2113. nextstmt = stats[i + 1][0]
  2114. have = _leading_space_count(lines[thisstmt])
  2115. want = thislevel * indent_size
  2116. if want < 0:
  2117. # A comment line.
  2118. if have:
  2119. # An indented comment line. If we saw the same
  2120. # indentation before, reuse what it most recently
  2121. # mapped to.
  2122. want = have2want.get(have, -1)
  2123. if want < 0:
  2124. # Then it probably belongs to the next real stmt.
  2125. for j in range(i + 1, len(stats) - 1):
  2126. jline, jlevel = stats[j]
  2127. if jlevel >= 0:
  2128. if have == _leading_space_count(lines[jline]):
  2129. want = jlevel * indent_size
  2130. break
  2131. if want < 0: # Maybe it's a hanging
  2132. # comment like this one,
  2133. # in which case we should shift it like its base
  2134. # line got shifted.
  2135. for j in range(i - 1, -1, -1):
  2136. jline, jlevel = stats[j]
  2137. if jlevel >= 0:
  2138. want = (have + _leading_space_count(
  2139. after[jline - 1]) -
  2140. _leading_space_count(lines[jline]))
  2141. break
  2142. if want < 0:
  2143. # Still no luck -- leave it alone.
  2144. want = have
  2145. else:
  2146. want = 0
  2147. assert want >= 0
  2148. have2want[have] = want
  2149. diff = want - have
  2150. if diff == 0 or have == 0:
  2151. after.extend(lines[thisstmt:nextstmt])
  2152. else:
  2153. for line_number, line in enumerate(lines[thisstmt:nextstmt],
  2154. start=thisstmt):
  2155. if line_number in self.string_content_line_numbers:
  2156. after.append(line)
  2157. elif diff > 0:
  2158. if line == '\n':
  2159. after.append(line)
  2160. else:
  2161. after.append(' ' * diff + line)
  2162. else:
  2163. remove = min(_leading_space_count(line), -diff)
  2164. after.append(line[remove:])
  2165. return ''.join(after)
  2166. def getline(self):
  2167. """Line-getter for tokenize."""
  2168. if self.index >= len(self.lines):
  2169. line = ''
  2170. else:
  2171. line = self.lines[self.index]
  2172. self.index += 1
  2173. return line
  2174. def _reindent_stats(tokens):
  2175. """Return list of (lineno, indentlevel) pairs.
  2176. One for each stmt and comment line. indentlevel is -1 for comment
  2177. lines, as a signal that tokenize doesn't know what to do about them;
  2178. indeed, they're our headache!
  2179. """
  2180. find_stmt = 1 # Next token begins a fresh stmt?
  2181. level = 0 # Current indent level.
  2182. stats = []
  2183. for t in tokens:
  2184. token_type = t[0]
  2185. sline = t[2][0]
  2186. line = t[4]
  2187. if token_type == tokenize.NEWLINE:
  2188. # A program statement, or ENDMARKER, will eventually follow,
  2189. # after some (possibly empty) run of tokens of the form
  2190. # (NL | COMMENT)* (INDENT | DEDENT+)?
  2191. find_stmt = 1
  2192. elif token_type == tokenize.INDENT:
  2193. find_stmt = 1
  2194. level += 1
  2195. elif token_type == tokenize.DEDENT:
  2196. find_stmt = 1
  2197. level -= 1
  2198. elif token_type == tokenize.COMMENT:
  2199. if find_stmt:
  2200. stats.append((sline, -1))
  2201. # But we're still looking for a new stmt, so leave
  2202. # find_stmt alone.
  2203. elif token_type == tokenize.NL:
  2204. pass
  2205. elif find_stmt:
  2206. # This is the first "real token" following a NEWLINE, so it
  2207. # must be the first token of the next program statement, or an
  2208. # ENDMARKER.
  2209. find_stmt = 0
  2210. if line: # Not endmarker.
  2211. stats.append((sline, level))
  2212. return stats
  2213. def _leading_space_count(line):
  2214. """Return number of leading spaces in line."""
  2215. i = 0
  2216. while i < len(line) and line[i] == ' ':
  2217. i += 1
  2218. return i
  2219. def refactor_with_2to3(source_text, fixer_names, filename=''):
  2220. """Use lib2to3 to refactor the source.
  2221. Return the refactored source code.
  2222. """
  2223. from lib2to3.refactor import RefactoringTool
  2224. fixers = ['lib2to3.fixes.fix_' + name for name in fixer_names]
  2225. tool = RefactoringTool(fixer_names=fixers, explicit=fixers)
  2226. from lib2to3.pgen2 import tokenize as lib2to3_tokenize
  2227. try:
  2228. # The name parameter is necessary particularly for the "import" fixer.
  2229. return unicode(tool.refactor_string(source_text, name=filename))
  2230. except lib2to3_tokenize.TokenError:
  2231. return source_text
  2232. def check_syntax(code):
  2233. """Return True if syntax is okay."""
  2234. try:
  2235. return compile(code, '<string>', 'exec')
  2236. except (SyntaxError, TypeError, UnicodeDecodeError):
  2237. return False
  2238. def filter_results(source, results, aggressive):
  2239. """Filter out spurious reports from pycodestyle.
  2240. If aggressive is True, we allow possibly unsafe fixes (E711, E712).
  2241. """
  2242. non_docstring_string_line_numbers = multiline_string_lines(
  2243. source, include_docstrings=False)
  2244. all_string_line_numbers = multiline_string_lines(
  2245. source, include_docstrings=True)
  2246. commented_out_code_line_numbers = commented_out_code_lines(source)
  2247. has_e901 = any(result['id'].lower() == 'e901' for result in results)
  2248. for r in results:
  2249. issue_id = r['id'].lower()
  2250. if r['line'] in non_docstring_string_line_numbers:
  2251. if issue_id.startswith(('e1', 'e501', 'w191')):
  2252. continue
  2253. if r['line'] in all_string_line_numbers:
  2254. if issue_id in ['e501']:
  2255. continue
  2256. # We must offset by 1 for lines that contain the trailing contents of
  2257. # multiline strings.
  2258. if not aggressive and (r['line'] + 1) in all_string_line_numbers:
  2259. # Do not modify multiline strings in non-aggressive mode. Remove
  2260. # trailing whitespace could break doctests.
  2261. if issue_id.startswith(('w29', 'w39')):
  2262. continue
  2263. if aggressive <= 0:
  2264. if issue_id.startswith(('e711', 'e72', 'w6')):
  2265. continue
  2266. if aggressive <= 1:
  2267. if issue_id.startswith(('e712', 'e713', 'e714', 'w5')):
  2268. continue
  2269. if aggressive <= 2:
  2270. if issue_id.startswith(('e704', 'w5')):
  2271. continue
  2272. if r['line'] in commented_out_code_line_numbers:
  2273. if issue_id.startswith(('e26', 'e501')):
  2274. continue
  2275. # Do not touch indentation if there is a token error caused by
  2276. # incomplete multi-line statement. Otherwise, we risk screwing up the
  2277. # indentation.
  2278. if has_e901:
  2279. if issue_id.startswith(('e1', 'e7')):
  2280. continue
  2281. yield r
  2282. def multiline_string_lines(source, include_docstrings=False):
  2283. """Return line numbers that are within multiline strings.
  2284. The line numbers are indexed at 1.
  2285. Docstrings are ignored.
  2286. """
  2287. line_numbers = set()
  2288. previous_token_type = ''
  2289. try:
  2290. for t in generate_tokens(source):
  2291. token_type = t[0]
  2292. start_row = t[2][0]
  2293. end_row = t[3][0]
  2294. if token_type == tokenize.STRING and start_row != end_row:
  2295. if (
  2296. include_docstrings or
  2297. previous_token_type != tokenize.INDENT
  2298. ):
  2299. # We increment by one since we want the contents of the
  2300. # string.
  2301. line_numbers |= set(range(1 + start_row, 1 + end_row))
  2302. previous_token_type = token_type
  2303. except (SyntaxError, tokenize.TokenError):
  2304. pass
  2305. return line_numbers
  2306. def commented_out_code_lines(source):
  2307. """Return line numbers of comments that are likely code.
  2308. Commented-out code is bad practice, but modifying it just adds even
  2309. more clutter.
  2310. """
  2311. line_numbers = []
  2312. try:
  2313. for t in generate_tokens(source):
  2314. token_type = t[0]
  2315. token_string = t[1]
  2316. start_row = t[2][0]
  2317. line = t[4]
  2318. # Ignore inline comments.
  2319. if not line.lstrip().startswith('#'):
  2320. continue
  2321. if token_type == tokenize.COMMENT:
  2322. stripped_line = token_string.lstrip('#').strip()
  2323. if (
  2324. ' ' in stripped_line and
  2325. '#' not in stripped_line and
  2326. check_syntax(stripped_line)
  2327. ):
  2328. line_numbers.append(start_row)
  2329. except (SyntaxError, tokenize.TokenError):
  2330. pass
  2331. return line_numbers
  2332. def shorten_comment(line, max_line_length, last_comment=False):
  2333. """Return trimmed or split long comment line.
  2334. If there are no comments immediately following it, do a text wrap.
  2335. Doing this wrapping on all comments in general would lead to jagged
  2336. comment text.
  2337. """
  2338. assert len(line) > max_line_length
  2339. line = line.rstrip()
  2340. # PEP 8 recommends 72 characters for comment text.
  2341. indentation = _get_indentation(line) + '# '
  2342. max_line_length = min(max_line_length,
  2343. len(indentation) + 72)
  2344. MIN_CHARACTER_REPEAT = 5
  2345. if (
  2346. len(line) - len(line.rstrip(line[-1])) >= MIN_CHARACTER_REPEAT and
  2347. not line[-1].isalnum()
  2348. ):
  2349. # Trim comments that end with things like ---------
  2350. return line[:max_line_length] + '\n'
  2351. elif last_comment and re.match(r'\s*#+\s*\w+', line):
  2352. split_lines = textwrap.wrap(line.lstrip(' \t#'),
  2353. initial_indent=indentation,
  2354. subsequent_indent=indentation,
  2355. width=max_line_length,
  2356. break_long_words=False,
  2357. break_on_hyphens=False)
  2358. return '\n'.join(split_lines) + '\n'
  2359. else:
  2360. return line + '\n'
  2361. def normalize_line_endings(lines, newline):
  2362. """Return fixed line endings.
  2363. All lines will be modified to use the most common line ending.
  2364. """
  2365. return [line.rstrip('\n\r') + newline for line in lines]
  2366. def mutual_startswith(a, b):
  2367. return b.startswith(a) or a.startswith(b)
  2368. def code_match(code, select, ignore):
  2369. if ignore:
  2370. assert not isinstance(ignore, unicode)
  2371. for ignored_code in [c.strip() for c in ignore]:
  2372. if mutual_startswith(code.lower(), ignored_code.lower()):
  2373. return False
  2374. if select:
  2375. assert not isinstance(select, unicode)
  2376. for selected_code in [c.strip() for c in select]:
  2377. if mutual_startswith(code.lower(), selected_code.lower()):
  2378. return True
  2379. return False
  2380. return True
  2381. def fix_code(source, options=None, encoding=None, apply_config=False):
  2382. """Return fixed source code.
  2383. "encoding" will be used to decode "source" if it is a byte string.
  2384. """
  2385. options = _get_options(options, apply_config)
  2386. if not isinstance(source, unicode):
  2387. source = source.decode(encoding or get_encoding())
  2388. sio = io.StringIO(source)
  2389. return fix_lines(sio.readlines(), options=options)
  2390. def _get_options(raw_options, apply_config):
  2391. """Return parsed options."""
  2392. if not raw_options:
  2393. return parse_args([''], apply_config=apply_config)
  2394. if isinstance(raw_options, dict):
  2395. options = parse_args([''], apply_config=apply_config)
  2396. for name, value in raw_options.items():
  2397. if not hasattr(options, name):
  2398. raise ValueError("No such option '{}'".format(name))
  2399. # Check for very basic type errors.
  2400. expected_type = type(getattr(options, name))
  2401. if not isinstance(expected_type, (str, unicode)):
  2402. if isinstance(value, (str, unicode)):
  2403. raise ValueError(
  2404. "Option '{}' should not be a string".format(name))
  2405. setattr(options, name, value)
  2406. else:
  2407. options = raw_options
  2408. return options
  2409. def fix_lines(source_lines, options, filename=''):
  2410. """Return fixed source code."""
  2411. # Transform everything to line feed. Then change them back to original
  2412. # before returning fixed source code.
  2413. original_newline = find_newline(source_lines)
  2414. tmp_source = ''.join(normalize_line_endings(source_lines, '\n'))
  2415. # Keep a history to break out of cycles.
  2416. previous_hashes = set()
  2417. if options.line_range:
  2418. # Disable "apply_local_fixes()" for now due to issue #175.
  2419. fixed_source = tmp_source
  2420. else:
  2421. # Apply global fixes only once (for efficiency).
  2422. fixed_source = apply_global_fixes(tmp_source,
  2423. options,
  2424. filename=filename)
  2425. passes = 0
  2426. long_line_ignore_cache = set()
  2427. while hash(fixed_source) not in previous_hashes:
  2428. if options.pep8_passes >= 0 and passes > options.pep8_passes:
  2429. break
  2430. passes += 1
  2431. previous_hashes.add(hash(fixed_source))
  2432. tmp_source = copy.copy(fixed_source)
  2433. fix = FixPEP8(
  2434. filename,
  2435. options,
  2436. contents=tmp_source,
  2437. long_line_ignore_cache=long_line_ignore_cache)
  2438. fixed_source = fix.fix()
  2439. sio = io.StringIO(fixed_source)
  2440. return ''.join(normalize_line_endings(sio.readlines(), original_newline))
  2441. def fix_file(filename, options=None, output=None, apply_config=False):
  2442. if not options:
  2443. options = parse_args([filename], apply_config=apply_config)
  2444. original_source = readlines_from_file(filename)
  2445. fixed_source = original_source
  2446. if options.in_place or output:
  2447. encoding = detect_encoding(filename)
  2448. if output:
  2449. output = LineEndingWrapper(wrap_output(output, encoding=encoding))
  2450. fixed_source = fix_lines(fixed_source, options, filename=filename)
  2451. if options.diff:
  2452. new = io.StringIO(fixed_source)
  2453. new = new.readlines()
  2454. diff = get_diff_text(original_source, new, filename)
  2455. if output:
  2456. output.write(diff)
  2457. output.flush()
  2458. else:
  2459. return diff
  2460. elif options.in_place:
  2461. fp = open_with_encoding(filename, encoding=encoding, mode='w')
  2462. fp.write(fixed_source)
  2463. fp.close()
  2464. else:
  2465. if output:
  2466. output.write(fixed_source)
  2467. output.flush()
  2468. else:
  2469. return fixed_source
  2470. def global_fixes():
  2471. """Yield multiple (code, function) tuples."""
  2472. for function in list(globals().values()):
  2473. if inspect.isfunction(function):
  2474. arguments = _get_parameters(function)
  2475. if arguments[:1] != ['source']:
  2476. continue
  2477. code = extract_code_from_function(function)
  2478. if code:
  2479. yield (code, function)
  2480. def _get_parameters(function):
  2481. # pylint: disable=deprecated-method
  2482. if sys.version_info >= (3, 3):
  2483. # We need to match "getargspec()", which includes "self" as the first
  2484. # value for methods.
  2485. # https://bugs.python.org/issue17481#msg209469
  2486. if inspect.ismethod(function):
  2487. function = function.__func__
  2488. return list(inspect.signature(function).parameters)
  2489. else:
  2490. return inspect.getargspec(function)[0]
  2491. def apply_global_fixes(source, options, where='global', filename=''):
  2492. """Run global fixes on source code.
  2493. These are fixes that only need be done once (unlike those in
  2494. FixPEP8, which are dependent on pycodestyle).
  2495. """
  2496. if any(code_match(code, select=options.select, ignore=options.ignore)
  2497. for code in ['E101', 'E111']):
  2498. source = reindent(source,
  2499. indent_size=options.indent_size)
  2500. for (code, function) in global_fixes():
  2501. if code_match(code, select=options.select, ignore=options.ignore):
  2502. if options.verbose:
  2503. print('---> Applying {0} fix for {1}'.format(where,
  2504. code.upper()),
  2505. file=sys.stderr)
  2506. source = function(source,
  2507. aggressive=options.aggressive)
  2508. source = fix_2to3(source,
  2509. aggressive=options.aggressive,
  2510. select=options.select,
  2511. ignore=options.ignore,
  2512. filename=filename)
  2513. return source
  2514. def extract_code_from_function(function):
  2515. """Return code handled by function."""
  2516. if not function.__name__.startswith('fix_'):
  2517. return None
  2518. code = re.sub('^fix_', '', function.__name__)
  2519. if not code:
  2520. return None
  2521. try:
  2522. int(code[1:])
  2523. except ValueError:
  2524. return None
  2525. return code
  2526. def _get_package_version():
  2527. packages = ["pycodestyle: {0}".format(pycodestyle.__version__)]
  2528. return ", ".join(packages)
  2529. def create_parser():
  2530. """Return command-line parser."""
  2531. # Do import locally to be friendly to those who use autopep8 as a library
  2532. # and are supporting Python 2.6.
  2533. import argparse
  2534. parser = argparse.ArgumentParser(description=docstring_summary(__doc__),
  2535. prog='autopep8')
  2536. parser.add_argument('--version', action='version',
  2537. version='%(prog)s {0} ({1})'.format(
  2538. __version__, _get_package_version()))
  2539. parser.add_argument('-v', '--verbose', action='count',
  2540. default=0,
  2541. help='print verbose messages; '
  2542. 'multiple -v result in more verbose messages')
  2543. parser.add_argument('-d', '--diff', action='store_true',
  2544. help='print the diff for the fixed source')
  2545. parser.add_argument('-i', '--in-place', action='store_true',
  2546. help='make changes to files in place')
  2547. parser.add_argument('--global-config', metavar='filename',
  2548. default=DEFAULT_CONFIG,
  2549. help='path to a global pep8 config file; if this file '
  2550. 'does not exist then this is ignored '
  2551. '(default: {0})'.format(DEFAULT_CONFIG))
  2552. parser.add_argument('--ignore-local-config', action='store_true',
  2553. help="don't look for and apply local config files; "
  2554. 'if not passed, defaults are updated with any '
  2555. "config files in the project's root directory")
  2556. parser.add_argument('-r', '--recursive', action='store_true',
  2557. help='run recursively over directories; '
  2558. 'must be used with --in-place or --diff')
  2559. parser.add_argument('-j', '--jobs', type=int, metavar='n', default=1,
  2560. help='number of parallel jobs; '
  2561. 'match CPU count if value is less than 1')
  2562. parser.add_argument('-p', '--pep8-passes', metavar='n',
  2563. default=-1, type=int,
  2564. help='maximum number of additional pep8 passes '
  2565. '(default: infinite)')
  2566. parser.add_argument('-a', '--aggressive', action='count', default=0,
  2567. help='enable non-whitespace changes; '
  2568. 'multiple -a result in more aggressive changes')
  2569. parser.add_argument('--experimental', action='store_true',
  2570. help='enable experimental fixes')
  2571. parser.add_argument('--exclude', metavar='globs',
  2572. help='exclude file/directory names that match these '
  2573. 'comma-separated globs')
  2574. parser.add_argument('--list-fixes', action='store_true',
  2575. help='list codes for fixes; '
  2576. 'used by --ignore and --select')
  2577. parser.add_argument('--ignore', metavar='errors', default='',
  2578. help='do not fix these errors/warnings '
  2579. '(default: {0})'.format(DEFAULT_IGNORE))
  2580. parser.add_argument('--select', metavar='errors', default='',
  2581. help='fix only these errors/warnings (e.g. E4,W)')
  2582. parser.add_argument('--max-line-length', metavar='n', default=79, type=int,
  2583. help='set maximum allowed line length '
  2584. '(default: %(default)s)')
  2585. parser.add_argument('--line-range', '--range', metavar='line',
  2586. default=None, type=int, nargs=2,
  2587. help='only fix errors found within this inclusive '
  2588. 'range of line numbers (e.g. 1 99); '
  2589. 'line numbers are indexed at 1')
  2590. parser.add_argument('--indent-size', default=DEFAULT_INDENT_SIZE,
  2591. type=int, help=argparse.SUPPRESS)
  2592. parser.add_argument('files', nargs='*',
  2593. help="files to format or '-' for standard in")
  2594. return parser
  2595. def parse_args(arguments, apply_config=False):
  2596. """Parse command-line options."""
  2597. parser = create_parser()
  2598. args = parser.parse_args(arguments)
  2599. if not args.files and not args.list_fixes:
  2600. parser.error('incorrect number of arguments')
  2601. args.files = [decode_filename(name) for name in args.files]
  2602. if apply_config:
  2603. parser = read_config(args, parser)
  2604. args = parser.parse_args(arguments)
  2605. args.files = [decode_filename(name) for name in args.files]
  2606. if '-' in args.files:
  2607. if len(args.files) > 1:
  2608. parser.error('cannot mix stdin and regular files')
  2609. if args.diff:
  2610. parser.error('--diff cannot be used with standard input')
  2611. if args.in_place:
  2612. parser.error('--in-place cannot be used with standard input')
  2613. if args.recursive:
  2614. parser.error('--recursive cannot be used with standard input')
  2615. if len(args.files) > 1 and not (args.in_place or args.diff):
  2616. parser.error('autopep8 only takes one filename as argument '
  2617. 'unless the "--in-place" or "--diff" args are '
  2618. 'used')
  2619. if args.recursive and not (args.in_place or args.diff):
  2620. parser.error('--recursive must be used with --in-place or --diff')
  2621. if args.in_place and args.diff:
  2622. parser.error('--in-place and --diff are mutually exclusive')
  2623. if args.max_line_length <= 0:
  2624. parser.error('--max-line-length must be greater than 0')
  2625. if args.select:
  2626. args.select = _split_comma_separated(args.select)
  2627. if args.ignore:
  2628. args.ignore = _split_comma_separated(args.ignore)
  2629. elif not args.select:
  2630. if args.aggressive:
  2631. # Enable everything by default if aggressive.
  2632. args.select = set(['E', 'W'])
  2633. else:
  2634. args.ignore = _split_comma_separated(DEFAULT_IGNORE)
  2635. if args.exclude:
  2636. args.exclude = _split_comma_separated(args.exclude)
  2637. else:
  2638. args.exclude = set([])
  2639. if args.jobs < 1:
  2640. # Do not import multiprocessing globally in case it is not supported
  2641. # on the platform.
  2642. import multiprocessing
  2643. args.jobs = multiprocessing.cpu_count()
  2644. if args.jobs > 1 and not args.in_place:
  2645. parser.error('parallel jobs requires --in-place')
  2646. if args.line_range:
  2647. if args.line_range[0] <= 0:
  2648. parser.error('--range must be positive numbers')
  2649. if args.line_range[0] > args.line_range[1]:
  2650. parser.error('First value of --range should be less than or equal '
  2651. 'to the second')
  2652. return args
  2653. def read_config(args, parser):
  2654. """Read both user configuration and local configuration."""
  2655. try:
  2656. from configparser import ConfigParser as SafeConfigParser
  2657. from configparser import Error
  2658. except ImportError:
  2659. from ConfigParser import SafeConfigParser
  2660. from ConfigParser import Error
  2661. config = SafeConfigParser()
  2662. try:
  2663. config.read(args.global_config)
  2664. if not args.ignore_local_config:
  2665. parent = tail = args.files and os.path.abspath(
  2666. os.path.commonprefix(args.files))
  2667. while tail:
  2668. if config.read([os.path.join(parent, fn)
  2669. for fn in PROJECT_CONFIG]):
  2670. break
  2671. (parent, tail) = os.path.split(parent)
  2672. defaults = dict()
  2673. option_list = dict([(o.dest, o.type or type(o.default))
  2674. for o in parser._actions])
  2675. for section in ['pep8', 'pycodestyle']:
  2676. if not config.has_section(section):
  2677. continue
  2678. for k, v in config.items(section):
  2679. norm_opt = k.lstrip('-').replace('-', '_')
  2680. opt_type = option_list[norm_opt]
  2681. if opt_type is int:
  2682. value = config.getint(section, k)
  2683. elif opt_type is bool:
  2684. value = config.getboolean(section, k)
  2685. else:
  2686. value = config.get(section, k)
  2687. defaults[norm_opt] = value
  2688. parser.set_defaults(**defaults)
  2689. except Error:
  2690. # Ignore for now.
  2691. pass
  2692. return parser
  2693. def _split_comma_separated(string):
  2694. """Return a set of strings."""
  2695. return set(text.strip() for text in string.split(',') if text.strip())
  2696. def decode_filename(filename):
  2697. """Return Unicode filename."""
  2698. if isinstance(filename, unicode):
  2699. return filename
  2700. else:
  2701. return filename.decode(sys.getfilesystemencoding())
  2702. def supported_fixes():
  2703. """Yield pep8 error codes that autopep8 fixes.
  2704. Each item we yield is a tuple of the code followed by its
  2705. description.
  2706. """
  2707. yield ('E101', docstring_summary(reindent.__doc__))
  2708. instance = FixPEP8(filename=None, options=None, contents='')
  2709. for attribute in dir(instance):
  2710. code = re.match('fix_([ew][0-9][0-9][0-9])', attribute)
  2711. if code:
  2712. yield (
  2713. code.group(1).upper(),
  2714. re.sub(r'\s+', ' ',
  2715. docstring_summary(getattr(instance, attribute).__doc__))
  2716. )
  2717. for (code, function) in sorted(global_fixes()):
  2718. yield (code.upper() + (4 - len(code)) * ' ',
  2719. re.sub(r'\s+', ' ', docstring_summary(function.__doc__)))
  2720. for code in sorted(CODE_TO_2TO3):
  2721. yield (code.upper() + (4 - len(code)) * ' ',
  2722. re.sub(r'\s+', ' ', docstring_summary(fix_2to3.__doc__)))
  2723. def docstring_summary(docstring):
  2724. """Return summary of docstring."""
  2725. return docstring.split('\n')[0] if docstring else ''
  2726. def line_shortening_rank(candidate, indent_word, max_line_length,
  2727. experimental=False):
  2728. """Return rank of candidate.
  2729. This is for sorting candidates.
  2730. """
  2731. if not candidate.strip():
  2732. return 0
  2733. rank = 0
  2734. lines = candidate.rstrip().split('\n')
  2735. offset = 0
  2736. if (
  2737. not lines[0].lstrip().startswith('#') and
  2738. lines[0].rstrip()[-1] not in '([{'
  2739. ):
  2740. for (opening, closing) in ('()', '[]', '{}'):
  2741. # Don't penalize empty containers that aren't split up. Things like
  2742. # this "foo(\n )" aren't particularly good.
  2743. opening_loc = lines[0].find(opening)
  2744. closing_loc = lines[0].find(closing)
  2745. if opening_loc >= 0:
  2746. if closing_loc < 0 or closing_loc != opening_loc + 1:
  2747. offset = max(offset, 1 + opening_loc)
  2748. current_longest = max(offset + len(x.strip()) for x in lines)
  2749. rank += 4 * max(0, current_longest - max_line_length)
  2750. rank += len(lines)
  2751. # Too much variation in line length is ugly.
  2752. rank += 2 * standard_deviation(len(line) for line in lines)
  2753. bad_staring_symbol = {
  2754. '(': ')',
  2755. '[': ']',
  2756. '{': '}'}.get(lines[0][-1])
  2757. if len(lines) > 1:
  2758. if (
  2759. bad_staring_symbol and
  2760. lines[1].lstrip().startswith(bad_staring_symbol)
  2761. ):
  2762. rank += 20
  2763. for lineno, current_line in enumerate(lines):
  2764. current_line = current_line.strip()
  2765. if current_line.startswith('#'):
  2766. continue
  2767. for bad_start in ['.', '%', '+', '-', '/']:
  2768. if current_line.startswith(bad_start):
  2769. rank += 100
  2770. # Do not tolerate operators on their own line.
  2771. if current_line == bad_start:
  2772. rank += 1000
  2773. if (
  2774. current_line.endswith(('.', '%', '+', '-', '/')) and
  2775. "': " in current_line
  2776. ):
  2777. rank += 1000
  2778. if current_line.endswith(('(', '[', '{', '.')):
  2779. # Avoid lonely opening. They result in longer lines.
  2780. if len(current_line) <= len(indent_word):
  2781. rank += 100
  2782. # Avoid the ugliness of ", (\n".
  2783. if (
  2784. current_line.endswith('(') and
  2785. current_line[:-1].rstrip().endswith(',')
  2786. ):
  2787. rank += 100
  2788. # Avoid the ugliness of "something[\n" and something[index][\n.
  2789. if (
  2790. current_line.endswith('[') and
  2791. len(current_line) > 1 and
  2792. (current_line[-2].isalnum() or current_line[-2] in ']')
  2793. ):
  2794. rank += 300
  2795. # Also avoid the ugliness of "foo.\nbar"
  2796. if current_line.endswith('.'):
  2797. rank += 100
  2798. if has_arithmetic_operator(current_line):
  2799. rank += 100
  2800. # Avoid breaking at unary operators.
  2801. if re.match(r'.*[(\[{]\s*[\-\+~]$', current_line.rstrip('\\ ')):
  2802. rank += 1000
  2803. if re.match(r'.*lambda\s*\*$', current_line.rstrip('\\ ')):
  2804. rank += 1000
  2805. if current_line.endswith(('%', '(', '[', '{')):
  2806. rank -= 20
  2807. # Try to break list comprehensions at the "for".
  2808. if current_line.startswith('for '):
  2809. rank -= 50
  2810. if current_line.endswith('\\'):
  2811. # If a line ends in \-newline, it may be part of a
  2812. # multiline string. In that case, we would like to know
  2813. # how long that line is without the \-newline. If it's
  2814. # longer than the maximum, or has comments, then we assume
  2815. # that the \-newline is an okay candidate and only
  2816. # penalize it a bit.
  2817. total_len = len(current_line)
  2818. lineno += 1
  2819. while lineno < len(lines):
  2820. total_len += len(lines[lineno])
  2821. if lines[lineno].lstrip().startswith('#'):
  2822. total_len = max_line_length
  2823. break
  2824. if not lines[lineno].endswith('\\'):
  2825. break
  2826. lineno += 1
  2827. if total_len < max_line_length:
  2828. rank += 10
  2829. else:
  2830. rank += 100 if experimental else 1
  2831. # Prefer breaking at commas rather than colon.
  2832. if ',' in current_line and current_line.endswith(':'):
  2833. rank += 10
  2834. # Avoid splitting dictionaries between key and value.
  2835. if current_line.endswith(':'):
  2836. rank += 100
  2837. rank += 10 * count_unbalanced_brackets(current_line)
  2838. return max(0, rank)
  2839. def standard_deviation(numbers):
  2840. """Return standard devation."""
  2841. numbers = list(numbers)
  2842. if not numbers:
  2843. return 0
  2844. mean = sum(numbers) / len(numbers)
  2845. return (sum((n - mean) ** 2 for n in numbers) /
  2846. len(numbers)) ** .5
  2847. def has_arithmetic_operator(line):
  2848. """Return True if line contains any arithmetic operators."""
  2849. for operator in pycodestyle.ARITHMETIC_OP:
  2850. if operator in line:
  2851. return True
  2852. return False
  2853. def count_unbalanced_brackets(line):
  2854. """Return number of unmatched open/close brackets."""
  2855. count = 0
  2856. for opening, closing in ['()', '[]', '{}']:
  2857. count += abs(line.count(opening) - line.count(closing))
  2858. return count
  2859. def split_at_offsets(line, offsets):
  2860. """Split line at offsets.
  2861. Return list of strings.
  2862. """
  2863. result = []
  2864. previous_offset = 0
  2865. current_offset = 0
  2866. for current_offset in sorted(offsets):
  2867. if current_offset < len(line) and previous_offset != current_offset:
  2868. result.append(line[previous_offset:current_offset].strip())
  2869. previous_offset = current_offset
  2870. result.append(line[current_offset:])
  2871. return result
  2872. class LineEndingWrapper(object):
  2873. r"""Replace line endings to work with sys.stdout.
  2874. It seems that sys.stdout expects only '\n' as the line ending, no matter
  2875. the platform. Otherwise, we get repeated line endings.
  2876. """
  2877. def __init__(self, output):
  2878. self.__output = output
  2879. def write(self, s):
  2880. self.__output.write(s.replace('\r\n', '\n').replace('\r', '\n'))
  2881. def flush(self):
  2882. self.__output.flush()
  2883. def match_file(filename, exclude):
  2884. """Return True if file is okay for modifying/recursing."""
  2885. base_name = os.path.basename(filename)
  2886. if base_name.startswith('.'):
  2887. return False
  2888. for pattern in exclude:
  2889. if fnmatch.fnmatch(base_name, pattern):
  2890. return False
  2891. if fnmatch.fnmatch(filename, pattern):
  2892. return False
  2893. if not os.path.isdir(filename) and not is_python_file(filename):
  2894. return False
  2895. return True
  2896. def find_files(filenames, recursive, exclude):
  2897. """Yield filenames."""
  2898. while filenames:
  2899. name = filenames.pop(0)
  2900. if recursive and os.path.isdir(name):
  2901. for root, directories, children in os.walk(name):
  2902. filenames += [os.path.join(root, f) for f in children
  2903. if match_file(os.path.join(root, f),
  2904. exclude)]
  2905. directories[:] = [d for d in directories
  2906. if match_file(os.path.join(root, d),
  2907. exclude)]
  2908. else:
  2909. yield name
  2910. def _fix_file(parameters):
  2911. """Helper function for optionally running fix_file() in parallel."""
  2912. if parameters[1].verbose:
  2913. print('[file:{0}]'.format(parameters[0]), file=sys.stderr)
  2914. try:
  2915. fix_file(*parameters)
  2916. except IOError as error:
  2917. print(unicode(error), file=sys.stderr)
  2918. def fix_multiple_files(filenames, options, output=None):
  2919. """Fix list of files.
  2920. Optionally fix files recursively.
  2921. """
  2922. filenames = find_files(filenames, options.recursive, options.exclude)
  2923. if options.jobs > 1:
  2924. import multiprocessing
  2925. pool = multiprocessing.Pool(options.jobs)
  2926. pool.map(_fix_file,
  2927. [(name, options) for name in filenames])
  2928. else:
  2929. for name in filenames:
  2930. _fix_file((name, options, output))
  2931. def is_python_file(filename):
  2932. """Return True if filename is Python file."""
  2933. if filename.endswith('.py'):
  2934. return True
  2935. try:
  2936. with open_with_encoding(
  2937. filename,
  2938. limit_byte_check=MAX_PYTHON_FILE_DETECTION_BYTES) as f:
  2939. text = f.read(MAX_PYTHON_FILE_DETECTION_BYTES)
  2940. if not text:
  2941. return False
  2942. first_line = text.splitlines()[0]
  2943. except (IOError, IndexError):
  2944. return False
  2945. if not PYTHON_SHEBANG_REGEX.match(first_line):
  2946. return False
  2947. return True
  2948. def is_probably_part_of_multiline(line):
  2949. """Return True if line is likely part of a multiline string.
  2950. When multiline strings are involved, pep8 reports the error as being
  2951. at the start of the multiline string, which doesn't work for us.
  2952. """
  2953. return (
  2954. '"""' in line or
  2955. "'''" in line or
  2956. line.rstrip().endswith('\\')
  2957. )
  2958. def wrap_output(output, encoding):
  2959. """Return output with specified encoding."""
  2960. return codecs.getwriter(encoding)(output.buffer
  2961. if hasattr(output, 'buffer')
  2962. else output)
  2963. def get_encoding():
  2964. """Return preferred encoding."""
  2965. return locale.getpreferredencoding() or sys.getdefaultencoding()
  2966. def main(argv=None, apply_config=True):
  2967. """Command-line entry."""
  2968. if argv is None:
  2969. argv = sys.argv
  2970. try:
  2971. # Exit on broken pipe.
  2972. signal.signal(signal.SIGPIPE, signal.SIG_DFL)
  2973. except AttributeError: # pragma: no cover
  2974. # SIGPIPE is not available on Windows.
  2975. pass
  2976. try:
  2977. args = parse_args(argv[1:], apply_config=apply_config)
  2978. if args.list_fixes:
  2979. for code, description in sorted(supported_fixes()):
  2980. print('{code} - {description}'.format(
  2981. code=code, description=description))
  2982. return 0
  2983. if args.files == ['-']:
  2984. assert not args.in_place
  2985. encoding = sys.stdin.encoding or get_encoding()
  2986. # LineEndingWrapper is unnecessary here due to the symmetry between
  2987. # standard in and standard out.
  2988. wrap_output(sys.stdout, encoding=encoding).write(
  2989. fix_code(sys.stdin.read(), args, encoding=encoding))
  2990. else:
  2991. if args.in_place or args.diff:
  2992. args.files = list(set(args.files))
  2993. else:
  2994. assert len(args.files) == 1
  2995. assert not args.recursive
  2996. fix_multiple_files(args.files, args, sys.stdout)
  2997. except KeyboardInterrupt:
  2998. return 1 # pragma: no cover
  2999. class CachedTokenizer(object):
  3000. """A one-element cache around tokenize.generate_tokens().
  3001. Original code written by Ned Batchelder, in coverage.py.
  3002. """
  3003. def __init__(self):
  3004. self.last_text = None
  3005. self.last_tokens = None
  3006. def generate_tokens(self, text):
  3007. """A stand-in for tokenize.generate_tokens()."""
  3008. if text != self.last_text:
  3009. string_io = io.StringIO(text)
  3010. self.last_tokens = list(
  3011. tokenize.generate_tokens(string_io.readline)
  3012. )
  3013. self.last_text = text
  3014. return self.last_tokens
  3015. _cached_tokenizer = CachedTokenizer()
  3016. generate_tokens = _cached_tokenizer.generate_tokens
  3017. if __name__ == '__main__':
  3018. sys.exit(main())