public inbox for gentoo-commits@lists.gentoo.org
 help / color / mirror / Atom feed
* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2013-06-23  7:13 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2013-06-23  7:13 UTC (permalink / raw
  To: gentoo-commits

commit:     11795d9e10e11000dbf36397f4870fed5635bdc8
Author:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
AuthorDate: Sat Jun 22 19:41:31 2013 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Sun Jun 23 04:30:59 2013 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=11795d9e

Make the logger, namespace able.

---
 gkeyldap/cli.py |  3 +++
 gkeys/cli.py    |  3 +++
 gkeys/log.py    | 12 +++++++++++-
 3 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/gkeyldap/cli.py b/gkeyldap/cli.py
index 21e551f..8d9dc85 100644
--- a/gkeyldap/cli.py
+++ b/gkeyldap/cli.py
@@ -7,7 +7,10 @@ import sys
 import os
 import argparse
 
+from gkeys import log
+log.set_logger('gkeyldap')
 from gkeys.log import logger
+
 from gkeys.config import GKeysConfig, GKEY
 from gkeys.seed import Seeds
 from gkeyldap.search import (LdapSearch, UID, gkey2ldap_map, gkey2SEARCH)

diff --git a/gkeys/cli.py b/gkeys/cli.py
index b9846d9..47c8777 100644
--- a/gkeys/cli.py
+++ b/gkeys/cli.py
@@ -16,7 +16,10 @@ from __future__ import print_function
 import argparse
 import sys
 
+from gkeys import log
+log.set_logger('gkeys')
 from gkeys.log import logger
+
 from gkeys.config import GKeysConfig, GKEY
 from gkeys.seed import Seeds
 

diff --git a/gkeys/log.py b/gkeys/log.py
index c0a33e7..4608eba 100644
--- a/gkeys/log.py
+++ b/gkeys/log.py
@@ -14,5 +14,15 @@ import logging
 
 logging.basicConfig()
 
-logger = logging.getLogger('gentoo-keys')
+NAMESPACE = 'gentoo-keys'
+logger = None
+
+def set_logger(namespace=None):
+    global logger, NAMESPACE
+    if not namespace:
+        namespace = Namespace
+    else:
+        NAMESPACE = namespace
+    logger = logging.getLogger(namespace)
+
 


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2013-06-23  7:13 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2013-06-23  7:13 UTC (permalink / raw
  To: gentoo-commits

commit:     a35a3b9db04a9b4d3759bdce14619f4e2b6edce2
Author:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
AuthorDate: Sat Jun 22 19:29:02 2013 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Sun Jun 23 04:30:49 2013 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=a35a3b9d

Unify logger message identification

---
 gkeyldap/cli.py | 34 ++++++++++++++++++++++------------
 gkeys/cli.py    | 31 +++++++++++++++----------------
 gkeys/config.py |  2 +-
 gkeys/seed.py   | 12 ++++++------
 4 files changed, 44 insertions(+), 35 deletions(-)

diff --git a/gkeyldap/cli.py b/gkeyldap/cli.py
index ccc9159..21e551f 100644
--- a/gkeyldap/cli.py
+++ b/gkeyldap/cli.py
@@ -46,7 +46,7 @@ class Main(object):
         @param args: list
         @returns argparse.Namespace object
         '''
-        logger.debug('args: %s' % args)
+        logger.debug('MAIN: parse_args; args: %s' % args)
         actions = ['ldapsearch', 'updateseeds']
         parser = argparse.ArgumentParser(
             prog='gkeys',
@@ -83,17 +83,18 @@ class Main(object):
         @param args: list or argparse.Namespace object
         '''
         if not args:
-            logger.error("Main.run() invalid args argument passed in")
+            logger.error("Main: run; invalid args argument passed in")
         if isinstance(args, list):
             args = self.parse_args(args)
         if args.config:
-            logger.debug("Found alternate config request: %s" % args.config)
+            logger.debug("Main: run; Found alternate config request: %s"
+                % args.config)
             self.config.defaults['config'] = args.config
         # now make it load the config file
         self.config.read_config()
 
         func = getattr(self, '_action_%s' % args.action)
-        logger.debug('Found action: %s' % args.action)
+        logger.debug('Main: run; Found action: %s' % args.action)
         results = func(args)
         return results
 
@@ -103,7 +104,7 @@ class Main(object):
         if not l.connect():
             print("Aborting Search...Connection failed")
             return False
-        logging.debug("args = %s" % str(args))
+        logger.debug("MAIN: _action_ldapsearch; args = %s" % str(args))
         x, target, search_field = self.get_args(args)
         results = l.search(target, search_field)
         devs = l.result2dict(results, gkey2ldap_map[x])
@@ -121,19 +122,26 @@ class Main(object):
             return False
         results = l.search('*', UID)
         info = l.result2dict(results, 'uid')
-        logger.debug("_action_updateseeds, got results :) converted to info")
+        logger.debug(
+            "MAIN: _action_updateseeds; got results :) converted to info")
         if not self.create_seedfile(info):
             logger.error("Dev seed file update failure: "
                 "Original seed file is intact & untouched.")
         old = self.config['dev-seedfile'] + '.old'
         try:
             if os.path.exists(old):
-                logger.debug("Removing 'old' seed file: %s" % old)
+                logger.debug(
+                    "MAIN: _action_updateseeds; Removing 'old' seed file: %s"
+                    % old)
                 os.unlink(old)
             if os.path.exists(self.config['dev-seedfile']):
-                logger.debug("Renaming current seed file to: %s" % old)
+                logger.debug(
+                    "MAIN: _action_updateseeds; Renaming current seed file to: "
+                    "%s" % old)
                 os.rename(self.config['dev-seedfile'], old)
-            logger.debug("Renaming 'new' seed file to: %s" % self.config['dev-seedfile']))
+            logger.debug(
+                "MAIN: _action_updateseeds; Renaming '.new' seed file to: %s"
+                % self.config['dev-seedfile'])
             os.rename(self.config['dev-seedfile'] + '.new',
                 self.config['dev-seedfile'])
         except IOError:
@@ -150,12 +158,14 @@ class Main(object):
         for dev in sorted(devs):
             if devs[dev]['gentooStatus'][0] not in ['active']:
                 continue
-            #logger.debug("create_seedfile, dev = %s, %s" % (str(dev), str(devs[dev])))
+            #logger.debug("create_seedfile, dev = "
+            #   "%s, %s" % (str(dev), str(devs[dev])))
             new_gkey = GKEY._make(self.build_gkeylist(devs[dev]))
             self.seeds.add(new_gkey)
             count += 1
         print("Total number of seeds created:", count)
-        logger.debug("MAIN: create_seedfile; seeds created...saving file: %s" % filename)
+        logger.debug("MAIN: create_seedfile; seeds created...saving file: %s"
+            % filename)
         return self.seeds.save()
 
 
@@ -193,7 +203,7 @@ class Main(object):
     @staticmethod
     def build_gkeylist(info):
         keyinfo = []
-        #logger.debug("build_gkeylist, info = %s" % str(info))
+        #logger.debug("MAIN: build_gkeylist; info = %s" % str(info))
         for x in GKEY._fields:
             field = gkey2ldap_map[x]
             if not field:

diff --git a/gkeys/cli.py b/gkeys/cli.py
index 133a14f..b9846d9 100644
--- a/gkeys/cli.py
+++ b/gkeys/cli.py
@@ -41,7 +41,6 @@ class Main(object):
 
 
     def __call__(self, args=None):
-        logger.debug("Main:__call__()")
         if args:
             self.run(self.parse_args(args))
         else:
@@ -54,7 +53,7 @@ class Main(object):
         @param args: list
         @returns argparse.Namespace object
         '''
-        logger.debug('args: %s' % args)
+        logger.debug('MAIN: parse_args; args: %s' % args)
         actions = ['listseed', 'addseed', 'removeseed', 'moveseed', 'listkey',
             'addkey', 'removekey', 'movekey']
         parser = argparse.ArgumentParser(
@@ -98,17 +97,17 @@ class Main(object):
         @param args: list or argparse.Namespace object
         '''
         if not args:
-            logger.error("Main.run() invalid args argument passed in")
+            logger.error("Main: run; invalid args argument passed in")
         if isinstance(args, list):
             args = self.parse_args(args)
         if args.config:
-            logger.debug("Found alternate config request: %s" % args.config)
+            logger.debug("Main: run; Found alternate config request: %s" % args.config)
             self.config.defaults['config'] = args.config
         # now make it load the config file
         self.config.read_config()
 
         func = getattr(self, '_action_%s' % args.action)
-        logger.debug('Found action: %s' % args.action)
+        logger.debug('Main: run; Found action: %s' % args.action)
         results = func(args)
         if not results:
             print("No results found.  Check your configuration and that the",
@@ -149,7 +148,7 @@ class Main(object):
         if not filename:
             return None
         filepath = self.config.get_key(filename + "-seedfile")
-        logger.debug("_load_seeds(); seeds filepath to load: "
+        logger.debug("MAIN: _load_seeds; seeds filepath to load: "
             "%s" % filepath)
         seeds = Seeds()
         seeds.load(filepath)
@@ -159,7 +158,7 @@ class Main(object):
     def _action_listseed(self, args):
         '''Action listseed method'''
         kwargs = self.build_gkeydict(args)
-        logger.debug("_action_listseed(); kwargs: %s" % str(kwargs))
+        logger.debug("MAIN: _action_listseed; kwargs: %s" % str(kwargs))
         seeds = self._load_seeds(args.seeds)
         if seeds:
             results = seeds.list(**kwargs)
@@ -171,11 +170,11 @@ class Main(object):
         '''Action addseed method'''
         parts = self.build_gkeylist(args)
         gkey = GKEY._make(parts)
-        logger.debug("_action_addseed(); new gkey: %s" % str(gkey))
+        logger.debug("MAIN: _action_addseed; new gkey: %s" % str(gkey))
         seeds = self._load_seeds(args.seeds)
         gkeys = self._action_listseed(args)
         if len(gkeys) == 0:
-            logger.debug("_action_addkey(); now adding gkey: %s" % str(gkey))
+            logger.debug("MAIN: _action_addkey; now adding gkey: %s" % str(gkey))
             success = seeds.add(gkey)
             if success:
                 success = seeds.save()
@@ -191,11 +190,11 @@ class Main(object):
         '''Action removeseed method'''
         parts = self.build_gkeylist(args)
         searchkey = GKEY._make(parts)
-        logger.debug("_action_removeseed(); gkey: %s" % str(searchkey))
+        logger.debug("MAIN: _action_removeseed; gkey: %s" % str(searchkey))
         seeds = self._load_seeds(args.seeds)
         gkeys = self._action_listseed(args)
         if len(gkeys) == 1:
-            logger.debug("_action_removeseed(); now deleting gkey: %s" % str(gkeys[0]))
+            logger.debug("MAIN: _action_removeseed; now deleting gkey: %s" % str(gkeys[0]))
             success = seeds.delete(gkeys[0])
             if success:
                 success = seeds.save()
@@ -213,7 +212,7 @@ class Main(object):
         '''Action moveseed method'''
         parts = self.build_gkeylist(args)
         searchkey = GKEY._make(parts)
-        logger.debug("_action_moveseed(); gkey: %s" % str(searchkey))
+        logger.debug("MAIN: _action_moveseed; gkey: %s" % str(searchkey))
         seeds = self._load_seeds(args.seeds)
         kwargs = self.build_gkeydict(args)
         sourcekeys = seeds.list(**kwargs)
@@ -221,15 +220,15 @@ class Main(object):
         destkeys = dest.list(**kwargs)
         messages = []
         if len(sourcekeys) == 1 and destkeys == []:
-            logger.debug("_action_moveseed(); now adding destination gkey: %s"
+            logger.debug("MAIN: _action_moveseed; now adding destination gkey: %s"
                 % str(sourcekeys[0]))
             success = dest.add(sourcekeys[0])
-            logger.debug("_action_moveseed(); success: %s" %str(success))
-            logger.debug("_action_moveseed(); now deleting sourcekey: %s" % str(sourcekeys[0]))
+            logger.debug("MAIN: _action_moveseed; success: %s" %str(success))
+            logger.debug("MAIN: _action_moveseed; now deleting sourcekey: %s" % str(sourcekeys[0]))
             success = seeds.delete(sourcekeys[0])
             if success:
                 success = dest.save()
-                logger.debug("_action_moveseed(); destination saved... %s" %str(success))
+                logger.debug("MAIN: _action_moveseed; destination saved... %s" %str(success))
                 success = seeds.save()
             messages.extend(["Successfully Moved %s seed: %s"
                 % (args.seeds, str(success)), sourcekeys[0]])

diff --git a/gkeys/config.py b/gkeys/config.py
index 3da1c21..f775d23 100644
--- a/gkeys/config.py
+++ b/gkeys/config.py
@@ -86,7 +86,7 @@ class GKeysConfig(GPGConfig):
             return self.options[key]
         elif key in self.defaults:
             return self.defaults[key]
-        logger.error("GKeysConfig: _get_(); didn't find :", key)
+        logger.error("GKeysConfig: _get_; didn't find :", key)
         return None
 
 

diff --git a/gkeys/seed.py b/gkeys/seed.py
index 4b4710a..fc71551 100644
--- a/gkeys/seed.py
+++ b/gkeys/seed.py
@@ -39,7 +39,7 @@ class Seeds(object):
         if filename:
             self.filename = filename
         if not self.filename:
-            logger.debug("Seed.load() Not a valid filename: '%s'" % str(self.filename))
+            logger.debug("Seed: load; Not a valid filename: '%s'" % str(self.filename))
             return False
         logger.debug("Seeds: Begin loading seed file %s" % self.filename)
         seedlines = None
@@ -57,7 +57,7 @@ class Seeds(object):
                 self.seeds.append(GKEY._make(parts))
             except Exception as err:
                 self._error(err)
-        logger.debug("Completed loading seed file %s" % self.filename)
+        logger.debug("Seed: load; Completed loading seed file %s" % self.filename)
         return True
 
 
@@ -66,9 +66,9 @@ class Seeds(object):
         if filename:
             self.filename = filename
         if not self.filename:
-            logger.debug("Seed.load() Not a valid filename: '%s'" % str(self.filename))
+            logger.debug("Seed: save; Not a valid filename: '%s'" % str(self.filename))
             return False
-        logger.debug("Begin saving seed file %s" % self.filename)
+        logger.debug("Seed: save; Begin saving seed file %s" % self.filename)
         try:
             with open(self.filename, 'w') as seedfile:
                 seedlines = [x.value_string(self.separator) for x in self.seeds]
@@ -141,8 +141,8 @@ class Seeds(object):
 
     def _error(self, err):
         '''Class error logging function'''
-        logger.error("Error processing seed file %s" % self.filename)
-        logger.error("Error was: %s" % str(err))
+        logger.error("Seed: Error processing seed file %s" % self.filename)
+        logger.error("Seed: Error was: %s" % str(err))
 
 
     @staticmethod


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2013-06-23  7:13 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2013-06-23  7:13 UTC (permalink / raw
  To: gentoo-commits

commit:     7cce980577bdb9f88337f52f1e488796964361b4
Author:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
AuthorDate: Sat Jun 22 20:20:43 2013 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Sun Jun 23 04:30:59 2013 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=7cce9805

Add -D, --debug level to cli

Comment out a parse_argrs logger line, move the debug reassignment to after it's setting.

---
 gkeyldap/cli.py | 11 ++++++++---
 gkeys/cli.py    | 11 ++++++++---
 2 files changed, 16 insertions(+), 6 deletions(-)

diff --git a/gkeyldap/cli.py b/gkeyldap/cli.py
index ba0218b..b506f64 100644
--- a/gkeyldap/cli.py
+++ b/gkeyldap/cli.py
@@ -16,8 +16,8 @@ from gkeys.seed import Seeds
 from gkeyldap.search import (LdapSearch, UID, gkey2ldap_map, gkey2SEARCH)
 
 
-# set debug level to max
-logger.setLevel(1)
+# set debug level to min
+logger.setLevel(0)
 
 
 class Main(object):
@@ -49,7 +49,7 @@ class Main(object):
         @param args: list
         @returns argparse.Namespace object
         '''
-        logger.debug('MAIN: parse_args; args: %s' % args)
+        #logger.debug('MAIN: parse_args; args: %s' % args)
         actions = ['ldapsearch', 'updateseeds']
         parser = argparse.ArgumentParser(
             prog='gkeys',
@@ -76,6 +76,8 @@ class Main(object):
             help='The gpg fingerprint to search for')
         parser.add_argument('-S', '--status', default=False,
             help='The seedfile path to use')
+        parser.add_argument('-D', '--debug', default=0,
+            help='The logging level to use and report with')
 
         return parser.parse_args(args)
 
@@ -89,6 +91,9 @@ class Main(object):
             logger.error("Main: run; invalid args argument passed in")
         if isinstance(args, list):
             args = self.parse_args(args)
+        if args.debug:
+            logger.setLevel(int(args.debug))
+            logger.debug("MAIN: run; Found alternate debug setting: %s" % str(args.debug))
         if args.config:
             logger.debug("Main: run; Found alternate config request: %s"
                 % args.config)

diff --git a/gkeys/cli.py b/gkeys/cli.py
index 47c8777..743b622 100644
--- a/gkeys/cli.py
+++ b/gkeys/cli.py
@@ -24,8 +24,8 @@ from gkeys.config import GKeysConfig, GKEY
 from gkeys.seed import Seeds
 
 
-# set debug level to max
-logger.setLevel(1)
+# set debug level to min
+logger.setLevel(0)
 
 
 class Main(object):
@@ -56,7 +56,7 @@ class Main(object):
         @param args: list
         @returns argparse.Namespace object
         '''
-        logger.debug('MAIN: parse_args; args: %s' % args)
+        #logger.debug('MAIN: parse_args; args: %s' % args)
         actions = ['listseed', 'addseed', 'removeseed', 'moveseed', 'listkey',
             'addkey', 'removekey', 'movekey']
         parser = argparse.ArgumentParser(
@@ -90,6 +90,8 @@ class Main(object):
             help='The seeds file to use or update')
         parser.add_argument('-S', '--seedfile', dest='seedfile', default=None,
             help='The seedfile path to use')
+        parser.add_argument('-D', '--debug', default=0,
+            help='The logging level to use and report with')
 
         return parser.parse_args(args)
 
@@ -103,6 +105,9 @@ class Main(object):
             logger.error("Main: run; invalid args argument passed in")
         if isinstance(args, list):
             args = self.parse_args(args)
+        if args.debug:
+            logger.setLevel(int(args.debug))
+            logger.debug("MAIN: run; Found alternate debug setting: %s" % str(args.debug))
         if args.config:
             logger.debug("Main: run; Found alternate config request: %s" % args.config)
             self.config.defaults['config'] = args.config


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2013-06-23  7:13 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2013-06-23  7:13 UTC (permalink / raw
  To: gentoo-commits

commit:     6f9daea91be0a41bf42ce1da065fa7e2d5782235
Author:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
AuthorDate: Sun Jun 23 01:26:52 2013 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Sun Jun 23 04:36:47 2013 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=6f9daea9

Strip line feeds from seeds when loading

---
 gkeyldap/cli.py | 14 ++++++++++----
 gkeys/seed.py   |  1 +
 2 files changed, 11 insertions(+), 4 deletions(-)

diff --git a/gkeyldap/cli.py b/gkeyldap/cli.py
index cd813d4..bf4e00e 100644
--- a/gkeyldap/cli.py
+++ b/gkeyldap/cli.py
@@ -223,11 +223,18 @@ class Main(object):
             if not field:
                 continue
             try:
-                values = info[field]
+                # strip errant line feeds
+                values = [y.strip('\n') for y in info[field]]
                 if values and values in ['uid', 'cn' ]:
                     value = values[0]
+                # separate out short/long key id's
+                elif values and x in ['keyid', 'longkeyid']:
+                    value = get_key_ids(x, values)
                 else:
                     value = values
+                if 'undefined' in values:
+                    logger.error('%s = "undefined" for %s, %s'
+                        %(field, info['uid'][0], info['cn'][0]))
                 if value:
                     keyinfo[x] = value
             except KeyError:
@@ -245,11 +252,10 @@ class Main(object):
                 keyinfo.append(None)
                 continue
             try:
-                values = info[field]
                 # strip errant line feeds
-                values = [x.strip('\n') for x in values]
+                values = [y.strip('\n') for y in info[field]]
                 if values and field in ['uid', 'cn' ]:
-                    value = values[0].strip('\n')
+                    value = values[0]
                 # separate out short/long key id's
                 elif values and x in ['keyid', 'longkeyid']:
                     value = get_key_ids(x, values)

diff --git a/gkeys/seed.py b/gkeys/seed.py
index 544ab02..5cfa5fe 100644
--- a/gkeys/seed.py
+++ b/gkeys/seed.py
@@ -54,6 +54,7 @@ class Seeds(object):
 
         for seed in seedlines:
             try:
+                seed = seed.strip('\n')
                 parts = self._split_seed(seed, self.separator)
                 self.seeds.append(GKEY._make(parts))
             except Exception as err:


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2013-11-10  1:01 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2013-11-10  1:01 UTC (permalink / raw
  To: gentoo-commits

commit:     dbd6861ec6e35b1ce8862303ca16021e86276a7d
Author:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
AuthorDate: Wed Jul 17 01:52:30 2013 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Wed Jul 17 01:52:30 2013 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=dbd6861e

Change to make keys install to individual directories.

Git has no options to set the git keydir or keyring.
Must set GNUPGHOME env variable to the desired keydir before 
calling git log --show-signature  to verify commits.

---
 gkeyldap/search.py |  6 +++---
 gkeys/actions.py   | 14 ++++++-------
 gkeys/cli.py       | 10 ++++-----
 gkeys/config.py    |  4 ++--
 gkeys/lib.py       | 60 +++++++++++++++++++++++++++++++-----------------------
 5 files changed, 51 insertions(+), 43 deletions(-)

diff --git a/gkeyldap/search.py b/gkeyldap/search.py
index f7d2045..92471df 100644
--- a/gkeyldap/search.py
+++ b/gkeyldap/search.py
@@ -21,9 +21,9 @@ gkey2ldap_map = {
     'name': 'cn',
     'keyid': 'gpgkey',
     'longkeyid': 'gpgkey',
-    # map the uid to keyring, since we want
-    # dev keyrings to be separate from each other
-    'keyring': 'uid',
+    # map the uid to keydir, since we want
+    # dev keydir to be separate from each other
+    'keydir': 'uid',
     'fingerprint': 'gpgfingerprint'
 }
 # Sanity check they are in sync

diff --git a/gkeys/actions.py b/gkeys/actions.py
index 9873362..7efcd44 100644
--- a/gkeys/actions.py
+++ b/gkeys/actions.py
@@ -190,25 +190,25 @@ class Actions(object):
             #failed = []
             print(" GPG output:")
             for key in keyresults:
-                if not key.keyring and not args.nick == '*':
-                    self.logger.debug("ACTIONS: listkey; NO keyring... Ignoring")
+                if not key.keydir and not args.nick == '*':
+                    self.logger.debug("ACTIONS: listkey; NO keydir... Ignoring")
                     return {"Failed: No keyid's found for %s" % key.name : ''}
-                self.logger.debug("ACTIONS: listkey; listing keyring:"
-                    + str(key.keyring))
-                results[key.name] = self.gpg.list_keys(key.keyring)
+                self.logger.debug("ACTIONS: listkey; listing keydir:"
+                    + str(key.keydir))
+                results[key.name] = self.gpg.list_keys(key.keydir)
                 if self.config.options['print_results']:
                     print(results[key.name].output)
                     self.logger.debug("data output:\n" +
                         str(results[key.name].output))
                     #for result in results[key.name].status.data:
-                        #print("key desired:", key.name, ", keyring listed:",
+                        #print("key desired:", key.name, ", keydir listed:",
                             #result)
                         #self.logger.debug("data record: " + str(result))
                 else:
                     return results
             return {'done': True}
         else:
-            return {"No keyrings to list": False}
+            return {"No keydirs to list": False}
 
 
     def addkey(self, args):

diff --git a/gkeys/cli.py b/gkeys/cli.py
index d34ed4d..46344f9 100644
--- a/gkeys/cli.py
+++ b/gkeys/cli.py
@@ -67,12 +67,12 @@ class Main(object):
                 be hazardous to your system!''')
         # actions
         parser.add_argument('action', choices=actions, nargs='?',
-            default='listseeds', help='Add to seed file or keyring')
+            default='listseeds', help='List the seeds in the file')
         # options
         parser.add_argument('-c', '--config', dest='config', default=None,
             help='The path to an alternate config file')
         parser.add_argument('-d', '--dest', dest='destination', default=None,
-            help='The destination seed file or keyring for move, copy operations')
+            help='The destination seed file or keydir for move, copy operations')
         parser.add_argument('-f', '--fingerprint', dest='fingerprint', default=None,
             help='The fingerprint of the the key')
         parser.add_argument('-N', '--name', dest='name', default=None,
@@ -83,9 +83,9 @@ class Main(object):
             help='The keyid of the the key')
         parser.add_argument('-l', '--longkeyid', dest='longkeyid', default=None,
             help='The longkeyid of the the key')
-        parser.add_argument('-r', '--keyring',
-            choices=['release', 'dev', 'overlays'], dest='keyring', default=None,
-            help='The keyring to use or update')
+        parser.add_argument('-r', '--keydir',
+            choices=['release', 'dev', 'overlays'], dest='keydir', default=None,
+            help='The keydir to use or update')
         parser.add_argument('-s', '--seeds',
             choices=['release', 'dev'], dest='seeds', default=None,
             help='The seeds file to use or update')

diff --git a/gkeys/config.py b/gkeys/config.py
index 043f84f..96b4aee 100644
--- a/gkeys/config.py
+++ b/gkeys/config.py
@@ -97,11 +97,11 @@ class GKeysConfig(GPGConfig):
 
 
 class GKEY(namedtuple('GKEY', ['nick', 'name', 'keyid', 'longkeyid',
-    'keyring', 'fingerprint'])):
+    'keydir', 'fingerprint'])):
     '''Class to hold the relavent info about a key'''
 
     field_types = {'nick': str, 'name': str, 'keyid': list,
-        'longkeyid': list, 'keyring': str, 'fingerprint': list}
+        'longkeyid': list, 'keydir': str, 'fingerprint': list}
     field_separator = "|"
     list_separator = ":"
     __slots__ = ()

diff --git a/gkeys/lib.py b/gkeys/lib.py
index 0420f7c..a97b7e7 100644
--- a/gkeys/lib.py
+++ b/gkeys/lib.py
@@ -30,12 +30,13 @@ class GkeysGPG(GPG):
         '''class init function
 
         @param config: GKeysConfig config instance to use
-        @param keyring: string, the path to the keydir to be used
+        @param keydir: string, the path to the keydir to be used
                         for all operations.
         '''
         GPG.__init__(self, config)
         self.config = config
-        self.keydir = keydir
+        self.basedir = keydir
+        self.keydir = None
         self.task = None
         self.task_value = None
 
@@ -60,13 +61,20 @@ class GkeysGPG(GPG):
             self.task_value = None
 
 
+    def set_keydir(self, keydir):
+        logger.debug("basedir: %s, keydir: %s" % (self.basedir, keydir))
+        self.task = task
+        self.keydir = pjoin(self.basedir, keydir)
+        return
+
+
     def add_key(self, gkey):
-        '''Add the specified key to the specified keyring
+        '''Add the specified key to the specified keydir
 
         @param gkey: GKEY namedtuple with
-            (name, keyid/longkeyid, keyring, fingerprint,)
+            (name, keyid/longkeyid, keydir, fingerprint,)
         '''
-        self.set_keypath(gkey.keyring, self.config['tasks']['recv-keys'])
+        self.set_keydir(gkey.keydir)
 
         # prefer the longkeyid if available
         #logger.debug("LIB: add_key; keyids %s, %s"
@@ -105,60 +113,60 @@ class GkeysGPG(GPG):
         return results
 
 
-    def del_key(self, gkey, keyring):
-        '''Delete the specified key to the specified keyring
+    def del_key(self, gkey, keydir):
+        '''Delete the specified key in the specified keydir
 
         @param gkey: GKEY namedtuple with (name, keyid/longkeyid, fingerprint)
         '''
         return []
 
 
-    def del_keyring(self, keyring):
-        '''Delete the specified key to the specified keyring
+    def del_keydir(self, keydir):
+        '''Delete the specified keydir
         '''
         return []
 
 
-    def update_key(self, gkey, keyring):
-        '''Update the specified key in the specified keyring
+    def update_key(self, gkey, keydir):
+        '''Update the specified key in the specified keydir
 
         @param key: tuple of (name, keyid, fingerprint)
-        @param keyring: the keyring to add the key to
+        @param keydir: the keydir to add the key to
         '''
         return []
 
 
-    def list_keys(self, keyring):
-        '''List all keys in the specified keyring or
-        all key in all keyrings if keyring=None
+    def list_keys(self, keydir):
+        '''List all keys in the specified keydir or
+        all keys in all keydir if keydir=None
 
-        @param keyring: the keyring to add the key to
+        @param keydir: the keydir to list the keys for
         '''
-        if not keyring:
-            logger.debug("LIB: list_keys(), invalid keyring parameter: %s"
-                % str(keyring))
+        if not keydir:
+            logger.debug("LIB: list_keys(), invalid keydir parameter: %s"
+                % str(keydir))
             return []
         if '--with-colons' in self.config['tasks']['list-keys']:
             self.config['tasks']['list-keys'].remove('--with-colons')
 
-        self.set_keypath(keyring, self.config['tasks']['list-keys'])
+        self.set_keydir(keydir)
         logger.debug("** Calling runGPG with Running 'gpg %s --list-keys %s'"
-            % (' '.join(self.config['tasks']['list-keys']), keyring)
+            % (' '.join(self.config['tasks']['list-keys']), keydir)
             )
-        result = self.runGPG(task='list-keys', inputfile=keyring)
+        result = self.runGPG(task='list-keys')
         logger.info('GPG return code: ' + str(result.returncode))
-        self.reset_task()
+        #self.reset_task()
         return result
 
 
-    def list_keyrings(self):
-        '''List all available keyrings
+    def list_keydirs(self):
+        '''List all available keydirs
         '''
         return []
 
 
     def verify_key(self, gkey):
-        '''verify the specified key from the specified keyring
+        '''verify the specified key from the specified keydir
 
         @param gkey: GKEY namedtuple with (name, keyid/longkeyid, fingerprint)
         '''


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2013-11-15  9:16 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2013-11-15  9:16 UTC (permalink / raw
  To: gentoo-commits

commit:     efd7245edae94842b6c480ca26424185e60f0bdd
Author:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
AuthorDate: Mon Nov 11 16:43:17 2013 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Fri Nov 15 09:13:32 2013 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=efd7245e

Begin migration to fingerprints only in ldap info

---
 gkeyldap/actions.py | 52 +++++++++++++++++++++++++++++++++++-----------------
 gkeys/config.py     | 10 ++++++++++
 2 files changed, 45 insertions(+), 17 deletions(-)

diff --git a/gkeyldap/actions.py b/gkeyldap/actions.py
index 07130eb..be02dfd 100644
--- a/gkeyldap/actions.py
+++ b/gkeyldap/actions.py
@@ -13,7 +13,7 @@
 import os
 import re
 
-from gkeys.config import GKEY
+from gkeys.config import GKEY, KEYID, LONGKEYID, FINGERPRINT
 from gkeys.seed import Seeds
 from gkeyldap.search import (LdapSearch, UID, gkey2ldap_map, gkey2SEARCH)
 
@@ -211,26 +211,43 @@ class Actions(object):
                     is_good = False
                 keyinfo.append(value)
             except KeyError:
-                self.logger.error('ERROR in ldap info for: %s, %s'
+                self.logger.debug('Ldap info for: %s, %s'
                     %(info['uid'][0],info['cn'][0]))
-                self.logger.error('  MISSING or EMPTY ldap field ' +
+                self.logger.debug('  MISSING or EMPTY ldap field ' +
                     '[%s] GPGKey field [%s]' %(field, x))
                 if x in ['keyid', 'longkeyid']:
                     keyid_missing = True
+                else:
+                    is_good = False
                 keyinfo.append(None)
-                is_good = False
-        if not keyid_found and not keyid_missing:
+        if not keyid_found and keyid_missing:
+            fingerprint = None
             try:
-                gpgkey = info[gkey2ldap_map['longkeyid']]
+                fingerprint = info[gkey2ldap_map['fingerprint']]
+                self.logger.debug('  Generate gpgkey, Found ldap fingerprint field')
             except KeyError:
-                gpgkey = 'Missing from ldap info'
-            self.logger.error('ERROR in ldap info for: %s, %s'
-                %(info['uid'][0],info['cn'][0]))
-            self.logger.error('  A valid keyid or longkeyid was not found '
-                "%s : gpgkey = %s" %(info['cn'][0], gpgkey))
-            is_good = False
-        else:
-            if keyinfo[5]: # fingerprints exist check
+                gpgkey = 'Missing fingerprint from ldap info'
+                self.logger.debug('  Generate gpgkey, ldap fingerprint KeyError')
+            if fingerprint:
+                values = [y.strip('\n') for y in fingerprint]
+                value = [v.replace(' ', '') for v in values]
+                # assign it to gpgkey to prevent a possible
+                # "gpgkey" undefined error
+                gpgkey = ['0x' + x[-KEY_LEN['longkeyid']:] for x in value]
+                keyinfo[LONGKEYID] = gpgkey
+                self.logger.debug('  Generate gpgkey, NEW keyinfo[LONGKEYID] = %s'
+                    % str(keyinfo[LONGKEYID]))
+            else:
+                gpgkey = 'Missing or Bad fingerprint from ldap info'
+                is_good = False
+            if not keyinfo[LONGKEYID]:
+                self.logger.error('ERROR in ldap info for: %s, %s'
+                    %(info['uid'][0],info['cn'][0]))
+                self.logger.error('  A valid keyid, longkeyid or fingerprint '
+                    'was not found for %s : gpgkey = %s' %(info['cn'][0], gpgkey))
+                is_good = False
+        if is_good:
+            if keyinfo[FINGERPRINT]: # fingerprints exist check
                 is_ok = self._check_fingerprint_integrity(info, keyinfo)
                 is_match = self._check_id_fingerprint_match(info, keyinfo)
                 if not is_ok or not is_match:
@@ -243,13 +260,14 @@ class Actions(object):
     def _check_id_fingerprint_match(self, info, keyinfo):
         # assume it's good until found an error is found
         is_good = True
-        for x in [2, 3]:
+        for x in [KEYID, LONGKEYID]:
             # skip blank id field
             if not keyinfo[x]:
                 continue
             for y in keyinfo[x]:
                 index = len(y.lstrip('0x'))
-                if y.lstrip('0x').lower() not in [x[-index:].lower() for x in keyinfo[5]]:
+                if y.lstrip('0x').upper() not in \
+                        [x[-index:].upper() for x in keyinfo[FINGERPRINT]]:
                     self.logger.error('ERROR in ldap info for: %s, %s'
                         %(info['uid'][0],info['cn'][0]))
                     self.logger.error('  ' + str(keyinfo))
@@ -262,7 +280,7 @@ class Actions(object):
     def _check_fingerprint_integrity(self, info, keyinfo):
         # assume it's good until found an error is found
         is_good = True
-        for x in keyinfo[5]:
+        for x in keyinfo[FINGERPRINT]:
             # check fingerprint integrity
             if len(x) != 40:
                 self.logger.error('ERROR in ldap info for: %s, %s'

diff --git a/gkeys/config.py b/gkeys/config.py
index 5b220a8..20a00b7 100644
--- a/gkeys/config.py
+++ b/gkeys/config.py
@@ -104,6 +104,16 @@ class GKeysConfig(GPGConfig):
             return super(GKeysConfig, self)._get_(key, subkey)
 
 
+# some constants used in gkeyldap/actions.py
+# they map the index values of the GKEY input data fields
+NICK = 0
+NAME = 1
+KEYID = 2
+LONGKEYID = 3
+KEYDIR = 4
+FINGERPRINT = 5
+
+
 class GKEY(namedtuple('GKEY', ['nick', 'name', 'keyid', 'longkeyid',
     'keydir', 'fingerprint'])):
     '''Class to hold the relavent info about a key'''


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2013-11-15  9:16 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2013-11-15  9:16 UTC (permalink / raw
  To: gentoo-commits

commit:     a998ae25de96cd4e11be48f639dead56886d9a8f
Author:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
AuthorDate: Sun Nov 10 07:45:16 2013 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Fri Nov 15 09:12:36 2013 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=a998ae25

preliminary coding to make gkeyldap py3 capable

---
 gkeyldap/search.py | 12 +++++++++++-
 gkeys/config.py    |  9 ++++++++-
 2 files changed, 19 insertions(+), 2 deletions(-)

diff --git a/gkeyldap/search.py b/gkeyldap/search.py
index 92471df..2cbc4b9 100644
--- a/gkeyldap/search.py
+++ b/gkeyldap/search.py
@@ -2,7 +2,17 @@
 #-*- coding:utf-8 -*-
 
 
-import ldap
+try:
+    import ldap
+except ImportError:
+    import sys
+    # py3.2
+    if sys.hexversion >= 0x30200f0:
+        print('To run "ldap-seeds" in python 3, it requires a python3 '
+            'compatible version of dev-python/python-ldap be installed')
+        print('Currently only dev-python/python-ldap-9999 has that capability')
+        raise
+
 
 from gkeys import log
 from gkeys.config import GKEY

diff --git a/gkeys/config.py b/gkeys/config.py
index fe78dec..5b220a8 100644
--- a/gkeys/config.py
+++ b/gkeys/config.py
@@ -11,7 +11,14 @@
 """
 
 import os
-import ConfigParser
+import sys
+
+# py3.2
+if sys.hexversion >= 0x30200f0:
+    import configparser as ConfigParser
+else:
+    import ConfigParser
+
 from collections import namedtuple
 
 


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2013-11-17  7:39 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2013-11-17  7:39 UTC (permalink / raw
  To: gentoo-commits

commit:     c308f253c89740eca7e792b4cd78dc9cb43f7151
Author:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
AuthorDate: Sat Nov 16 19:51:29 2013 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Sat Nov 16 19:51:29 2013 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=c308f253

Move KEY_LEN to config.

---
 gkeyldap/actions.py | 13 +++----------
 gkeys/config.py     |  6 ++++++
 2 files changed, 9 insertions(+), 10 deletions(-)

diff --git a/gkeyldap/actions.py b/gkeyldap/actions.py
index 13e67f7..2c65a90 100644
--- a/gkeyldap/actions.py
+++ b/gkeyldap/actions.py
@@ -13,18 +13,11 @@
 import os
 import re
 
-from gkeys.config import GKEY, KEYID, LONGKEYID, FINGERPRINT
+from gkeys.config import GKEY, KEYID, LONGKEYID, FINGERPRINT, KEY_LEN
 from gkeys.seed import Seeds
 from gkeyldap.search import (LdapSearch, UID, gkey2ldap_map, gkey2SEARCH)
 
 
-# set some defaults
-KEY_LEN = {
-    'keyid': 8,
-    'longkeyid': 16,
-}
-
-
 Avialable_Actions = ['ldapsearch', 'updateseeds']
 
 
@@ -187,9 +180,9 @@ class Actions(object):
         keyinfo = []
         keyid_found = False
         keyid_missing = False
-        # assume it's good until found an error is found
+        # assume it's good until an error is found
         is_good = True
-        #self.logger.debug("MAIN: build_gkeylist; info = %s" % str(info))
+        #self.logger.debug("Actions: build_gkeylist; info = %s" % str(info))
         for x in GKEY._fields:
             field = gkey2ldap_map[x]
             if not field:

diff --git a/gkeys/config.py b/gkeys/config.py
index 5fe3871..6785c7b 100644
--- a/gkeys/config.py
+++ b/gkeys/config.py
@@ -120,6 +120,12 @@ LONGKEYID = 3
 KEYDIR = 4
 FINGERPRINT = 5
 
+# set some defaults
+KEY_LEN = {
+    'keyid': 8,
+    'longkeyid': 16,
+}
+
 
 class GKEY(namedtuple('GKEY', ['nick', 'name', 'keyid', 'longkeyid',
     'keydir', 'fingerprint'])):


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2014-03-01 17:49 Pavlos Ratis
  0 siblings, 0 replies; 14+ messages in thread
From: Pavlos Ratis @ 2014-03-01 17:49 UTC (permalink / raw
  To: gentoo-commits

commit:     92fc2f1603d88bbda26fe228137e02854c6c25fe
Author:     Pavlos Ratis <dastergon <AT> gentoo <DOT> org>
AuthorDate: Sat Mar  1 13:12:53 2014 +0000
Commit:     Pavlos Ratis <dastergon <AT> gentoo <DOT> org>
CommitDate: Sat Mar  1 13:12:53 2014 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=92fc2f16

fix typo

---
 gkeyldap/actions.py | 2 +-
 gkeyldap/cli.py     | 4 ++--
 gkeys/actions.py    | 2 +-
 gkeys/cli.py        | 4 ++--
 4 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/gkeyldap/actions.py b/gkeyldap/actions.py
index 2c65a90..5b33600 100644
--- a/gkeyldap/actions.py
+++ b/gkeyldap/actions.py
@@ -18,7 +18,7 @@ from gkeys.seed import Seeds
 from gkeyldap.search import (LdapSearch, UID, gkey2ldap_map, gkey2SEARCH)
 
 
-Avialable_Actions = ['ldapsearch', 'updateseeds']
+Available_Actions = ['ldapsearch', 'updateseeds']
 
 
 def get_key_ids(key, info):

diff --git a/gkeyldap/cli.py b/gkeyldap/cli.py
index 097cfc2..1eba841 100644
--- a/gkeyldap/cli.py
+++ b/gkeyldap/cli.py
@@ -15,7 +15,7 @@ from gkeys import seed
 
 from gkeys.config import GKeysConfig
 from gkeyldap import search
-from gkeyldap.actions import Actions, Avialable_Actions
+from gkeyldap.actions import Actions, Available_Actions
 logger = log.logger
 
 
@@ -49,7 +49,7 @@ class Main(object):
         @returns argparse.Namespace object
         '''
         #logger.debug('MAIN: parse_args; args: %s' % args)
-        actions = Avialable_Actions
+        actions = Available_Actions
         parser = argparse.ArgumentParser(
             prog='gkeys',
             description='Gentoo-keys manager program',

diff --git a/gkeys/actions.py b/gkeys/actions.py
index 2e2b1b7..25013b3 100644
--- a/gkeys/actions.py
+++ b/gkeys/actions.py
@@ -20,7 +20,7 @@ from gkeys.lib import GkeysGPG
 from gkeys.seed import Seeds
 
 
-Avialable_Actions = ['listseed', 'addseed', 'removeseed', 'moveseed',
+Available_Actions = ['listseed', 'addseed', 'removeseed', 'moveseed',
             'listseedfiles', 'listkey', 'addkey', 'removekey', 'movekey',
             'installed']
 

diff --git a/gkeys/cli.py b/gkeys/cli.py
index 46344f9..f688756 100644
--- a/gkeys/cli.py
+++ b/gkeys/cli.py
@@ -24,7 +24,7 @@ from gkeys import seed
 from gkeys import lib
 
 from gkeys.config import GKeysConfig
-from gkeys.actions import Actions, Avialable_Actions
+from gkeys.actions import Actions, Available_Actions
 
 
 
@@ -59,7 +59,7 @@ class Main(object):
         @returns argparse.Namespace object
         '''
         #logger.debug('MAIN: parse_args; args: %s' % args)
-        actions = Avialable_Actions
+        actions = Available_Actions
         parser = argparse.ArgumentParser(
             prog='gkeys',
             description='Gentoo-keys manager program',


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2014-05-27 20:56 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2014-05-27 20:56 UTC (permalink / raw
  To: gentoo-commits

commit:     030a76d75fe5cdad175355c90680361cd5b59723
Author:     Pavlos Ratis <dastergon <AT> gentoo <DOT> org>
AuthorDate: Mon May 19 23:38:01 2014 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Tue May 20 12:27:15 2014 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=030a76d7

misc improvements

* Rename some variables to a more easy-to-understand name
* Improve some strings and fix typos

---
 gkeyldap/actions.py  | 105 +++++++++++++++++++++++++--------------------------
 gkeyldap/search.py   |   9 ++---
 gkeys/actions.py     |  10 ++---
 gkeys/config.py      |   2 +-
 gkeys/seed.py        |   1 -
 gkeys/seedhandler.py |  30 +++++++--------
 6 files changed, 77 insertions(+), 80 deletions(-)

diff --git a/gkeyldap/actions.py b/gkeyldap/actions.py
index 27b35bf..55c3e13 100644
--- a/gkeyldap/actions.py
+++ b/gkeyldap/actions.py
@@ -13,7 +13,7 @@
 import os
 import re
 
-from gkeys.config import GKEY, KEYID, LONGKEYID, FINGERPRINT, KEY_LEN
+from gkeys.config import GKEY, KEYID, LONGKEYID, FINGERPRINT, KEYLEN_MAP
 from gkeys.seed import Seeds
 from gkeyldap.search import (LdapSearch, UID, gkey2ldap_map, gkey2SEARCH)
 
@@ -21,22 +21,21 @@ from gkeyldap.search import (LdapSearch, UID, gkey2ldap_map, gkey2SEARCH)
 Available_Actions = ['ldapsearch', 'updateseeds']
 
 
-def get_key_ids(key, info):
+def get_key_ids(key_len, keyids):
     '''Small utility function to return only keyid (short)
     or longkeyid's
 
-    @param key: string, the key length desired
-    @param info: list of keysid's to process
+    @param key_len: string, the key length desired
+    @param keyids: list of keysid's to process
     @return list of the desired key length id's
     '''
     result = []
-    for x in info:
-        if x.startswith('0x'):
-            mylen = KEY_LEN[key] + 2
-        else:
-            mylen = KEY_LEN[key]
-        if len(x) == mylen:
-            result.append(x)
+    for keyid in keyids:
+        target_len = KEYLEN_MAP[key_len]
+        if keyid.startswith('0x'):
+            target_len = KEYLEN_MAP[key_len] + 2
+        if len(keyid) == target_len:
+            result.append(keyid)
     return result
 
 
@@ -53,11 +52,11 @@ class Actions(object):
 
     def ldapsearch(self, args):
         l = LdapSearch()
-        self.logger.info("Search...establishing connection")
-        self.output("Search...establishing connection")
+        self.logger.info("Search... Establishing connection")
+        self.output("Search... Establishing connection")
         if not l.connect():
-            self.logger.info("Aborting Search...Connection failed")
-            self.output("Aborting Search...Connection failed")
+            self.logger.info("Aborting search... Connection failed")
+            self.output("Aborting search... Connection failed")
             return False
         self.logger.debug("MAIN: _action_ldapsearch; args = %s" % str(args))
         x, target, search_field = self.get_args(args)
@@ -66,26 +65,26 @@ class Actions(object):
         for dev in sorted(devs):
             self.output(dev, devs[dev])
         self.output("============================================")
-        self.output("Total number of devs in results:", len(devs))
+        self.output("Total number of developers in results:", len(devs))
         self.logger.info("============================================")
-        self.logger.info("Total number of devs in results: %d" % len(devs))
+        self.logger.info("Total number of developers in results: %d" % len(devs))
         return True
 
 
     def updateseeds(self, args):
-        self.logger.info("Beginning ldap search...")
-        self.output("Beginning ldap search...")
+        self.logger.info("Beginning LDAP search...")
+        self.output("Beginning LDAP search...")
         l = LdapSearch()
         if not l.connect():
-            self.output("Aborting Update...Connection failed")
-            self.logger.info("Aborting Update...Connection failed")
+            self.output("Aborting update... Connection failed")
+            self.logger.info("Aborting update... Connection failed")
             return False
         results = l.search('*', UID)
         info = l.result2dict(results, 'uid')
         self.logger.debug(
             "MAIN: _action_updateseeds; got results :) converted to info")
         if not self.create_seedfile(info):
-            self.logger.error("Dev seed file update failure: "
+            self.logger.error("Developer seed file update failure: "
                 "Original seed file is intact & untouched.")
         filename = self.config['dev-seedfile']
         old = filename + '.old'
@@ -108,12 +107,12 @@ class Actions(object):
             os.rename(filename + '.new', filename)
         except IOError:
             raise
-        self.output("Developer Seed file updated")
+        self.output("Developer seed file updated!")
         return True
 
 
     def create_seedfile(self, devs):
-        self.output("Creating seeds from ldap data...")
+        self.output("Creating seeds from LDAP data...")
         filename = self.config['dev-seedfile'] + '.new'
         self.seeds = Seeds(filename)
         count = 0
@@ -131,22 +130,22 @@ class Actions(object):
             else:
                 error_count += 1
         self.output("Total number of seeds created:", count)
-        self.output("Seeds created...saving file: %s" % filename)
-        self.output("Total number of Dev's with gpg errors:", error_count)
+        self.output("Seeds created... Saving file: %s" % filename)
+        self.output("Total number of Dev's with GPG errors:", error_count)
         self.logger.info("Total number of seeds created: %d" % count)
-        self.logger.info("Seeds created...saving file: %s" % filename)
-        self.logger.info("Total number of Dev's with gpg errors: %d" % error_count)
+        self.logger.info("Seeds created... Saving file: %s" % filename)
+        self.logger.info("Total number of Dev's with GPG errors: %d" % error_count)
         return self.seeds.save()
 
 
     @staticmethod
     def get_args(args):
-        for x in ['nick', 'name', 'gpgkey', 'fingerprint', 'status']:
-            if x:
-                target = getattr(args, x)
-                search_field = gkey2SEARCH[x]
+        for attr in ['nick', 'name', 'gpgkey', 'fingerprint', 'status']:
+            if attr:
+                target = getattr(args, attr)
+                search_field = gkey2SEARCH[attr]
                 break
-        return (x, target, search_field)
+        return (attr, target, search_field)
 
 
     def build_gkeylist(self, info):
@@ -156,8 +155,8 @@ class Actions(object):
         # assume it's good until an error is found
         is_good = True
         #self.logger.debug("Actions: build_gkeylist; info = %s" % str(info))
-        for x in GKEY._fields:
-            field = gkey2ldap_map[x]
+        for attr in GKEY._fields:
+            field = gkey2ldap_map[attr]
             if not field:
                 keyinfo.append(None)
                 continue
@@ -167,24 +166,24 @@ class Actions(object):
                 if values and field in ['uid', 'cn' ]:
                     value = values[0]
                 # separate out short/long key id's
-                elif values and x in ['keyid', 'longkeyid']:
-                    value = get_key_ids(x, values)
+                elif values and attr in ['keyid', 'longkeyid']:
+                    value = get_key_ids(attr, values)
                     if len(value):
                         keyid_found = True
-                elif values and x in ['fingerprint']:
+                elif values and attr in ['fingerprint']:
                     value = [v.replace(' ', '') for v in values]
                 else:
                     value = values
                 if 'undefined' in values:
-                    self.logger.error('ERROR in ldap info for: %s, %s'
+                    self.logger.error('ERROR in LDAP info for: %s, %s'
                         %(info['uid'][0],info['cn'][0]))
                     self.logger.error('  %s = "undefined"' %(field))
                     is_good = False
                 keyinfo.append(value)
             except KeyError:
-                self.logger.debug('Ldap info for: %s, %s'
+                self.logger.debug('LDAP info for: %s, %s'
                     %(info['uid'][0],info['cn'][0]))
-                self.logger.debug('  MISSING or EMPTY ldap field ' +
+                self.logger.debug('  MISSING or EMPTY LDAP field ' +
                     '[%s] GPGKey field [%s]' %(field, x))
                 if x in ['keyid', 'longkeyid']:
                     keyid_missing = True
@@ -195,21 +194,21 @@ class Actions(object):
             fingerprint = None
             try:
                 fingerprint = info[gkey2ldap_map['fingerprint']]
-                self.logger.debug('  Generate gpgkey, Found ldap fingerprint field')
+                self.logger.debug('  Generate gpgkey, Found LDAP fingerprint field')
             except KeyError:
-                gpgkey = 'Missing fingerprint from ldap info'
-                self.logger.debug('  Generate gpgkey, ldap fingerprint KeyError')
+                gpgkey = 'Missing fingerprint from LDAP info'
+                self.logger.debug('  Generate gpgkey, LDAP fingerprint KeyError')
             if fingerprint:
                 values = [y.strip('\n') for y in fingerprint]
                 value = [v.replace(' ', '') for v in values]
                 # assign it to gpgkey to prevent a possible
                 # "gpgkey" undefined error
-                gpgkey = ['0x' + x[-KEY_LEN['longkeyid']:] for x in value]
+                gpgkey = ['0x' + x[-KEYLEN_MAP['longkeyid']:] for x in value]
                 keyinfo[LONGKEYID] = gpgkey
                 self.logger.debug('  Generate gpgkey, NEW keyinfo[LONGKEYID] = %s'
                     % str(keyinfo[LONGKEYID]))
             else:
-                gpgkey = 'Missing or Bad fingerprint from ldap info'
+                gpgkey = 'Missing or Bad fingerprint from LDAP info'
                 is_good = False
             if not keyinfo[LONGKEYID]:
                 self.logger.error('ERROR in ldap info for: %s, %s'
@@ -239,7 +238,7 @@ class Actions(object):
                 index = len(y.lstrip('0x'))
                 if y.lstrip('0x').upper() not in \
                         [x[-index:].upper() for x in keyinfo[FINGERPRINT]]:
-                    self.logger.error('ERROR in ldap info for: %s, %s'
+                    self.logger.error('ERROR in LDAP info for: %s, %s'
                         %(info['uid'][0],info['cn'][0]))
                     self.logger.error('  ' + str(keyinfo))
                     self.logger.error('  GPGKey id %s not found in the '
@@ -251,19 +250,19 @@ class Actions(object):
     def _check_fingerprint_integrity(self, info, keyinfo):
         # assume it's good until found an error is found
         is_good = True
-        for x in keyinfo[FINGERPRINT]:
+        for fingerprint in keyinfo[FINGERPRINT]:
             # check fingerprint integrity
-            if len(x) != 40:
-                self.logger.error('ERROR in ldap info for: %s, %s'
+            if len(fingerprint) != 40:
+                self.logger.error('ERROR in LDAP info for: %s, %s'
                     %(info['uid'][0],info['cn'][0]))
                 self.logger.error('  GPGKey incorrect fingerprint ' +
-                    'length (%s) for fingerprint: %s' %(len(x), x))
+                    'length (%s) for fingerprint: %s' %(len(fingerprint), fingerprint))
                 is_good = False
                 continue
-            if not self.fingerprint_re.match(x):
+            if not self.fingerprint_re.match(fingerprint):
                 self.logger.error('ERROR in ldap info for: %s, %s'
                     %(info['uid'][0],info['cn'][0]))
                 self.logger.error('  GPGKey: Non hexadecimal digits in ' +
-                    'fingerprint for fingerprint: ' + x)
+                    'fingerprint for fingerprint: ' + fingerprint)
                 is_good = False
         return is_good

diff --git a/gkeyldap/search.py b/gkeyldap/search.py
index 2cbc4b9..087bee6 100644
--- a/gkeyldap/search.py
+++ b/gkeyldap/search.py
@@ -60,7 +60,7 @@ gkey2SEARCH = {
 
 
 class LdapSearch(object):
-    '''Class to perform searches on the configured ldap server
+    '''Class to perform searches on the configured LDAP server
     '''
 
     def __init__(self, server=None, fields=None, criteria=None):
@@ -74,9 +74,9 @@ class LdapSearch(object):
 
 
     def connect(self, server=None,):
-        '''Creates our ldap server connection
-
+        '''Creates our LDAP server connection
         '''
+
         if server:
             self.server = server
             logger.debug('LdapSearch: connect; new server: %s' % self.server)
@@ -93,9 +93,8 @@ class LdapSearch(object):
         return True
 
 
-
     def search(self, target, search_field=UID, fields=None, criteria=None):
-        '''Perform the ldap search
+        '''Perform the LDAP search
         '''
         if not target:
             logger.debug('LdapSearch: search; invalid target: "%s"' % target)

diff --git a/gkeys/actions.py b/gkeys/actions.py
index 85c0e0e..79690fc 100644
--- a/gkeys/actions.py
+++ b/gkeys/actions.py
@@ -76,7 +76,7 @@ class Actions(object):
             success = self.seeds.add(gkey)
             if success:
                 success = self.seeds.save()
-                return ["Successfully Added new seed: %s" % str(success), gkey]
+                return ["Successfully added new seed: %s" % str(success), gkey]
         else:
             messages = ["Matching seeds found in seeds file",
                 "Aborting... \nMatching seeds:"]
@@ -91,20 +91,20 @@ class Actions(object):
         self.logger.debug("ACTIONS: removeseed; gkey: %s" % str(searchkey))
         gkeys = self.listseed(args)
         if not gkeys:
-            return ["Failed to Removed seed: No gkeys returned from listseed()",
+            return ["Failed to remove seed: No gkeys returned from listseed()",
                 None]
         if len(gkeys) == 1:
             self.logger.debug("ACTIONS: removeseed; now deleting gkey: %s" % str(gkeys[0]))
             success = self.seeds.delete(gkeys[0])
             if success:
                 success = self.seeds.save()
-            return ["Successfully Removed seed: %s" % str(success),
+            return ["Successfully removed seed: %s" % str(success),
                 gkeys[0]]
         elif len(gkeys):
             messages = ["Too many seeds found to remove"]
             messages.extend(gkeys)
             return messages
-        return ["Failed to Remove seed:", searchkey,
+        return ["Failed to remove seed:", searchkey,
             "No matching seed found"]
 
 
@@ -138,7 +138,7 @@ class Actions(object):
             messages = ["Too many seeds found to move"]
             messages.extend(sourcekeys)
             return messages
-        messages.append("Failed to Move seed:")
+        messages.append("Failed to move seed:")
         messages.append(searchkey)
         messages.append('\n')
         messages.append("Source seeds found...")

diff --git a/gkeys/config.py b/gkeys/config.py
index 1ff5a18..b20d5cd 100644
--- a/gkeys/config.py
+++ b/gkeys/config.py
@@ -120,7 +120,7 @@ KEYDIR = 4
 FINGERPRINT = 5
 
 # set some defaults
-KEY_LEN = {
+KEYLEN_MAP = {
     'keyid': 8,
     'longkeyid': 16,
 }

diff --git a/gkeys/seed.py b/gkeys/seed.py
index 1dd8fc4..d5a92e3 100644
--- a/gkeys/seed.py
+++ b/gkeys/seed.py
@@ -92,7 +92,6 @@ class Seeds(object):
         return False
 
 
-
     def delete(self, gkey=None, index=None):
         '''Delete the key from the seeds in memory
 

diff --git a/gkeys/seedhandler.py b/gkeys/seedhandler.py
index 2506277..7f73857 100644
--- a/gkeys/seedhandler.py
+++ b/gkeys/seedhandler.py
@@ -13,7 +13,7 @@
 import re
 
 from gkeys.config import (GKEY, NICK, NAME, KEYID, LONGKEYID, FINGERPRINT,
-    KEY_LEN)
+    KEYLEN_MAP)
 
 
 class SeedHandler(object):
@@ -40,11 +40,11 @@ class SeedHandler(object):
     @staticmethod
     def build_gkeydict(args):
         keyinfo = {}
-        for x in GKEY._fields:
+        for attr in GKEY._fields:
             try:
-                value = getattr(args, x)
+                value = getattr(args, attr)
                 if value:
-                    keyinfo[x] = value
+                    keyinfo[attr] = value
             except AttributeError:
                 pass
         return keyinfo
@@ -56,20 +56,20 @@ class SeedHandler(object):
         # assume it's good until an error is found
         is_good = True
         #self.logger.debug("SeedHandler: build_gkeylist; args = %s" % str(args))
-        for x in GKEY._fields:
-            if GKEY.field_types[x] is str:
+        for attr in GKEY._fields:
+            if GKEY.field_types[attr] is str:
                 try:
-                    value = getattr(args, x)
+                    value = getattr(args, attr)
                 except AttributeError:
                     value = None
-            elif GKEY.field_types[x] is list:
+            elif GKEY.field_types[attr] is list:
                 try:
-                    values = [y for y in getattr(args, x).split(':')]
+                    values = [y for y in getattr(args, attr).split(':')]
                     value = [v.replace(' ', '') for v in values]
                 except AttributeError:
                     value = None
             keyinfo.append(value)
-            if x in ["keyid", "longkeyid"] and value:
+            if attr in ["keyid", "longkeyid"] and value:
                 keyid_found = True
         if not keyid_found and needkeyid:
             fingerprint = keyinfo[FINGERPRINT]
@@ -78,7 +78,7 @@ class SeedHandler(object):
                     'fingerprint in args')
                 # assign it to gpgkey to prevent a possible
                 # "gpgkey" undefined error
-                gpgkey = ['0x' + x[-KEY_LEN['longkeyid']:] for x in fingerprint]
+                gpgkey = ['0x' + x[-KEYLEN_MAP['longkeyid']:] for x in fingerprint]
                 keyinfo[LONGKEYID] = gpgkey
                 self.logger.debug('  Generate gpgkey longkeyid, NEW '
                     'keyinfo[LONGKEYID] = %s' % str(keyinfo[LONGKEYID]))
@@ -139,19 +139,19 @@ class SeedHandler(object):
     def _check_fingerprint_integrity(self, keyinfo):
         # assume it's good until an error is found
         is_good = True
-        for x in keyinfo[FINGERPRINT]:
+        for fingerprint in keyinfo[FINGERPRINT]:
             # check fingerprint integrity
-            if len(x) != 40:
+            if len(fingerprint) != 40:
                 self.logger.error('ERROR in keyinfo for: %s, %s'
                     %(keyinfo[NICK], keyinfo[NAME]))
                 self.logger.error('  GPGKey incorrect fingerprint ' +
                     'length (%s) for fingerprint: %s' %(len(x), x))
                 is_good = False
                 continue
-            if not self.fingerprint_re.match(x):
+            if not self.fingerprint_re.match(fingerprint):
                 self.logger.error('ERROR in keyinfo info for: %s, %s'
                     %(keyinfo[NICK], keyinfo[NAME]))
                 self.logger.error('  GPGKey: Non hexadecimal digits in ' +
-                    'fingerprint for fingerprint: ' + x)
+                    'fingerprint for fingerprint: ' + fingerprint)
                 is_good = False
         return is_good


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2014-05-27 20:56 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2014-05-27 20:56 UTC (permalink / raw
  To: gentoo-commits

commit:     958d93beb7f47590b7d1b3cf5b28460ff626f52c
Author:     Pavlos Ratis <dastergon <AT> gentoo <DOT> org>
AuthorDate: Tue May 20 23:27:35 2014 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Tue May 20 23:27:35 2014 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=958d93be

switch current seed file format to JSON

---
 gkeyldap/actions.py | 74 ++++++++++++++++++++++++++---------------------------
 gkeys/config.py     | 14 ++++++++++
 gkeys/seed.py       | 20 +++++++++------
 3 files changed, 62 insertions(+), 46 deletions(-)

diff --git a/gkeyldap/actions.py b/gkeyldap/actions.py
index 55c3e13..4b28a19 100644
--- a/gkeyldap/actions.py
+++ b/gkeyldap/actions.py
@@ -13,7 +13,8 @@
 import os
 import re
 
-from gkeys.config import GKEY, KEYID, LONGKEYID, FINGERPRINT, KEYLEN_MAP
+from collections import defaultdict
+from gkeys.config import GKEY, KEYLEN_MAP
 from gkeys.seed import Seeds
 from gkeyldap.search import (LdapSearch, UID, gkey2ldap_map, gkey2SEARCH)
 
@@ -117,15 +118,16 @@ class Actions(object):
         self.seeds = Seeds(filename)
         count = 0
         error_count = 0
+        gkeyattr_dev = defaultdict()
         for dev in sorted(devs):
             if devs[dev]['gentooStatus'][0] not in ['active']:
                 continue
             #self.logger.debug("create_seedfile, dev = "
             #   "%s, %s" % (str(dev), str(devs[dev])))
-            keyinfo = self.build_gkeylist(devs[dev])
-            if keyinfo:
-                new_gkey = GKEY._make(keyinfo)
-                self.seeds.add(new_gkey)
+            developer_attrs = self.build_gkeydict(devs[dev])
+            if developer_attrs:
+                gkeyattr_dev[dev] = developer_attrs
+                self.seeds.add(gkeyattr_dev)
                 count += 1
             else:
                 error_count += 1
@@ -148,8 +150,8 @@ class Actions(object):
         return (attr, target, search_field)
 
 
-    def build_gkeylist(self, info):
-        keyinfo = []
+    def build_gkeydict(self, info):
+        keyinfo = defaultdict()
         keyid_found = False
         keyid_missing = False
         # assume it's good until an error is found
@@ -158,38 +160,34 @@ class Actions(object):
         for attr in GKEY._fields:
             field = gkey2ldap_map[attr]
             if not field:
-                keyinfo.append(None)
+                keyinfo[attr] = None
                 continue
             try:
+                values = info[field]
                 # strip errant line feeds
-                values = [y.strip('\n') for y in info[field]]
-                if values and field in ['uid', 'cn' ]:
-                    value = values[0]
+                values = [y.strip('\n') for y in values]
                 # separate out short/long key id's
-                elif values and attr in ['keyid', 'longkeyid']:
-                    value = get_key_ids(attr, values)
-                    if len(value):
+                if values and attr in ['keyid', 'longkeyid']:
+                    if len(get_key_ids(attr, values)):
                         keyid_found = True
                 elif values and attr in ['fingerprint']:
-                    value = [v.replace(' ', '') for v in values]
-                else:
-                    value = values
+                    values = [v.replace(' ', '') for v in values]
                 if 'undefined' in values:
                     self.logger.error('ERROR in LDAP info for: %s, %s'
-                        %(info['uid'][0],info['cn'][0]))
-                    self.logger.error('  %s = "undefined"' %(field))
+                        % (info['uid'][0],info['cn'][0]))
+                    self.logger.error('  %s = "undefined"' % (field))
                     is_good = False
-                keyinfo.append(value)
+                keyinfo[attr] = values
             except KeyError:
                 self.logger.debug('LDAP info for: %s, %s'
-                    %(info['uid'][0],info['cn'][0]))
+                    % (info['uid'][0],info['cn'][0]))
                 self.logger.debug('  MISSING or EMPTY LDAP field ' +
-                    '[%s] GPGKey field [%s]' %(field, x))
-                if x in ['keyid', 'longkeyid']:
+                    '[%s] GPGKey field [%s]' % (field, attr))
+                if attr in ['keyid', 'longkeyid']:
                     keyid_missing = True
                 else:
                     is_good = False
-                keyinfo.append(None)
+                keyinfo[attr] = None
         if not keyid_found and keyid_missing:
             fingerprint = None
             try:
@@ -200,24 +198,24 @@ class Actions(object):
                 self.logger.debug('  Generate gpgkey, LDAP fingerprint KeyError')
             if fingerprint:
                 values = [y.strip('\n') for y in fingerprint]
-                value = [v.replace(' ', '') for v in values]
+                values = [v.replace(' ', '') for v in values]
                 # assign it to gpgkey to prevent a possible
                 # "gpgkey" undefined error
-                gpgkey = ['0x' + x[-KEYLEN_MAP['longkeyid']:] for x in value]
-                keyinfo[LONGKEYID] = gpgkey
-                self.logger.debug('  Generate gpgkey, NEW keyinfo[LONGKEYID] = %s'
-                    % str(keyinfo[LONGKEYID]))
+                gpgkey = ['0x' + x[-KEYLEN_MAP['longkeyid']:] for x in values]
+                keyinfo['longkeyid'] = gpgkey
+                self.logger.debug('  Generate gpgkey, NEW keyinfo[\'fingerprint\'] = %s'
+                    % str(keyinfo['longkeyid']))
             else:
                 gpgkey = 'Missing or Bad fingerprint from LDAP info'
                 is_good = False
-            if not keyinfo[LONGKEYID]:
+            if not keyinfo['longkeyid']:
                 self.logger.error('ERROR in ldap info for: %s, %s'
                     %(info['uid'][0],info['cn'][0]))
                 self.logger.error('  A valid keyid, longkeyid or fingerprint '
                     'was not found for %s : gpgkey = %s' %(info['cn'][0], gpgkey))
                 is_good = False
         if is_good:
-            if keyinfo[FINGERPRINT]: # fingerprints exist check
+            if keyinfo['fingerprint']: # fingerprints exist check
                 is_ok = self._check_fingerprint_integrity(info, keyinfo)
                 is_match = self._check_id_fingerprint_match(info, keyinfo)
                 if not is_ok or not is_match:
@@ -230,14 +228,14 @@ class Actions(object):
     def _check_id_fingerprint_match(self, info, keyinfo):
         # assume it's good until found an error is found
         is_good = True
-        for x in [KEYID, LONGKEYID]:
+        for attr in ['keyid', 'longkeyid']:
             # skip blank id field
-            if not keyinfo[x]:
+            if not keyinfo[attr]:
                 continue
-            for y in keyinfo[x]:
+            for y in keyinfo[attr]:
                 index = len(y.lstrip('0x'))
                 if y.lstrip('0x').upper() not in \
-                        [x[-index:].upper() for x in keyinfo[FINGERPRINT]]:
+                        [x[-index:].upper() for x in keyinfo['fingerprint']]:
                     self.logger.error('ERROR in LDAP info for: %s, %s'
                         %(info['uid'][0],info['cn'][0]))
                     self.logger.error('  ' + str(keyinfo))
@@ -250,7 +248,7 @@ class Actions(object):
     def _check_fingerprint_integrity(self, info, keyinfo):
         # assume it's good until found an error is found
         is_good = True
-        for fingerprint in keyinfo[FINGERPRINT]:
+        for fingerprint in keyinfo['fingerprint']:
             # check fingerprint integrity
             if len(fingerprint) != 40:
                 self.logger.error('ERROR in LDAP info for: %s, %s'
@@ -260,8 +258,8 @@ class Actions(object):
                 is_good = False
                 continue
             if not self.fingerprint_re.match(fingerprint):
-                self.logger.error('ERROR in ldap info for: %s, %s'
-                    %(info['uid'][0],info['cn'][0]))
+                self.logger.error('ERROR in LDAP info for: %s, %s'
+                    % (info['uid'][0],info['cn'][0]))
                 self.logger.error('  GPGKey: Non hexadecimal digits in ' +
                     'fingerprint for fingerprint: ' + fingerprint)
                 is_good = False

diff --git a/gkeys/config.py b/gkeys/config.py
index b20d5cd..818f5b1 100644
--- a/gkeys/config.py
+++ b/gkeys/config.py
@@ -184,6 +184,20 @@ class GKEY(namedtuple('GKEY', ['nick', 'name', 'keyid', 'longkeyid',
                 result = data.split(self.list_separator)
         return result
 
+    def _unpack_dict(self, data):
+        values = []
+        for attr in self._fields:
+            values.append(data[attr])
+        return values
+
+    def make_packed_dict(self, packed_dict):
+        '''Creates a new instance of Gkey from a dictionary
+
+        @param packed_dict: data inside a dictionary
+        @return new GKEY instance containing the data
+        '''
+        return GKEY._make(self._unpack_dict(packed_dict))
+
     def make_packed(self, packed_string):
         '''Creates a new instance of Gkey from the packed
         value string

diff --git a/gkeys/seed.py b/gkeys/seed.py
index d5a92e3..aebf63d 100644
--- a/gkeys/seed.py
+++ b/gkeys/seed.py
@@ -15,7 +15,9 @@ with gentoo-keys specific convienience functions.
              Brian Dolbec <dolsen@gentoo.org>
 
 '''
+import json
 
+from collections import defaultdict
 from gkeys.log import logger
 from gkeys.config import GKEY
 
@@ -45,18 +47,16 @@ class Seeds(object):
         self.seeds = []
         try:
             with open(self.filename) as seedfile:
-                seedlines = seedfile.readlines()
+                seedlines = json.load(seedfile)
         except IOError as err:
             logger.debug("Seed: load; IOError occurred while loading file")
             self._error(err)
             return False
-
         # initialize a dummy instance, so it can make new ones
         gkey = GKEY._make([None,None,None,None,None,None])
-        for seed in seedlines:
+        for seed in seedlines.items():
             #try:
-            seed = seed.strip('\n')
-            self.seeds.append(gkey.make_packed(seed))
+            self.seeds.append(gkey.make_packed_dict(seed[1]))
             #except Exception as err:
                 #logger.debug("Seed: load; Error splitting seed: %s" % seed)
                 #logger.debug("Seed: load; ...............parts: %s" % str(parts))
@@ -75,8 +75,7 @@ class Seeds(object):
         logger.debug("Seed: save; Begin saving seed file %s" % self.filename)
         try:
             with open(self.filename, 'w') as seedfile:
-                seedlines = [x.packed_string for x in self.seeds]
-                seedfile.write('\n'.join(seedlines))
+                seedfile.write(self._seeds2json(self.seeds))
                 seedfile.write("\n")
         except IOError as err:
             self._error(err)
@@ -86,9 +85,11 @@ class Seeds(object):
 
     def add(self, gkey):
         '''Add a new seed key to memory'''
-        if isinstance(gkey, GKEY):
+        if isinstance(gkey, defaultdict):
             self.seeds.append(gkey)
             return True
+        elif isinstance(gkey, GKEY):
+            pass
         return False
 
 
@@ -150,3 +151,6 @@ class Seeds(object):
         logger.error("Seed: Error processing seed file %s" % self.filename)
         logger.error("Seed: Error was: %s" % str(err))
 
+
+    def _seeds2json(self, seeds):
+        return json.dumps(self.seeds[0], sort_keys=True, indent=4)


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2014-05-27 20:56 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2014-05-27 20:56 UTC (permalink / raw
  To: gentoo-commits

commit:     c2ce0f379d7740dac246d5378bb5746abea8be1f
Author:     Pavlos Ratis <dastergon <AT> gentoo <DOT> org>
AuthorDate: Sun May 25 14:46:15 2014 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Sun May 25 14:46:15 2014 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=c2ce0f37

remove KEYLEN_MAP

---
 gkeyldap/actions.py | 10 +++++-----
 gkeyldap/search.py  |  3 ---
 gkeys/config.py     | 15 +--------------
 3 files changed, 6 insertions(+), 22 deletions(-)

diff --git a/gkeyldap/actions.py b/gkeyldap/actions.py
index 712f090..7c0608b 100644
--- a/gkeyldap/actions.py
+++ b/gkeyldap/actions.py
@@ -14,7 +14,7 @@ import os
 import re
 
 from collections import defaultdict
-from gkeys.config import GKEY, KEYLEN_MAP
+from gkeys.config import GKEY
 from gkeys.seed import Seeds
 from gkeyldap.search import (LdapSearch, UID, gkey2ldap_map, gkey2SEARCH)
 
@@ -32,9 +32,9 @@ def get_key_ids(key_len, keyids):
     '''
     result = []
     for keyid in keyids:
-        target_len = KEYLEN_MAP[key_len]
+        target_len = 16
         if keyid.startswith('0x'):
-            target_len = KEYLEN_MAP[key_len] + 2
+            target_len = target_len + 2
         if len(keyid) == target_len:
             result.append(keyid)
     return result
@@ -155,7 +155,7 @@ class Actions(object):
         # assume it's good until an error is found
         is_good = True
         #self.logger.debug("Actions: build_gkeylist; info = %s" % str(info))
-        for attr in GKEY._fields:
+        for attr in gkey2ldap_map:
             field = gkey2ldap_map[attr]
             if not field:
                 keyinfo[attr] = None
@@ -199,7 +199,7 @@ class Actions(object):
                 values = [v.replace(' ', '') for v in values]
                 # assign it to gpgkey to prevent a possible
                 # "gpgkey" undefined error
-                gpgkey = ['0x' + x[-KEYLEN_MAP['longkeyid']:] for x in values]
+                gpgkey = ['0x' + x[-16:] for x in values]
                 keyinfo['longkeyid'] = gpgkey
                 self.logger.debug('  Generate gpgkey, NEW keyinfo[\'fingerprint\'] = %s'
                     % str(keyinfo['longkeyid']))

diff --git a/gkeyldap/search.py b/gkeyldap/search.py
index 087bee6..5f2ffbd 100644
--- a/gkeyldap/search.py
+++ b/gkeyldap/search.py
@@ -36,9 +36,6 @@ gkey2ldap_map = {
     'keydir': 'uid',
     'fingerprint': 'gpgfingerprint'
 }
-# Sanity check they are in sync
-if not sorted(gkey2ldap_map) == sorted(GKEY._fields):
-    raise "Search.py out of sync with GKEY class"
 
 
 # Now for some search field defaults

diff --git a/gkeys/config.py b/gkeys/config.py
index b1a0447..b932fb2 100644
--- a/gkeys/config.py
+++ b/gkeys/config.py
@@ -110,23 +110,10 @@ class GKeysConfig(GPGConfig):
             return super(GKeysConfig, self)._get_(key, subkey)
 
 
-# set some defaults
-KEYLEN_MAP = {
-    'keyid': 8,
-    'longkeyid': 16,
-}
 
-
-class GKEY(namedtuple('GKEY', ['nick', 'name', 'keyid', 'longkeyid',
-    'keydir', 'fingerprint'])):
+class GKEY(namedtuple('GKEY', ['nick', 'name', 'keydir', 'fingerprint'])):
     '''Class to hold the relavent info about a key'''
 
-    # subclass __new__ to make both gkeys and gkeyldap work properly
-    # delete it when keyid and longkeyid are removed from LDAP
-    def __new__(cls, nick=None, name=None, keydir=None, fingerprint=None,
-                keyid=None, longkeyid=None):
-        return super(GKEY, cls).__new__(cls, nick, name, keydir, fingerprint,
-                                        keyid, longkeyid)
 
     field_types = {'nick': str, 'name': str, 'keyid': list,
         'longkeyid': list, 'keydir': str, 'fingerprint': list}


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2014-05-27 20:56 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2014-05-27 20:56 UTC (permalink / raw
  To: gentoo-commits

commit:     2fde2e6a825d0aad0992eccf3e0b4e69e1a68d23
Author:     Pavlos Ratis <dastergon <AT> gentoo <DOT> org>
AuthorDate: Sat May 24 17:35:04 2014 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Sat May 24 17:38:48 2014 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=2fde2e6a

switch seed handling from list to dictionary

---
 gkeyldap/actions.py |  4 +---
 gkeys/seed.py       | 39 ++++++++++++++++++++-------------------
 2 files changed, 21 insertions(+), 22 deletions(-)

diff --git a/gkeyldap/actions.py b/gkeyldap/actions.py
index 4b28a19..712f090 100644
--- a/gkeyldap/actions.py
+++ b/gkeyldap/actions.py
@@ -118,7 +118,6 @@ class Actions(object):
         self.seeds = Seeds(filename)
         count = 0
         error_count = 0
-        gkeyattr_dev = defaultdict()
         for dev in sorted(devs):
             if devs[dev]['gentooStatus'][0] not in ['active']:
                 continue
@@ -126,8 +125,7 @@ class Actions(object):
             #   "%s, %s" % (str(dev), str(devs[dev])))
             developer_attrs = self.build_gkeydict(devs[dev])
             if developer_attrs:
-                gkeyattr_dev[dev] = developer_attrs
-                self.seeds.add(gkeyattr_dev)
+                self.seeds.add(dev, developer_attrs)
                 count += 1
             else:
                 error_count += 1

diff --git a/gkeys/seed.py b/gkeys/seed.py
index ecbbf83..24748dd 100644
--- a/gkeys/seed.py
+++ b/gkeys/seed.py
@@ -17,7 +17,6 @@ with gentoo-keys specific convienience functions.
 '''
 import json
 
-from collections import defaultdict
 from gkeys.log import logger
 from gkeys.config import GKEY
 
@@ -32,7 +31,7 @@ class Seeds(object):
         @param filepath: string of the file to load
         '''
         self.filename = filepath
-        self.seeds = []
+        self.seeds = {}
 
 
     def load(self, filename=None):
@@ -44,7 +43,7 @@ class Seeds(object):
             return False
         logger.debug("Seeds: load; Begin loading seed file %s" % self.filename)
         seedlines = None
-        self.seeds = []
+        self.seeds = {}
         try:
             with open(self.filename) as seedfile:
                 seedlines = json.load(seedfile)
@@ -54,7 +53,7 @@ class Seeds(object):
             return False
         for seed in seedlines.items():
             #try:
-            self.seeds.append(GKEY(**seed[1]))
+            self.seeds[seed[0]] = GKEY(**seed[1])
             #except Exception as err:
                 #logger.debug("Seed: load; Error splitting seed: %s" % seed)
                 #logger.debug("Seed: load; ...............parts: %s" % str(parts))
@@ -81,13 +80,11 @@ class Seeds(object):
         return True
 
 
-    def add(self, gkey):
+    def add(self, dev, gkey):
         '''Add a new seed key to memory'''
-        if isinstance(gkey, defaultdict):
-            self.seeds.append(gkey)
+        if isinstance(gkey, dict) or isinstance(gkey, GKEY):
+            self.seeds[dev] = gkey
             return True
-        elif isinstance(gkey, GKEY):
-            pass
         return False
 
 
@@ -98,7 +95,7 @@ class Seeds(object):
         @param index: int, '''
         if gkey:
             try:
-                self.seeds.remove(gkey)
+                self.seeds.pop(getattr(gkey[0], 'nick')[0], None)
             except ValueError:
                 return False
             return True
@@ -113,17 +110,15 @@ class Seeds(object):
         @param kwargs: dict of GKEY._fields and values
         @returns list
         '''
-        if not kwargs:
-            return self.seeds
-        if kwargs['nick'] == '*':
-            return self.seeds[:]
+        if not kwargs or kwargs['nick'] == '*':
+            return self.seeds.values()[0]
         # proceed with the search
         # discard any invalid keys
-        keys = set(list(kwargs)).intersection(GKEY._fields)
-        result = self.seeds[:]
+        keys = kwargs
+        result = self.seeds
         for key in keys:
-            result = [x for x in result if getattr(x , key) == kwargs[key]]
-        return result
+            result = {dev: gkey for dev, gkey in result.items() if kwargs[key] in getattr(gkey, key)}
+        return result.values()
 
 
     def search(self, pattern):
@@ -151,4 +146,10 @@ class Seeds(object):
 
 
     def _seeds2json(self, seeds):
-        return json.dumps(self.seeds[0], sort_keys=True, indent=4)
+        is_gkey=False
+        if isinstance(seeds.values()[0], GKEY):
+            is_gkey = True
+        for dev, value in seeds.items():
+            if is_gkey:
+                seeds[dev] = dict(value._asdict())
+        return json.dumps(seeds, sort_keys=True, indent=4)


^ permalink raw reply related	[flat|nested] 14+ messages in thread

* [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/
@ 2014-05-27 20:56 Brian Dolbec
  0 siblings, 0 replies; 14+ messages in thread
From: Brian Dolbec @ 2014-05-27 20:56 UTC (permalink / raw
  To: gentoo-commits

commit:     bf526d025a101b3ee8999acbc98ad90ae4c603dc
Author:     Pavlos Ratis <dastergon <AT> gentoo <DOT> org>
AuthorDate: Mon May 26 19:25:34 2014 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Mon May 26 19:25:34 2014 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/gentoo-keys.git;a=commit;h=bf526d02

remove unused GKEY code

---
 gkeyldap/actions.py |  1 -
 gkeyldap/search.py  |  1 -
 gkeys/config.py     | 62 +----------------------------------------------------
 3 files changed, 1 insertion(+), 63 deletions(-)

diff --git a/gkeyldap/actions.py b/gkeyldap/actions.py
index 7c0608b..3de4308 100644
--- a/gkeyldap/actions.py
+++ b/gkeyldap/actions.py
@@ -14,7 +14,6 @@ import os
 import re
 
 from collections import defaultdict
-from gkeys.config import GKEY
 from gkeys.seed import Seeds
 from gkeyldap.search import (LdapSearch, UID, gkey2ldap_map, gkey2SEARCH)
 

diff --git a/gkeyldap/search.py b/gkeyldap/search.py
index 5f2ffbd..c19a088 100644
--- a/gkeyldap/search.py
+++ b/gkeyldap/search.py
@@ -15,7 +15,6 @@ except ImportError:
 
 
 from gkeys import log
-from gkeys.config import GKEY
 
 logger = log.logger
 

diff --git a/gkeys/config.py b/gkeys/config.py
index b932fb2..14756e7 100644
--- a/gkeys/config.py
+++ b/gkeys/config.py
@@ -114,66 +114,6 @@ class GKeysConfig(GPGConfig):
 class GKEY(namedtuple('GKEY', ['nick', 'name', 'keydir', 'fingerprint'])):
     '''Class to hold the relavent info about a key'''
 
-
     field_types = {'nick': str, 'name': str, 'keyid': list,
-        'longkeyid': list, 'keydir': str, 'fingerprint': list}
-    field_separator = "|"
-    list_separator = ":"
+                   'longkeyid': list, 'keydir': str, 'fingerprint': list}
     __slots__ = ()
-
-    def _packed_values(self):
-        '''Returns a list of the field values'''
-        v = []
-        for f in self._fields:
-            v.append(self._pack(f))
-        return v
-
-    @property
-    def packed_string(self):
-        '''Returns a separator joined string of the field values'''
-        return self.field_separator.join([str(x) for x in self._packed_values()])
-
-    def _unpack_string(self, packed_data):
-        '''Returns a list of the separator joined string of the field values'''
-        values = []
-        data = packed_data.split(self.field_separator)
-        for x in self._fields:
-            values.append(self._unpack(x, data.pop(0)))
-        return values
-
-    def _pack(self, field):
-        '''pack field data into a string'''
-        if self.field_types[field] == str:
-            return getattr(self, field)
-        elif self.field_types[field] == list:
-            info = getattr(self, field)
-            if info:
-                return self.list_separator.join(info)
-            else:
-                # force an empty list to None
-                return 'None'
-        else:
-            raise "ERROR packing %s" %str(getattr(self, field))
-
-    def _unpack(self, field, data):
-        '''unpack field data to the desired type'''
-        if self.field_types[field] == str:
-            result = data
-            if result == 'None':
-                result = None
-        else:
-            if data == 'None':
-                # make it an empty list
-                result = []
-            else:
-                result = data.split(self.list_separator)
-        return result
-
-    def make_packed(self, packed_string):
-        '''Creates a new instance of Gkey from the packed
-        value string
-
-        @param packed_string: string of data separated by field_separator
-        @return new GKEY instance containing the data
-        '''
-        return GKEY._make(self._unpack_string(packed_string))


^ permalink raw reply related	[flat|nested] 14+ messages in thread

end of thread, other threads:[~2014-05-27 20:56 UTC | newest]

Thread overview: 14+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2014-05-27 20:56 [gentoo-commits] proj/gentoo-keys:master commit in: gkeyldap/, gkeys/ Brian Dolbec
  -- strict thread matches above, loose matches on Subject: below --
2014-05-27 20:56 Brian Dolbec
2014-05-27 20:56 Brian Dolbec
2014-05-27 20:56 Brian Dolbec
2014-05-27 20:56 Brian Dolbec
2014-03-01 17:49 Pavlos Ratis
2013-11-17  7:39 Brian Dolbec
2013-11-15  9:16 Brian Dolbec
2013-11-15  9:16 Brian Dolbec
2013-11-10  1:01 Brian Dolbec
2013-06-23  7:13 Brian Dolbec
2013-06-23  7:13 Brian Dolbec
2013-06-23  7:13 Brian Dolbec
2013-06-23  7:13 Brian Dolbec

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox