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