linecache.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. """Cache lines from Python source files.
  2. This is intended to read lines from modules imported -- hence if a filename
  3. is not found, it will look down the module search path for a file by
  4. that name.
  5. """
  6. import functools
  7. import sys
  8. import os
  9. import tokenize
  10. __all__ = ["getline", "clearcache", "checkcache", "lazycache"]
  11. # The cache. Maps filenames to either a thunk which will provide source code,
  12. # or a tuple (size, mtime, lines, fullname) once loaded.
  13. cache = {}
  14. def clearcache():
  15. """Clear the cache entirely."""
  16. cache.clear()
  17. def getline(filename, lineno, module_globals=None):
  18. """Get a line for a Python source file from the cache.
  19. Update the cache if it doesn't contain an entry for this file already."""
  20. lines = getlines(filename, module_globals)
  21. if 1 <= lineno <= len(lines):
  22. return lines[lineno - 1]
  23. return ''
  24. def getlines(filename, module_globals=None):
  25. """Get the lines for a Python source file from the cache.
  26. Update the cache if it doesn't contain an entry for this file already."""
  27. if filename in cache:
  28. entry = cache[filename]
  29. if len(entry) != 1:
  30. return cache[filename][2]
  31. try:
  32. return updatecache(filename, module_globals)
  33. except MemoryError:
  34. clearcache()
  35. return []
  36. def checkcache(filename=None):
  37. """Discard cache entries that are out of date.
  38. (This is not checked upon each call!)"""
  39. if filename is None:
  40. filenames = list(cache.keys())
  41. elif filename in cache:
  42. filenames = [filename]
  43. else:
  44. return
  45. for filename in filenames:
  46. entry = cache[filename]
  47. if len(entry) == 1:
  48. # lazy cache entry, leave it lazy.
  49. continue
  50. size, mtime, lines, fullname = entry
  51. if mtime is None:
  52. continue # no-op for files loaded via a __loader__
  53. try:
  54. stat = os.stat(fullname)
  55. except OSError:
  56. cache.pop(filename, None)
  57. continue
  58. if size != stat.st_size or mtime != stat.st_mtime:
  59. cache.pop(filename, None)
  60. def updatecache(filename, module_globals=None):
  61. """Update a cache entry and return its list of lines.
  62. If something's wrong, print a message, discard the cache entry,
  63. and return an empty list."""
  64. if filename in cache:
  65. if len(cache[filename]) != 1:
  66. cache.pop(filename, None)
  67. if not filename or (filename.startswith('<') and filename.endswith('>')):
  68. return []
  69. fullname = filename
  70. try:
  71. stat = os.stat(fullname)
  72. except OSError:
  73. basename = filename
  74. # Realise a lazy loader based lookup if there is one
  75. # otherwise try to lookup right now.
  76. if lazycache(filename, module_globals):
  77. try:
  78. data = cache[filename][0]()
  79. except (ImportError, OSError):
  80. pass
  81. else:
  82. if data is None:
  83. # No luck, the PEP302 loader cannot find the source
  84. # for this module.
  85. return []
  86. cache[filename] = (
  87. len(data),
  88. None,
  89. [line + '\n' for line in data.splitlines()],
  90. fullname
  91. )
  92. return cache[filename][2]
  93. # Try looking through the module search path, which is only useful
  94. # when handling a relative filename.
  95. if os.path.isabs(filename):
  96. return []
  97. for dirname in sys.path:
  98. try:
  99. fullname = os.path.join(dirname, basename)
  100. except (TypeError, AttributeError):
  101. # Not sufficiently string-like to do anything useful with.
  102. continue
  103. try:
  104. stat = os.stat(fullname)
  105. break
  106. except OSError:
  107. pass
  108. else:
  109. return []
  110. try:
  111. with tokenize.open(fullname) as fp:
  112. lines = fp.readlines()
  113. except (OSError, UnicodeDecodeError, SyntaxError):
  114. return []
  115. if lines and not lines[-1].endswith('\n'):
  116. lines[-1] += '\n'
  117. size, mtime = stat.st_size, stat.st_mtime
  118. cache[filename] = size, mtime, lines, fullname
  119. return lines
  120. def lazycache(filename, module_globals):
  121. """Seed the cache for filename with module_globals.
  122. The module loader will be asked for the source only when getlines is
  123. called, not immediately.
  124. If there is an entry in the cache already, it is not altered.
  125. :return: True if a lazy load is registered in the cache,
  126. otherwise False. To register such a load a module loader with a
  127. get_source method must be found, the filename must be a cacheable
  128. filename, and the filename must not be already cached.
  129. """
  130. if filename in cache:
  131. if len(cache[filename]) == 1:
  132. return True
  133. else:
  134. return False
  135. if not filename or (filename.startswith('<') and filename.endswith('>')):
  136. return False
  137. # Try for a __loader__, if available
  138. if module_globals and '__name__' in module_globals:
  139. name = module_globals['__name__']
  140. if (loader := module_globals.get('__loader__')) is None:
  141. if spec := module_globals.get('__spec__'):
  142. try:
  143. loader = spec.loader
  144. except AttributeError:
  145. pass
  146. get_source = getattr(loader, 'get_source', None)
  147. if name and get_source:
  148. get_lines = functools.partial(get_source, name)
  149. cache[filename] = (get_lines,)
  150. return True
  151. return False