path.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. def join(*paths):
  2. """Like os.path.join but doesn't treat absolute RHS specially"""
  3. import os.path
  4. return os.path.normpath("/".join(paths))
  5. def relative(src, dest):
  6. """ Return a relative path from src to dest.
  7. >>> relative("/usr/bin", "/tmp/foo/bar")
  8. ../../tmp/foo/bar
  9. >>> relative("/usr/bin", "/usr/lib")
  10. ../lib
  11. >>> relative("/tmp", "/tmp/foo/bar")
  12. foo/bar
  13. """
  14. import os.path
  15. if hasattr(os.path, "relpath"):
  16. return os.path.relpath(dest, src)
  17. else:
  18. destlist = os.path.normpath(dest).split(os.path.sep)
  19. srclist = os.path.normpath(src).split(os.path.sep)
  20. # Find common section of the path
  21. common = os.path.commonprefix([destlist, srclist])
  22. commonlen = len(common)
  23. # Climb back to the point where they differentiate
  24. relpath = [ os.path.pardir ] * (len(srclist) - commonlen)
  25. if commonlen < len(destlist):
  26. # Add remaining portion
  27. relpath += destlist[commonlen:]
  28. return os.path.sep.join(relpath)
  29. def format_display(path, metadata):
  30. """ Prepare a path for display to the user. """
  31. rel = relative(metadata.getVar("TOPDIR", 1), path)
  32. if len(rel) > len(path):
  33. return path
  34. else:
  35. return rel
  36. def remove(path):
  37. """Equivalent to rm -f or rm -rf"""
  38. import os, errno, shutil
  39. try:
  40. os.unlink(path)
  41. except OSError, exc:
  42. if exc.errno == errno.EISDIR:
  43. shutil.rmtree(path)
  44. elif exc.errno != errno.ENOENT:
  45. raise
  46. def symlink(source, destination, force=False):
  47. """Create a symbolic link"""
  48. import os, errno
  49. try:
  50. if force:
  51. remove(destination)
  52. os.symlink(source, destination)
  53. except OSError, e:
  54. if e.errno != errno.EEXIST or os.readlink(destination) != source:
  55. raise