Work in progress changes to get add_key coded & working.
[gentoo-keys.git] / gkeys / config.py
1 #
2 #-*- coding:utf-8 -*-
3
4 """
5     Gentoo-keys - config.py
6
7     Holds configuration keys and values
8
9     @copyright: 2012 by Brian Dolbec <dol-sen@gentoo.org>
10     @license: GNU GNU GPL2, see COPYING for details.
11 """
12
13 import os
14 import ConfigParser
15 from collections import namedtuple
16
17
18 from pygpg.config import GPGConfig
19
20 from gkeys.log import logger
21 from gkeys.utils import path
22
23
24 # establish the eprefix, initially set so eprefixify can
25 # set it on install
26 EPREFIX = "@GENTOO_PORTAGE_EPREFIX@"
27
28 # check and set it if it wasn't
29 if "GENTOO_PORTAGE_EPREFIX" in EPREFIX:
30     EPREFIX = ''
31
32
33
34 class GKeysConfig(GPGConfig):
35     """ Configuration superclass which holds our gentoo-keys
36     config settings for pygpg """
37
38     def __init__ (self, config=None, root=None, read_configfile=False):
39         """ Class initialiser """
40         GPGConfig.__init__(self)
41
42         self.root = root or ''
43         if config:
44             self.defaults['config'] = config
45             self.defaults['configdir'] = os.path.dirname(config)
46         else:
47             self.defaults['configdir'] = path([self.root, EPREFIX, '/etc/gentoo-keys'])
48             self.defaults['config'] = '%(configdir)s/gkeys.conf'
49         self.configparser = None
50         if read_configfile:
51             self.read_config()
52
53
54     def _add_gkey_defaults(self):
55         self.defaults['keysdir'] = path([self.root, EPREFIX, '/var/gentoo/gkeys'])
56         self.defaults['dev-keydir'] = '%(keysdir)s/devs'
57         self.defaults['release-keydir'] = '%(keysdir)s/release'
58         self.defaults['overlays-keydir'] = '%(keysdir)s/overlays'
59         self.defaults['known-keysfile'] = '%(keysdir)s/knownkeys'
60         self.defaults['release-seedfile'] = '%(configdir)s/release.seeds'
61         self.defaults['dev-seedfile'] = '%(configdir)s/developer.seeds'
62
63
64
65     def read_config(self):
66         '''Reads the config file into memory
67         '''
68         if "%(configdir)s" in self.defaults['config']:
69             # fix the config path
70             self.defaults['config'] = self.defaults['config'] \
71                 % {'configdir': self.defaults['configdir']}
72         defaults = self.get_defaults()
73         # remove some defaults from being entered into the configparser
74         for key in ['gpg_defaults', 'only_usable', 'refetch', 'tasks']:
75             defaults.pop(key)
76         self.configparser = ConfigParser.ConfigParser(defaults)
77         self.configparser.add_section('MAIN')
78         self.configparser.read(defaults['config'])
79
80
81     def get_key(self, key, subkey=None):
82         return self._get_(key, subkey)
83
84
85     def _get_(self, key, subkey=None):
86         if self.configparser and self.configparser.has_option('MAIN', key):
87             logger.debug("Found %s in configparser... %s"
88                 % (key, str(self.configparser.get('MAIN', key))))
89             logger.debug("type(key)= %s"
90                 % str(type(self.configparser.get('MAIN', key))))
91             return self.configparser.get('MAIN', key)
92         else:
93             return super(GKeysConfig, self)._get_(key, subkey)
94         #elif key in self.options:
95             #logger.debug("Found %s in options... %s"
96                 #% (key, str(self.options[key])))
97             #return self.options[key]
98         #elif key in self.defaults:
99             #logger.debug("type(key)= %s" %str(type(self.defaults[key])))
100             #logger.debug("Found %s in defaults... %s"
101                 #% (key, str(self.defaults[key])))
102             #logger.debug("type(key)= %s" %str(type(self.defaults[key])))
103             #return self.defaults[key]
104         #logger.error("GKeysConfig: _get_; didn't find :", key)
105         #return None
106
107
108 class GKEY(namedtuple('GKEY', ['nick', 'name', 'keyid', 'longkeyid',
109     'keyring', 'fingerprint'])):
110     '''Class to hold the relavent info about a key'''
111
112     field_types = {'nick': str, 'name': str, 'keyid': list,
113         'longkeyid': list, 'keyring': str, 'fingerprint': list}
114     field_separator = "|"
115     list_separator = ":"
116     __slots__ = ()
117
118     def _packed_values(self):
119         '''Returns a list of the field values'''
120         v = []
121         for f in self._fields:
122             v.append(self._pack(f))
123         return v
124
125     @property
126     def packed_string(self):
127         '''Returns a separator joined string of the field values'''
128         return self.field_separator.join([x for x in self._packed_values()])
129
130     def _unpack_string(self, packed_data):
131         '''Returns a list of the separator joined string of the field values'''
132         values = []
133         data = packed_data.split(self.field_separator)
134         for x in self._fields:
135             values.append(self._unpack(x, data.pop(0)))
136         return values
137
138     def _pack(self, field):
139         '''pack field data into a string'''
140         if self.field_types[field] == str:
141             return getattr(self, field)
142         elif self.field_types[field] == list:
143             info = getattr(self, field)
144             if info:
145                 return self.list_separator.join(info)
146             else:
147                 # force an empty list to None
148                 return 'None'
149         else:
150             raise "ERROR packing %s" %str(getattr(self, field))
151
152     def _unpack(self, field, data):
153         '''unpack field data to the desired type'''
154         if self.field_types[field] == str:
155             result = data
156             if result == 'None':
157                 result = None
158         else:
159             if data == 'None':
160                 # make it an empty list
161                 result = []
162             else:
163                 result = data.split(self.list_separator)
164         return result
165
166     def make_packed(self, packed_string):
167         '''Creates a new instance of Gkey from the packed
168         value string
169
170         @param packed_string: string of data separated by field_separator
171         @return new GKEY instance containing the data
172         '''
173         return GKEY._make(self._unpack_string(packed_string))