files.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
  2. # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
  3. """File wrangling."""
  4. import fnmatch
  5. import ntpath
  6. import os
  7. import os.path
  8. import posixpath
  9. import re
  10. import sys
  11. from coverage import env
  12. from coverage.backward import unicode_class
  13. from coverage.misc import contract, CoverageException, join_regex, isolate_module
  14. os = isolate_module(os)
  15. def set_relative_directory():
  16. """Set the directory that `relative_filename` will be relative to."""
  17. global RELATIVE_DIR, CANONICAL_FILENAME_CACHE
  18. # The absolute path to our current directory.
  19. RELATIVE_DIR = os.path.normcase(abs_file(os.curdir) + os.sep)
  20. # Cache of results of calling the canonical_filename() method, to
  21. # avoid duplicating work.
  22. CANONICAL_FILENAME_CACHE = {}
  23. def relative_directory():
  24. """Return the directory that `relative_filename` is relative to."""
  25. return RELATIVE_DIR
  26. @contract(returns='unicode')
  27. def relative_filename(filename):
  28. """Return the relative form of `filename`.
  29. The file name will be relative to the current directory when the
  30. `set_relative_directory` was called.
  31. """
  32. fnorm = os.path.normcase(filename)
  33. if fnorm.startswith(RELATIVE_DIR):
  34. filename = filename[len(RELATIVE_DIR):]
  35. return unicode_filename(filename)
  36. @contract(returns='unicode')
  37. def canonical_filename(filename):
  38. """Return a canonical file name for `filename`.
  39. An absolute path with no redundant components and normalized case.
  40. """
  41. if filename not in CANONICAL_FILENAME_CACHE:
  42. if not os.path.isabs(filename):
  43. for path in [os.curdir] + sys.path:
  44. if path is None:
  45. continue
  46. f = os.path.join(path, filename)
  47. if os.path.exists(f):
  48. filename = f
  49. break
  50. cf = abs_file(filename)
  51. CANONICAL_FILENAME_CACHE[filename] = cf
  52. return CANONICAL_FILENAME_CACHE[filename]
  53. def flat_rootname(filename):
  54. """A base for a flat file name to correspond to this file.
  55. Useful for writing files about the code where you want all the files in
  56. the same directory, but need to differentiate same-named files from
  57. different directories.
  58. For example, the file a/b/c.py will return 'a_b_c_py'
  59. """
  60. name = ntpath.splitdrive(filename)[1]
  61. return re.sub(r"[\\/.:]", "_", name)
  62. if env.WINDOWS:
  63. _ACTUAL_PATH_CACHE = {}
  64. _ACTUAL_PATH_LIST_CACHE = {}
  65. def actual_path(path):
  66. """Get the actual path of `path`, including the correct case."""
  67. if env.PY2 and isinstance(path, unicode_class):
  68. path = path.encode(sys.getfilesystemencoding())
  69. if path in _ACTUAL_PATH_CACHE:
  70. return _ACTUAL_PATH_CACHE[path]
  71. head, tail = os.path.split(path)
  72. if not tail:
  73. # This means head is the drive spec: normalize it.
  74. actpath = head.upper()
  75. elif not head:
  76. actpath = tail
  77. else:
  78. head = actual_path(head)
  79. if head in _ACTUAL_PATH_LIST_CACHE:
  80. files = _ACTUAL_PATH_LIST_CACHE[head]
  81. else:
  82. try:
  83. files = os.listdir(head)
  84. except OSError:
  85. files = []
  86. _ACTUAL_PATH_LIST_CACHE[head] = files
  87. normtail = os.path.normcase(tail)
  88. for f in files:
  89. if os.path.normcase(f) == normtail:
  90. tail = f
  91. break
  92. actpath = os.path.join(head, tail)
  93. _ACTUAL_PATH_CACHE[path] = actpath
  94. return actpath
  95. else:
  96. def actual_path(filename):
  97. """The actual path for non-Windows platforms."""
  98. return filename
  99. if env.PY2:
  100. @contract(returns='unicode')
  101. def unicode_filename(filename):
  102. """Return a Unicode version of `filename`."""
  103. if isinstance(filename, str):
  104. encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
  105. filename = filename.decode(encoding, "replace")
  106. return filename
  107. else:
  108. @contract(filename='unicode', returns='unicode')
  109. def unicode_filename(filename):
  110. """Return a Unicode version of `filename`."""
  111. return filename
  112. @contract(returns='unicode')
  113. def abs_file(filename):
  114. """Return the absolute normalized form of `filename`."""
  115. path = os.path.expandvars(os.path.expanduser(filename))
  116. path = os.path.abspath(os.path.realpath(path))
  117. path = actual_path(path)
  118. path = unicode_filename(path)
  119. return path
  120. RELATIVE_DIR = None
  121. CANONICAL_FILENAME_CACHE = None
  122. set_relative_directory()
  123. def isabs_anywhere(filename):
  124. """Is `filename` an absolute path on any OS?"""
  125. return ntpath.isabs(filename) or posixpath.isabs(filename)
  126. def prep_patterns(patterns):
  127. """Prepare the file patterns for use in a `FnmatchMatcher`.
  128. If a pattern starts with a wildcard, it is used as a pattern
  129. as-is. If it does not start with a wildcard, then it is made
  130. absolute with the current directory.
  131. If `patterns` is None, an empty list is returned.
  132. """
  133. prepped = []
  134. for p in patterns or []:
  135. if p.startswith(("*", "?")):
  136. prepped.append(p)
  137. else:
  138. prepped.append(abs_file(p))
  139. return prepped
  140. class TreeMatcher(object):
  141. """A matcher for files in a tree."""
  142. def __init__(self, directories):
  143. self.dirs = list(directories)
  144. def __repr__(self):
  145. return "<TreeMatcher %r>" % self.dirs
  146. def info(self):
  147. """A list of strings for displaying when dumping state."""
  148. return self.dirs
  149. def match(self, fpath):
  150. """Does `fpath` indicate a file in one of our trees?"""
  151. for d in self.dirs:
  152. if fpath.startswith(d):
  153. if fpath == d:
  154. # This is the same file!
  155. return True
  156. if fpath[len(d)] == os.sep:
  157. # This is a file in the directory
  158. return True
  159. return False
  160. class ModuleMatcher(object):
  161. """A matcher for modules in a tree."""
  162. def __init__(self, module_names):
  163. self.modules = list(module_names)
  164. def __repr__(self):
  165. return "<ModuleMatcher %r>" % (self.modules)
  166. def info(self):
  167. """A list of strings for displaying when dumping state."""
  168. return self.modules
  169. def match(self, module_name):
  170. """Does `module_name` indicate a module in one of our packages?"""
  171. if not module_name:
  172. return False
  173. for m in self.modules:
  174. if module_name.startswith(m):
  175. if module_name == m:
  176. return True
  177. if module_name[len(m)] == '.':
  178. # This is a module in the package
  179. return True
  180. return False
  181. class FnmatchMatcher(object):
  182. """A matcher for files by file name pattern."""
  183. def __init__(self, pats):
  184. self.pats = pats[:]
  185. # fnmatch is platform-specific. On Windows, it does the Windows thing
  186. # of treating / and \ as equivalent. But on other platforms, we need to
  187. # take care of that ourselves.
  188. fnpats = (fnmatch.translate(p) for p in pats)
  189. fnpats = (p.replace(r"\/", r"[\\/]") for p in fnpats)
  190. if env.WINDOWS:
  191. # Windows is also case-insensitive. BTW: the regex docs say that
  192. # flags like (?i) have to be at the beginning, but fnmatch puts
  193. # them at the end, and having two there seems to work fine.
  194. fnpats = (p + "(?i)" for p in fnpats)
  195. self.re = re.compile(join_regex(fnpats))
  196. def __repr__(self):
  197. return "<FnmatchMatcher %r>" % self.pats
  198. def info(self):
  199. """A list of strings for displaying when dumping state."""
  200. return self.pats
  201. def match(self, fpath):
  202. """Does `fpath` match one of our file name patterns?"""
  203. return self.re.match(fpath) is not None
  204. def sep(s):
  205. """Find the path separator used in this string, or os.sep if none."""
  206. sep_match = re.search(r"[\\/]", s)
  207. if sep_match:
  208. the_sep = sep_match.group(0)
  209. else:
  210. the_sep = os.sep
  211. return the_sep
  212. class PathAliases(object):
  213. """A collection of aliases for paths.
  214. When combining data files from remote machines, often the paths to source
  215. code are different, for example, due to OS differences, or because of
  216. serialized checkouts on continuous integration machines.
  217. A `PathAliases` object tracks a list of pattern/result pairs, and can
  218. map a path through those aliases to produce a unified path.
  219. """
  220. def __init__(self):
  221. self.aliases = []
  222. def add(self, pattern, result):
  223. """Add the `pattern`/`result` pair to the list of aliases.
  224. `pattern` is an `fnmatch`-style pattern. `result` is a simple
  225. string. When mapping paths, if a path starts with a match against
  226. `pattern`, then that match is replaced with `result`. This models
  227. isomorphic source trees being rooted at different places on two
  228. different machines.
  229. `pattern` can't end with a wildcard component, since that would
  230. match an entire tree, and not just its root.
  231. """
  232. # The pattern can't end with a wildcard component.
  233. pattern = pattern.rstrip(r"\/")
  234. if pattern.endswith("*"):
  235. raise CoverageException("Pattern must not end with wildcards.")
  236. pattern_sep = sep(pattern)
  237. # The pattern is meant to match a filepath. Let's make it absolute
  238. # unless it already is, or is meant to match any prefix.
  239. if not pattern.startswith('*') and not isabs_anywhere(pattern):
  240. pattern = abs_file(pattern)
  241. pattern += pattern_sep
  242. # Make a regex from the pattern. fnmatch always adds a \Z to
  243. # match the whole string, which we don't want.
  244. regex_pat = fnmatch.translate(pattern).replace(r'\Z(', '(')
  245. # We want */a/b.py to match on Windows too, so change slash to match
  246. # either separator.
  247. regex_pat = regex_pat.replace(r"\/", r"[\\/]")
  248. # We want case-insensitive matching, so add that flag.
  249. regex = re.compile(r"(?i)" + regex_pat)
  250. # Normalize the result: it must end with a path separator.
  251. result_sep = sep(result)
  252. result = result.rstrip(r"\/") + result_sep
  253. self.aliases.append((regex, result, pattern_sep, result_sep))
  254. def map(self, path):
  255. """Map `path` through the aliases.
  256. `path` is checked against all of the patterns. The first pattern to
  257. match is used to replace the root of the path with the result root.
  258. Only one pattern is ever used. If no patterns match, `path` is
  259. returned unchanged.
  260. The separator style in the result is made to match that of the result
  261. in the alias.
  262. Returns the mapped path. If a mapping has happened, this is a
  263. canonical path. If no mapping has happened, it is the original value
  264. of `path` unchanged.
  265. """
  266. for regex, result, pattern_sep, result_sep in self.aliases:
  267. m = regex.match(path)
  268. if m:
  269. new = path.replace(m.group(0), result)
  270. if pattern_sep != result_sep:
  271. new = new.replace(pattern_sep, result_sep)
  272. new = canonical_filename(new)
  273. return new
  274. return path
  275. def find_python_files(dirname):
  276. """Yield all of the importable Python files in `dirname`, recursively.
  277. To be importable, the files have to be in a directory with a __init__.py,
  278. except for `dirname` itself, which isn't required to have one. The
  279. assumption is that `dirname` was specified directly, so the user knows
  280. best, but sub-directories are checked for a __init__.py to be sure we only
  281. find the importable files.
  282. """
  283. for i, (dirpath, dirnames, filenames) in enumerate(os.walk(dirname)):
  284. if i > 0 and '__init__.py' not in filenames:
  285. # If a directory doesn't have __init__.py, then it isn't
  286. # importable and neither are its files
  287. del dirnames[:]
  288. continue
  289. for filename in filenames:
  290. # We're only interested in files that look like reasonable Python
  291. # files: Must end with .py or .pyw, and must not have certain funny
  292. # characters that probably mean they are editor junk.
  293. if re.match(r"^[^.#~!$@%^&*()+=,]+\.pyw?$", filename):
  294. yield os.path.join(dirpath, filename)