contrib/import-checker.py
changeset 28919 a94f34306bb9
parent 28713 806d260c6f3b
child 28920 cdf331b54eb8
equal deleted inserted replaced
28918:72f683260f31 28919:a94f34306bb9
   565     return cycles
   565     return cycles
   566 
   566 
   567 def _cycle_sortkey(c):
   567 def _cycle_sortkey(c):
   568     return len(c), c
   568     return len(c), c
   569 
   569 
       
   570 def sources(f, modname):
       
   571     if f.endswith('.py'):
       
   572         with open(f) as src:
       
   573             yield src.read(), modname
       
   574 
   570 def main(argv):
   575 def main(argv):
   571     if len(argv) < 2 or (argv[1] == '-' and len(argv) > 2):
   576     if len(argv) < 2 or (argv[1] == '-' and len(argv) > 2):
   572         print('Usage: %s {-|file [file] [file] ...}')
   577         print('Usage: %s {-|file [file] [file] ...}')
   573         return 1
   578         return 1
   574     if argv[1] == '-':
   579     if argv[1] == '-':
   578     used_imports = {}
   583     used_imports = {}
   579     any_errors = False
   584     any_errors = False
   580     for source_path in argv[1:]:
   585     for source_path in argv[1:]:
   581         modname = dotted_name_of_path(source_path, trimpure=True)
   586         modname = dotted_name_of_path(source_path, trimpure=True)
   582         localmods[modname] = source_path
   587         localmods[modname] = source_path
   583     for modname, source_path in sorted(localmods.items()):
   588     for localmodname, source_path in sorted(localmods.items()):
   584         f = open(source_path)
   589         for src, modname in sources(source_path, localmodname):
   585         src = f.read()
   590             used_imports[modname] = sorted(
   586         used_imports[modname] = sorted(
   591                 imported_modules(src, modname, localmods, ignore_nested=True))
   587             imported_modules(src, modname, localmods, ignore_nested=True))
   592             for error, lineno in verify_import_convention(modname, src,
   588         for error, lineno in verify_import_convention(modname, src, localmods):
   593                                                           localmods):
   589             any_errors = True
   594                 any_errors = True
   590             print('%s:%d: %s' % (source_path, lineno, error))
   595                 print('%s:%d: %s' % (source_path, lineno, error))
   591         f.close()
       
   592     cycles = find_cycles(used_imports)
   596     cycles = find_cycles(used_imports)
   593     if cycles:
   597     if cycles:
   594         firstmods = set()
   598         firstmods = set()
   595         for c in sorted(cycles, key=_cycle_sortkey):
   599         for c in sorted(cycles, key=_cycle_sortkey):
   596             first = c.split()[0]
   600             first = c.split()[0]