Command line sugar

This commit is contained in:
uid 2020-10-11 01:11:56 +02:00
parent a5bb63fb14
commit d762251476

View File

@ -2,6 +2,7 @@
from pprint import pformat as pp from pprint import pformat as pp
import sys import sys
import argparse import argparse
import inspect
import phi.ldap.client import phi.ldap.client
from phi.config import get_config from phi.config import get_config
@ -11,21 +12,55 @@ from phi.ldap.user import get_user_by_uid
log = get_logger(__name__) log = get_logger(__name__)
if __name__ == '__main__':
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument( parser.add_argument(
'--config', metavar='config.yml', help='custom configuration file') '--config', metavar='config.yml', help='custom configuration file')
subparses = parser.add_subparsers(title='actions', dest='action') subparses = parser.add_subparsers(title='actions', dest='action')
parser_showuser = subparses.add_parser( cli_callbacks = {}
'showuser', help='display user fields')
parser_showuser.add_argument(dest='uid', help='user identifier')
def cli_register(action_info='', param_infos=[]):
def decorator(action):
# Get function name and arguments
action_name = action.__name__
param_names = inspect.getfullargspec(action)[0]
# Create subparser for specific action
subparser = subparses.add_parser(action_name, help=action_info)
for name, info in zip(param_names, param_infos):
subparser.add_argument(dest=name, help=info)
# Register action
cli_callbacks[action_name] = action, param_names
return action
return decorator
def cli_run(args):
for action_name, (action, param_names) in cli_callbacks.items():
if args['action'] == action_name:
action(**{pname: args[pname] for pname in param_names})
def cli_get_args():
namespace = parser.parse_args(sys.argv[1:]) namespace = parser.parse_args(sys.argv[1:])
config_file = namespace.config args = namespace.__dict__
return args
@cli_register('dispaly user field', ['user identifier'])
def showuser(uid):
user = get_user_by_uid(client, uid)
print('\nuid: {}\n{}\n\n'.format(uid, pp(user)))
if __name__ == '__main__':
args = cli_get_args()
config_file = args['config']
config_file, config = get_config(config_file) config_file, config = get_config(config_file)
setup_logging(config.get('logging', {})) setup_logging(config.get('logging', {}))
@ -38,12 +73,9 @@ if __name__ == '__main__':
log.info('Opening LDAP client') log.info('Opening LDAP client')
client.open() client.open()
log.info('Arguments: {}'.format(pp(namespace.__dict__))) log.info('Arguments: {}'.format(pp(args)))
if namespace.action == 'showuser': cli_run(args)
uid = namespace.uid
user = get_user_by_uid(client, uid)
print('\nuid: {}\n{}\n\n'.format(uid, pp(user)))
log.info('Closing LDAP client') log.info('Closing LDAP client')
client.close() client.close()