Skip to content

Commit c4ba772

Browse files
author
paul
committed
remove pythone-fire dependency; implement simple_argparser and list commands using builtin inspect
1 parent 85ee828 commit c4ba772

17 files changed

Lines changed: 156 additions & 246 deletions

‎m/constant.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
M_ROOT = Path(os.path.dirname(os.path.realpath(__file__)))
55

6+
TAB = " " * 4
67
DOTFILES = os.path.expanduser("~/dev/dotfiles")
78
HOME = os.path.expanduser("~")
89
ROOT = os.path.expanduser("~/dev")

‎m/git_util.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33

44
def groot():
5+
# TODO: should be implemented without relying on shell alias
56
_, out, _ = shell("groot")
67
return out
78

‎m/h5_util.py‎

Lines changed: 0 additions & 24 deletions
This file was deleted.

‎m/log.conf‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"formatters": {
44
"simpleFormater": {
55
"datefmt": "%Y/%m/%d %H:%M:%S",
6-
"format": "[%(asctime)s %(filename)s:%(lineno)d] %(levelname)s\\n %(message)s"
6+
"format": "[%(asctime)s %(filename)s:%(lineno)d] %(levelname)s %(message)s"
77
}
88
},
99
"handlers": {

‎m/m‎

Lines changed: 71 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,78 @@
11
#!/usr/local/bin/m_venv3/bin/python
2+
import glob
3+
import importlib
4+
import inspect
25
import json
36
import logging.config
47
import os
8+
import pathlib as pl
59

6-
import fire
7-
8-
from constant import M_ROOT
10+
import m_base
11+
import simple_argparse as sa
12+
from constant import M_ROOT, TAB
913

1014
with open(os.path.join(M_ROOT, "./log.conf")) as conf:
1115
logging.config.dictConfig(json.load(conf))
1216
logger = logging.getLogger()
1317

1418

1519
class M2:
16-
def __init__(self):
17-
from m_audio import Audio
18-
from m_chef import Chef
19-
from m_deploy import Deploy
20-
from m_docker import Docker
21-
from m_keras import Keras
22-
from m_pipe import Pipe
23-
from m_watcher import Watcher
24-
from m_www import Www
25-
from m_shell import Shell
26-
from m_voixdb import Voixdb
27-
28-
self.audio = Audio()
29-
self.chef = Chef()
30-
self.deploy = Deploy()
31-
self.docker = Docker()
32-
self.keras = Keras()
33-
self.pipe = Pipe()
34-
self.shell = Shell()
35-
self.voixdb = Voixdb()
36-
self.watcher = Watcher()
37-
self.www = Www()
20+
def list_m_modules(self):
21+
cmds = [
22+
(pl.Path(cmd).name[2:], slice(-3) if cmd.endswith(".py") else slice(999))
23+
for cmd in glob.glob(f"{M_ROOT}/m_*")
24+
]
25+
cmds = [cmd[s] for (cmd, s) in cmds]
26+
return cmds
27+
28+
def exec_m_module_command(self, m_module, sub_cmds, *args, **kwargs):
29+
logger.debug(f"exec_m_module_command: {args}, {kwargs}")
30+
31+
assert (
32+
len(sub_cmds) == 1
33+
), f"Only first level cmd supported for now; got {sub_cmds}"
34+
cmd = sub_cmds[0]
35+
getattr(m_module, cmd)(*args, **kwargs)
36+
37+
def exec_m_modules(self, cmd, *args, **kwargs):
38+
cmd, *subcommands = cmd.split(".")
39+
cmds = self.list_m_modules()
40+
41+
# cmd exist
42+
if cmd in cmds:
43+
m_module_name = f"m_{cmd}"
44+
45+
cmd_module = importlib.import_module(m_module_name)
46+
clsmembers = inspect.getmembers(
47+
cmd_module,
48+
lambda cls: inspect.isclass(cls)
49+
and cls.__module__ == m_module_name
50+
and issubclass(cls, m_base.Base),
51+
)
52+
53+
assert (
54+
len(clsmembers) == 1
55+
), f"{m_module_name} exports more than 1 m_base.Base. Found {clsmembers}"
56+
57+
_, cls = clsmembers[0]
58+
59+
if not subcommands:
60+
cls().print_cmds()
61+
else:
62+
self.exec_m_module_command(cls(), subcommands, *args, **kwargs)
63+
else:
64+
logger.error(f"{cmd} not found")
65+
66+
def print_m_modules(self):
67+
sa.print_commands(self.list_m_modules())
3868

3969
def noop(self):
4070
"""
4171
Noop method for speed tests
4272
"""
4373
return
4474

45-
def update(self):
75+
def update(self, pip_install_only=False):
4676
"""
4777
Updates the m tool
4878
"""
@@ -52,14 +82,14 @@ class M2:
5282
import fs_util
5383
import git_util
5484

55-
logger.info("updating m tool by rebasing...")
56-
57-
with fs_util.Cwd(M_ROOT):
58-
git_util.stash()
59-
git_util.rebase()
60-
git_util.stash_pop()
61-
_, stdout, _ = git_util.log("--pretty=oneline --abbrev-commit -1")
62-
logger.info("m updated:: %s", stdout.decode("utf-8").strip())
85+
if not pip_install_only:
86+
logger.info("updating m tool by rebasing...")
87+
with fs_util.Cwd(M_ROOT):
88+
git_util.stash()
89+
git_util.rebase()
90+
git_util.stash_pop()
91+
_, stdout, _ = git_util.log("--pretty=oneline --abbrev-commit -1")
92+
logger.info("m updated:: %s", stdout.decode("utf-8").strip())
6393

6494
# also install dependency
6595
subprocess.check_call(
@@ -75,4 +105,10 @@ class M2:
75105

76106

77107
if __name__ == "__main__":
78-
fire.Fire(M2())
108+
import sys
109+
110+
pos, named = sa.parse(sys.argv[1:])
111+
if not pos:
112+
sys.exit(M2().print_m_modules())
113+
else:
114+
M2().exec_m_modules(pos[0], *pos[1:], **named)

‎m/m_base.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import inspect
12
import logging.config
23
import os
34
import subprocess
@@ -6,6 +7,7 @@
67
import coloredlogs
78

89
import shell_util
10+
import simple_argparse as sa
911

1012
FMT = "[%(asctime)s %(filename)s:%(lineno)d %(levelname)s] %(message)s"
1113

@@ -46,6 +48,20 @@ def _all_modules(self):
4648
def _debug_mode(self):
4749
return self._debugging
4850

51+
def list_cmds(self):
52+
return inspect.getmembers(
53+
self,
54+
predicate=lambda x: inspect.ismethod(x) and not x.__name__.startswith("_"),
55+
)
56+
57+
def print_cmds(self):
58+
sa.print_commands(
59+
[name for (name, _) in self.list_cmds()], top_lv=self.__class__.__name__
60+
)
61+
62+
def info(self):
63+
self._logger.info(self.__class__)
64+
4965
def shell(self, cmd, timeout=None, **kwargs):
50-
self._logger.debug(cmd)
66+
self._logger.debug(f"running shell `{cmd}`")
5167
return shell_util.shell(cmd, timeout=timeout, **kwargs)

‎m/m_docker.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
1+
import contextlib
12
import logging
23
import os
34
import shutil
4-
import constant
5-
import contextlib
6-
7-
from util import get_config_yml, m_path
85

6+
import constant
97
from git_util import groot
108
from m_base import Base
9+
from util import get_config_yml, m_path
1110

1211
DEFAULT_GCR_TAG = "gcr.io/euraio/{img}:{tag}"
1312

‎m/m_keras.py‎

Lines changed: 0 additions & 11 deletions
This file was deleted.

‎m/m_voixdb.py‎

Lines changed: 0 additions & 64 deletions
This file was deleted.

‎m/m_watcher.py‎

Lines changed: 0 additions & 9 deletions
This file was deleted.

0 commit comments

Comments
 (0)