commit:     8be6c1ff9d7717d82d8d6e088899af6a749dc9ef
Author:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
AuthorDate: Tue Dec 30 19:40:31 2014 +0000
Commit:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
CommitDate: Thu Jan  1 02:39:51 2015 +0000
URL:        
http://sources.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=8be6c1ff

gkeys-gen: Initial migration to use gkeys.base.CliBase class

Add a new gkeys-gen specific config file extension to gkeys.conf.
Change gpghome to use the configured gpg-home setting.
Remove default SPEC and GPG_CONF settings, use configured ones.
bin/gkey-gen update exit.

---
 gkeys-gen/bin/gkey-gen       |   5 +-
 gkeys-gen/etc/gkeys-gen.conf |  29 ++++++++++++
 gkeys-gen/gkeygen/actions.py | 100 +++++++++++++++++++++++----------------
 gkeys-gen/gkeygen/cli.py     | 110 +++++++++++--------------------------------
 gkeys/gkeys/base.py          |   2 +-
 5 files changed, 120 insertions(+), 126 deletions(-)

diff --git a/gkeys-gen/bin/gkey-gen b/gkeys-gen/bin/gkey-gen
index e322f11..9acfc88 100755
--- a/gkeys-gen/bin/gkey-gen
+++ b/gkeys-gen/bin/gkey-gen
@@ -47,4 +47,7 @@ if 'ROOT' in os.environ:
     root = os.environ['ROOT']
 
 main = Main(root=root)
-main()
+success = main()
+
+# exit is boolean opposite normal True/False
+sys.exit(not success)

diff --git a/gkeys-gen/etc/gkeys-gen.conf b/gkeys-gen/etc/gkeys-gen.conf
new file mode 100644
index 0000000..d67f10a
--- /dev/null
+++ b/gkeys-gen/etc/gkeys-gen.conf
@@ -0,0 +1,29 @@
+# Gentoo-keys configuration file
+#
+
+[gkeys-gen]
+
+
+gpg-home = %(user-dir)s/gpghome
+
+
+[spec]
+
+glep-63 = %(user-dir)s/glep63.spec'
+
+default-spec = glep-63
+
+
+[spec-urls]
+
+glep-63 = https://api.gentoo.org/gentoo-keys/specs/glep63.spec
+
+
+[gpg-configs]
+
+glep-63 = %(user-dir)s/glep63-gpg-conf.skel
+
+
+[gpg-urls]
+
+glep-63 = https://api.gentoo.org/gentoo-keys/specs/glep63-gpg-conf.skel

diff --git a/gkeys-gen/gkeygen/actions.py b/gkeys-gen/gkeygen/actions.py
index e33ebb8..b3aecb9 100644
--- a/gkeys-gen/gkeygen/actions.py
+++ b/gkeys-gen/gkeygen/actions.py
@@ -26,10 +26,35 @@ else:
 
 from gkeys.fileops import ensure_dirs
 
-Available_Actions = ["genkey"]
 
-GPG_CONF = "https://api.gentoo.org/gentoo-keys/specs/glep63-gpg-conf.skel";
-SPEC = "https://api.gentoo.org/gentoo-keys/specs/glep63.spec";
+Available_Actions = ["gen-key"]
+
+Action_Options = {
+    'gen-key': ['dest'],
+}
+
+Action_Map = {
+    'gen-key': 'genkey',
+}
+
+
+LARRY = """
+    ____________________
+    < Generating GPG key >
+     --------------------
+            \   ^__^
+             \  (oo)\_______
+                (__)\       )\/
+                    ||----w |
+                    ||     ||"""
+
+GPG_INFO_STRING = """
+        GPG key info:
+            Full Name: %s,
+            Email: %s,
+            Fingerprint: %s
+                        """
+
 
 class Actions(object):
 
@@ -38,16 +63,18 @@ class Actions(object):
         self.output = output
         self.logger = logger
 
+
     def genkey(self, args):
         '''Key generation action'''
-        if not args.homedir:
-            gpghome = os.path.join(os.getcwd(), 'gpghome')
+        messages = []
+        if not args.destination:
+            gpghome = self.config.get_key('gkeys-gen', 'gpg-home')
         else:
-            if os.path.exists(args.homedir):
-                gpghome = os.path.join(args.homedir, 'gpghome')
+            if os.path.exists(args.destination):
+                gpghome = os.path.join(args.destination, 'gpghome')
             else:
-                self.output("Aborting... %s path does not exist." % 
args.homedir)
-                return False
+                messages.extend(['', "Aborting... %s path does not exist." % 
args.destination])
+                return (False, messages)
         self.logger.debug("MAIN: _action_genkey; setting gpghome destination: 
%s" % gpghome)
         self.logger.debug("MAIN: _action_genkey; args= %s" % str(args))
         key_params = self.get_input()
@@ -55,68 +82,59 @@ class Actions(object):
         while ack not in ["y", "yes", "n", "no"]:
             ack = py_input("Continue?[y/n]: ").lower()
         if ack in ["n", "no"]:
-            self.output("\nKey generation aborted.")
-            return False
+            messages.extend(['', "\nKey generation aborted."])
+            return (False. messages)
         elif ack in ["y", "yes"]:
             # Set the environment to custom gpg directory
             os.environ['GNUPGHOME'] = gpghome
             gpghome_full_path = os.path.abspath(gpghome)
             self.logger.info("MAIN: _action_genkey; create custom gpg 
directory: %s" % gpghome_full_path)
-            self.output("\n* Creating gpg folder at %s" % gpghome_full_path)
+            self.output(["\n* Creating gpg folder at %s" % gpghome_full_path])
             ensure_dirs(gpghome)
             # Copy default gpg-conf.skel and append glep63 requirements
-            self.output("* Creating gpg.conf file at %s" % gpghome_full_path)
+            self.output(["* Creating gpg.conf file at %s" % gpghome_full_path])
             newgpgconfpath = os.path.join(gpghome, 'gpg.conf')
             shutil.copy('/usr/share/gnupg/gpg-conf.skel', newgpgconfpath)
             with open(newgpgconfpath, 'a') as conf:
-                for line in urlopen(GPG_CONF):
+                for line in urlopen(self.config.defaults['gpg.conf-url']):
                     conf.write(_unicode(line))
             # Key generation
             ctx = gpgme.Context()
             self.logger.info("MAIN: _action_genkey: Generating GPG key...")
-            self.output("""
-    ____________________
-    < Generating GPG key >
-     --------------------
-            \   ^__^
-             \  (oo)\_______
-                (__)\       )\/
-                    ||----w |
-                    ||     ||""")
-            self.output("\n* Give the password for the key. (Pick a strong 
one)\n")
+            self.output([LARRY])
+            self.output(["* Give the password for the key. (Pick a strong 
one)",
+                "    Please surf the internet, type on your keyboard, etc. ",
+                "    This helps the random number generator work effectively"])
             try:
                 result = ctx.genkey(key_params)
             except gpgme.GpgmeError:
                 self.logger.debug("MAIN: _action_genkey: Aborting... No given 
password.")
-                self.output("Aborting... No given password.")
-                return False
+                messages.extend(['', "Aborting... No given password."])
+                return (False, messages)
             key = ctx.get_key(result.fpr, True)
             self.logger.debug("MAIN: _action_genkey: Generated key: %s - %s"
                               % (key.uids[0].uid, key.subkeys[0].fpr))
-            self.output("Your new GLEP 63 based OpenPGP key has been created 
in %s" % gpghome_full_path)
-            self.output("""
-        GPG key info:
-            Full Name: %s,
-            Email: %s,
-            Fingerprint: %s
-                        """ % (key.uids[0].name, key.uids[0].email,
-                               key.subkeys[0].fpr))
-            self.output("In order to use your new key, place the new gpghome 
to your ~/.gnupg folder by running the following command:\n"
+            self.output(["Your new GLEP 63 based OpenPGP key has been created 
in %s" % gpghome_full_path])
+            self.output([GPG_INFO_STRING % (key.uids[0].name, 
key.uids[0].email,
+                               key.subkeys[0].fpr)])
+            self.output(["In order to use your new key, place the new gpghome 
to your ~/.gnupg folder by running the following command:\n"
                         "    mv %s ~/.gnupg\n"
                         "Important: If you have another old key in ~/.gnupg 
please make sure you backup it up first.\n\n"
                         "Please read the FAQ for post-generation steps that 
are available in: \n"
-                        
"https://wiki.gentoo.org/wiki/Project:Gentoo-keys/Generating_GLEP_63_based_OpenPGP_keys\n";
 % gpghome_full_path)
-            return True
+                        
"https://wiki.gentoo.org/wiki/Project:Gentoo-keys/Generating_GLEP_63_based_OpenPGP_keys\n";
 % gpghome_full_path])
+            return (True, messages)
+
 
     def get_input(self):
         '''Interactive user input'''
-        self.output("\nGPG key creator based on GLEP 63\n"
-                    "(https://wiki.gentoo.org/wiki/GLEP:63)\n")
+        self.output(["\nGPG key creator based on GLEP 63\n"
+                    "(https://wiki.gentoo.org/wiki/GLEP:63)\n"])
         name = py_input("Give your Full Name: ")
         email = py_input("Give your Email: ")
         while not re.match(r'[\w.-]+@[\w.-]+', email):
-            self.output("\nBad email input. Try again.")
+            self.output(["\nBad email input. Try again."])
             email = py_input("Give your Email: ")
         print("\nReview:\n Full Name: %s\n Email: %s\n" % (name, email))
-        key_properties = urlopen(SPEC).read()
+        key_properties = urlopen(self.config.defaults['key-spec-url']).read()
         return _unicode(key_properties).format(name, email)
+

diff --git a/gkeys-gen/gkeygen/cli.py b/gkeys-gen/gkeygen/cli.py
index e05ea1e..818dbbd 100644
--- a/gkeys-gen/gkeygen/cli.py
+++ b/gkeys-gen/gkeygen/cli.py
@@ -4,14 +4,17 @@
 from __future__ import print_function
 
 
-import sys
 import argparse
+import os
+import sys
 
 from gkeys.config import GKeysConfig
 from gkeys.log import log_levels, set_logger
-from gkeygen.actions import Actions, Available_Actions
+from gkeys.base import CliBase
+from gkeygen.actions import Actions, Available_Actions, Action_Options, 
Action_Map
 
-class Main(object):
+
+class Main(CliBase):
     '''Main command line interface class'''
 
 
@@ -22,10 +25,19 @@ class Main(object):
         @param config: optional GKeysConfig instance, For API use
         @param print_results: optional boolean, for API use
         """
+        CliBase.__init__(self)
         self.root = root or "/"
         self.config = config or GKeysConfig(root=root)
-        self.print_results = print_results
-        self.args = None
+        self.config.options['print_results'] = print_results
+        self.cli_config = {
+            'Actions': Actions,
+            'Available_Actions': Available_Actions,
+            'Action_Options': Action_Options,
+            'Action_Map': Action_Map,
+            'prog': 'gkeys-gen',
+            'description': 'Gentoo Keys GPG key generator program',
+            'epilog': '''CAUTION: adding UNTRUSTED keys can be HAZARDOUS to 
your system!'''
+        }
 
 
     def __call__(self, args=None):
@@ -35,82 +47,14 @@ class Main(object):
                      Defaults to sys.argv[1:]
         """
         if args:
-            self.run(self.parse_args(args))
+            ok = self.setup(args, configs)
+            if ok:
+                return self.run(self.parse_args(args))
         else:
-            self.run(self.parse_args(sys.argv[1:]))
-
-
-    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)
-        actions = Available_Actions
-        parser = argparse.ArgumentParser(
-            prog='gkeys-gen',
-            description='Gentoo Keys GPG key generator program',
-            epilog='''Caution: adding untrusted keys to these keyrings can
-                be hazardous to your system!''')
-        # actions
-        parser.add_argument('action', choices=actions, nargs='?',
-                            default='genkey', help='Generate GPG key based on 
GLEP 63')
-        # 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')
-        parser.add_argument('-H', '--homedir', dest='homedir', default=None,
-                            help='The destination for the generated key')
-        parser.add_argument('-m', '--mail', dest='mail', default=None,
-                            help='The email address to search for')
-        parser.add_argument('-n', '--nick', dest='nick', default=None,
-                            help='The nick or user id (uid) to search for')
-        parser.add_argument('-N', '--name', dest='name', default=None,
-                            help='The name to search for')
-        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-gen', 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
-
-        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, print, logger)
-
-        logger.info("Begin running action: %s" % args.action)
-
-        # run the action
-        func = getattr(self.actions, '%s' % args.action)
-
-        logger.debug('Main: run; Found action: %s' % args.action)
-        results = func(args)
-        return results
+            args = self.parse_args(sys.argv[1:])
+            configs = [os.path.join(self.config['configdir'],'gkeys.conf'),
+            os.path.join(self.config['configdir'],'gkeys-gen.conf')]
+            ok = self.setup(args, configs)
+            if ok:
+                return self.run(args)
+        return False

diff --git a/gkeys/gkeys/base.py b/gkeys/gkeys/base.py
index 052d45f..6e53f87 100644
--- a/gkeys/gkeys/base.py
+++ b/gkeys/gkeys/base.py
@@ -302,7 +302,7 @@ class CliBase(object):
 
 
     @staticmethod
-    def output_results(results, header):
+    def output_results(results, header=None):
         # super simple output for the time being
         if header:
             print(header)

Reply via email to