PageRenderTime 62ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/meta/lib/oe/path.py

https://gitlab.com/oryx/openembedded-core
Python | 295 lines | 294 code | 1 blank | 0 comment | 3 complexity | 484dbe4cb26945fc38a16b1eb88ea64e MD5 | raw file
  1. import errno
  2. import glob
  3. import shutil
  4. import subprocess
  5. import os.path
  6. def join(*paths):
  7. """Like os.path.join but doesn't treat absolute RHS specially"""
  8. return os.path.normpath("/".join(paths))
  9. def relative(src, dest):
  10. """ Return a relative path from src to dest.
  11. >>> relative("/usr/bin", "/tmp/foo/bar")
  12. ../../tmp/foo/bar
  13. >>> relative("/usr/bin", "/usr/lib")
  14. ../lib
  15. >>> relative("/tmp", "/tmp/foo/bar")
  16. foo/bar
  17. """
  18. return os.path.relpath(dest, src)
  19. def make_relative_symlink(path):
  20. """ Convert an absolute symlink to a relative one """
  21. if not os.path.islink(path):
  22. return
  23. link = os.readlink(path)
  24. if not os.path.isabs(link):
  25. return
  26. # find the common ancestor directory
  27. ancestor = path
  28. depth = 0
  29. while ancestor and not link.startswith(ancestor):
  30. ancestor = ancestor.rpartition('/')[0]
  31. depth += 1
  32. if not ancestor:
  33. print("make_relative_symlink() Error: unable to find the common ancestor of %s and its target" % path)
  34. return
  35. base = link.partition(ancestor)[2].strip('/')
  36. while depth > 1:
  37. base = "../" + base
  38. depth -= 1
  39. os.remove(path)
  40. os.symlink(base, path)
  41. def replace_absolute_symlinks(basedir, d):
  42. """
  43. Walk basedir looking for absolute symlinks and replacing them with relative ones.
  44. The absolute links are assumed to be relative to basedir
  45. (compared to make_relative_symlink above which tries to compute common ancestors
  46. using pattern matching instead)
  47. """
  48. for walkroot, dirs, files in os.walk(basedir):
  49. for file in files + dirs:
  50. path = os.path.join(walkroot, file)
  51. if not os.path.islink(path):
  52. continue
  53. link = os.readlink(path)
  54. if not os.path.isabs(link):
  55. continue
  56. walkdir = os.path.dirname(path.rpartition(basedir)[2])
  57. base = os.path.relpath(link, walkdir)
  58. bb.debug(2, "Replacing absolute path %s with relative path %s" % (link, base))
  59. os.remove(path)
  60. os.symlink(base, path)
  61. def format_display(path, metadata):
  62. """ Prepare a path for display to the user. """
  63. rel = relative(metadata.getVar("TOPDIR"), path)
  64. if len(rel) > len(path):
  65. return path
  66. else:
  67. return rel
  68. def copytree(src, dst):
  69. # We could use something like shutil.copytree here but it turns out to
  70. # to be slow. It takes twice as long copying to an empty directory.
  71. # If dst already has contents performance can be 15 time slower
  72. # This way we also preserve hardlinks between files in the tree.
  73. bb.utils.mkdirhier(dst)
  74. cmd = "tar --xattrs --xattrs-include='*' -cf - -S -C %s -p . | tar --xattrs --xattrs-include='*' -xf - -C %s" % (src, dst)
  75. subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
  76. def copyhardlinktree(src, dst):
  77. """ Make the hard link when possible, otherwise copy. """
  78. bb.utils.mkdirhier(dst)
  79. if os.path.isdir(src) and not len(os.listdir(src)):
  80. return
  81. if (os.stat(src).st_dev == os.stat(dst).st_dev):
  82. # Need to copy directories only with tar first since cp will error if two
  83. # writers try and create a directory at the same time
  84. cmd = "cd %s; find . -type d -print | tar --xattrs --xattrs-include='*' -cf - -S -C %s -p --no-recursion --files-from - | tar --xattrs --xattrs-include='*' -xhf - -C %s" % (src, src, dst)
  85. subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
  86. source = ''
  87. if os.path.isdir(src):
  88. if len(glob.glob('%s/.??*' % src)) > 0:
  89. source = './.??* '
  90. source += './*'
  91. s_dir = src
  92. else:
  93. source = src
  94. s_dir = os.getcwd()
  95. cmd = 'cp -afl --preserve=xattr %s %s' % (source, os.path.realpath(dst))
  96. subprocess.check_output(cmd, shell=True, cwd=s_dir, stderr=subprocess.STDOUT)
  97. else:
  98. copytree(src, dst)
  99. def remove(path, recurse=True):
  100. """
  101. Equivalent to rm -f or rm -rf
  102. NOTE: be careful about passing paths that may contain filenames with
  103. wildcards in them (as opposed to passing an actual wildcarded path) -
  104. since we use glob.glob() to expand the path. Filenames containing
  105. square brackets are particularly problematic since the they may not
  106. actually expand to match the original filename.
  107. """
  108. for name in glob.glob(path):
  109. try:
  110. os.unlink(name)
  111. except OSError as exc:
  112. if recurse and exc.errno == errno.EISDIR:
  113. shutil.rmtree(name)
  114. elif exc.errno != errno.ENOENT:
  115. raise
  116. def symlink(source, destination, force=False):
  117. """Create a symbolic link"""
  118. try:
  119. if force:
  120. remove(destination)
  121. os.symlink(source, destination)
  122. except OSError as e:
  123. if e.errno != errno.EEXIST or os.readlink(destination) != source:
  124. raise
  125. def find(dir, **walkoptions):
  126. """ Given a directory, recurses into that directory,
  127. returning all files as absolute paths. """
  128. for root, dirs, files in os.walk(dir, **walkoptions):
  129. for file in files:
  130. yield os.path.join(root, file)
  131. ## realpath() related functions
  132. def __is_path_below(file, root):
  133. return (file + os.path.sep).startswith(root)
  134. def __realpath_rel(start, rel_path, root, loop_cnt, assume_dir):
  135. """Calculates real path of symlink 'start' + 'rel_path' below
  136. 'root'; no part of 'start' below 'root' must contain symlinks. """
  137. have_dir = True
  138. for d in rel_path.split(os.path.sep):
  139. if not have_dir and not assume_dir:
  140. raise OSError(errno.ENOENT, "no such directory %s" % start)
  141. if d == os.path.pardir: # '..'
  142. if len(start) >= len(root):
  143. # do not follow '..' before root
  144. start = os.path.dirname(start)
  145. else:
  146. # emit warning?
  147. pass
  148. else:
  149. (start, have_dir) = __realpath(os.path.join(start, d),
  150. root, loop_cnt, assume_dir)
  151. assert(__is_path_below(start, root))
  152. return start
  153. def __realpath(file, root, loop_cnt, assume_dir):
  154. while os.path.islink(file) and len(file) >= len(root):
  155. if loop_cnt == 0:
  156. raise OSError(errno.ELOOP, file)
  157. loop_cnt -= 1
  158. target = os.path.normpath(os.readlink(file))
  159. if not os.path.isabs(target):
  160. tdir = os.path.dirname(file)
  161. assert(__is_path_below(tdir, root))
  162. else:
  163. tdir = root
  164. file = __realpath_rel(tdir, target, root, loop_cnt, assume_dir)
  165. try:
  166. is_dir = os.path.isdir(file)
  167. except:
  168. is_dir = false
  169. return (file, is_dir)
  170. def realpath(file, root, use_physdir = True, loop_cnt = 100, assume_dir = False):
  171. """ Returns the canonical path of 'file' with assuming a
  172. toplevel 'root' directory. When 'use_physdir' is set, all
  173. preceding path components of 'file' will be resolved first;
  174. this flag should be set unless it is guaranteed that there is
  175. no symlink in the path. When 'assume_dir' is not set, missing
  176. path components will raise an ENOENT error"""
  177. root = os.path.normpath(root)
  178. file = os.path.normpath(file)
  179. if not root.endswith(os.path.sep):
  180. # letting root end with '/' makes some things easier
  181. root = root + os.path.sep
  182. if not __is_path_below(file, root):
  183. raise OSError(errno.EINVAL, "file '%s' is not below root" % file)
  184. try:
  185. if use_physdir:
  186. file = __realpath_rel(root, file[(len(root) - 1):], root, loop_cnt, assume_dir)
  187. else:
  188. file = __realpath(file, root, loop_cnt, assume_dir)[0]
  189. except OSError as e:
  190. if e.errno == errno.ELOOP:
  191. # make ELOOP more readable; without catching it, there will
  192. # be printed a backtrace with 100s of OSError exceptions
  193. # else
  194. raise OSError(errno.ELOOP,
  195. "too much recursions while resolving '%s'; loop in '%s'" %
  196. (file, e.strerror))
  197. raise
  198. return file
  199. def is_path_parent(possible_parent, *paths):
  200. """
  201. Return True if a path is the parent of another, False otherwise.
  202. Multiple paths to test can be specified in which case all
  203. specified test paths must be under the parent in order to
  204. return True.
  205. """
  206. def abs_path_trailing(pth):
  207. pth_abs = os.path.abspath(pth)
  208. if not pth_abs.endswith(os.sep):
  209. pth_abs += os.sep
  210. return pth_abs
  211. possible_parent_abs = abs_path_trailing(possible_parent)
  212. if not paths:
  213. return False
  214. for path in paths:
  215. path_abs = abs_path_trailing(path)
  216. if not path_abs.startswith(possible_parent_abs):
  217. return False
  218. return True
  219. def which_wild(pathname, path=None, mode=os.F_OK, *, reverse=False, candidates=False):
  220. """Search a search path for pathname, supporting wildcards.
  221. Return all paths in the specific search path matching the wildcard pattern
  222. in pathname, returning only the first encountered for each file. If
  223. candidates is True, information on all potential candidate paths are
  224. included.
  225. """
  226. paths = (path or os.environ.get('PATH', os.defpath)).split(':')
  227. if reverse:
  228. paths.reverse()
  229. seen, files = set(), []
  230. for index, element in enumerate(paths):
  231. if not os.path.isabs(element):
  232. element = os.path.abspath(element)
  233. candidate = os.path.join(element, pathname)
  234. globbed = glob.glob(candidate)
  235. if globbed:
  236. for found_path in sorted(globbed):
  237. if not os.access(found_path, mode):
  238. continue
  239. rel = os.path.relpath(found_path, element)
  240. if rel not in seen:
  241. seen.add(rel)
  242. if candidates:
  243. files.append((found_path, [os.path.join(p, rel) for p in paths[:index+1]]))
  244. else:
  245. files.append(found_path)
  246. return files