Skip to content

Commit

Permalink
support feature request #3, #4
Browse files Browse the repository at this point in the history
  • Loading branch information
wjo1212 committed Nov 29, 2017
1 parent 705c163 commit 6f9121b
Show file tree
Hide file tree
Showing 3 changed files with 106 additions and 12 deletions.
40 changes: 34 additions & 6 deletions aliyunlogcli/cli_core.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@



import jmespath
from aliyun.log import LogException, LogClient
import six.moves.configparser as configparser
from docopt import docopt
from docopt import docopt, DocoptExit
from six import StringIO
from .version import __version__, USER_AGENT
from .config import load_config, LOG_CONFIG_SECTION
from .parser import *
import sys


def configure_confidential(secure_id, secure_key, endpoint, client_name=LOG_CONFIG_SECTION):
Expand Down Expand Up @@ -74,10 +73,40 @@ def _sort_str_dict(obj, enclosed=False):
return _get_str(obj, enclosed)


def docopt_ex(doc, usage, help=True, version=None):
argv = sys.argv[1:]

# support customized help
if len(argv) <= 0 or "--help" in argv[0]:
print(usage)
return

first_cmd = argv[0]

try:
return docopt(doc, help=help, version=version)
except DocoptExit as ex:
# show customized error
if first_cmd == "configure":
print("Usage:\n" + MORE_DOCOPT_CMD)
return
elif first_cmd == "log" and len(argv) > 1:
second_cmd = argv[1]
for cmd in doc.split("\n"):
if "aliyun log " + second_cmd in cmd:
print("Usage:\n" + cmd)
return

print(usage)


def main():
method_types, optdoc = parse_method_types_optdoc_from_class(LogClient, LOG_CLIENT_METHOD_BLACK_LIST)
method_types, optdoc, usage = parse_method_types_optdoc_from_class(LogClient, LOG_CLIENT_METHOD_BLACK_LIST)

arguments = docopt_ex(optdoc, usage, help=False, version=__version__)
if arguments is None:
return

arguments = docopt(optdoc, version=__version__)
system_options = normalize_system_options(arguments)

# process normal log command
Expand Down Expand Up @@ -113,4 +142,3 @@ def main():
args = arguments['<secure_id>'], arguments['<secure_key>'], arguments['<endpoint>'], \
arguments['<client_name>'] or LOG_CONFIG_SECTION
configure_confidential(*args)

36 changes: 35 additions & 1 deletion aliyunlogcli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from jmespath.exceptions import ParseError

LOG_CLIENT_METHOD_BLACK_LIST = (r'_.+', r'\w+acl', 'set_source', 'delete_shard', 'heart_beat',
'set_user_agent'
'set_user_agent', 'get_unicode',
)

LOG_CREDS_FILENAME = "%s/.aliyunlogcli" % os.path.expanduser('~')
Expand All @@ -17,6 +17,40 @@

SystemConfig = namedtuple('SystemConfig', "access_id access_key endpoint jmes_filter")

API_GROUP = [('project$', 'Project'), 'logstore', ('index|topics', "Index"),
('logtail_config', "Logtail Config"), ('machine', "Machine Group"), 'shard',
'cursor', ('logs|histogram', "Logs"), ('consumer|check_point', "Consumer Group"), 'shipper']


USAGE_STR_TEMPLATE = """
Usage:
1. aliyun log <subcommand> [parameters | global options]
2. aliyun configure <access_id> <access-key> <endpoint> [<client-name>]
3. aliyun [--help | --version]
Examples:
1. aliyun configure AKID123 AKKEY123 cn-hangzhou.log.aliyuncs.com
2. aliyun log create_project --project_name="test"
Subcommand:
{grouped_api}
Global Options:
[--access-id=<value>] : use this access id in this command
[--access-key=<value>] : use this access key in this command
[--region-endpoint=<value>] : use this endpoint in this command
[--client-name=<value>] : use this client name in configured accounts
[--jmes-filter=<value>] : filter results using JMES syntax
Refer to http://aliyun-log-cli.readthedocs.io/ for more info.
"""

MORE_DOCOPT_CMD = """aliyun configure <secure_id> <secure_key> <endpoint> [<client_name>]
"""


def load_config_from_file(client_name):
# load config from file
Expand Down
42 changes: 37 additions & 5 deletions aliyunlogcli/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from aliyun.log.util import Util
from .config import *
from .config import load_default_config_from_file_env, load_config_from_file, LOG_CONFIG_SECTION
from collections import OrderedDict
from six import StringIO


def _parse_method(func):
Expand Down Expand Up @@ -303,10 +305,38 @@ def _match_black_list(method_name, black_list):
return False


def _attach_more_cmd():
cmd = """aliyun configure <secure_id> <secure_key> <endpoint> [<client_name>]\n"""
def _attach_more_cmd_docopt():
return MORE_DOCOPT_CMD

return cmd

def _get_grouped_usage(method_list):
dct = OrderedDict()
for k in API_GROUP:
des = k[1] if isinstance(k, (list, tuple)) else k.title()
dct[des] = []

for x in method_list:
for k in API_GROUP:
key = k[0] if isinstance(k, (list, tuple)) else k
des = k[1] if isinstance(k, (list, tuple)) else k.title()
if re.search(key, x):
dct[des].append(x)
break
else:
dct["Others"].append(x)

usage = StringIO()
for k, v in dct.items():
usage.write("\n\t")
usage.write(k)
usage.write("\n\t" + "-" * 35)
for d in sorted(v):
usage.write("\n\t")
usage.write(d)

usage.write("\n")

return usage.getvalue()


def parse_method_types_optdoc_from_class(cls, black_list=None):
Expand All @@ -322,8 +352,10 @@ def parse_method_types_optdoc_from_class(cls, black_list=None):

params_types = {}

usage = USAGE_STR_TEMPLATE.format(grouped_api=_get_grouped_usage(method_list))

doc = 'Usage:\n'
doc += _attach_more_cmd()
doc += MORE_DOCOPT_CMD

for m in method_list:
method = getattr(cls, m, None)
Expand All @@ -334,7 +366,7 @@ def parse_method_types_optdoc_from_class(cls, black_list=None):
doc += _parse_method_cli(method)

doc += '\n'
return params_types, doc
return params_types, doc, usage


def _convert_args(args_values, method_types):
Expand Down

0 comments on commit 6f9121b

Please sign in to comment.