d3d0786d196494f8a375480aace4ba5d1f6c52b0
[gentoo-keys.git] / gkeys / cli.py
1 #
2 #-*- coding:utf-8 -*-
3
4 """
5     Gentoo-keys - cli.py
6
7     Command line interface module
8
9     @copyright: 2012 by Brian Dolbec <dol-sen@gentoo.org>
10     @license: GNU GPL2, see COPYING for details.
11 """
12
13 from __future__ import print_function
14
15
16 import argparse
17 import sys
18
19 from gkeys.log import logger
20 from gkeys.config import GKeysConfig, GKEY
21 from gkeys.seed import Seeds
22
23
24 # set debug level to max
25 logger.setLevel(1)
26
27
28 class Main(object):
29     '''Main command line interface class'''
30
31
32     def __init__(self, root=None, config=None, print_results=True):
33         """ Main class init function.
34
35         @param root: string, root path to use
36         """
37         self.root = root or "/"
38         self.config = config or GKeysConfig(root=root)
39         self.print_results = print_results
40         self.args = None
41
42
43     def __call__(self, args=None):
44         logger.debug("Main:__call__()")
45         if args:
46             self.run(self.parse_args(args))
47         else:
48             self.run(self.parse_args(sys.argv[1:]))
49
50
51     def parse_args(self, args):
52         '''Parse a list of aruments
53
54         @param args: list
55         @returns argparse.Namespace object
56         '''
57         logger.debug('args: %s' % args)
58         actions = ['listseed', 'addseed', 'removeseed', 'moveseed', 'listkey',
59             'addkey', 'removekey', 'movekey']
60         parser = argparse.ArgumentParser(
61             prog='gkeys',
62             description='Gentoo-keys manager program',
63             epilog='''Caution: adding untrusted keys to these keyrings can
64                 be hazardous to your system!''')
65         # actions
66         parser.add_argument('action', choices=actions, nargs='?',
67             default='listseeds', help='Add to seed file or keyring')
68         # options
69         parser.add_argument('-c', '--config', dest='config', default=None,
70             help='The path to an alternate config file')
71         parser.add_argument('-d', '--dest', dest='destination', default=None,
72             help='The destination seed file or keyring for move, copy operations')
73         parser.add_argument('-f', '--fingerprint', dest='fingerprint', default=None,
74             help='The fingerprint of the the key')
75         parser.add_argument('-n', '--name', dest='name', default=None,
76             help='The name of the the key')
77         parser.add_argument('-k', '--keyid', dest='keyid', default=None,
78             help='The keyid of the the key')
79         parser.add_argument('-l', '--longkeyid', dest='longkeyid', default=None,
80             help='The longkeyid of the the key')
81         parser.add_argument('-r', '--keyring',
82             choices=['release', 'dev', 'overlays'], dest='keyring', default=None,
83             help='The keyring to use or update')
84         parser.add_argument('-s', '--seeds',
85             choices=['release', 'dev'], dest='seeds', default=None,
86             help='The seeds file to use or update')
87         parser.add_argument('-S', '--seedfile', dest='seedfile', default=None,
88             help='The seedfile path to use')
89
90         return parser.parse_args(args)
91
92
93     def run(self, args):
94         '''Run the args passed in
95
96         @param args: list or argparse.Namespace object
97         '''
98         if not args:
99             logger.error("Main.run() invalid args argument passed in")
100         if isinstance(args, list):
101             args = self.parse_args(args)
102         if args.config:
103             logger.debug("Found alternate config request: %s" % args.config)
104             self.config.defaults['config'] = args.config
105         # now make it load the config file
106         self.config.read_config()
107
108         func = getattr(self, '_action_%s' % args.action)
109         logger.debug('Found action: %s' % args.action)
110         results = func(args)
111         # super simple output for the time being
112         if self.print_results:
113             print('\n\nGkey results:')
114             print("\n".join([str(x) for x in results]))
115             print()
116
117
118     @staticmethod
119     def build_gkeydict(args):
120         keyinfo = {}
121         for x in GKEY._fields:
122             try:
123                 value = getattr(args, x)
124                 if value:
125                     keyinfo[x] = value
126             except AttributeError:
127                 pass
128         return keyinfo
129
130
131     @staticmethod
132     def build_gkeylist(args):
133         keyinfo = []
134         for x in GKEY._fields:
135             try:
136                 keyinfo.append(getattr(args, x))
137             except AttributeError:
138                 keyinfo.append(None)
139         return keyinfo
140
141
142     def _load_seeds(self, filename):
143         filepath = self.config.get_key(filename + "-seedfile")
144         logger.debug("_load_seeds(); seeds filepath to load: "
145             "%s" % filepath)
146         seeds = Seeds()
147         seeds.load(filepath)
148         return seeds
149
150
151     def _action_listseed(self, args):
152         '''Action listseed method'''
153         kwargs = self.build_gkeydict(args)
154         logger.debug("_action_listseed(); kwargs: %s" % str(kwargs))
155         seeds = self._load_seeds(args.seeds)
156         results = seeds.list(**kwargs)
157         return results
158
159
160     def _action_addseed(self, args):
161         '''Action addseed method'''
162         parts = self.build_gkeylist(args)
163         gkey = GKEY._make(parts)
164         logger.debug("_action_addseed(); new gkey: %s" % str(gkey))
165         seeds = self._load_seeds(args.seeds)
166         gkeys = self._action_listseed(args)
167         if len(gkeys) == 0:
168             logger.debug("_action_addkey(); now adding gkey: %s" % str(gkey))
169             success = seeds.add(gkey)
170             if success:
171                 success = seeds.save()
172                 return ["Successfully Added new seed: %s" % str(success), gkey]
173         else:
174             messages = ["Matching seeds found in seeds file",
175                 "Aborting... \nMatching seeds:"]
176             messages.extend(gkeys)
177             return messages
178
179
180     def _action_removeseed(self, args):
181         '''Action removeseed method'''
182         parts = self.build_gkeylist(args)
183         searchkey = GKEY._make(parts)
184         logger.debug("_action_removeseed(); gkey: %s" % str(searchkey))
185         seeds = self._load_seeds(args.seeds)
186         gkeys = self._action_listseed(args)
187         if len(gkeys) == 1:
188             logger.debug("_action_removeseed(); now deleting gkey: %s" % str(gkeys[0]))
189             success = seeds.delete(gkeys[0])
190             if success:
191                 success = seeds.save()
192             return ["Successfully Removed seed: %s" % str(success),
193                 gkeys[0]]
194         elif len(gkeys):
195             messages = ["Too many seeds found to remove"]
196             messages.extend(gkeys)
197             return messages
198         return ["Failed to Remove seed:", searchkey,
199             "No matching seed found"]
200
201
202     def _action_moveseed(self, args):
203         '''Action moveseed method'''
204         parts = self.build_gkeylist(args)
205         searchkey = GKEY._make(parts)
206         logger.debug("_action_moveseed(); gkey: %s" % str(searchkey))
207         seeds = self._load_seeds(args.seeds)
208         kwargs = self.build_gkeydict(args)
209         sourcekeys = seeds.list(**kwargs)
210         dest = self._load_seeds(args.destination)
211         destkeys = dest.list(**kwargs)
212         messages = []
213         if len(sourcekeys) == 1 and destkeys == []:
214             logger.debug("_action_moveseed(); now adding destination gkey: %s"
215                 % str(sourcekeys[0]))
216             success = dest.add(sourcekeys[0])
217             logger.debug("_action_moveseed(); success: %s" %str(success))
218             logger.debug("_action_moveseed(); now deleting sourcekey: %s" % str(sourcekeys[0]))
219             success = seeds.delete(sourcekeys[0])
220             if success:
221                 success = dest.save()
222                 logger.debug("_action_moveseed(); destination saved... %s" %str(success))
223                 success = seeds.save()
224             messages.extend(["Successfully Moved %s seed: %s"
225                 % (args.seeds, str(success)), sourcekeys[0]])
226             return messages
227         elif len(sourcekeys):
228             messages = ["Too many seeds found to remove"]
229             messages.extend(sourcekeys)
230             return messages
231         messages.append("Failed to Move seed:")
232         messages.append(searchkey)
233         messages.append('\n')
234         messages.append("Source seeds found...")
235         messages.extend(sourcekeys or ["None\n"])
236         messages.append("Destination seeds found...")
237         messages.extend(destkeys or ["None\n"])
238         return messages
239
240
241     def _action_listkey(self, args):
242         '''Action listskey method'''
243         pass
244
245
246     def _action_addkey(self, args):
247         '''Action addkey method'''
248         pass
249
250
251     def _action_removekey(self, args):
252         '''Action removekey method'''
253         pass
254
255
256     def _action_movekey(self, args):
257         '''Action movekey method'''
258         pass
259
260
261
262
263
264