i fޛ1@sdZddlZddlZddlZddlmZddlZddlZddlZddl Z yddl Z [ dZ Wne k rdZ YnXyddl mZWne k rdZYnXyddlmZWne k rdZYnXdd d d d d ddddddddddddddddddd gZGd!ddeZGd"d d eZGd#ddeZGd$ddeZGd%d&d&eZGd'd(d(eZd}d+dZd,d-Zd.dd/d Zd.dd0d Zeed1r4d.dd2d3Zn d4d3Zd.dd5d Z d.dd6d Z!d.dd7d Z"d8dZ#dde"dd9dZ$d:d;Z%d<d=Z&ej'ejej(ej)hej*koej+ej,koejej-kZ.ddd>dZ/e.e/_0d?d@Z1dAdZ2dBdCZ3dDdEZ4dFdGZ5dHddddddIdJZ6dddKdLZ7ddddMdNZ8ie6d~gdPfdQ6e6dgdRfdS6e8gdTfdU6Z9e re6dgdWfe9dXd_d`Z?ddZdadZ@dbdZAdcddZBdedfZCdgdhZDididjgeDgdPfdQ6dkgeDgdRfdS6dlgeCgdTfdU6ZEe rdmgeDgdWfeEdX._nopcstt|S)N)getattrr-)rL)rRr!r"lookupszcopystat..lookupcs)tt|}|tjkr%|SS)N)rSr-supports_follow_symlinks)rLr?)rRr!r"rTsr8utimerBst_flagsZchflags EOPNOTSUPPrG)rXzENOTSUP)r-r.r;r8rDr: st_atime_ns st_mtime_nsNotImplementedErrorr,rWr/rFrSrN) r1r2r4ZfollowrTr@modewhyerrr!)rRr"rs,+!   'cCs`tjj|r6tjj|tjj|}nt||d|t||d||S)a3Copy data and mode bits ("cp src dst"). Return the file's destination. The destination may be a directory. If follow_symlinks is false, symlinks won't be followed. This resembles GNU's "cp -P src dst". If source and destination are the same file, a SameFileError will be raised. r4)r-r.isdirjoinbasenamerr)r1r2r4r!r!r"r s $cCs`tjj|r6tjj|tjj|}nt||d|t||d||S)zCopy data and all stat info ("cp -p src dst"). Return the file's destination." The destination may be a directory. If follow_symlinks is false, symlinks won't be followed. This resembles GNU's "cp -P src dst". r4)r-r.r_r`rarr)r1r2r4r!r!r"r s $csfdd}|S)zFunction that can be used as copytree() ignore parameter. Patterns is a sequence of glob-style patterns that are used to exclude filescs:g}x'D]}|jtj||q Wt|S)N)extendfnmatchfilterset)r.rJ ignored_namespattern)patternsr!r"_ignore_patternss z)ignore_patterns.._ignore_patternsr!)rhrir!)rhr"rscCstj|}|dk r-|||}n t}tj|g}x|D]} | |krhqPntjj|| } tjj|| } ytjj| r=tj| } |rtj| | t | | d| qutjj |  r|rwPntjj | r-t | | |||qu|| | n8tjj | rht | | |||n || | WqPt k r} z|j| jdWYdd} ~ XqPtk r}z!|j| | t|fWYdd}~XqPXqPWyt ||Wn\tk re}z<t|dddkrS|j||t|fnWYdd}~XnX|r{t |n|S)aRecursively copy a directory tree. The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. If the file pointed by the symlink doesn't exist, an exception will be added in the list of errors raised in an Error exception at the end of the copy process. You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Notice that this has no effect on platforms that don't support os.symlink. The optional ignore argument is a callable. If given, it is called with the `src` parameter, which is the directory being visited by copytree(), and `names` which is the list of `src` contents, as returned by os.listdir(): callable(src, names) -> ignored_names Since copytree() is called recursively, the callable will be called once for each directory that is copied. It returns a list of names relative to the `src` directory that should not be copied. The optional copy_function argument is a callable that will be used to copy each file. It will be called with the source path and the destination path as arguments. By default, copy2() is used, but any function that supports the same signature (like copy()) can be used. Nr4rZwinerror)r-listdirremakedirsr.r`r;r=r<rexistsr_r rrbrOr/appendstrrS)r1r2symlinksignoreZ copy_functionZignore_dangling_symlinksrJrferrorsrLZsrcnameZdstnamelinktor^r]r!r!r"r sL$      &32c$Csy%tjj|r$tdnWn2tk rY|tjj|tjdSYnXg}ytj|}Wn+tk r|tj|tjYnXx|D]}tjj||}ytj|j }Wntk rd}YnXt j |rt ||qytj |Wqtk rQ|tj |tjYqXqWytj|Wn+tk r|tj|tjYnXdS)Nz%Cannot call rmtree on a symbolic linkr)r-r.r;r/sysexc_inforjr`rCr:r8S_ISDIR_rmtree_unsafeunlinkrmdir)r.onerrorrJrLfullnamer\r!r!r"rv_s6       " rvc 0Cs@g}ytj|}WnGtk rb}z'||_|tj|tjWYdd}~XnXx|D]}tjj||}y(tj|d|dd}|j }Wntk rd}YnXtj |rytj |tj d|} Wn+tk r#|tj |tjYq8Xztjj |tj| rt| ||ytj|d|Wqtk r|tj|tjYqXnAytdWn.tk r|tjj|tjYnXWdtj| Xqjytj|d|Wqjtk r7|tj|tjYqjXqjWdS)Ndir_fdr4Frz%Cannot call rmtree on a symbolic link)r-rjr/filenamersrtr.r`r8r:rur>O_RDONLYsamestatfstat_rmtree_safe_fdrxr;closerw) topfdr.ryrJr^rLrzorig_str\dirfdr!r!r"rsD ,      ! % rc!Cs|rdd}n|dkr0dd}ntrt|trWtj|}nytj|}Wn/tk r|tj|tjdSYnXytj |tj }Wn/tk r|tj|tjdSYnXztj j |tj |rZt|||ytj|Wqtk rV|tj|tjYqXnAytdWn.tk r|tj j|tjYnXWdtj|Xn t||SdS)aRecursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is platform and implementation dependent; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised. cWsdS)Nr!)rOr!r!r"ryszrmtree..onerrorNcWsdS)Nr!)rOr!r!r"rysz%Cannot call rmtree on a symbolic link)_use_fd_functions isinstancebytesr-fsdecoderC Exceptionrsrtr>r}r.r~rrrxr/r;rrv)r. ignore_errorsryrfdr!r!r"r s<       ! %cCs5tjjtjjpd}tjj|j|S)N)r-r.sepaltseprarstrip)r.rr!r!r" _basenamesrc Cs`|}tjj|r~t||r;tj||dStjj|t|}tjj|r~td|q~nytj||Wnt k r[tjj |rtj |}tj ||tj |nttjj|r=t||rtd||fnt||ddt|nt||tj |YnX|S)a0Recursively move a file or directory to another location. This is similar to the Unix "mv" command. Return the file or directory's destination. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. Symlinks are recreated under the new name if os.rename() fails because of cross filesystem renames. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. Nz$Destination path '%s' already existsz.Cannot move a directory '%s' into itself '%s'.roT)r-r.r_r3renamer`rrlrr/r;r=r<rw _destinsrcr r r )r1r2Zreal_dstrrr!r!r"r s.   cCsut|}t|}|jtjjs@|tjj7}n|jtjjsh|tjj7}n|j|S)N)rendswithr-r.r startswith)r1r2r!r!r"rs  rc Cs_tdks|dkrdSyt|}Wntk rFd}YnX|dk r[|dSdS)z"Returns a gid, given a group name.N)rKeyError)rLresultr!r!r"_get_gid(s   rc Cs_tdks|dkrdSyt|}Wntk rFd}YnX|dk r[|dSdS)z"Returns an uid, given a user name.Nr)rr)rLrr!r!r"_get_uid4s   rgzipc sidd6dd6}idd6} tr>d|d._set_uid_gidzw|%srd)_BZ2_SUPPORTED ValueErrorr7getr-r.dirnamerlinforkrrtarfiler>addr) base_namebase_dircompressverbosedry_runrrloggerZtar_compressionZ compress_extZ archive_name archive_dirrtarr!)rrrrr" _make_tarball@s4         rc Cs~|rd}nd}ddlm}ddlm}y |d|||gd|Wn"|k rytd|YnXdS) Nz-rz-rqr)DistutilsExecError)spawnziprzkunable to create zip file '%s': could neither import the 'zipfile' module nor find a standalone zip utility)Zdistutils.errorsrZdistutils.spawnrr)r zip_filenamerrZ zipoptionsrrr!r!r"_call_external_zip~s    rcCsN|d}tjj|}|rmtjj| rm|dk rT|jd|n|smtj|qmnyddl}Wntk rd}YnX|dkrt||||n|dk r|jd||n|sJ|j |dd|j H}tjj |} |j | | |dk rA|jd| nxtj |D]\} } } xdt| D]V} tjj tjj| | } |j | | |dk rm|jd| qmqmWxs| D]k} tjj tjj| | } tjj| r|j | | |dk r9|jd| q9qqWqQWWdQXn|S) amCreate a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file. z.zipNz creating %srz#creating '%s' and adding '%s' to itwZ compressionz adding '%s')r-r.rrlrrkzipfile ImportErrorrZipFileZ ZIP_DEFLATEDnormpathr(walksortedr`isfile)rrrrrrrrZzfr.dirpathZdirnames filenamesrLr!r!r" _make_zipfilesH         !  ! 'rrzgzip'ed tar-fileZgztarzuncompressed tar filerzZIP filerrzbzip2'ed tar-fileZbztarcCs'ddtjD}|j|S)zReturns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) cSs&g|]\}}||dfqS)rr!).0rLregistryr!r!r" s z'get_archive_formats..)_ARCHIVE_FORMATSitemssort)formatsr!r!r"rs  rcCs|dkrg}nt|s4td|nt|ttfsXtdnxE|D]=}t|ttf st|dkr_tdq_q_W|||ft|.)_UNPACK_FORMATSrr)rr!r!r"r(s  c Csi}x9tjD]+\}}x|dD]}|||r(r) r| extract_dirrrrrLtargetdatafr!r!r"_unpack_zipfilees0    rcCs^ytj|}Wn%tjk r:td|YnXz|j|Wd|jXdS)z:Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` z/%s is not a compressed or uncompressed tar fileN)rr>ZTarErrorr$Z extractallr)r|rZtarobjr!r!r"_unpack_tarfilesrz.tar.gzz.tgzz.tarz.zipz.bz2cCsIxBtjD]4\}}x%|dD]}|j|r$|Sq$Wq WdS)Nr)rrr)r|rLrrr!r!r"_find_unpack_formats  rcCs|dkrtj}n|dk ryt|}Wn'tk r^tdj|YnX|d}|||t|dnbt|}|dkrtdj|nt|d}tt|d}||||dS)aUnpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", or "gztar". Or any other registered format. If not provided, unpack_archive will use the filename extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised. NzUnknown unpack format '{0}'rrzUnknown archive format '{0}') r-rrrrr7dictrr$)r|rr7rrrPr!r!r"rs      statvfs disk_usageZusageztotal used freecCsVtj|}|j|j}|j|j}|j|j|j}t|||S)zReturn disk usage statistics about the given path. Returned value is a named tuple with attributes 'total', 'used' and 'free', which are the amount of total, used and free space, in bytes. )r-rf_bavailf_frsizef_blocksf_bfree_ntuple_diskusage)r.r@freetotalusedr!r!r"rs ntcCs/tj|\}}||}t|||S)zReturn disk usage statistics about the given path. Returned values is a named tuple with attributes 'total', 'used' and 'free', which are the amount of total, used and free space, in bytes. )rZ _getdiskusager)r.rrrr!r!r"rs cCs|dkr'|dkr'tdn|}|}|dkrHd}nBt|trt|}|dkrtdj|qn|dkrd}nBt|tst|}|dkrtdj|qntj |||dS)zChange owner user and group of the given path. user and group can be the uid/gid or the user/group names, and in that case, they are converted to their respective uid/gid. Nzuser and/or group must be setrzno such user: {!r}zno such group: {!r}r) rrrnr LookupErrorr7intrr-r)r.userrZ_userZ_groupr!r!r"rs"        PcCsyttjd}Wnttfk r7d}YnXyttjd}Wnttfk rod}YnX|dks|dkrytjtjj}Wn't t fk rtj |}YnX|dkr|j }n|dkr|j }qntj ||fS)aGet the size of the terminal window. For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used. When COLUMNS or LINES is not defined, which is the common case, the terminal connected to sys.__stdout__ is queried by invoking os.get_terminal_size. If the terminal size cannot be successfully queried, either because the system doesn't support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. Fallback defaults to (80, 24) which is the default size used by many terminal emulators. The value returned is a named tuple of type os.terminal_size. ZCOLUMNSrZLINES)rr-environrrrrs __stdout__fileno NameErrorr/ terminal_sizecolumnslines)Zfallbackrrsizer!r!r"rs$     c sdd}tjjr5||r1SdS|dkr\tjjdtj}n|sfdS|jtj}tj dkrtj |kr|j dtj ntjjddjtj}t fd d |Drg}qfd d |D}n g}t }xu|D]m}tjj|}||kr-|j|x9|D].} tjj|| } || |re| SqeWq-q-WdS) a3Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. cSs5tjj|o4tj||o4tjj| S)N)r-r.rlaccessr_)r?r\r!r!r" _access_checkFs$zwhich.._access_checkNPATHwin32rZPATHEXTrc3s*|] }jj|jVqdS)N)lowerr)rr)cmdr!r" cszwhich..csg|]}|qSr!r!)rr)r r!r"rfs zwhich..)r-r.rrrdefpathrpathseprsplatformrinsertanyrer0rr`) r r\r.rZpathextfilesseendirZnormdirZthefilerLr!)r r"r9s8  !       i@)compresszgzip)rN)rzbzip2)rr)Sr#r-rsr8Zos.pathrrc collectionsrFrrrrpwdrZgrpr__all__r/rrrrr$rr%rr3rrr,rNrr r rr rvrr>rwrxsupports_dir_fdrj supports_fdrUrr Zavoids_symlink_attacksrr rrrrrrrrrrrrrrrrrrrrrrm namedtuplerrrLrrrF_OKX_OKrr!r!r!r"s                    6 Y ! , 5   1 =6    6    %   %     +