3 \=m@s<dZdZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z m Z m Z ddlmZddlmZmZdd lmZd&d d ZGd ddeZddZddZddZddZejd'krddlZejZddZ ddZ!n eZeZ eZ!ddZ"GdddeZ#Gd d!d!e$Z%Gd"d#d#eZ&Gd$d%d%e%Z'dS)(zRefactoring framework. Used as a main program, this can refactor any number of files and/or recursively descend down directories. Imported as a module, this provides infrastructure to write your own refactoring tool. z#Guido van Rossum N)chain)drivertokenizetoken) find_root)pytreepygram) btm_matcherTcCstt|ggdg}tjj|j}g}xLttj|D]:}|jdr2|jdr2|rZ|dd}|j |ddq2W|S)zEReturn a sorted list of all available fix names in the given package.*fix_z.pyN) __import__ospathdirname__file__sortedlistdir startswithendswithappend)Z fixer_pkgZ remove_prefixZpkgZ fixer_dirZ fix_namesnamer /usr/lib64/python3.6/refactor.pyget_all_fix_namess rc@s eZdZdS) _EveryNodeN)__name__ __module__ __qualname__rrrrr+srcCst|tjtjfr(|jdkr t|jhSt|tjrH|jrDt|jStt|tj rt }x*|jD] }x|D]}|j t|qlWqbW|St d|dS)zf Accepts a pytree Pattern Node and returns a set of the pattern types which will match first. Nz$Oh no! I don't understand pattern %s) isinstancerZ NodePatternZ LeafPatterntyperZNegatedPatternZcontent_get_head_typesZWildcardPatternsetupdate Exception)Zpatrpxrrrr$/s      r$c Cstjt}g}x|D]|}|jrjyt|j}Wntk rJ|j|YqXxB|D]}||j|qRWq|jdk r||jj|q|j|qWx,tt j j j t j j D]}||j|qWt|S)z^ Accepts a list of fixers and returns a dictionary of head node type --> fixer list. N) collections defaultdictlistpatternr$rrZ _accept_typerr python_grammarZ symbol2numbervaluestokensextenddict)Z fixer_listZ head_nodesZeveryfixerZheadsZ node_typerrr_get_headnode_dictKs"    r5csfddtdDS)zN Return the fully qualified names for fixers in the package pkg_name. csg|]}d|qS).r).0fix_name)pkg_namerr hsz+get_fixers_from_package..F)r)r9r)r9rget_fixers_from_packageds r;cCs|S)Nr)objrrr _identityksr=rcCs |jddS)Nz  )replace)inputrrr_from_system_newlinesrsrAcCs tjdkr|jdtjS|SdS)Nr>)rlinesepr?)r@rrr_to_system_newlinests rCc sTd}tjtj|jfdd}ttjtjtj h}t }yx|\}}||krVq@q@|tj krl|rfPd}q@|tj ko||dkr,|\}}|tj ks|dkrP|\}}|tj ks|dkrP|\}}|tj kr|dkr|\}}xJ|tj kr(|j||\}}|tj ks|d krP|\}}qWq@Pq@WWntk rJYnXt|S) NFcst}|d|dfS)Nrr)next)tok)genrradvancesz(_detect_future_features..advanceTfromZ __future__import(,)rgenerate_tokensioStringIOreadline frozensetrNEWLINENLCOMMENTr%STRINGNAMEOPadd StopIteration)sourceZhave_docstringrGignorefeaturestpvaluer)rFr_detect_future_featuressD          r^c@seZdZdZdS) FixerErrorzA fixer could not be loaded.N)rr r!__doc__rrrrr_sr_c@seZdZdddZdZdZd4ddZdd Zd d Zd d Z ddZ ddZ d5ddZ d6ddZ ddZd7ddZddZd8ddZddZd d!Zd9d"d#Zd:d$d%Zd&Zd'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3ZdS);RefactoringToolF)print_functionwrite_unchanged_filesZFixr NcCs2||_|p g|_|jj|_|dk r0|jj||jdrDtj|_ntj |_|jj d|_ g|_ t jd|_g|_d|_tj|jtj|jd|_|j\|_|_g|_tj|_g|_g|_xXt|j|jD]F}|j r|jj!|q||jkr|jj"|q||jkr|jj"|qWt#|j|_$t#|j|_%dS)zInitializer. Args: fixer_names: a list of fixers to import options: a dict with configuration. explicit: a list of fixers to run even if they are explicit. NrbrcraF)convertlogger)&fixersexplicit_default_optionscopyoptionsr&r !python_grammar_no_print_statementgrammarr/getrcerrorsloggingZ getLoggerre fixer_logwroterZDriverrrd get_fixers pre_order post_orderfilesbmZ BottomMatcherBMZ bmi_pre_orderZbmi_post_orderrZ BM_compatibleZ add_fixerrr5bmi_pre_order_headsbmi_post_order_heads)selfZ fixer_namesrjrgr4rrr__init__s<           zRefactoringTool.__init__c Cs\g}g}x&|jD]}t|iidg}|jddd}|j|jrV|t|jd}|jd}|jdjdd|D}yt ||}Wn$t k rt d ||fYnX||j |j } | jr|jd k r||jkr|jd |q|jd || jd kr|j| q| jdkr |j| qt d| jqWtjd} |j| d|j| d||fS)aInspects the options to load the requested patterns and handlers. Returns: (pre_order, post_order), where pre_order is the list of fixers that want a pre-order AST traversal, and post_order is the list that want post-order traversal. r r6rN_cSsg|] }|jqSr)title)r7r)rrrr:sz.RefactoringTool.get_fixers..zCan't find %s.%sTzSkipping optional fixer: %szAdding transformation: %sZpreZpostzIllegal fixer order: %rZ run_order)key)rfrrsplitr FILE_PREFIXlensplit CLASS_PREFIXjoingetattrAttributeErrorr_rjrprg log_message log_debugorderroperator attrgettersort) rzZpre_order_fixersZpost_order_fixersZ fix_mod_pathmodr8parts class_nameZ fix_classr4Zkey_funcrrrrrs8            zRefactoringTool.get_fixerscOsdS)zCalled when an error occurs.Nr)rzmsgargskwdsrrr log_errorszRefactoringTool.log_errorcGs|r ||}|jj|dS)zHook to log a message.N)reinfo)rzrrrrrrszRefactoringTool.log_messagecGs|r ||}|jj|dS)N)redebug)rzrrrrrrszRefactoringTool.log_debugcCsdS)zTCalled with the old version, new version, and filename of a refactored file.Nr)rzold_textnew_textfilenameequalrrr print_outputszRefactoringTool.print_outputcCs<x6|D].}tjj|r&|j|||q|j|||qWdS)z)Refactor a list of files and directories.N)rrisdir refactor_dir refactor_file)rzitemswrite doctests_onlyZ dir_or_filerrrrefactor#s  zRefactoringTool.refactorc Cstjd}xtj|D]\}}}|jd||j|jxH|D]@}|jd rBtjj|d|krBtjj||} |j | ||qBWdd|D|dd<qWdS)zDescends down a directory and refactor every Python file found. Python files are assumed to have a .py extension. Files and subdirectories starting with '.' are skipped. pyzDescending into %sr6rcSsg|]}|jds|qS)r6)r)r7Zdnrrrr:>sz0RefactoringTool.refactor_dir..N) rextsepwalkrrrrsplitextrr) rzZdir_namerrZpy_extdirpathZdirnames filenamesrfullnamerrrr,s    zRefactoringTool.refactor_dircCsyt|d}Wn.tk r<}z|jd||dSd}~XnXztj|jd}Wd|jXt|d|d}t|j |fSQRXdS)zG Do our best to decode a Python source file correctly. rbzCan't open %s: %sNrr()encoding)NN) openOSErrorrrdetect_encodingrOclose_open_with_encodingrAread)rzrferrrrrr_read_python_source@s z#RefactoringTool._read_python_sourcecCs|j|\}}|dkrdS|d7}|rn|jd||j||}|jsL||kr`|j|||||q|jd|nH|j||}|js|r|jr|jt|dd|||dn |jd|dS) zRefactors a file.Nr>zRefactoring doctests in %szNo doctest changes in %sr)rrzNo changes in %sr)rrrefactor_docstringrcprocessed_filerefactor_string was_changedstr)rzrrrr@routputtreerrrrPs    zRefactoringTool.refactor_filecCst|}d|krtj|j_zJy|jj|}Wn4tk r`}z|jd||jj |dSd}~XnXWd|j|j_X||_ |j d||j |||S)aFRefactor a given input string. Args: data: a string holding the code to be refactored. name: a human-readable name for use in error/log messages. Returns: An AST corresponding to the refactored input stream; None if there were errors during the parse. rbzCan't parse %s: %s: %sNzRefactoring %s) r^r rkrrlZ parse_stringr'r __class__rfuture_featuresr refactor_tree)rzdatarr[rrrrrrgs     zRefactoringTool.refactor_stringcCstjj}|rN|jd|j|d}|js2||krB|j|d|q|jdn:|j|d}|jsj|r~|jr~|jt |d|n |jddS)NzRefactoring doctests in stdinzzNo doctest changes in stdinzNo changes in stdin) sysstdinrrrrcrrrr)rzrr@rrrrrrefactor_stdins     zRefactoringTool.refactor_stdinc Csx"t|j|jD]}|j||qW|j|j|j|j|j|j|jj|j }xvt |j rАx`|jj D]R}||ko||rv||j tjjdd|jr||j tjjdx t||D]}|||kr||j|y t|Wntk rwYnX|jr(||jkr(q|j|}|r|j||}|dk r|j|x,|jD] }|jspg|_|jj|q^W|jj|j }x2|D]*} | |krg|| <|| j|| qWqWqvWq\Wx$t|j|jD]}|j||qW|jS)aRefactors a parse tree (modifying the tree in place). For compatible patterns the bottom matcher module is used. Otherwise the tree is traversed node-to-node for matches. Args: tree: a pytree.Node instance representing the root of the tree to be refactored. name: a human-readable name for this tree. Returns: True if the tree was modified, False otherwise. T)rreverse)rN)rrsrtZ start_tree traverse_byrxryrwZrunZleavesanyr0rfrrZBaseZdepthZkeep_line_orderZ get_linenor-remover ValueErrorZfixers_appliedmatch transformr?rr2Z finish_treer) rzrrr4Z match_setnoderesultsnewZ new_matchesZfxrrrrrsJ       $zRefactoringTool.refactor_treecCs^|sdSxP|D]H}xB||jD]4}|j|}|r|j||}|dk r|j||}qWqWdS)aTraverse an AST, applying a set of fixers to each node. This is a helper method for refactor_tree(). Args: fixers: a list of fixer instances. traversal: a generator that yields AST nodes. Returns: None N)r#rrr?)rzrfZ traversalrr4rrrrrrs     zRefactoringTool.traverse_bycCs|jj||dkr.|j|d}|dkr.dS||k}|j|||||r`|jd||js`dS|rv|j||||n |jd|dS)zR Called when a file has been refactored and there may be changes. NrzNo changes to %szNot writing changes to %s)rurrrrrc write_file)rzrrrrrrrrrrs  zRefactoringTool.processed_filec%Csyt|d|d}Wn.tk r@}z|jd||dSd}~XnXzHy|jt|Wn0tk r}z|jd||WYdd}~XnXWd|jX|jd|d|_dS)zWrites a string to a file. It first shows a unified diff between the old text and the new text, and then rewrites the file; the latter is only done if the write option is set. w)rzCan't create %s: %sNzCan't write %s: %szWrote changes to %sT)rrrrrCrrrq)rzrrrrrrrrrr s$  zRefactoringTool.write_filez>>> z... c Csg}d}d}d}d}x|jddD]}|d7}|jj|jr|dk r\|j|j|||||}|g}|j|j} |d| }q"|dk r|j||js|||jjdkr|j |q"|dk r|j|j||||d}d}|j |q"W|dk r|j|j||||dj |S)aRefactors a docstring, looking for doctests. This returns a modified version of the input string. It looks for doctests, which start with a ">>>" prompt, and may be continued with "..." prompts, as long as the "..." is indented the same as the ">>>". (Unfortunately we can't use the doctest module's parser, since, like most parsers, it is not geared towards preserving the original source.) NrT)keependsrr>r}) splitlineslstriprPS1r2refactor_doctestfindPS2rstriprr) rzr@rresultblockZ block_linenoindentlinenolineirrrr%s:          z"RefactoringTool.refactor_docstringc s(yj||}Wndtk rv}zHjjtjrRx|D]}jd|jdq8Wjd|||j j ||Sd}~XnXj ||r$t |j dd}|d|d||dd} }| dg|dkst| |d jds|d d7<j|jdg}|r$|fd d |D7}|S) zRefactors one doctest. A doctest is given as a block of lines, the first of which starts with ">>>" (possibly indented), while the remaining lines start with "..." (identically indented). z Source: %sr>z+Can't parse docstring in %s line %s: %s: %sNT)rrrcsg|]}j|qSr)r)r7r)rrzrrr:jsz4RefactoringTool.refactor_doctest..rr) parse_blockr'reZ isEnabledForroDEBUGrrrrrrrrAssertionErrorrrpop) rzrrrrrrrrZclippedr)rrzrrPs& "z RefactoringTool.refactor_doctestcCs|jr d}nd}|js$|jd|n&|jd|x|jD]}|j|q8W|jrt|jdx|jD]}|j|qbW|jrt|jdkr|jdn|jdt|jx&|jD]\}}}|j|f||qWdS) Nwerez need to bezNo files %s modified.zFiles that %s modified:z$Warnings/messages while refactoring:rzThere was 1 error:zThere were %d errors:)rqrurrprnr)rzrfilemessagerrrrrr summarizems$     zRefactoringTool.summarizecCs"|jj|j|||}t|_|S)zParses a block into a tree. This is necessary to get correct line number / offset information in the parser diagnostics and embedded into the parse tree. )rZ parse_tokens wrap_toksrPr)rzrrrrrrrrszRefactoringTool.parse_blockc cshtj|j||j}xN|D]F\}}\}}\} } } ||d7}| |d7} ||||f| | f| fVqWdS)z;Wraps a tokenize stream to systematically modify start/end.rN)rrL gen_lines__next__) rzrrrr1r#r]Zline0Zcol0Zline1Zcol1Z line_textrrrrs   zRefactoringTool.wrap_toksccs||j}||j}|}xV|D]N}|j|r@|t|dVn(||jdkrXdVntd||f|}qWx dVqrWdS)zGenerates lines as expected by tokenize from a list of lines. This strips the first len(indent + self.PS1) characters off each line. Nr>zline=%r, prefix=%rr})rrrrrr)rzrrprefix1Zprefix2prefixrrrrrs    zRefactoringTool.gen_lines)NN)FF)FF)FF)F)NFN)N)rr r!rhrrr{rrrrrrrrrrrrrrrrrrrrrrrrrrrrras: 4(   O  + rac@s eZdZdS)MultiprocessingUnsupportedN)rr r!rrrrrsrcsBeZdZfddZd fdd ZfddZfd d ZZS) MultiprocessRefactoringToolcs"tt|j||d|_d|_dS)N)superrr{queue output_lock)rzrkwargs)rrrr{sz$MultiprocessRefactoringTool.__init__Frcs|dkrttj|||Sy ddlWntk r@tYnXjdk rTtdj_j _ fddt |D}z.x|D] }|j qWttj|||Wdjj xt |D]}jjdqWx|D]}|jr|j qWd_XdS)Nrrz already doing multiple processescsg|]}jjdqS))target)ZProcess_child)r7r)multiprocessingrzrrr:sz8MultiprocessRefactoringTool.refactor..)rrrr ImportErrorrr RuntimeErrorZ JoinableQueueZLockrrangestartrputZis_alive)rzrrrZ num_processesZ processesr)r)r)rrzrrs2               z$MultiprocessRefactoringTool.refactorc sR|jj}xB|dk rL|\}}ztt|j||Wd|jjX|jj}q WdS)N)rrmrrrZ task_done)rzZtaskrr)rrrrs     z"MultiprocessRefactoringTool._childcs2|jdk r|jj||fntt|j||SdS)N)rrrrr)rzrr)rrrrs  z)MultiprocessRefactoringTool.refactor_file)FFr)rr r!r{rrr __classcell__rr)rrrs   r)T)rr)(r` __author__rrrorr+rM itertoolsrZpgen2rrrZ fixer_utilrr}rr r rvrr'rr$r5r;r= version_infocodecsrrrArCr^r_objectrarrrrrr sF      (