fix missed copy/paste edit.
[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("Seeds: 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 saving 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 False
78         return True
79
80
81     def add(self, gkey):
82         '''Add a new seed key to memory'''
83         if isinstance(gkey, GKEY):
84             self.seeds.append(gkey)
85             return True
86         return False
87
88
89
90     def delete(self, gkey=None, index=None):
91         '''Delete the key from the seeds in memory
92
93         @param gkey: GKEY, the matching GKEY to delete
94         @param index: int, '''
95         if gkey:
96             try:
97                 self.seeds.remove(gkey)
98             except ValueError:
99                 return False
100             return True
101         elif index:
102             self.seeds.pop(index)
103             return True
104
105
106     def list(self, **kwargs):
107         '''List the key or keys matching the kwargs argument or all
108
109         @param kwargs: dict of GKEY._fields and values
110         @returns list
111         '''
112         if not kwargs:
113             return self.seeds
114         # discard any invalid keys
115         keys = set(list(kwargs)).intersection(GKEY._fields)
116         result = self.seeds[:]
117         for key in keys:
118             result = [x for x in result if getattr(x , key) == kwargs[key]]
119         return result
120
121
122     def search(self, pattern):
123         '''Search for the keys matching the regular expression pattern'''
124         pass
125
126
127     def index(self, gkey):
128         '''The index of the gkey in the seeds list
129
130         @param gkey: GKEY, the matching GKEY to delete
131         @return int
132         '''
133         try:
134             index = self.seeds.index(gkey)
135         except ValueError:
136             return None
137         return index
138
139
140     def _error(self, err):
141         '''Class error logging function'''
142         logger.error("Error processing seed file %s" % self.filename)
143         logger.error("Error was: %s" % str(err))
144
145
146     @staticmethod
147     def _split_seed(seed):
148         '''Splits the seed string and
149         replaces all occurances of 'None' with the python type None'''
150         iterable = seed.split()
151         for i in range(len(iterable)):
152             if iterable[i] == 'None':
153                 iterable[i] = None
154         return iterable
155