-
Notifications
You must be signed in to change notification settings - Fork 1
/
processor.py
259 lines (209 loc) · 8.32 KB
/
processor.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# -*- coding:utf-8 -*-
from typing import Any, Dict, List, Optional, Tuple, Union
import os
import re
import textwrap
import random
import logging
from ..common.utils import exec_cmd, confirm, similar_command, traceback_info
from ..common.singleton import Singleton
from ..render import get_console
from ..render.str_utils import shorten
from .shortcmds import GIT_CMDS, CommandType
Log = logging.getLogger(__name__)
def get_extra_cmds(name: str, path: str) -> Dict:
"""Get custom cmds.
Load the `extra_cmds.py` file under PIGIT HOME, check whether `extra_cmds`
exists, and return it. If not have, return a empty dict.
Returns:
(dict[str,str]): extra cmds dict.
"""
import importlib.util
extra_cmds = {}
if os.path.isfile(path):
try:
# load a module form localtion.
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
except Exception:
Log.error(traceback_info(f"Can't load file '{path}'."))
else:
try:
extra_cmds = module.extra_cmds # type: ignore
except AttributeError:
Log.error("Can't found dict name is 'extra_cmds'.")
return extra_cmds
class ShortGitter(metaclass=Singleton):
"""Git short command processor."""
def __init__(
self,
extra_cmds: Optional[dict] = None,
command_prompt: bool = True,
show_original: bool = True,
**kwargs,
) -> None:
self.use_recommend = command_prompt
self.show_original = show_original
# Init commands.
self.cmds = GIT_CMDS
if extra_cmds:
if not isinstance(extra_cmds, dict):
raise TypeError("Custom cmds must be a dict.") from None
self.cmds.update(extra_cmds)
@staticmethod
def color_command(command: str) -> str:
"""Return the command string with color.
prog : green;
command : yellow;
arguments : skyblue;
values : white.
"""
handle = re.match(r"(\w+)\s+(\w+)", command)
prop = handle.group(1)
cmd = handle.group(2)
next_position = handle.span()[1]
color_command = f"b`{prop}`<ok> b`{cmd}`<goldenrod> "
arguments = re.findall(
r"\s+(-?-?[^\s]+)(=?([\w-]+:)?(\".*?\"|\'.*?\'))?", command[next_position:]
)
for arg_handle, value, _, _ in arguments:
color_command += f"`{arg_handle}`<sky_blue>{value} "
return color_command
def process_command(
self, command_: str, args: Optional[Union[List, Tuple]] = None
) -> None:
"""Process command and arguments.
Args:
command_ (str): short command string
args (list|None, optional): command arguments. Defaults to None.
Raises:
SystemExit: not git.
SystemExit: short command not right.
"""
option: Optional[Dict[str, Dict]] = self.cmds.get(command_, None)
# Invalid, if need suggest.
if option is None:
get_console().echo(
f"Don't support this command: `{command_}`<error>, please try `--show-commands`<gold>"
)
if self.use_recommend: # check config.
predicted_command = similar_command(command_, self.cmds.keys())
if confirm(
get_console().render_str(
f":thinking: The wanted command is `{predicted_command}`<ok> ?[y/n]:"
)
):
self.process_command(predicted_command, args=args)
return None
command: Dict[str, Any] = option.get("command", None)
# Has no command can be executed.
if not command:
get_console().echo(
"`Invalid custom short command, nothing can to exec.`<error>"
)
return None
if not option.get("has_arguments", False) and args:
get_console().echo(
f"`The command does not accept parameters. Discard {args}.`<error>"
)
args = []
_type = option.get("type", "command")
if _type == "func":
try:
command(args)
except Exception as e:
get_console().echo(f"`{e}`<error>")
else: # is command.
if args:
args_str = " ".join(args)
command = " ".join([command, args_str])
if self.show_original:
get_console().echo(f":rainbow: {self.color_command(command)}")
exec_cmd(command, reply=False)
# ============================
# Print command help message.
# ============================
def _generate_help_by_key(
self, _key: str, use_color: bool = True, max_width=90
) -> str:
"""Generate one help by given key.
Args:
_key (str): Short command string.
use_color (bool, optional): Whether color help message. Defaults to True.
Returns:
(str): Help message of one command.
"""
help_position = 15
msg_max_width = max_width - help_position
# Get help message and command.
_help: str = self.cmds[_key].get("help", "").strip()
if _help:
_help = textwrap.wrap(_help, msg_max_width)
help_msg = _help[0] + "\n"
for line in _help[1:]:
help_msg += "%*s%s\n" % (help_position, "", line)
else:
help_msg = ""
_command = self.cmds[_key].get("command", "ERROR: empty command.")
if callable(_command):
_command = f"Func: {_command.__name__}"
_command = shorten(_command, msg_max_width, placeholder="...")
command_msg = "%*s%s" % (help_position, "", _command) if help_msg else _command
if use_color:
return f" `{_key:<13}`<ok>{help_msg}`{command_msg}`<gold>"
else:
return f" {_key:<12} {_help}{command_msg}"
def print_help(self) -> None:
"""Print help message."""
print("These are short commands that can replace git operations:")
for key in self.cmds.keys():
msg = self._generate_help_by_key(key)
get_console().echo(msg)
def print_help_by_type(self, command_type: str) -> None:
"""Print a part of help message.
Print the help information of the corresponding part according to the
incoming command type string. If there is no print error prompt for the
type.
Args:
command_type (str): A command type of `TYPE`.
"""
# Process received type.
command_type = command_type.capitalize().strip()
# Checking the type whether right.
if command_type not in CommandType.__members__:
get_console().echo(
"`There is no such type.`<error>\n"
"Please use `git --types`<ok> to view the supported types."
)
if self.use_recommend:
predicted_type = similar_command(
command_type, CommandType.__members__.keys()
)
if confirm(
get_console().render_str(
f":thinking: The wanted type is `{predicted_type}`<ok> ?[y/n]:"
)
):
self.print_help_by_type(predicted_type)
return None
# Print help.
print("These are the orders of {0}".format(command_type))
for k, v in self.cmds.items():
belong = v.get("belong", CommandType.Extra)
# Prevent the `belong` attribute from being set in the custom command.
if isinstance(belong, CommandType) and belong.value == command_type:
msg = self._generate_help_by_key(k)
get_console().echo(msg)
@classmethod
def print_types(cls) -> None:
"""Print all command types with random color."""
res = []
for member in CommandType:
color_str = "#{:02X}{:02X}{:02X}".format(
random.randint(70, 255),
random.randint(70, 255),
random.randint(70, 255),
)
res.append(f"`{member.value}`<{color_str}>")
get_console().echo(" ".join(res))