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