Add a configured separator for the in file seed info.
[gentoo-keys.git] / gkeys / seed.py
1 #
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     separator = '|'
27
28     def __init__(self, filepath=None):
29         '''Seeds class init function
30
31         @param filepath: string of the file to load
32         '''
33         self.filename = filepath
34         self.seeds = []
35
36
37     def load(self, filename=None):
38         '''Load the seed file into memory'''
39         if filename:
40             self.filename = filename
41         if not self.filename:
42             logger.debug("Seed.load() Not a valid filename: '%s'" % str(self.filename))
43             return False
44         logger.debug("Seeds: Begin loading seed file %s" % self.filename)
45         seedlines = None
46         self.seeds = []
47         try:
48             with open(self.filename) as seedfile:
49                 seedlines = seedfile.readlines()
50         except IOError as err:
51             self._error(err)
52             return False
53
54         for seed in seedlines:
55             try:
56                 parts = self._split_seed(seed)
57                 self.seeds.append(GKEY._make(parts))
58             except Exception as err:
59                 self._error(err)
60         logger.debug("Completed loading seed file %s" % self.filename)
61         return True
62
63
64     def save(self, filename=None):
65         '''Save the seeds to the file'''
66         if filename:
67             self.filename = filename
68         if not self.filename:
69             logger.debug("Seed.load() Not a valid filename: '%s'" % str(self.filename))
70             return False
71         logger.debug("Begin saving seed file %s" % self.filename)
72         try:
73             with open(self.filename, 'w') as seedfile:
74                 seedlines = [x.value_string(self.separator) for x in self.seeds]
75                 seedfile.write('\n'.join(seedlines))
76                 seedfile.write("\n")
77         except IOError as err:
78             self._error(err)
79             return False
80         return True
81
82
83     def add(self, gkey):
84         '''Add a new seed key to memory'''
85         if isinstance(gkey, GKEY):
86             self.seeds.append(gkey)
87             return True
88         return False
89
90
91
92     def delete(self, gkey=None, index=None):
93         '''Delete the key from the seeds in memory
94
95         @param gkey: GKEY, the matching GKEY to delete
96         @param index: int, '''
97         if gkey:
98             try:
99                 self.seeds.remove(gkey)
100             except ValueError:
101                 return False
102             return True
103         elif index:
104             self.seeds.pop(index)
105             return True
106
107
108     def list(self, **kwargs):
109         '''List the key or keys matching the kwargs argument or all
110
111         @param kwargs: dict of GKEY._fields and values
112         @returns list
113         '''
114         if not kwargs:
115             return self.seeds
116         # discard any invalid keys
117         keys = set(list(kwargs)).intersection(GKEY._fields)
118         result = self.seeds[:]
119         for key in keys:
120             result = [x for x in result if getattr(x , key) == kwargs[key]]
121         return result
122
123
124     def search(self, pattern):
125         '''Search for the keys matching the regular expression pattern'''
126         pass
127
128
129     def index(self, gkey):
130         '''The index of the gkey in the seeds list
131
132         @param gkey: GKEY, the matching GKEY to delete
133         @return int
134         '''
135         try:
136             index = self.seeds.index(gkey)
137         except ValueError:
138             return None
139         return index
140
141
142     def _error(self, err):
143         '''Class error logging function'''
144         logger.error("Error processing seed file %s" % self.filename)
145         logger.error("Error was: %s" % str(err))
146
147
148     @staticmethod
149     def _split_seed(seed):
150         '''Splits the seed string and
151         replaces all occurances of 'None' with the python type None'''
152         iterable = seed.split(self.separator)
153         for i in range(len(iterable)):
154             if iterable[i] == 'None':
155                 iterable[i] = None
156         return iterable
157