2021-07-19 16:12:29 +00:00
|
|
|
import re
|
2021-07-18 16:17:09 +00:00
|
|
|
import shlex
|
2021-07-19 16:12:29 +00:00
|
|
|
from core.docopt import docopt, DocoptExit
|
|
|
|
|
|
|
|
|
|
|
|
class InvalidHelpDocTypeError(BaseException):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
pass
|
2021-07-18 16:17:09 +00:00
|
|
|
|
|
|
|
|
2021-07-19 05:34:29 +00:00
|
|
|
class InvalidCommandFormatError(BaseException):
|
2021-07-18 16:17:09 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class CommandParser:
|
2021-07-19 05:34:29 +00:00
|
|
|
def __init__(self, args: [str, list, tuple]):
|
2021-07-19 16:12:29 +00:00
|
|
|
"""
|
|
|
|
Format: https://github.com/jazzband/docopt-ng#usage-pattern-format
|
|
|
|
* {} - Detail help information
|
|
|
|
"""
|
|
|
|
self.args_raw = args
|
2021-07-19 05:34:29 +00:00
|
|
|
if isinstance(args, str):
|
2021-07-19 16:12:29 +00:00
|
|
|
args = [args]
|
|
|
|
if isinstance(args, (list, tuple)):
|
|
|
|
arglst = []
|
|
|
|
for x in args:
|
|
|
|
match_detail_help = re.match('(.*){.*}$', x)
|
|
|
|
if match_detail_help:
|
|
|
|
x = match_detail_help.group(1)
|
|
|
|
arglst.append(x)
|
|
|
|
self.args = f'Usage:\n ' + '\n '.join(y for y in arglst)
|
2021-07-19 05:34:29 +00:00
|
|
|
else:
|
2021-07-19 16:12:29 +00:00
|
|
|
raise InvalidHelpDocTypeError
|
|
|
|
|
|
|
|
def return_formatted_help_doc(self):
|
|
|
|
args_raw = self.args_raw
|
|
|
|
|
|
|
|
if isinstance(args_raw, str):
|
|
|
|
args_raw = [args_raw]
|
|
|
|
if isinstance(args_raw, (list, tuple)):
|
|
|
|
arglst = []
|
|
|
|
for x in args_raw:
|
|
|
|
match_detail_help = re.match('(.*){(.*)}$', x)
|
|
|
|
if match_detail_help:
|
|
|
|
x = f'{match_detail_help.group(1)} - {match_detail_help.group(2)}'
|
|
|
|
arglst.append(x)
|
|
|
|
args = f'用法:\n ' + '\n '.join(y for y in arglst)
|
|
|
|
else:
|
|
|
|
raise InvalidHelpDocTypeError
|
|
|
|
return args
|
|
|
|
|
2021-07-18 16:17:09 +00:00
|
|
|
|
|
|
|
def parse(self, command):
|
2021-07-19 16:12:29 +00:00
|
|
|
split_command = shlex.split(command)
|
|
|
|
if len(split_command) == 1:
|
|
|
|
return None
|
|
|
|
try:
|
|
|
|
return docopt(self.args, argvs=split_command[1:], default_help=False)
|
|
|
|
except DocoptExit:
|
|
|
|
raise InvalidCommandFormatError
|