Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

autopep8.py 152KB

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