salt/tests/modparser.py

95 lines
2.3 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python
2020-04-02 20:10:20 -05:00
import argparse
2020-04-02 20:10:20 -05:00
import modulefinder
import os
import pprint
import sys
import salt.utils.json
import salt.utils.yaml
2015-07-11 15:25:36 -06:00
def parse():
2020-04-02 20:10:20 -05:00
"""
2015-07-11 15:25:36 -06:00
Parse the arguments
2020-04-02 20:10:20 -05:00
"""
2015-07-11 15:25:36 -06:00
parser = argparse.ArgumentParser()
parser.add_argument(
2020-04-02 20:10:20 -05:00
"-r",
"--root",
dest="root",
default=".",
help="The base code directory to look in",
)
parser.add_argument("-i", "--bif", dest="bif", default="site-packages")
2015-07-11 15:36:58 -06:00
parser.add_argument(
2020-04-02 20:10:20 -05:00
"-f", "--format", dest="format", choices=("pprint", "yaml"), default="pprint"
)
2015-07-11 15:25:36 -06:00
out = parser.parse_args()
return out.__dict__
def mod_data(opts, full):
2020-04-02 20:10:20 -05:00
"""
2015-07-12 19:26:33 +01:00
Grab the module's data
2020-04-02 20:10:20 -05:00
"""
2015-07-11 15:25:36 -06:00
ret = {}
finder = modulefinder.ModuleFinder()
try:
finder.load_file(full)
2015-07-12 12:30:24 +01:00
except ImportError as exc:
print(f"ImportError - {full} (Reason: {exc})", file=sys.stderr)
2015-07-11 15:25:36 -06:00
return ret
for name, mod in finder.modules.items():
2020-04-02 20:10:20 -05:00
basemod = name.split(".")[0]
2015-07-11 15:25:36 -06:00
if basemod in ret:
continue
2020-04-02 20:10:20 -05:00
if basemod.startswith("_"):
2015-07-11 15:25:36 -06:00
continue
if not mod.__file__:
continue
2020-04-02 20:10:20 -05:00
if opts["bif"] not in mod.__file__:
2015-07-11 15:25:36 -06:00
# Bif - skip
continue
if name == os.path.basename(mod.__file__)[:-3]:
continue
ret[basemod] = mod.__file__
for name, err in finder.badmodules.items():
2020-04-02 20:10:20 -05:00
basemod = name.split(".")[0]
2015-07-11 15:25:36 -06:00
if basemod in ret:
continue
2020-04-02 20:10:20 -05:00
if basemod.startswith("_"):
2015-07-11 15:25:36 -06:00
continue
ret[basemod] = err
return ret
def scan(opts):
2020-04-02 20:10:20 -05:00
"""
Scan the provided root for python source files
2020-04-02 20:10:20 -05:00
"""
2015-07-11 15:25:36 -06:00
ret = {}
2020-04-02 20:10:20 -05:00
for root, dirs, files in os.walk(opts["root"]):
2015-07-11 15:25:36 -06:00
for fn_ in files:
full = os.path.join(root, fn_)
2020-04-02 20:10:20 -05:00
if full.endswith(".py"):
2015-07-11 15:25:36 -06:00
ret.update(mod_data(opts, full))
return ret
2020-04-02 20:10:20 -05:00
if __name__ == "__main__":
2015-07-11 15:25:36 -06:00
opts = parse()
try:
scand = scan(opts)
2020-04-02 20:10:20 -05:00
if opts["format"] == "yaml":
print(salt.utils.yaml.safe_dump(scand))
2020-04-02 20:10:20 -05:00
if opts["format"] == "json":
print(salt.utils.json.dumps(scand))
else:
pprint.pprint(scand)
exit(0)
except KeyboardInterrupt:
2020-04-02 20:10:20 -05:00
print("\nInterrupted on user request", file=sys.stderr)
exit(1)