Ϫf&dZddlmZddlZddlZddlZddlZddlmZmZm Z ddl m Z m Z m Z mZmZmZmZmZmZddlmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"ddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3ddl4m5Z5m6Z6m7Z7dd l#m8Z8dd l9m:Z:m;Z;dd lm?Z?dd l@mAZAmBZBmCZCmDZDmEZEejejzejzeEzZIe0ddZJejZLejZNGdde6ZOGddePZQGddePZRGddeSZTd'dZUe0deVeWZXe8dZYGdde*e'ZZGdde?Z[Gd d!e?Z\d(d)d"Z]d*d+d#Z^ d* d,d$Z_e;e7eOGd%d&eZe'Z`y)-z1 Object-oriented filesystem path representation. ) annotationsN)listdirstatutime) abspathbasenamedirnameexistsisabsislinkjoinnormpathsplitext)S_IMODES_IRGRPS_IROTHS_IRUSRS_ISBLKS_ISDIRS_ISREGS_ISSOCKS_IWGRPS_IWOTHS_IWUSRS_IXGRPS_IXOTHS_IXUSR)IO TYPE_CHECKINGAnyAnyStrCallableDictGenericIterableListOptionalSequenceTupleTypeVarUnioncastoverload) Attribute Interface implementer)Literal)cmp comparable)platform) FancyEqMixin)ERROR_DIRECTORYERROR_FILE_NOT_FOUNDERROR_INVALID_NAMEERROR_PATH_NOT_FOUNDO_BINARY_SelfzAbstractFilePath[Any]boundceZdZdZedZddZdddZddZddZ ddZ ddZ dd Z dd Z dd Zdd Zdd ZddZddZddZy) IFilePatha File path object. A file path represents a location for a file-like-object and can be organized into a hierarchy; a file path can can children which are themselves file paths. A file path has a name which unique identifies it in the context of its parent (if it has one); a file path can not have two children with the same name. This name is referred to as the file path's "base name". A series of such names can be used to locate nested children of a file path; such a series is referred to as the child's "path", relative to the parent. In this case, each name in the path is referred to as a "path segment"; the child's base name is the segment in the path. When representing a file path as a string, a "path separator" is used to delimit the path segments within the string. For a file system path, that would be C{os.sep}. Note that the values of child names may be restricted. For example, a file system path will not allow the use of the path separator in a name, and certain names (e.g. C{"."} and C{".."}) may be reserved or have special meanings. @since: 12.1 z3The path separator to use in string representationscy)a Obtain a direct child of this file path. The child may or may not exist. @param name: the name of a child of this path. C{name} must be a direct child of this path and may not contain a path separator. @return: the child of this path with the given C{name}. @raise InsecurePath: if C{name} describes a file path that is not a direct child of this file path. Nnames 9/usr/lib/python3/dist-packages/twisted/python/filepath.pychildzIFilePath.childycy)z Opens this file path with the given mode. @return: a file-like object. @raise Exception: if this file path cannot be opened. NrA)modes rDopenzIFilePath.openrFrGcy)zT Clear any cached information about the state of this path on disk. NrArArGrDchangedzIFilePath.changedrFrGcy)z Retrieve the size of this file in bytes. @return: the size of the file at this file path in bytes. @raise Exception: if the size cannot be obtained. NrArArGrDgetsizezIFilePath.getsizerFrGcy) Retrieve the time of last access from this file. @return: a number of seconds from the epoch. @rtype: L{float} NrArArGrDgetModificationTimezIFilePath.getModificationTimerFrGcy) Retrieve the time of the last status change for this file. @return: a number of seconds from the epoch. @rtype: L{float} NrArArGrDgetStatusChangeTimezIFilePath.getStatusChangeTimerFrGcy) Retrieve the time that this file was last accessed. @return: a number of seconds from the epoch. @rtype: L{float} NrArArGrD getAccessTimezIFilePath.getAccessTimerFrGcy)z Check if this file path exists. @return: C{True} if the file at this file path exists, C{False} otherwise. @rtype: L{bool} NrArArGrDr zIFilePath.existsrFrGcy)z Check if this file path refers to a directory. @return: C{True} if the file at this file path is a directory, C{False} otherwise. NrArArGrDisdirzIFilePath.isdirrFrGcy)z Check if this file path refers to a regular file. @return: C{True} if the file at this file path is a regular file, C{False} otherwise. NrArArGrDisfilezIFilePath.isfilerFrGcy)z List the children of this path object. @return: a sequence of the children of the directory at this file path. @raise Exception: if the file at this file path is not a directory. NrArArGrDchildrenzIFilePath.childrenrFrGcy)a Retrieve the final component of the file path's path (everything after the final path separator). @note: In implementors, the return type should be generic, i.e. C{AbstractFilePath[str].basename()} is a C{str}. However, L{Interface} objects cannot be generic as of this writing. @return: the base name of this file path. NrArArGrDrzIFilePath.basenamerFrGcy)zV A file path for the directory containing the file at this file path. NrArArGrDparentzIFilePath.parentrFrGcy)a$ A file path for the directory containing the file at this file path. @param name: the name of a sibling of this path. C{name} must be a direct sibling of this path and may not contain a path separator. @return: a sibling file path of this one. NrArBs rDsiblingzIFilePath.siblingrFrGN)rCr!returnr?rrIFileModerd IO[bytes]rdNonerdintrdfloatrdbool)rdzIterable[IFilePath])rdUnion[str, bytes])rdr?)__name__ __module__ __qualname____doc__r.seprErJrLrNrQrTrWr rZr\r^rrarcrArGrDr?r?ZsZ8 I JC                rGr?ceZdZdZy) InsecurePathzP Error that is raised when the path provided to L{FilePath} is invalid. NrsrtrurvrArGrDryrysrGryceZdZdZy) LinkErrorz An error with symlinks - either that there are cyclical symlinks or that symlink are not supported on this platform. NrzrArGrDr|r|srGr|ceZdZdZddZy)UnlistableErrorai An exception which is used to distinguish between errors which mean 'this is not a directory you can list' and other, more catastrophic errors. This error will try to look as much like the original error as possible, while still being catchable as an independent type. @ivar originalException: the actual original exception instance. c\|jj|j||_y)zq Create an UnlistableError exception. @param originalException: an instance of OSError. N)__dict__updateoriginalException)selfrs rD__init__zUnlistableError.__init__s% .778!2rGN)rOSError)rsrtrurvrrArGrDr~r~s 3rGr~cHttddd}t||S)a Compute a string usable as a new, temporary filename. @param path: The path that the new temporary filename should be able to be concatenated with. @return: A pseudorandom, 16 byte string for use in secure filenames. @rtype: the type of C{path} N)armor randomBytes_coerceToFilesystemEncoding)pathsecureishStrings rD_secureEnoughStringrs&KO,Sb1O &t_ ==rG OtherAnyStr)rfwazr+zw+za+ceZdZUdZeddZded<ddZddZdd Z ddd Z dd Z d d Z d!d Z d"dZd#dZd$dZd%dZd&dZ d' d(dZd)dZ d*dZd+dZd,dZd,dZd,dZd,dZy)-AbstractFilePathaa Abstract implementation of an L{IFilePath}; must be completed by a subclass. This class primarily exists to provide common implementations of certain methods in L{IFilePath}. It is *not* a required parent class for L{IFilePath} implementations, just a useful starting point. @ivar path: Subclasses must set this variable. SelfishAbstractFilePath[AnyStr]r<r!rct)zZ Subclasses must implement this. @see: L{FilePath.getAccessTime} NotImplementedErrorrs rDrWzAbstractFilePath.getAccessTime3 "##rGct)z` Subclasses must implement this. @see: L{FilePath.getModificationTime} rrs rDrQz$AbstractFilePath.getModificationTime;rrGct)z` Subclasses must implement this. @see: L{FilePath.getStatusChangeTime} rrs rDrTz$AbstractFilePath.getStatusChangeTimeCrrGctz1 Subclasses must implement this. rrrIs rDrJzAbstractFilePath.openK "##rGctrrrs rDrZzAbstractFilePath.isdirQrrGctrrrs rDrzAbstractFilePath.basenameWrrGctrrrs rDrazAbstractFilePath.parent]rrGctrrrs rDrzAbstractFilePath.listdircrrGctrrrrs rDrEzAbstractFilePath.childirrGcn|j5}|jcdddS#1swYyxYw)z Retrieve the contents of the file at this path. @return: the contents of the file @rtype: L{bytes} N)rJread)rfps rD getContentzAbstractFilePath.getContentos-YY[ B779   s+4c#tK|}|j}||k7r||}|j}||k7ryyw)z Retrieve an iterator of all the ancestors of this path. @return: an iterator of all the ancestors of this path, from the most recent (its immediate parent) to the root of its filesystem. N)ra)rrras rDparentszAbstractFilePath.parentsys=fnLD]]_Ffns388cl |j}g}|D]$}|j|}|j|&|S#t$rk}t|ddttt t fvr t||jtjtjfvr t|d}~wwxYw)a List the children of this path object. @raise OSError: If an error occurs while listing the directory. If the error is 'serious', meaning that the operation failed due to an access violation, exhaustion of some kind of resource (file descriptors or memory), OSError or a platform-specific variant will be raised. @raise UnlistableError: If the inability to list the directory is due to this path not existing or not being a directory, the more specific OSError subclass L{UnlistableError} is raised instead. @return: an iterable of all currently-existing children of this object. winerrorN) rrgetattrr9r7r8r6r~errnoENOENTENOTDIRrEappend)rsubnamesoseresultrCrEs rDr^zAbstractFilePath.childrens %)\\^H2 !D ::d+E MM%  !  ? sJ-$$" 2 &c**yyU\\5==99%c** / s? B3A&B..B3Nc#K||jr|jD]}|||r|j|D]p}tjj |jj tjj |jr td|r|yyw)a Yield myself, then each of my children, and each of those children's children in turn. The optional argument C{descend} is a predicate that takes a FilePath, and determines whether or not that FilePath is traversed/descended into. It will be called with each path for which C{isdir} returns C{True}. If C{descend} is not specified, all directories will be traversed (including symbolic links which refer to directories). @param descend: A one-argument callable that will return True for FilePaths that should be traversed, False otherwise. @return: a generator yielding FilePath-like objects. NzCycle in file graph.)rZr^walkosrrealpath startswithr|)rdescendcsubcs rDrzAbstractFilePath.walks& ::<]]_ ?gaj !w#77++DII6AAGG,,TYY7#,,B"CC" #G  sB?Cc@|jj|S)a Return a L{FilePath} with the same directory as this instance but with a basename of C{path}. @note: for type-checking, subclasses should override this signature to make it clear that it returns the subclass and not L{AbstractFilePath}. @param path: The basename of the L{FilePath} to return. @type path: L{str} @return: The sibling path. @rtype: L{FilePath} )rarErs rDrczAbstractFilePath.siblings{{}""4((rGc:|}|D]}|j|}|S)a Retrieve a child or child's child of this path. @note: for type-checking, subclasses should override this signature to make it clear that it returns the subclass and not L{AbstractFilePath}. @param segments: A sequence of path segments as L{str} instances. @return: A L{FilePath} constructed by looking up the C{segments[0]} child of this path, the C{segments[1]} child of that path, and so on. @since: 10.2 )rE)rsegmentsrrCs rD descendantzAbstractFilePath.descendants+$/3 $D::d#D $ rGc|}|j}g}||k7r6||k7r1|jg|dd|}|j}||k7r||k7r1||k(r|r|St|d|)a Return a list of segments between a child and its ancestor. For example, in the case of a path X representing /a/b/c/d and a path Y representing /a/b, C{Y.segmentsFrom(X)} will return C{['c', 'd']}. @param ancestor: an instance of the same class as self, ostensibly an ancestor of self. @raise ValueError: If the C{ancestor} parameter is not actually an ancestor, i.e. a path for /x/y/z is passed as an ancestor for /a/b/c/d. @return: a list of strs rz not parent of )rar ValueError)rancestorfprs rD segmentsFromzAbstractFilePath.segmentsFroms~& 88:!#8mQZZ\NHQqMA A8mQ =XOH<th?@@rGcDt|j|jfS)zZ Hash the same as another L{AbstractFilePath} with the same path as mine. )hash __class__rrs rD__hash__zAbstractFilePath.__hash__#sT^^TYY/00rGc4t|jS)z? Deprecated. Use getModificationTime instead. )rmrQrs rDgetmtimezAbstractFilePath.getmtime*4++-..rGc4t|jS)z9 Deprecated. Use getAccessTime instead. )rmrWrs rDgetatimezAbstractFilePath.getatime0s4%%'((rGc4t|jS)z? Deprecated. Use getStatusChangeTime instead. )rmrTrs rDgetctimezAbstractFilePath.getctime6rrGrnrergrprdr!)rdrrd List[AnyStr])rrrdAbstractFilePath[OtherAnyStr])rdbytes)rdz"Iterable[AbstractFilePath[AnyStr]])rr;rdIterable[_Self]N)rr;rz!Optional[Callable[[_Self], bool]]rdr)rr;rrrdr)rSequence[OtherAnyStr]rdr)rr;rr;rdrrl)rsrtrurvr*r__annotations__rWrQrTrJrZrrarrErrr^rrcrrrrrrrArGrDrr#s i'ABG L$$$$ $ $ $ $ $  %0h6:  2   D)"- &.A>1/ ) /rGrc,eZdZdZdZddZddZddZy) RWXa A class representing read/write/execute permissions for a single user category (i.e. user/owner, group, or other/world). Instantiate with three boolean values: readable? writable? executable?. @type read: C{bool} @ivar read: Whether permission to read is given @type write: C{bool} @ivar write: Whether permission to write is given @type execute: C{bool} @ivar execute: Whether permission to execute is given @since: 11.1 rwriteexecutec.||_||_||_yrr)rreadablewritable executables rDrz RWX.__init__Qs  ! rGcddj|j|j|jS)Nz"RWX(read={}, write={}, execute={}))formatrrrrs rD__repr__z RWX.__repr__Vs*3:: II JJ LL  rGcgd}d}|j|j|jfD]}|sd||<|dz }dj|S)z Returns a short string representing the permission bits. Looks like part of what is printed by command line utilities such as 'ls -l' (e.g. 'rwx') @return: The shorthand string. @rtype: L{str} )rfrxr-)rrrr )r returnvalivals rD shorthandz RWX.shorthand]sV$ IItzz4<<8 C" ! FA wwy!!rGN)rrqrrqrrqrdrkrdstrrsrtrurvcompareAttributesrrrrArGrDrr=s"5"  "rGrc,eZdZdZdZddZddZddZy) Permissionsae A class representing read/write/execute permissions. Instantiate with any portion of the file's mode that includes the permission bits. @type user: L{RWX} @ivar user: User/Owner permissions @type group: L{RWX} @ivar group: Group permissions @type other: L{RWX} @ivar other: Other/World permissions @since: 11.1 )usergroupothercfdtttgttt gt ttgfD\|_ |_ |_ y)Nc3@K|]}tfd|Dyw)c3.K|] }|zdkDyw)rNrA).0bit statModeInts rD z1Permissions.__init__...s.s$-  <8< =- s) rrrrrrrrrrrr)rrs `rDrzPermissions.__init__sA- '7+'7+'7+- ) 4:tzrGcdt|jdt|jdt|jdS)N[z | ])rrrrrs rDrzPermissions.__repr__s83tyy>"#c$**o%6c#djj/9J!LLrGcdj|j|j|jfDcgc]}|j c}Scc}w)z Returns a short string representing the permission bits. Looks like what is printed by command line utilities such as 'ls -l' (e.g. 'rwx-wx--x') @return: The shorthand string. @rtype: L{str} r)r rrrr)rrs rDrzPermissions.shorthands:ww 4::tzz/RS! STTSsAN)rrmrdrkrrrArGrDrros  3 M UrGrcxt|tr|S|stj}|j |dS)aR Return C{path} as a string of L{bytes} suitable for use on this system's filesystem. @param path: The path to be made suitable. @type path: L{bytes} or L{unicode} @param encoding: The encoding to use if coercing to L{bytes}. If none is given, L{sys.getfilesystemencoding} is used. @return: L{bytes} surrogateescapeerrors) isinstancersysgetfilesystemencodingencoderencodings rD_asFilesystemBytesrs8$ 002H{{8,={>>rGcxt|tr|S|tj}|j |dS)aY Return C{path} as a string of L{unicode} suitable for use on this system's filesystem. @param path: The path to be made suitable. @type path: L{bytes} or L{unicode} @param encoding: The encoding to use if coercing to L{unicode}. If none is given, L{sys.getfilesystemencoding} is used. @return: L{unicode} rr)r rr r decoders rD_asFilesystemTextrs;$  002H{{8,={>>rGcVt|tr t||St||S)a Return a C{newpath} that is suitable for joining to C{path}. @param path: The path that it should be suitable for joining to. @param newpath: The new portion of the path to be coerced if needed. @param encoding: If coerced, the encoding that will be used. r)r rrr)rnewpathrs rDrrs($!'H== 8<dZd<Z?dldmd=Z@dnd>ZAdad?ZBd_dod@ZCdpdAZDeEdZdBZFeE dqdCZF dQ dqdDZFdEZG d_ drdFZH d_ drdGZIy)sFilePatha I am a path on the filesystem that only permits 'downwards' access. Instantiate me with a pathname (for example, FilePath('/home/myuser/public_html')) and I will attempt to only provide access to files which reside inside that path. I may be a path to a file, a directory, or a file which does not exist. The correct way to use me is to instantiate me, and then do ALL filesystem access through me. In other words, do not import the 'os' module; if you need to open a file, call my 'open' method. If you need to list a directory, call my 'path' method. Even if you pass me a relative path, I will convert that to an absolute path internally. The type of C{path} when instantiating decides the mode of the L{FilePath}. That is, C{FilePath(b"/")} will return a L{bytes} mode L{FilePath}, and C{FilePath(u"/")} will return a L{unicode} mode L{FilePath}. C{FilePath("/")} will return a L{bytes} mode L{FilePath} on Python 2, and a L{unicode} mode L{FilePath} on Python 3. Methods that return a new L{FilePath} use the type of the given subpath to decide its mode. For example, C{FilePath(b"/").child(u"tmp")} will return a L{unicode} mode L{FilePath}. @type alwaysCreate: L{bool} @ivar alwaysCreate: When opening this file, only succeed if the file does not already exist. @ivar path: The path from which 'downward' traversal is permitted. Nr!rc2t||_||_y)z Convert a path string to an absolute path if necessary and initialize the L{FilePath} with the result. N)rr alwaysCreaterrrs rDrzFilePath.__init__s DM (rGcyrrArs rDrczFilePath.sibling rGcyrrA)rrs rDrzFilePath.descendantrrGcyrrArs rDrzFilePath.parents rrGcyrrArrs rD__gt__zFilePath.__gt__rrGcyrrAr!s rD__ge__zFilePath.__ge__rrGcyrrAr!s rD__lt__zFilePath.__lt__rrGcyrrAr!s rD__le__zFilePath.__le__rrGcyrrAr!s rD__eq__zFilePath.__eq__rrGcyrrAr!s rD__ne__zFilePath.__ne__rrGct|S)ze Make an object of the same type as this FilePath, but with path of C{path}. )rrs rD clonePathzFilePath.clonePath!s~rGcH|jj}d|vr|d=|S)zv Support serialization by discarding cached L{os.stat} results and returning everything else. _statinfo)rcopy)rds rD __getstate__zFilePath.__getstate__*s* MM    ! +rGcJt|jtjS)z Return a filesystem separator. @return: The native filesystem separator. @returntype: The same type as C{self.path}. )rrrrwrs rDrwz FilePath.sep4s+499bff==rGc0t|j|S)z Return the path of this L{FilePath} as bytes. @param encoding: The encoding to use if coercing to L{bytes}. If none is given, L{sys.getfilesystemencoding} is used. @return: L{bytes} r)rrrrs rD _asBytesPathzFilePath._asBytesPath>s"$))h??rGc0t|j|S)z Return the path of this L{FilePath} as text. @param encoding: The encoding to use if coercing to L{unicode}. If none is given, L{sys.getfilesystemencoding} is used. @return: L{unicode} r)rrr6s rD _asTextPathzFilePath._asTextPathIs!X>>rGc|t|jtr!|j|j |S|S)z Return this L{FilePath} in L{bytes}-mode. @param encoding: The encoding to use if coercing to L{bytes}. If none is given, L{sys.getfilesystemencoding} is used. @return: L{bytes} mode L{FilePath} r)r rrr.r7r6s rD asBytesModezFilePath.asBytesModeTs4 dii %>>$"3"3X"3"FG G rGc|t|jtr!|j|j |S|S)z Return this L{FilePath} in L{unicode}-mode. @param encoding: The encoding to use if coercing to L{unicode}. If none is given, L{sys.getfilesystemencoding} is used. @return: L{unicode} mode L{FilePath} r)r rrr.r9r6s rD asTextModezFilePath.asTextModeas4 dii '>>$"2"2H"2"EF F rGcbt|tr|jS|jS)a If C{pattern} is C{bytes}, return L{FilePath.path} as L{bytes}. Otherwise, return L{FilePath.path} as L{unicode}. @param pattern: The new element of the path that L{FilePath.path} may need to be coerced to match. )r rr7r9)rpatterns rD_getPathAsSameTypeAszFilePath._getPathAsSameTypeAsns, gu %$$& &##% %rGct|d}t|tj}|j|}t j r|j |rt|dt|}||vrt|dtt||}|j|st|d||j|S)a0 Create and return a new L{FilePath} representing a path contained by C{self}. @param path: The base name of the new L{FilePath}. If this contains directory separators or parent references it will be rejected. @type path: L{bytes} or L{unicode} @raise InsecurePath: If the result of combining this path with C{path} would result in a path which is not a direct child of this path. @return: The child path. @rtype: L{FilePath} with a mode equal to the type of C{path}. :z contains a colon.z* contains one or more directory separators is not a child of ) rrrwr@r4 isWindowscountryrrjoinpathrr.)rrcolonrwourPathnormrs rDrEzFilePath.child{s,D#6)$7++D1    DJJu$5$);<= =~ $;$)STU U(7D12!!'*',?{KL L~~g&&rGc|j|}tt|t|}|j |st |d||j |S)a Use me if C{path} might have slashes in it, but you know they're safe. @param path: A relative path (ie, a path not starting with C{"/"}) which will be interpreted as a child or descendant of this path. @type path: L{bytes} or L{unicode} @return: The child path. @rtype: L{FilePath} with a mode equal to the type of C{path}. rC)r@rrFrrryr.)rrrHrs rD preauthChildzFilePath.preauthChilds]++D1(7HTN;<!!'*',?{KL L~~g&&rGc|D]=}|j|}t||}t|s,|j|cSy)a Return my first existing child with a name in C{paths}. C{paths} is expected to be a list of *pre-secured* path fragments; in most cases this will be specified by a system administrator and not an arbitrary user. If no appropriately-named children exist, this will return L{None}. @return: L{None} or the child path. @rtype: L{None} or L{FilePath} N)r@rFr r.)rpathsrErjps rDchildSearchPreauthzFilePath.childSearchPreauthsJ *E))%0A!U#Bbz~~b))  * rGc |D]}|s2|jr"|j|j|cS|j|}t|d}t|d}||k(r`t ||z}t t |D];}|j|s|jtt ||ccS||z}t|s|j|cSy)a Attempt to return a path with my name, given multiple possible extensions. Each extension in C{exts} will be tested and the first path which exists will be returned. If no path exists, L{None} will be returned. If C{''} is in C{exts}, then if the file referred to by this path exists, C{self} will be returned. The extension '*' has a magic meaning, which means "any path that begins with C{self.path + '.'} is acceptable". *.N) r r.r@rrrr rrF) rextsextrstardotbasedotfnp2s rDsiblingExtensionSearchzFilePath.siblingExtensionSearchs *C4;;=~~d&?&?&DEE))#.A.sC8D-c37Cd{"1++!'!*-HB}}W-#~~hwqz2.FGGHSBbz~~b)) * rGc|jrTtjj|j}||jk(r t d|j |S|S)a Returns the absolute target as a L{FilePath} if self is a link, self otherwise. The absolute link is the ultimate file or directory the link refers to (for instance, if the link refers to another link, and another...). If the filesystem does not support symlinks, or if the link is cyclical, raises a L{LinkError}. Behaves like L{os.path.realpath} in that it does not resolve link names in the middle (ex. /x/y/z, y is a link to w - realpath on z will return /x/y/z, not /x/w/z). @return: L{FilePath} of the target path. @rtype: L{FilePath} @raises LinkError: if links are not supported or links are cyclical. z!Cyclical link - will loop forever)r rrrr|r.)rrs rDrzFilePath.realpathsQ$ ;;=WW%%dii0F" CDD>>&) ) rGcL|j|}|j||zS)a Attempt to return a path with my name, given the extension at C{ext}. @param ext: File-extension to search for. @type ext: L{bytes} or L{unicode} @return: The sibling path. @rtype: L{FilePath} with the same mode as the type of C{ext}. )r@r.)rrTrHs rDsiblingExtensionzFilePath.siblingExtensions'++C0~~gm,,rGcXtj|j|jy)a Creates a symlink to self to at the path in the L{FilePath} C{linkFilePath}. Only works on posix systems due to its dependence on L{os.symlink}. Propagates L{OSError}s up from L{os.symlink} if C{linkFilePath.parent()} does not exist, or C{linkFilePath} already exists. @param linkFilePath: a FilePath representing the link to be created. @type linkFilePath: L{FilePath} N)rsymlinkr)r linkFilePaths rDlinkTozFilePath.linkTo s 499l//0rGc|jrd|vsJd|jSt|j|j dddzS)a Open this file using C{mode} or for writing if C{alwaysCreate} is C{True}. In all cases the file is opened in binary mode, so it is not necessary to include C{"b"} in C{mode}. @param mode: The mode to open the file in. Default is C{"r"}. @raises AssertionError: If C{"a"} is included in the mode and C{alwaysCreate} is C{True}. @return: An open file-like object. rz1Appending not supported when alwaysCreate == Truebr)rcreaterJrreplacers rDrJz FilePath.opensR   d? F ?;;= DIIt||C4s:;;rGcl t|j|_y#t$r d|_|rYywxYw)a Re-calculate cached effects of 'stat'. To refresh information on this path after you know the filesystem may have changed, call this method. @param reraise: a boolean. If true, re-raise exceptions from L{os.stat}; otherwise, mark this path as not existing, and remove any cached stat information. @raise Exception: If C{reraise} is C{True} and an exception occurs while reloading metadata. N)rrr0r)rreraises rDrestatzFilePath.restat0s7 !$))_DN !DN s 33cd|_y)zl Clear any cached information about the state of this path on disk. @since: 10.1.0 N)r0rs rDrLzFilePath.changedCs rGcDtj|j|y)z Changes the permissions on self, if possible. Propagates errors from L{os.chmod} up. @param mode: integer representing the new permissions desired (same as the command line chmod) @type mode: L{int} N)rchmodrrs rDrkzFilePath.chmodKs D!rGcv|j}|s|j|j}|J|jS)z Retrieve the size of this file in bytes. @return: The size of the file at this file path in bytes. @raise Exception: if the size cannot be obtained. @rtype: L{int} )r0rhst_sizersts rDrNzFilePath.getsizeVs6^^ KKMB~~zzrGc|j}|s|j|j}|Jt|jS)rP)r0rhrost_mtimerns rDrQzFilePath.getModificationTimee;^^ KKMB~~R[[!!rGc|j}|s|j|j}|Jt|jS)rS)r0rhrost_ctimerns rDrTzFilePath.getStatusChangeTimesrrrGc|j}|s|j|j}|Jt|jS)rV)r0rhrost_atimerns rDrWzFilePath.getAccessTimerrrGctjrt|j}|s|j |j}|J|j S)a Retrieve the file serial number, also called inode number, which distinguishes this file from all other files on the same device. @raise NotImplementedError: if the platform is Windows, since the inode number would be a dummy value for all files in Windows @return: a number representing the file serial number @rtype: L{int} @since: 11.0 )r4rDrr0rhst_inorns rDgetInodeNumberzFilePath.getInodeNumbersH    % % ^^ KKMB~~yyrGctjrt|j}|s|j |j}|J|j S)a Retrieves the device containing the file. The inode number and device number together uniquely identify the file, but the device number is not necessarily consistent across reboots or system crashes. @raise NotImplementedError: if the platform is Windows, since the device number would be 0 for all partitions on a Windows platform @return: a number representing the device @rtype: L{int} @since: 11.0 )r4rDrr0rhst_devrns rD getDevicezFilePath.getDevicesH    % % ^^ KKMB~~yyrGctjrt|j}|s|j |j}|J|j S)a Retrieves the number of hard links to the file. This count keeps track of how many directories have entries for this file. If the count is ever decremented to zero then the file itself is discarded as soon as no process still holds it open. Symbolic links are not counted in the total. @raise NotImplementedError: if the platform is Windows, since Windows doesn't maintain a link count for directories, and L{os.stat} does not set C{st_nlink} on Windows anyway. @return: the number of hard links to the file @rtype: L{int} @since: 11.0 )r4rDrr0rhst_nlinkrns rDgetNumberOfHardLinkszFilePath.getNumberOfHardLinkssH    % % ^^ KKMB~~{{rGctjrt|j}|s|j |j}|J|j S)a  Returns the user ID of the file's owner. @raise NotImplementedError: if the platform is Windows, since the UID is always 0 on Windows @return: the user ID of the file's owner @rtype: L{int} @since: 11.0 )r4rDrr0rhst_uidrns rD getUserIDzFilePath.getUserIDH    % % ^^ KKMB~~yyrGctjrt|j}|s|j |j}|J|j S)z Returns the group ID of the file. @raise NotImplementedError: if the platform is Windows, since the GID is always 0 on windows @return: the group ID of the file @rtype: L{int} @since: 11.0 )r4rDrr0rhst_gidrns rD getGroupIDzFilePath.getGroupIDrrGc|j}|s|j|j}|Jtt|jS)a Returns the permissions of the file. Should also work on Windows, however, those permissions may not be what is expected in Windows. @return: the permissions for the file @rtype: L{Permissions} @since: 11.1 )r0rhrrst_moderns rDgetPermissionszFilePath.getPermissionss@^^ KKMB~~72::.//rGcZ|jry|jd|jryy)z Check if this L{FilePath} exists. @return: C{True} if the stats of C{path} can be retrieved successfully, C{False} in the other cases. @rtype: L{bool} TF)r0rhrs rDr zFilePath.existss' >> KK ~~rGc|j}|s |jd|j}|syt|jS)z Check if this L{FilePath} refers to a directory. @return: C{True} if this L{FilePath} refers to a directory, C{False} otherwise. @rtype: L{bool} F)r0rhrrrns rDrZzFilePath.isdir:^^ KK Brzz""rGc|j}|s |jd|j}|syt|jS)z Check if this file path refers to a regular file. @return: C{True} if this L{FilePath} points to a regular file (not a directory, socket, named pipe, etc), C{False} otherwise. @rtype: L{bool} F)r0rhrrrns rDr\zFilePath.isfile/rrGc|j}|s |jd|j}|syt|jS)z Returns whether the underlying path is a block device. @return: C{True} if it is a block device, C{False} otherwise @rtype: L{bool} @since: 11.1 F)r0rhrrrns rD isBlockDevicezFilePath.isBlockDevice?rrGc|j}|s |jd|j}|syt|jS)z Returns whether the underlying path is a socket. @return: C{True} if it is a socket, C{False} otherwise @rtype: L{bool} @since: 11.1 F)r0rhrrrns rDisSocketzFilePath.isSocketOs:^^ KK B ##rGc,t|jS)z Check if this L{FilePath} points to a symbolic link. @return: C{True} if this L{FilePath} points to a symbolic link, C{False} otherwise. @rtype: L{bool} )r rrs rDr zFilePath.islink_sdii  rGc,t|jS)z Check if this L{FilePath} refers to an absolute path. This always returns C{True}. @return: C{True}, always. @rtype: L{bool} )r rrs rDr zFilePath.isabsmsTYYrGc,t|jS)a List the base names of the direct children of this L{FilePath}. @return: A L{list} of L{bytes}/L{unicode} giving the names of the contents of the directory this L{FilePath} refers to. These names are relative to this L{FilePath}. @rtype: L{list} @raise OSError: Any exception the platform L{os.listdir} implementation may raise. )rrrs rDrzFilePath.listdirxstyy!!rGc,t|jS)a Split the file path into a pair C{(root, ext)} such that C{root + ext == path}. @return: Tuple where the first item is the filename and second item is the file extension. See Python docs for L{os.path.splitext}. @rtype: L{tuple} )rrrs rDrzFilePath.splitext ""rGc"d|jdS)Nz FilePath())rrs rDrzFilePath.__repr__s499-q))rGc |jdjt|jdy#t$rY"wxYw)a$ Updates the access and last modification times of the file at this file path to the current time. Also creates the file if it does not already exist. @raise Exception: if unable to create or modify the last modification time of the file. rN)rJcloserrrrs rDtouchzFilePath.touchs?  IIcN " dii   s8 AAc,|jrU|jsE|jD]}|jt j |j nt j|j |jy)z Removes the file or directory that is represented by self. If C{self.path} is a directory, recursively remove all its children before removing the directory. If it's a file or link, just delete it. N)rZr r^removerrmdirrrL)rrEs rDrzFilePath.removes\ ::<     HHTYY  IIdii  rGc tj|jy#t$r:}|jtj k(r|r|j sYd}~yd}~wwxYw)a Create all directories not yet existing in C{path} segments, using L{os.makedirs}. @param ignoreExistingDirectory: Don't raise L{OSError} if directory already exists. @type ignoreExistingDirectory: L{bool} @return: L{None} N)rmakedirsrrrEEXISTrZ)rignoreExistingDirectoryes rDrzFilePath.makedirssL  KK " 5<<',C IU s" A%0A  A%ct|tj}|j|}ddl}|d|k(xr||zxs|j ||g}|j |Dcgc]}|j |c}Scc}w)a Assuming I am representing a directory, return a list of FilePaths representing my children that match the given pattern. @param pattern: A glob pattern to use to match child paths. @type pattern: L{unicode} or L{bytes} @return: A L{list} of matching children. @rtype: L{list} of L{FilePath}, with the mode of C{pattern}'s type rN)rrrwr@globr r.)rr?rwrHrrrs rD globChildrenzFilePath.globChildrensw*'266:++G4r{c!7g&7W388WgDV;W+/99T?;aq!;;;s'Bc,t|jS)a: Retrieve the final component of the file path's path (everything after the final path separator). @return: The final component of the L{FilePath}'s path (Everything after the final path separator). @rtype: the same type as this L{FilePath}'s C{path} attribute )rrrs rDrzFilePath.basenamerrGc,t|jS)ah Retrieve all of the components of the L{FilePath}'s path except the last one (everything up to the final path separator). @return: All of the components of the L{FilePath}'s path except the last one (everything up to the final path separator). @rtype: the same type as this L{FilePath}'s C{path} attribute )r rrs rDr zFilePath.dirnamestyy!!rGc@|j|jS)z A file path for the directory containing the file at this file path. @return: A L{FilePath} representing the path which directly contains this L{FilePath}. @rtype: L{FilePath} )r.r rs rDrazFilePath.parents~~dlln--rGc|j|}|jd5}|j|dddtjr4t |j rtj|j tj|j |jj y#1swYxYw)a Replace the file at this path with a new file that contains the given bytes, trying to avoid data-loss in the meanwhile. On UNIX-like platforms, this method does its best to ensure that by the time this method returns, either the old contents I{or} the new contents of the file will be present at this path for subsequent readers regardless of premature device removal, program crash, or power loss, making the following assumptions: - your filesystem is journaled (i.e. your filesystem will not I{itself} lose data due to power loss) - your filesystem's C{rename()} is atomic - your filesystem will not discard new data while preserving new metadata (see U{http://mjg59.livejournal.com/108257.html} for more detail) On most versions of Windows there is no atomic C{rename()} (see U{http://bit.ly/win32-overwrite} for more information), so this method is slightly less helpful. There is a small window where the file at this path may be deleted before the new file is moved to replace it: however, the new file will be fully written and flushed beforehand so in the unlikely event that there is a crash at that point, it should be possible for the user to manually recover the new version of their data. In the future, Twisted will support atomic file moves on those versions of Windows which I{do} support them: see U{Twisted ticket 3004}. This method should be safe for use by multiple concurrent processes, but note that it is not easy to predict which process's contents will ultimately end up on disk if they invoke this method at close to the same time. @param content: The desired contents of the file at this path. @type content: L{bytes} @param ext: An extension to append to the temporary filename used to store the bytes while they are being written. This can be used to make sure that temporary files can be identified by their suffix, for cleanup in case of crashes. @type ext: L{bytes} rN) temporarySiblingrJrr4rDr rrunlinkrenamer;)rcontentrTsibrs rD setContentzFilePath.setContentsZ##C( XXc] a GGG      F499$5 IIdii  #((D,,.334   s B>>Ccnt|tstSt|j|jSr)r rNotImplementedr2rr!s rD__cmp__zFilePath.__cmp__+s'%*! !499ejj))rGcBtj|jy)z Create the directory the L{FilePath} refers to. @see: L{makedirs} @raise OSError: If the directory cannot be created. N)rmkdirrrs rDcreateDirectoryzFilePath.createDirectory0s rGc||_y)z Sets the C{alwaysCreate} variable. @param val: C{True} or C{False}, indicating whether opening this path will be required to create the file or not. @type val: L{bool} @return: L{None} N)r)rrs rD requireCreatezFilePath.requireCreate:s  rGctj|jt}t t t tj|dS)z Exclusively create a file, only if this file previously did not exist. @return: A file-like object opened from this path. zw+b)rrJr _CREATE_FLAGSr,rrfdopen)rfdints rDrdzFilePath.createFs6  =1 BuIryy677rGcyrrArs rDrzFilePath.temporarySiblingTs rGcyrrA)r extensions rDrzFilePath.temporarySiblingXs rGc||jdd}n|}|j|}|jt||j |j z|z}|j |S)a Construct a path referring to a sibling of this path. The resulting path will be unpredictable, so that other subprocesses should neither accidentally attempt to refer to the same path before it is created, nor they should other processes be able to guess its name in advance. @param extension: A suffix to append to the created filename. (Note that if you want an extension with a '.' you must include the '.' yourself.) @type extension: L{bytes} or L{unicode} @return: a path object with the given extension suffix, C{alwaysCreate} set to True. @rtype: L{FilePath} with a mode equal to the type of C{extension} r)rr@rcrr.rr)rrrTrHrs rDrzFilePath.temporarySibling^sv*  ))Aa.CC++C0ll  (4>>'+B+K+K+M MPS S   rGicB|jr@|s>tjtj|j|jy|j rg|j s|j|jD]3}|j|j}|j||5y|jr||jd5}|j5} |j|j}|j!|t#||jkrnF ddddddy|j st%t&j(dt+d#1swYGxYw#1swYyxYw)a Copies self to destination. If self doesn't exist, an OSError is raised. If self is a directory, this method copies its children (but not itself) recursively to destination - if destination does not exist as a directory, this method creates it. If destination is a file, an IOError will be raised. If self is a file, this method copies it to destination. If destination is a file, this method overwrites it. If destination is a directory, an IOError will be raised. If self is a link (and followLinks is False), self will be copied over as a new symlink with the same target as returned by os.readlink. That means that if it is absolute, both the old and new symlink will link to the same thing. If it's relative, then perhaps not (and it's also possible that this relative link will be broken). File/directory permissions and ownership will NOT be copied over. If followLinks is True, symlinks are followed so that they're treated as their targets. In other words, if self is a link, the link's target will be copied. If destination is a link, self will be copied to the destination's target (the actual destination will be destination's target). Symlinks under self (if self is a directory) will be followed and its target's children be copied recursively. If followLinks is False, symlinks will be copied over as symlinks. @param destination: the destination (a FilePath) to which self should be copied @param followLinks: whether symlinks in self should be treated as links or as their targets NrzNo such file or directoryz/Only copying of files and directories supported)r rr_readlinkrrZr rr^rErcopyTor\rJr _chunkSizerlenrrrr)r destination followLinksrE destChild writefilereadfilechunks rDrzFilePath.copyTosPN ;;= JJr{{499-{/?/? @  ::<%%'++- 5'--enn.>?  Y 4 5[[]!!#& )TYY[ H %MM$//:EOOE*5zDOO3   %,,(CD D &&WX X%    s%)F:AF F F FFc tj|j|j|j|j |j y#t $r}|j t jk(rg|j}|j|||j|||j}|j|||jnYd}~yd}~wwxYw)a Move self to destination - basically renaming self to whatever destination is named. If destination is an already-existing directory, moves all children to destination if destination is empty. If destination is a non-empty directory, or destination is a file, an OSError will be raised. If moving between filesystems, self needs to be copied, and everything that applies to copyTo applies to moveTo. @param destination: the destination (a FilePath) to which self should be copied @param followLinks: whether symlinks in self should be treated as links or as their targets (only applicable when moving between filesystems) N) rrr@rrLrrEXDEVrrmoveTor)rrrrsecsibmysecsibs rDrzFilePath.moveTos* " IId// 0@0@A;CSCS T, LLN    !- yyEKK'%557 FK0 k;7 002 Hk2!"# s9A C4%BC//C4)F)rr!rrqrdrk)rr;rrrdFilePath[OtherAnyStr])rrrdr)rdzIterable[FilePath[AnyStr]])robjectrdrq)rrrrqrdr)rdzDict[str, object]rr)r Optional[str]rdr)rrrdr)rrrdzFilePath[bytes])rrrdz FilePath[str])r?rrdr)rrrdr)rMrrdOptional[FilePath[OtherAnyStr]])rSrrdr)rdFilePath[AnyStr])rTrrdr)r`rrdrkrerg)T)rgrqrdrkrj)rIrmrdrkrlrn)rdrrpr)rdzTuple[AnyStr, AnyStr]r)rrqrdrk)r?rrdzList[FilePath[OtherAnyStr]])z.new)rrrTrrrdrk)rrrdrm)rrqrdrk)rdri)rzOptional[OtherAnyStr]rdr)rrrrqrdrk)Jrsrtrurvr0rrrrcrrr"r$r&r(r*r,r.r3propertyrwr7r9r;r=r@rErKrOrZrr]rarJrhrLrkrNrQrTrWryr|rrrrr rZr\rrr r rrrrrrrrr rarrrrrdr-rrrrrArGrDrrsEBI L)         7</3 >> @ ?   &'@'$! (,  (B2 - 1<.& "  " " "*04((0 "# # # $ !   " #*  &<& # ".25h*    8   .   26 .   DJGKGY0GY?CGY GYTGK-"0-"?C-" -"rGr)rr!rdr!)r)rUnion[bytes, str]rrrdrr)rrrrrdr)rr!rrrrrdr!)arv __future__rbase64rrr rrros.pathrrr r r r r rFrrrrrrrrrrrrrrrrtypingrrr r!r"r#r$r%r&r'r(r)r*r+r,r-zope.interfacer.r/r0r1twisted.python.compatr2r3twisted.python.runtimer4twisted.python.utilr5twisted.python.win32r6r7r8r9r:O_EXCLO_CREATO_RDWRrr;urandomrurlsafe_b64encoderr? Exceptionryr|rr~rrrrrhrrrrrrrrArGrDrs # ##    &=<1+, BJJ&2X= 67jj   R R j9  3g3* >mS%0 2 3W/wvW/t/",/"d)U,)UX?(?,IM =  =, =8E =  =   Yb"'b" b"rG