aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBrian Dolbec <dolsen@gentoo.org>2014-12-30 11:40:31 -0800
committerBrian Dolbec <dolsen@gentoo.org>2014-12-31 18:39:51 -0800
commit8be6c1ff9d7717d82d8d6e088899af6a749dc9ef (patch)
tree522fe795cf869aeb9f9c399a1e91b6e9304750ba /gkeys-gen/gkeygen
parentgkeys/config.py: Move default config file setting to a function (diff)
downloadgentoo-keys-8be6c1ff9d7717d82d8d6e088899af6a749dc9ef.tar.gz
gentoo-keys-8be6c1ff9d7717d82d8d6e088899af6a749dc9ef.tar.bz2
gentoo-keys-8be6c1ff9d7717d82d8d6e088899af6a749dc9ef.zip
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.
Diffstat (limited to 'gkeys-gen/gkeygen')
-rw-r--r--gkeys-gen/gkeygen/actions.py100
-rw-r--r--gkeys-gen/gkeygen/cli.py110
2 files changed, 86 insertions, 124 deletions
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