1
0

modparser.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/env python2
  3. from __future__ import absolute_import, print_function
  4. try:
  5. import argparse # pylint: disable=minimum-python-version
  6. HAS_ARGPARSE = True
  7. except ImportError:
  8. HAS_ARGPARSE = False
  9. import os
  10. import sys
  11. import os
  12. import modulefinder
  13. import pprint
  14. import salt.utils.json
  15. import salt.utils.yaml
  16. def parse():
  17. '''
  18. Parse the arguments
  19. '''
  20. parser = argparse.ArgumentParser()
  21. parser.add_argument(
  22. '-r',
  23. '--root',
  24. dest='root',
  25. default='.',
  26. help='The base code directory to look in')
  27. parser.add_argument(
  28. '-i',
  29. '--bif',
  30. dest='bif',
  31. default='site-packages')
  32. parser.add_argument(
  33. '-f',
  34. '--format',
  35. dest='format',
  36. choices=('pprint', 'yaml'),
  37. default='pprint')
  38. out = parser.parse_args()
  39. return out.__dict__
  40. def mod_data(opts, full):
  41. '''
  42. Grab the module's data
  43. '''
  44. ret = {}
  45. finder = modulefinder.ModuleFinder()
  46. try:
  47. finder.load_file(full)
  48. except ImportError as exc:
  49. print('ImportError - {0} (Reason: {1})'.format(full, exc), file=sys.stderr)
  50. return ret
  51. for name, mod in finder.modules.items():
  52. basemod = name.split('.')[0]
  53. if basemod in ret:
  54. continue
  55. if basemod.startswith('_'):
  56. continue
  57. if not mod.__file__:
  58. continue
  59. if opts['bif'] not in mod.__file__:
  60. # Bif - skip
  61. continue
  62. if name == os.path.basename(mod.__file__)[:-3]:
  63. continue
  64. ret[basemod] = mod.__file__
  65. for name, err in finder.badmodules.items():
  66. basemod = name.split('.')[0]
  67. if basemod in ret:
  68. continue
  69. if basemod.startswith('_'):
  70. continue
  71. ret[basemod] = err
  72. return ret
  73. def scan(opts):
  74. '''
  75. Scan the provided root for python source files
  76. '''
  77. ret = {}
  78. for root, dirs, files in os.walk(opts['root']):
  79. for fn_ in files:
  80. full = os.path.join(root, fn_)
  81. if full.endswith('.py'):
  82. ret.update(mod_data(opts, full))
  83. return ret
  84. if __name__ == '__main__':
  85. if not HAS_ARGPARSE:
  86. print('The argparse python module is required')
  87. opts = parse()
  88. try:
  89. scand = scan(opts)
  90. if opts['format'] == 'yaml':
  91. print(salt.utils.yaml.safe_dump(scand))
  92. if opts['format'] == 'json':
  93. print(salt.utils.json.dumps(scand))
  94. else:
  95. pprint.pprint(scand)
  96. exit(0)
  97. except KeyboardInterrupt:
  98. print('\nInterrupted on user request', file=sys.stderr)
  99. exit(1)