home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / python2.6 / posixpath.py < prev    next >
Encoding:
Python Source  |  2010-12-26  |  12.8 KB  |  415 lines

  1. """Common operations on Posix pathnames.
  2.  
  3. Instead of importing this module directly, import os and refer to
  4. this module as os.path.  The "os.path" name is an alias for this
  5. module on Posix systems; on other systems (e.g. Mac, Windows),
  6. os.path provides the same operations in a manner specific to that
  7. platform, and is an alias to another module (e.g. macpath, ntpath).
  8.  
  9. Some of this can actually be useful on non-Posix systems too, e.g.
  10. for manipulation of the pathname component of URLs.
  11. """
  12.  
  13. import os
  14. import stat
  15. import genericpath
  16. import warnings
  17. from genericpath import *
  18.  
  19. __all__ = ["normcase","isabs","join","splitdrive","split","splitext",
  20.            "basename","dirname","commonprefix","getsize","getmtime",
  21.            "getatime","getctime","islink","exists","lexists","isdir","isfile",
  22.            "ismount","walk","expanduser","expandvars","normpath","abspath",
  23.            "samefile","sameopenfile","samestat",
  24.            "curdir","pardir","sep","pathsep","defpath","altsep","extsep",
  25.            "devnull","realpath","supports_unicode_filenames","relpath"]
  26.  
  27. # strings representing various path-related bits and pieces
  28. curdir = '.'
  29. pardir = '..'
  30. extsep = '.'
  31. sep = '/'
  32. pathsep = ':'
  33. defpath = ':/bin:/usr/bin'
  34. altsep = None
  35. devnull = '/dev/null'
  36.  
  37. # Normalize the case of a pathname.  Trivial in Posix, string.lower on Mac.
  38. # On MS-DOS this may also turn slashes into backslashes; however, other
  39. # normalizations (such as optimizing '../' away) are not allowed
  40. # (another function should be defined to do that).
  41.  
  42. def normcase(s):
  43.     """Normalize case of pathname.  Has no effect under Posix"""
  44.     return s
  45.  
  46.  
  47. # Return whether a path is absolute.
  48. # Trivial in Posix, harder on the Mac or MS-DOS.
  49.  
  50. def isabs(s):
  51.     """Test whether a path is absolute"""
  52.     return s.startswith('/')
  53.  
  54.  
  55. # Join pathnames.
  56. # Ignore the previous parts if a part is absolute.
  57. # Insert a '/' unless the first part is empty or already ends in '/'.
  58.  
  59. def join(a, *p):
  60.     """Join two or more pathname components, inserting '/' as needed.
  61.     If any component is an absolute path, all previous path components
  62.     will be discarded."""
  63.     path = a
  64.     for b in p:
  65.         if b.startswith('/'):
  66.             path = b
  67.         elif path == '' or path.endswith('/'):
  68.             path +=  b
  69.         else:
  70.             path += '/' + b
  71.     return path
  72.  
  73.  
  74. # Split a path in head (everything up to the last '/') and tail (the
  75. # rest).  If the path ends in '/', tail will be empty.  If there is no
  76. # '/' in the path, head  will be empty.
  77. # Trailing '/'es are stripped from head unless it is the root.
  78.  
  79. def split(p):
  80.     """Split a pathname.  Returns tuple "(head, tail)" where "tail" is
  81.     everything after the final slash.  Either part may be empty."""
  82.     i = p.rfind('/') + 1
  83.     head, tail = p[:i], p[i:]
  84.     if head and head != '/'*len(head):
  85.         head = head.rstrip('/')
  86.     return head, tail
  87.  
  88.  
  89. # Split a path in root and extension.
  90. # The extension is everything starting at the last dot in the last
  91. # pathname component; the root is everything before that.
  92. # It is always true that root + ext == p.
  93.  
  94. def splitext(p):
  95.     return genericpath._splitext(p, sep, altsep, extsep)
  96. splitext.__doc__ = genericpath._splitext.__doc__
  97.  
  98. # Split a pathname into a drive specification and the rest of the
  99. # path.  Useful on DOS/Windows/NT; on Unix, the drive is always empty.
  100.  
  101. def splitdrive(p):
  102.     """Split a pathname into drive and path. On Posix, drive is always
  103.     empty."""
  104.     return '', p
  105.  
  106.  
  107. # Return the tail (basename) part of a path, same as split(path)[1].
  108.  
  109. def basename(p):
  110.     """Returns the final component of a pathname"""
  111.     i = p.rfind('/') + 1
  112.     return p[i:]
  113.  
  114.  
  115. # Return the head (dirname) part of a path, same as split(path)[0].
  116.  
  117. def dirname(p):
  118.     """Returns the directory component of a pathname"""
  119.     i = p.rfind('/') + 1
  120.     head = p[:i]
  121.     if head and head != '/'*len(head):
  122.         head = head.rstrip('/')
  123.     return head
  124.  
  125.  
  126. # Is a path a symbolic link?
  127. # This will always return false on systems where os.lstat doesn't exist.
  128.  
  129. def islink(path):
  130.     """Test whether a path is a symbolic link"""
  131.     try:
  132.         st = os.lstat(path)
  133.     except (os.error, AttributeError):
  134.         return False
  135.     return stat.S_ISLNK(st.st_mode)
  136.  
  137. # Being true for dangling symbolic links is also useful.
  138.  
  139. def lexists(path):
  140.     """Test whether a path exists.  Returns True for broken symbolic links"""
  141.     try:
  142.         st = os.lstat(path)
  143.     except os.error:
  144.         return False
  145.     return True
  146.  
  147.  
  148. # Are two filenames really pointing to the same file?
  149.  
  150. def samefile(f1, f2):
  151.     """Test whether two pathnames reference the same actual file"""
  152.     s1 = os.stat(f1)
  153.     s2 = os.stat(f2)
  154.     return samestat(s1, s2)
  155.  
  156.  
  157. # Are two open files really referencing the same file?
  158. # (Not necessarily the same file descriptor!)
  159.  
  160. def sameopenfile(fp1, fp2):
  161.     """Test whether two open file objects reference the same file"""
  162.     s1 = os.fstat(fp1)
  163.     s2 = os.fstat(fp2)
  164.     return samestat(s1, s2)
  165.  
  166.  
  167. # Are two stat buffers (obtained from stat, fstat or lstat)
  168. # describing the same file?
  169.  
  170. def samestat(s1, s2):
  171.     """Test whether two stat buffers reference the same file"""
  172.     return s1.st_ino == s2.st_ino and \
  173.            s1.st_dev == s2.st_dev
  174.  
  175.  
  176. # Is a path a mount point?
  177. # (Does this work for all UNIXes?  Is it even guaranteed to work by Posix?)
  178.  
  179. def ismount(path):
  180.     """Test whether a path is a mount point"""
  181.     if islink(path):
  182.         # A symlink can never be a mount point
  183.         return False
  184.     try:
  185.         s1 = os.lstat(path)
  186.         s2 = os.lstat(join(path, '..'))
  187.     except os.error:
  188.         return False # It doesn't exist -- so not a mount point :-)
  189.     dev1 = s1.st_dev
  190.     dev2 = s2.st_dev
  191.     if dev1 != dev2:
  192.         return True     # path/.. on a different device as path
  193.     ino1 = s1.st_ino
  194.     ino2 = s2.st_ino
  195.     if ino1 == ino2:
  196.         return True     # path/.. is the same i-node as path
  197.     return False
  198.  
  199.  
  200. # Directory tree walk.
  201. # For each directory under top (including top itself, but excluding
  202. # '.' and '..'), func(arg, dirname, filenames) is called, where
  203. # dirname is the name of the directory and filenames is the list
  204. # of files (and subdirectories etc.) in the directory.
  205. # The func may modify the filenames list, to implement a filter,
  206. # or to impose a different order of visiting.
  207.  
  208. def walk(top, func, arg):
  209.     """Directory tree walk with callback function.
  210.  
  211.     For each directory in the directory tree rooted at top (including top
  212.     itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
  213.     dirname is the name of the directory, and fnames a list of the names of
  214.     the files and subdirectories in dirname (excluding '.' and '..').  func
  215.     may modify the fnames list in-place (e.g. via del or slice assignment),
  216.     and walk will only recurse into the subdirectories whose names remain in
  217.     fnames; this can be used to implement a filter, or to impose a specific
  218.     order of visiting.  No semantics are defined for, or required of, arg,
  219.     beyond that arg is always passed to func.  It can be used, e.g., to pass
  220.     a filename pattern, or a mutable object designed to accumulate
  221.     statistics.  Passing None for arg is common."""
  222.     warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.",
  223.                       stacklevel=2)
  224.     try:
  225.         names = os.listdir(top)
  226.     except os.error:
  227.         return
  228.     func(arg, top, names)
  229.     for name in names:
  230.         name = join(top, name)
  231.         try:
  232.             st = os.lstat(name)
  233.         except os.error:
  234.             continue
  235.         if stat.S_ISDIR(st.st_mode):
  236.             walk(name, func, arg)
  237.  
  238.  
  239. # Expand paths beginning with '~' or '~user'.
  240. # '~' means $HOME; '~user' means that user's home directory.
  241. # If the path doesn't begin with '~', or if the user or $HOME is unknown,
  242. # the path is returned unchanged (leaving error reporting to whatever
  243. # function is called with the expanded path as argument).
  244. # See also module 'glob' for expansion of *, ? and [...] in pathnames.
  245. # (A function should also be defined to do full *sh-style environment
  246. # variable expansion.)
  247.  
  248. def expanduser(path):
  249.     """Expand ~ and ~user constructions.  If user or $HOME is unknown,
  250.     do nothing."""
  251.     if not path.startswith('~'):
  252.         return path
  253.     i = path.find('/', 1)
  254.     if i < 0:
  255.         i = len(path)
  256.     if i == 1:
  257.         if 'HOME' not in os.environ:
  258.             import pwd
  259.             userhome = pwd.getpwuid(os.getuid()).pw_dir
  260.         else:
  261.             userhome = os.environ['HOME']
  262.     else:
  263.         import pwd
  264.         try:
  265.             pwent = pwd.getpwnam(path[1:i])
  266.         except KeyError:
  267.             return path
  268.         userhome = pwent.pw_dir
  269.     userhome = userhome.rstrip('/') or userhome
  270.     return userhome + path[i:]
  271.  
  272.  
  273. # Expand paths containing shell variable substitutions.
  274. # This expands the forms $variable and ${variable} only.
  275. # Non-existent variables are left unchanged.
  276.  
  277. _varprog = None
  278.  
  279. def expandvars(path):
  280.     """Expand shell variables of form $var and ${var}.  Unknown variables
  281.     are left unchanged."""
  282.     global _varprog
  283.     if '$' not in path:
  284.         return path
  285.     if not _varprog:
  286.         import re
  287.         _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
  288.     i = 0
  289.     while True:
  290.         m = _varprog.search(path, i)
  291.         if not m:
  292.             break
  293.         i, j = m.span(0)
  294.         name = m.group(1)
  295.         if name.startswith('{') and name.endswith('}'):
  296.             name = name[1:-1]
  297.         if name in os.environ:
  298.             tail = path[j:]
  299.             path = path[:i] + os.environ[name]
  300.             i = len(path)
  301.             path += tail
  302.         else:
  303.             i = j
  304.     return path
  305.  
  306.  
  307. # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
  308. # It should be understood that this may change the meaning of the path
  309. # if it contains symbolic links!
  310.  
  311. def normpath(path):
  312.     """Normalize path, eliminating double slashes, etc."""
  313.     # Preserve unicode (if path is unicode)
  314.     slash, dot = (u'/', u'.') if isinstance(path, unicode) else ('/', '.')
  315.     if path == '':
  316.         return dot
  317.     initial_slashes = path.startswith('/')
  318.     # POSIX allows one or two initial slashes, but treats three or more
  319.     # as single slash.
  320.     if (initial_slashes and
  321.         path.startswith('//') and not path.startswith('///')):
  322.         initial_slashes = 2
  323.     comps = path.split('/')
  324.     new_comps = []
  325.     for comp in comps:
  326.         if comp in ('', '.'):
  327.             continue
  328.         if (comp != '..' or (not initial_slashes and not new_comps) or
  329.              (new_comps and new_comps[-1] == '..')):
  330.             new_comps.append(comp)
  331.         elif new_comps:
  332.             new_comps.pop()
  333.     comps = new_comps
  334.     path = slash.join(comps)
  335.     if initial_slashes:
  336.         path = slash*initial_slashes + path
  337.     return path or dot
  338.  
  339.  
  340. def abspath(path):
  341.     """Return an absolute path."""
  342.     if not isabs(path):
  343.         if isinstance(path, unicode):
  344.             cwd = os.getcwdu()
  345.         else:
  346.             cwd = os.getcwd()
  347.         path = join(cwd, path)
  348.     return normpath(path)
  349.  
  350.  
  351. # Return a canonical path (i.e. the absolute location of a file on the
  352. # filesystem).
  353.  
  354. def realpath(filename):
  355.     """Return the canonical path of the specified filename, eliminating any
  356. symbolic links encountered in the path."""
  357.     if isabs(filename):
  358.         bits = ['/'] + filename.split('/')[1:]
  359.     else:
  360.         bits = [''] + filename.split('/')
  361.  
  362.     for i in range(2, len(bits)+1):
  363.         component = join(*bits[0:i])
  364.         # Resolve symbolic links.
  365.         if islink(component):
  366.             resolved = _resolve_link(component)
  367.             if resolved is None:
  368.                 # Infinite loop -- return original component + rest of the path
  369.                 return abspath(join(*([component] + bits[i:])))
  370.             else:
  371.                 newpath = join(*([resolved] + bits[i:]))
  372.                 return realpath(newpath)
  373.  
  374.     return abspath(filename)
  375.  
  376.  
  377. def _resolve_link(path):
  378.     """Internal helper function.  Takes a path and follows symlinks
  379.     until we either arrive at something that isn't a symlink, or
  380.     encounter a path we've seen before (meaning that there's a loop).
  381.     """
  382.     paths_seen = []
  383.     while islink(path):
  384.         if path in paths_seen:
  385.             # Already seen this path, so we must have a symlink loop
  386.             return None
  387.         paths_seen.append(path)
  388.         # Resolve where the link points to
  389.         resolved = os.readlink(path)
  390.         if not isabs(resolved):
  391.             dir = dirname(path)
  392.             path = normpath(join(dir, resolved))
  393.         else:
  394.             path = normpath(resolved)
  395.     return path
  396.  
  397. supports_unicode_filenames = False
  398.  
  399. def relpath(path, start=curdir):
  400.     """Return a relative version of a path"""
  401.  
  402.     if not path:
  403.         raise ValueError("no path specified")
  404.  
  405.     start_list = abspath(start).split(sep)
  406.     path_list = abspath(path).split(sep)
  407.  
  408.     # Work out how much of the filepath is shared by start and path.
  409.     i = len(commonprefix([start_list, path_list]))
  410.  
  411.     rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
  412.     if not rel_list:
  413.         return curdir
  414.     return join(*rel_list)
  415.