-
Notifications
You must be signed in to change notification settings - Fork 11
/
cli.py
102 lines (78 loc) · 2.92 KB
/
cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"""
This module is a CLI for helping with development of the Baboon Tracking Project.
"""
# These are default python packages. No installed modules here.
import argparse
import importlib
import json
import os
import platform
import subprocess
import sys
from src.cli_plugins.cli_plugin import CliPlugin
def _short_circuit():
if len(sys.argv) > 1 and sys.argv[1].lower() != "shell":
os.environ["CLI_ACTIVE"] = "1"
subprocess.check_call(
["poetry", "run", "python", "./cli.py"] + sys.argv[1:],
shell=(sys.platform == "win32"),
)
elif len(sys.argv) > 1 and sys.argv[1].lower() == "shell":
from src.cli_plugins.shell import ( # pylint: disable=import-outside-toplevel
shell,
)
shell()
else:
return False
return True
def main():
"""
Main entry point for CLI.
"""
sys.path.append(os.getcwd() + "/src")
if os.getenv("VIRTUAL_ENV") is None or (
os.getenv("TRAVIS") is not None and os.getenv("CLI_ACTIVE") is None
):
from src.cli_plugins.install import ( # pylint: disable=import-outside-toplevel
install,
)
install()
if _short_circuit():
return
parser = argparse.ArgumentParser(description="Baboon Command Line Interface")
subparsers = parser.add_subparsers(dest="command")
subparsers.required = True
# We import the Cli plugin list from a json file instead of yaml,
# Python's yaml support is not built in
with open("./src/cli_plugins/plugins.json", "r", encoding="utf8") as f:
plugins_dict = json.load(f)
is_arm = platform.machine() == "aarch64"
# Plugins are loaded dynamically from ./src/cli_plugins/plugins.json
for plugin in plugins_dict["plugins"]:
if is_arm and "support_arm" in plugin and not plugin["support_arm"]:
continue
for subcommand in plugin["subcommands"]:
subparser = subparsers.add_parser(
subcommand, description=plugin["description"]
)
try:
module = importlib.import_module(
"." + plugin["module"], "src.cli_plugins"
)
except ModuleNotFoundError as err:
print(
"While loading plugins, ran into error: " + str(err),
file=sys.stderr,
)
print(
"Please run `./cli shell` to enter python environment",
file=sys.stderr,
)
sys.exit(1)
class_type = getattr(module, plugin["class"])
cli_plugin: CliPlugin = class_type(subparser)
subparser.set_defaults(run_plugin=cli_plugin.execute)
args = parser.parse_args()
args.run_plugin(args)
if __name__ == "__main__":
main()