files.py 13 KB

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