github.com/google/grumpy@v0.0.0-20171122020858-3ec87959189c/tools/pydeps (about) 1 #!/usr/bin/env python 2 3 # Copyright 2016 Google Inc. All Rights Reserved. 4 # 5 # Licensed under the Apache License, Version 2.0 (the "License"); 6 # you may not use this file except in compliance with the License. 7 # You may obtain a copy of the License at 8 # 9 # http://www.apache.org/licenses/LICENSE-2.0 10 # 11 # Unless required by applicable law or agreed to in writing, software 12 # distributed under the License is distributed on an "AS IS" BASIS, 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 # See the License for the specific language governing permissions and 15 # limitations under the License. 16 17 """Outputs names of modules imported by a script.""" 18 19 import argparse 20 import os 21 import sys 22 23 from grumpy.compiler import imputil 24 from grumpy.compiler import util 25 26 27 parser = argparse.ArgumentParser() 28 parser.add_argument('script', help='Python source filename') 29 parser.add_argument('-modname', default='__main__', help='Python module name') 30 31 32 def main(args): 33 gopath = os.getenv('GOPATH', None) 34 if not gopath: 35 print >> sys.stderr, 'GOPATH not set' 36 return 1 37 38 try: 39 imports = imputil.collect_imports(args.modname, args.script, gopath) 40 except SyntaxError as e: 41 print >> sys.stderr, '{}: line {}: invalid syntax: {}'.format( 42 e.filename, e.lineno, e.text) 43 return 2 44 except util.CompileError as e: 45 print >> sys.stderr, str(e) 46 return 2 47 48 names = set([args.modname]) 49 for imp in imports: 50 if imp.is_native: 51 print imp.name 52 else: 53 parts = imp.name.split('.') 54 # Iterate over all packages and the leaf module. 55 for i in xrange(len(parts)): 56 name = '.'.join(parts[:i+1]) 57 if name not in names: 58 names.add(name) 59 print name 60 61 62 if __name__ == '__main__': 63 main(parser.parse_args())