aboutsummaryrefslogtreecommitdiff
blob: 4c1e946b3625bc4e25ca09c5b10e4b9bcc203f62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#
#-*- coding:utf-8 -*-

"""
    Gentoo-keys - cli.py

    Command line interface module

    @copyright: 2012 by Brian Dolbec <dol-sen@gentoo.org>
    @license: GNU GPL2, see COPYING for details.
"""

from __future__ import print_function


import argparse
import sys

from gkeys import config, fileops, seed, lib
from gkeys.actions import Actions, Available_Actions, Action_Options
from gkeys.config import GKeysConfig
from gkeys.log import log_levels, set_logger



class Main(object):
    '''Main command line interface class'''


    def __init__(self, root=None, config=None, print_results=True):
        """ Main class init function.

        @param root: string, root path to use
        """
        self.root = root or "/"
        self.config = config or GKeysConfig(root=root)
        self.config.options['print_results'] = print_results
        self.args = None
        self.seeds = None
        self.actions = None


    def __call__(self, args=None):
        if args:
            return self.run(self.parse_args(args))
        else:
            return self.run(self.parse_args(sys.argv[1:]))


    def _add_options(self, parser, options):
        for opt in options:
            getattr(self, '_option_%s' % opt)(parser)

    @staticmethod
    def _option_dest(parser=None):
        parser.add_argument('-d', '--dest', dest='destination', default=None,
            help='The destination seed file or keydir for move, copy operations')

    @staticmethod
    def _option_fingerprint(parser=None):
        parser.add_argument('-f', '--fingerprint', dest='fingerprint',
            default=None, nargs='+',
            help='The fingerprint of the the key')

    @staticmethod
    def _option_gpgsearch(parser=None):
        parser.add_argument('-g', '--gpgsearch', dest='gpgsearch', default=None,
            help='Do a gpg search operations, rather than a gkey search')

    @staticmethod
    def _option_keyid(parser=None):
        parser.add_argument('-i', '--keyid', dest='keyid', default=None,
            nargs='+',
            help='The long keyid of the gpg key to search for')

    @staticmethod
    def _option_keyring(parser=None):
        parser.add_argument('-k', '--keyring', dest='keyring', default='trusted_keyring',
            help='The name of the keyring to use')

    @staticmethod
    def _option_nick(parser=None):
        parser.add_argument('-n', '--nick', dest='nick', default=None,
            help='The nick associated with the the key')

    @staticmethod
    def _option_name(parser=None):
        parser.add_argument('-N', '--name', dest='name', nargs='*',
            default=None, help='The name of the the key')

    @staticmethod
    def _option_category(parser=None):
        parser.add_argument('-C', '--category',
            choices=['rel', 'dev', 'overlays', 'sign'], dest='category', default=None,
            help='The key or seed directory category to use or update')

    @staticmethod
    def _option_keydir(parser=None):
        parser.add_argument('-r', '--keydir', dest='keydir', default=None,
            help='The keydir to use, update or search for/in')

    @staticmethod
    def _option_seedfile(parser=None):
        parser.add_argument('-S', '--seedfile', dest='seedfile', default=None,
            help='The seedfile to use from the gkeys.conf file')

    @staticmethod
    def _option_file(parser=None):
        parser.add_argument('-F', '--file', dest='filename', default=None,
            nargs='+',
            help='The path/URL to use for the (signed) file')

    @staticmethod
    def _option_signature(parser=None):
        parser.add_argument('-s','--signature', dest='signature', default=None,
           help='The path/URL to use for the signature')

    @staticmethod
    def _option_timestamp(parser=None):
        parser.add_argument('-t', '--timestamp', dest='timestamp', type=bool,
            default=False,
            help='Turn on timestamp use')


    def parse_args(self, args):
        '''Parse a list of aruments

        @param args: list
        @returns argparse.Namespace object
        '''
        #logger.debug('MAIN: parse_args; args: %s' % args)
        parser = argparse.ArgumentParser(
            prog='gkeys',
            description='Gentoo-keys manager program',
            epilog='''Caution: adding untrusted keys to these keyrings can
                be hazardous to your system!''')

        # options
        parser.add_argument('-c', '--config', dest='config', default=None,
            help='The path to an alternate config file')
        parser.add_argument('-D', '--debug', default='DEBUG',
            choices=list(log_levels),
            help='The logging level to set for the logfile')


        subparsers = parser.add_subparsers(help='actions')
        for name in Available_Actions:
            action_method = getattr(Actions, name)
            actiondoc = action_method.__doc__
            try:
                text = actiondoc.splitlines()[0]
            except AttributeError:
                text = ""
            action_parser = subparsers.add_parser(
                name,
                help=text,
                description=actiondoc,
                formatter_class=argparse.RawDescriptionHelpFormatter)
            action_parser.set_defaults(action=name)
            self._add_options(action_parser, Action_Options[name])

        return parser.parse_args(args)


    def run(self, args):
        '''Run the args passed in

        @param args: list or argparse.Namespace object
        '''
        global logger
        message = None
        if not args:
            message = "Main: run; invalid args argument passed in"
        if isinstance(args, list):
            args = self.parse_args(args)
        if args.config:
            self.config.defaults['config'] = args.config
        # now make it load the config file
        self.config.read_config()

        # establish our logger and update it in the imported files
        logger = set_logger('gkeys', self.config['logdir'], args.debug,
            dirmode=int(self.config.get_key('permissions', 'directories'),0),
            filemask=int(self.config.get_key('permissions', 'files'),0))
        config.logger = logger
        fileops.logger = logger
        seed.logger = logger
        lib.logger = logger

        if message:
            logger.error(message)

        # now that we have a logger, record the alternate config setting
        if args.config:
            logger.debug("Main: run; Found alternate config request: %s"
                % args.config)

        # establish our actions instance
        self.actions = Actions(self.config, self.output_results, logger)

        # run the action
        func = getattr(self.actions, '%s' % args.action)
        logger.debug('Main: run; Found action: %s' % args.action)
        success, results = func(args)
        if not results:
            print("No results found.  Check your configuration and that the",
                "seed file exists.")
            return success
        if self.config.options['print_results'] and 'done' not in list(results):
            self.output_results(results, '\n Gkey task results:')
        return success


    @staticmethod
    def output_results(results, header):
        # super simple output for the time being
        if header:
            print(header)
        for msg in results:
            if isinstance(msg, str):
                print('    ', msg)
            else:
                try:
                    print("\n".join([x.pretty_print for x in msg]))
                except AttributeError:
                    for x in msg:
                        print('    ', x)


    def output_failed(self, failed):
        pass