utils.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import sys
  2. import os
  3. def splitall(loc):
  4. """
  5. Return a list of the path components in loc. (Used by relpath_).
  6. The first item in the list will be either ``os.curdir``, ``os.pardir``, empty,
  7. or the root directory of loc (for example, ``/`` or ``C:\\).
  8. The other items in the list will be strings.
  9. Adapted from *path.py* by Jason Orendorff.
  10. """
  11. parts = []
  12. while loc != os.curdir and loc != os.pardir:
  13. prev = loc
  14. loc, child = os.path.split(prev)
  15. if loc == prev:
  16. break
  17. parts.append(child)
  18. parts.append(loc)
  19. parts.reverse()
  20. return parts
  21. def _make_path_relative(origin, dest):
  22. """
  23. Return the relative path between origin and dest.
  24. If it's not possible return dest.
  25. If they are identical return ``os.curdir``
  26. Adapted from `path.py <http://www.jorendorff.com/articles/python/path/>`_ by Jason Orendorff.
  27. """
  28. origin = os.path.abspath(origin).replace('\\', '/')
  29. dest = os.path.abspath(dest).replace('\\', '/')
  30. #
  31. orig_list = splitall(os.path.normcase(origin))
  32. # Don't normcase dest! We want to preserve the case.
  33. dest_list = splitall(dest)
  34. #
  35. if orig_list[0] != os.path.normcase(dest_list[0]):
  36. # Can't get here from there.
  37. return dest
  38. #
  39. # Find the location where the two paths start to differ.
  40. i = 0
  41. for start_seg, dest_seg in zip(orig_list, dest_list):
  42. if start_seg != os.path.normcase(dest_seg):
  43. break
  44. i += 1
  45. #
  46. # Now i is the point where the two paths diverge.
  47. # Need a certain number of "os.pardir"s to work up
  48. # from the origin to the point of divergence.
  49. segments = [os.pardir] * (len(orig_list) - i)
  50. # Need to add the diverging part of dest_list.
  51. segments += dest_list[i:]
  52. if len(segments) == 0:
  53. # If they happen to be identical, use os.curdir.
  54. return os.curdir
  55. else:
  56. # return os.path.join(*segments).replace('\\', '/')
  57. return os.path.join(*segments)
  58. def xml_indent(elem, level=0):
  59. i = "\n" + level*" "
  60. if len(elem):
  61. if not elem.text or not elem.text.strip():
  62. elem.text = i + " "
  63. if not elem.tail or not elem.tail.strip():
  64. elem.tail = i
  65. for elem in elem:
  66. xml_indent(elem, level+1)
  67. if not elem.tail or not elem.tail.strip():
  68. elem.tail = i
  69. else:
  70. if level and (not elem.tail or not elem.tail.strip()):
  71. elem.tail = i