pythondeps 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #!/usr/bin/env python3
  2. #
  3. # SPDX-License-Identifier: GPL-2.0-only
  4. #
  5. # Determine dependencies of python scripts or available python modules in a search path.
  6. #
  7. # Given the -d argument and a filename/filenames, returns the modules imported by those files.
  8. # Given the -d argument and a directory/directories, recurses to find all
  9. # python packages and modules, returns the modules imported by these.
  10. # Given the -p argument and a path or paths, scans that path for available python modules/packages.
  11. import argparse
  12. import ast
  13. import importlib
  14. from importlib import machinery
  15. import logging
  16. import os.path
  17. import sys
  18. logger = logging.getLogger('pythondeps')
  19. suffixes = importlib.machinery.all_suffixes()
  20. class PythonDepError(Exception):
  21. pass
  22. class DependError(PythonDepError):
  23. def __init__(self, path, error):
  24. self.path = path
  25. self.error = error
  26. PythonDepError.__init__(self, error)
  27. def __str__(self):
  28. return "Failure determining dependencies of {}: {}".format(self.path, self.error)
  29. class ImportVisitor(ast.NodeVisitor):
  30. def __init__(self):
  31. self.imports = set()
  32. self.importsfrom = []
  33. def visit_Import(self, node):
  34. for alias in node.names:
  35. self.imports.add(alias.name)
  36. def visit_ImportFrom(self, node):
  37. self.importsfrom.append((node.module, [a.name for a in node.names], node.level))
  38. def walk_up(path):
  39. while path:
  40. yield path
  41. path, _, _ = path.rpartition(os.sep)
  42. def get_provides(path):
  43. path = os.path.realpath(path)
  44. def get_fn_name(fn):
  45. for suffix in suffixes:
  46. if fn.endswith(suffix):
  47. return fn[:-len(suffix)]
  48. isdir = os.path.isdir(path)
  49. if isdir:
  50. pkg_path = path
  51. walk_path = path
  52. else:
  53. pkg_path = get_fn_name(path)
  54. if pkg_path is None:
  55. return
  56. walk_path = os.path.dirname(path)
  57. for curpath in walk_up(walk_path):
  58. if not os.path.exists(os.path.join(curpath, '__init__.py')):
  59. libdir = curpath
  60. break
  61. else:
  62. libdir = ''
  63. package_relpath = pkg_path[len(libdir)+1:]
  64. package = '.'.join(package_relpath.split(os.sep))
  65. if not isdir:
  66. yield package, path
  67. else:
  68. if os.path.exists(os.path.join(path, '__init__.py')):
  69. yield package, path
  70. for dirpath, dirnames, filenames in os.walk(path):
  71. relpath = dirpath[len(path)+1:]
  72. if relpath:
  73. if '__init__.py' not in filenames:
  74. dirnames[:] = []
  75. continue
  76. else:
  77. context = '.'.join(relpath.split(os.sep))
  78. if package:
  79. context = package + '.' + context
  80. yield context, dirpath
  81. else:
  82. context = package
  83. for fn in filenames:
  84. adjusted_fn = get_fn_name(fn)
  85. if not adjusted_fn or adjusted_fn == '__init__':
  86. continue
  87. fullfn = os.path.join(dirpath, fn)
  88. if context:
  89. yield context + '.' + adjusted_fn, fullfn
  90. else:
  91. yield adjusted_fn, fullfn
  92. def get_code_depends(code_string, path=None, provide=None, ispkg=False):
  93. try:
  94. code = ast.parse(code_string, path)
  95. except TypeError as exc:
  96. raise DependError(path, exc)
  97. except SyntaxError as exc:
  98. raise DependError(path, exc)
  99. visitor = ImportVisitor()
  100. visitor.visit(code)
  101. for builtin_module in sys.builtin_module_names:
  102. if builtin_module in visitor.imports:
  103. visitor.imports.remove(builtin_module)
  104. if provide:
  105. provide_elements = provide.split('.')
  106. if ispkg:
  107. provide_elements.append("__self__")
  108. context = '.'.join(provide_elements[:-1])
  109. package_path = os.path.dirname(path)
  110. else:
  111. context = None
  112. package_path = None
  113. levelzero_importsfrom = (module for module, names, level in visitor.importsfrom
  114. if level == 0)
  115. for module in visitor.imports | set(levelzero_importsfrom):
  116. if context and path:
  117. module_basepath = os.path.join(package_path, module.replace('.', '/'))
  118. if os.path.exists(module_basepath):
  119. # Implicit relative import
  120. yield context + '.' + module, path
  121. continue
  122. for suffix in suffixes:
  123. if os.path.exists(module_basepath + suffix):
  124. # Implicit relative import
  125. yield context + '.' + module, path
  126. break
  127. else:
  128. yield module, path
  129. else:
  130. yield module, path
  131. for module, names, level in visitor.importsfrom:
  132. if level == 0:
  133. continue
  134. elif not provide:
  135. raise DependError("Error: ImportFrom non-zero level outside of a package: {0}".format((module, names, level)), path)
  136. elif level > len(provide_elements):
  137. raise DependError("Error: ImportFrom level exceeds package depth: {0}".format((module, names, level)), path)
  138. else:
  139. context = '.'.join(provide_elements[:-level])
  140. if module:
  141. if context:
  142. yield context + '.' + module, path
  143. else:
  144. yield module, path
  145. def get_file_depends(path):
  146. try:
  147. code_string = open(path, 'r').read()
  148. except (OSError, IOError) as exc:
  149. raise DependError(path, exc)
  150. return get_code_depends(code_string, path)
  151. def get_depends_recursive(directory):
  152. directory = os.path.realpath(directory)
  153. provides = dict((v, k) for k, v in get_provides(directory))
  154. for filename, provide in provides.items():
  155. if os.path.isdir(filename):
  156. filename = os.path.join(filename, '__init__.py')
  157. ispkg = True
  158. elif not filename.endswith('.py'):
  159. continue
  160. else:
  161. ispkg = False
  162. with open(filename, 'r') as f:
  163. source = f.read()
  164. depends = get_code_depends(source, filename, provide, ispkg)
  165. for depend, by in depends:
  166. yield depend, by
  167. def get_depends(path):
  168. if os.path.isdir(path):
  169. return get_depends_recursive(path)
  170. else:
  171. return get_file_depends(path)
  172. def main():
  173. logging.basicConfig()
  174. parser = argparse.ArgumentParser(description='Determine dependencies and provided packages for python scripts/modules')
  175. parser.add_argument('path', nargs='+', help='full path to content to be processed')
  176. group = parser.add_mutually_exclusive_group()
  177. group.add_argument('-p', '--provides', action='store_true',
  178. help='given a path, display the provided python modules')
  179. group.add_argument('-d', '--depends', action='store_true',
  180. help='given a filename, display the imported python modules')
  181. args = parser.parse_args()
  182. if args.provides:
  183. modules = set()
  184. for path in args.path:
  185. for provide, fn in get_provides(path):
  186. modules.add(provide)
  187. for module in sorted(modules):
  188. print(module)
  189. elif args.depends:
  190. for path in args.path:
  191. try:
  192. modules = get_depends(path)
  193. except PythonDepError as exc:
  194. logger.error(str(exc))
  195. sys.exit(1)
  196. for module, imp_by in modules:
  197. print("{}\t{}".format(module, imp_by))
  198. else:
  199. parser.print_help()
  200. sys.exit(2)
  201. if __name__ == '__main__':
  202. main()