From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from lists.gentoo.org (pigeon.gentoo.org [208.92.234.80]) by finch.gentoo.org (Postfix) with ESMTP id E16BA1389E2 for ; Mon, 22 Dec 2014 23:11:52 +0000 (UTC) Received: from pigeon.gentoo.org (localhost [127.0.0.1]) by pigeon.gentoo.org (Postfix) with SMTP id C4007E0994; Mon, 22 Dec 2014 23:11:45 +0000 (UTC) Received: from smtp.gentoo.org (smtp.gentoo.org [140.211.166.183]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by pigeon.gentoo.org (Postfix) with ESMTPS id CEECDE097C for ; Mon, 22 Dec 2014 23:11:43 +0000 (UTC) Received: from oystercatcher.gentoo.org (oystercatcher.gentoo.org [148.251.78.52]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by smtp.gentoo.org (Postfix) with ESMTPS id 52D6E340623 for ; Mon, 22 Dec 2014 23:11:42 +0000 (UTC) Received: from localhost.localdomain (localhost [127.0.0.1]) by oystercatcher.gentoo.org (Postfix) with ESMTP id AA5BDD27F for ; Mon, 22 Dec 2014 23:11:39 +0000 (UTC) From: "Brian Dolbec" To: gentoo-commits@lists.gentoo.org Content-Transfer-Encoding: 8bit Content-type: text/plain; charset=UTF-8 Reply-To: gentoo-dev@lists.gentoo.org, "Brian Dolbec" Message-ID: <1419093965.8cdb30f524cf77267fc01c8813a98e89116a7406.dol-sen@gentoo> Subject: [gentoo-commits] proj/gentoo-keys:master commit in: gkeys/ X-VCS-Repository: proj/gentoo-keys X-VCS-Files: gkeys/base.py gkeys/cli.py X-VCS-Directories: gkeys/ X-VCS-Committer: dol-sen X-VCS-Committer-Name: Brian Dolbec X-VCS-Revision: 8cdb30f524cf77267fc01c8813a98e89116a7406 X-VCS-Branch: master Date: Mon, 22 Dec 2014 23:11:39 +0000 (UTC) Precedence: bulk List-Post: List-Help: List-Unsubscribe: List-Subscribe: List-Id: Gentoo Linux mail X-BeenThere: gentoo-commits@lists.gentoo.org X-Archives-Salt: 142ccc6a-b5d2-4a4f-880e-e20ac2a63190 X-Archives-Hash: 23edd78ae385297aff9f991c409010e4 commit: 8cdb30f524cf77267fc01c8813a98e89116a7406 Author: Brian Dolbec gentoo org> AuthorDate: Thu Dec 11 16:37:34 2014 +0000 Commit: Brian Dolbec gmail com> CommitDate: Sat Dec 20 16:46:05 2014 +0000 URL: http://sources.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=8cdb30f5 gkeys/cli.py: Split out a common CliBase class and base.py --- gkeys/{cli.py => base.py} | 78 +++++++++-------- gkeys/cli.py | 208 ++++------------------------------------------ 2 files changed, 59 insertions(+), 227 deletions(-) diff --git a/gkeys/cli.py b/gkeys/base.py similarity index 80% copy from gkeys/cli.py copy to gkeys/base.py index 8adc9ef..48de147 100644 --- a/gkeys/cli.py +++ b/gkeys/base.py @@ -2,9 +2,10 @@ #-*- coding:utf-8 -*- """ - Gentoo-keys - cli.py + Gentoo-keys - base.py - Command line interface module + Command line interface argsparse options module + and common functions @copyright: 2012 by Brian Dolbec @license: GNU GPL2, see COPYING for details. @@ -14,43 +15,31 @@ from __future__ import print_function import argparse -import sys from gkeys import config, fileops, seed, lib -from gkeys.actions import Actions, Available_Actions, Action_Options -from gkeys.config import GKeysConfig from gkeys.log import log_levels, set_logger +class CliBase(object): + '''Common cli and argsparse options class''' -class Main(object): - '''Main command line interface class''' - - def __init__(self, root=None, config=None, print_results=True): - """ Main class init function. - - @param root: string, root path to use - """ - self.root = root or "/" - self.config = config or GKeysConfig(root=root) - self.config.options['print_results'] = print_results + def __init__(self): + self.cli_config = { + 'Actions': [], + 'Available_Actions': [], + 'Action_Options': [], + 'prog': 'gkeys', + 'description': 'Gentoo-keys manager program', + 'epilog': '''Caution: adding untrusted keys to these keyrings can + be hazardous to your system!''' + } + self.config = None self.args = None self.seeds = None self.actions = None - def __call__(self, args=None): - if args: - return self.run(self.parse_args(args)) - else: - return self.run(self.parse_args(sys.argv[1:])) - - - def _add_options(self, parser, options): - for opt in options: - getattr(self, '_option_%s' % opt)(parser) - @staticmethod def _option_dest(parser=None): parser.add_argument('-d', '--dest', dest='destination', default=None, @@ -95,6 +84,19 @@ class Main(object): help='The key or seed directory category to use or update') @staticmethod + def _option_cleankey(parser=None): + parser.add_argument('--clean-key', + dest='cleankey', default=False, + help='Clean the key from the keyring due to failures') + + @staticmethod + def _option_cleanseed(parser=None): + parser.add_argument('--clean-seed', + dest='cleanseed', default=False, + help='Clean the seed from the seedfile due to failures. ' + 'Used during binary keyring release creation.') + + @staticmethod def _option_keydir(parser=None): parser.add_argument('-r', '--keydir', dest='keydir', default=None, help='The keydir to use, update or search for/in') @@ -128,12 +130,11 @@ class Main(object): @param args: list @returns argparse.Namespace object ''' - #logger.debug('MAIN: parse_args; args: %s' % args) + #logger.debug('CliBase: parse_args; args: %s' % args) parser = argparse.ArgumentParser( - prog='gkeys', - description='Gentoo-keys manager program', - epilog='''Caution: adding untrusted keys to these keyrings can - be hazardous to your system!''') + prog=self.cli_config['prog'], + description=self.cli_config['description'], + epilog=self.cli_config['epilog']) # options parser.add_argument('-c', '--config', dest='config', default=None, @@ -144,8 +145,8 @@ class Main(object): subparsers = parser.add_subparsers(help='actions') - for name in Available_Actions: - action_method = getattr(Actions, name) + for name in self.cli_config['Available_Actions']: + action_method = getattr(self.cli_config['Actions'], name) actiondoc = action_method.__doc__ try: text = actiondoc.splitlines()[0] @@ -157,11 +158,16 @@ class Main(object): description=actiondoc, formatter_class=argparse.RawDescriptionHelpFormatter) action_parser.set_defaults(action=name) - self._add_options(action_parser, Action_Options[name]) + self._add_options(action_parser, self.cli_config['Action_Options'][name]) return parser.parse_args(args) + def _add_options(self, parser, options): + for opt in options: + getattr(self, '_option_%s' % opt)(parser) + + def run(self, args): '''Run the args passed in @@ -196,7 +202,7 @@ class Main(object): % args.config) # establish our actions instance - self.actions = Actions(self.config, self.output_results, logger) + self.actions = self.cli_config['Actions'](self.config, self.output_results, logger) # run the action func = getattr(self.actions, '%s' % args.action) diff --git a/gkeys/cli.py b/gkeys/cli.py index 8adc9ef..32d2ec4 100644 --- a/gkeys/cli.py +++ b/gkeys/cli.py @@ -13,17 +13,15 @@ from __future__ import print_function -import argparse import sys -from gkeys import config, fileops, seed, lib +from gkeys.base import CliBase from gkeys.actions import Actions, Available_Actions, Action_Options from gkeys.config import GKeysConfig -from gkeys.log import log_levels, set_logger -class Main(object): +class Main(CliBase): '''Main command line interface class''' @@ -32,201 +30,29 @@ class Main(object): @param root: string, root path to use """ + CliBase.__init__(self) self.root = root or "/" self.config = config or GKeysConfig(root=root) self.config.options['print_results'] = print_results - self.args = None - self.seeds = None - self.actions = None + self.cli_config = { + 'Actions': Actions, + 'Available_Actions': Available_Actions, + 'Action_Options': Action_Options, + 'prog': 'gkeys', + 'description': 'Gentoo-keys manager program', + 'epilog': '''Caution: adding untrusted keys to these keyrings can + be hazardous to your system!''' + } def __call__(self, args=None): + """Main class call function + + @param args: Optional list of argumanets to parse and action to run + Defaults to sys.argv[1:] + """ if args: return self.run(self.parse_args(args)) else: return self.run(self.parse_args(sys.argv[1:])) - - def _add_options(self, parser, options): - for opt in options: - getattr(self, '_option_%s' % opt)(parser) - - @staticmethod - def _option_dest(parser=None): - parser.add_argument('-d', '--dest', dest='destination', default=None, - help='The destination seed file or keydir for move, copy operations') - - @staticmethod - def _option_fingerprint(parser=None): - parser.add_argument('-f', '--fingerprint', dest='fingerprint', - default=None, nargs='+', - help='The fingerprint of the the key') - - @staticmethod - def _option_gpgsearch(parser=None): - parser.add_argument('-g', '--gpgsearch', dest='gpgsearch', default=None, - help='Do a gpg search operations, rather than a gkey search') - - @staticmethod - def _option_keyid(parser=None): - parser.add_argument('-i', '--keyid', dest='keyid', default=None, - nargs='+', - help='The long keyid of the gpg key to search for') - - @staticmethod - def _option_keyring(parser=None): - parser.add_argument('-k', '--keyring', dest='keyring', default='trusted_keyring', - help='The name of the keyring to use') - - @staticmethod - def _option_nick(parser=None): - parser.add_argument('-n', '--nick', dest='nick', default=None, - help='The nick associated with the the key') - - @staticmethod - def _option_name(parser=None): - parser.add_argument('-N', '--name', dest='name', nargs='*', - default=None, help='The name of the the key') - - @staticmethod - def _option_category(parser=None): - parser.add_argument('-C', '--category', - choices=['rel', 'dev', 'overlays', 'sign'], dest='category', default=None, - help='The key or seed directory category to use or update') - - @staticmethod - def _option_keydir(parser=None): - parser.add_argument('-r', '--keydir', dest='keydir', default=None, - help='The keydir to use, update or search for/in') - - @staticmethod - def _option_seedfile(parser=None): - parser.add_argument('-S', '--seedfile', dest='seedfile', default=None, - help='The seedfile to use from the gkeys.conf file') - - @staticmethod - def _option_file(parser=None): - parser.add_argument('-F', '--file', dest='filename', default=None, - nargs='+', - help='The path/URL to use for the (signed) file') - - @staticmethod - def _option_signature(parser=None): - parser.add_argument('-s','--signature', dest='signature', default=None, - help='The path/URL to use for the signature') - - @staticmethod - def _option_timestamp(parser=None): - parser.add_argument('-t', '--timestamp', dest='timestamp', type=bool, - default=False, - help='Turn on timestamp use') - - - def parse_args(self, args): - '''Parse a list of aruments - - @param args: list - @returns argparse.Namespace object - ''' - #logger.debug('MAIN: parse_args; args: %s' % args) - parser = argparse.ArgumentParser( - prog='gkeys', - description='Gentoo-keys manager program', - epilog='''Caution: adding untrusted keys to these keyrings can - be hazardous to your system!''') - - # options - parser.add_argument('-c', '--config', dest='config', default=None, - help='The path to an alternate config file') - parser.add_argument('-D', '--debug', default='DEBUG', - choices=list(log_levels), - help='The logging level to set for the logfile') - - - subparsers = parser.add_subparsers(help='actions') - for name in Available_Actions: - action_method = getattr(Actions, name) - actiondoc = action_method.__doc__ - try: - text = actiondoc.splitlines()[0] - except AttributeError: - text = "" - action_parser = subparsers.add_parser( - name, - help=text, - description=actiondoc, - formatter_class=argparse.RawDescriptionHelpFormatter) - action_parser.set_defaults(action=name) - self._add_options(action_parser, Action_Options[name]) - - return parser.parse_args(args) - - - def run(self, args): - '''Run the args passed in - - @param args: list or argparse.Namespace object - ''' - global logger - message = None - if not args: - message = "Main: run; invalid args argument passed in" - if isinstance(args, list): - args = self.parse_args(args) - if args.config: - self.config.defaults['config'] = args.config - # now make it load the config file - self.config.read_config() - - # establish our logger and update it in the imported files - logger = set_logger('gkeys', self.config['logdir'], args.debug, - dirmode=int(self.config.get_key('permissions', 'directories'),0), - filemask=int(self.config.get_key('permissions', 'files'),0)) - config.logger = logger - fileops.logger = logger - seed.logger = logger - lib.logger = logger - - if message: - logger.error(message) - - # now that we have a logger, record the alternate config setting - if args.config: - logger.debug("Main: run; Found alternate config request: %s" - % args.config) - - # establish our actions instance - self.actions = Actions(self.config, self.output_results, logger) - - # run the action - func = getattr(self.actions, '%s' % args.action) - logger.debug('Main: run; Found action: %s' % args.action) - success, results = func(args) - if not results: - print("No results found. Check your configuration and that the", - "seed file exists.") - return success - if self.config.options['print_results'] and 'done' not in list(results): - self.output_results(results, '\n Gkey task results:') - return success - - - @staticmethod - def output_results(results, header): - # super simple output for the time being - if header: - print(header) - for msg in results: - if isinstance(msg, str): - print(' ', msg) - else: - try: - print("\n".join([x.pretty_print for x in msg])) - except AttributeError: - for x in msg: - print(' ', x) - print() - - - def output_failed(self, failed): - pass