New file seed.py, class Seeds for all seed file handling, config fixes and extend...
[gentoo-keys.git] / gkeys / seed.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3
4 '''Gentoo-keys - seed.py
5 This is gentoo-keys superclass which wraps the pyGPG lib
6 with gentoo-keys specific convienience functions.
7
8  Distributed under the terms of the GNU General Public License v2
9
10  Copyright:
11              (c) 2011 Brian Dolbec
12              Distributed under the terms of the GNU General Public License v2
13
14  Author(s):
15              Brian Dolbec <dolsen@gentoo.org>
16
17 '''
18
19 from gkeys.log import logger
20 from gkeys.config import GKEY
21
22
23 class Seeds(object):
24     '''Handles all seed key file operations'''
25
26     def __init__(self, filepath=None):
27         '''Seeds class init function
28
29         @param filepath: string of the file to load
30         '''
31         self.filename = filepath
32         self.seeds = []
33
34
35     def load(self, filename=None):
36         '''Load the seed file into memory'''
37         if filename:
38             self.filename = filename
39         if not self.filename:
40             logger.debug("Seed.load() Not a valid filename: '%s'" % str(self.filename))
41             return False
42         logger.debug("Begin loading seed file %s" % self.filename)
43         seedlines = None
44         self.seeds = []
45         try:
46             with open(self.filename) as seedfile:
47                 seedlines = seedfile.readlines()
48         except IOError as err:
49             self._error(err)
50             return False
51
52         for seed in seedlines:
53             try:
54                 parts = self._split_seed(seed)
55                 self.seeds.append(GKEY._make(parts))
56             except Exception as err:
57                 self._error(err)
58         logger.debug("Completed loading seed file %s" % self.filename)
59         return True
60
61
62     def save(self, filename=None):
63         '''Save the seeds to the file'''
64         if filename:
65             self.filename = filename
66         if not self.filename:
67             logger.debug("Seed.load() Not a valid filename: '%s'" % str(self.filename))
68             return False
69         logger.debug("Begin loading seed file %s" % self.filename)
70         try:
71             with open(self.filename, 'w') as seedfile:
72                 seedlines = [x.value_string() for x in self.seeds]
73                 seedfile.write('\n'.join(seedlines))
74                 seedfile.write("\n")
75         except IOError as err:
76             self._error(err)
77             return
78
79
80     def add(self, gkey):
81         '''Add a new seed key to memory'''
82         if isinstance(gkey, GKEY):
83             self.seeds.append(gkey)
84             return True
85         return False
86
87
88
89     def delete(self, gkey=None, index=None):
90         '''Delete the key from the seeds in memory
91
92         @param gkey: GKEY, the matching GKEY to delete
93         @param index: int, '''
94         if gkey:
95             try:
96                 self.seeds.remove(gkey)
97             except ValueError:
98                 return False
99             return True
100         elif index:
101             self.seeds.pop(index)
102             return True
103
104
105     def list(self, **kwargs):
106         '''List the key or keys matching the kwargs argument or all
107
108         @param kwargs: dict of GKEY._fields and values
109         @returns list
110         '''
111         if not kwargs:
112             return self.seeds
113         # discard any invalid keys
114         keys = set(list(kwargs)).intersection(GKEY._fields)
115         result = self.seeds[:]
116         for key in keys:
117             result = [x for x in result if getattr(x , key) == kwargs[key]]
118         return result
119
120
121     def search(self, pattern):
122         '''Search for the keys matching the regular expression pattern'''
123         pass
124
125
126     def index(self, gkey):
127         '''The index of the gkey in the seeds list
128
129         @param gkey: GKEY, the matching GKEY to delete
130         @return int
131         '''
132         try:
133             index = self.seeds.index(gkey)
134         except ValueError:
135             return None
136         return index
137
138
139     def _error(self, err):
140         '''Class error logging function'''
141         logger.error("Error processing seed file %s" % self.filename)
142         logger.error("Error was: %s" % str(err))
143
144
145     @staticmethod
146     def _split_seed(seed):
147         '''Splits the seed string and
148         replaces all occurances of 'None' with the python type None'''
149         iterable = seed.split()
150         for i in range(len(iterable)):
151             if iterable[i] == 'None':
152                 iterable[i] = None
153         return iterable
154