config.py 9.28 KB
Newer Older
André Anjos's avatar
André Anjos committed
1
2
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
André Anjos's avatar
André Anjos committed
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318

###############################################################################
#                                                                             #
# Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/           #
# Contact: beat.support@idiap.ch                                              #
#                                                                             #
# This file is part of the beat.cmdline module of the BEAT platform.          #
#                                                                             #
# Commercial License Usage                                                    #
# Licensees holding valid commercial BEAT licenses may use this file in       #
# accordance with the terms contained in a written agreement between you      #
# and Idiap. For further information contact tto@idiap.ch                     #
#                                                                             #
# Alternatively, this file may be used under the terms of the GNU Affero      #
# Public License version 3 as published by the Free Software and appearing    #
# in the file LICENSE.AGPL included in the packaging of this file.            #
# The BEAT platform is distributed in the hope that it will be useful, but    #
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY  #
# or FITNESS FOR A PARTICULAR PURPOSE.                                        #
#                                                                             #
# You should have received a copy of the GNU Affero Public License along      #
# with the BEAT platform. If not, see http://www.gnu.org/licenses/.           #
#                                                                             #
###############################################################################


"""Configuration manipulation and display

Usage:
  %(prog)s config save
  %(prog)s config list
  %(prog)s config set (<key> <value>)...
  %(prog)s config get <key>...
  %(prog)s config color [--list] [<theme>]
  %(prog)s config --help


Commands:
  save   Saves the commandline configuration to your prefix
  list   Lists the configuration after resolving defaults and saved variables
  set    Sets a specific known field to a value (or reset it, if no value given)
  get    Prints out the contents of a single field
  color  Sets the color theme (or reset it, if a theme is not given)


Options:
  -h, --help  Display this screen
  -l, --list  Lists all possible color themes


Examples:

  To list all available configuration parameters:

    $ %(prog)s config list

  To save a different user name token to a file and save results locally
  (notice you can pass multiple parameters at once using key-value pairs):

    $ %(prog)s config set user "me" token "1234567890abcdef1234567890abcde"

  To query for a specific parameter:

    $ %(prog)s config get token
    1234567890abcdef1234567890abcde

  To change the color schemes to a ``dark`` theme and save results locally:

    $ %(prog)s config color dark

  To list all possible color schemes:

    $ %(prog)s config color --list
"""


import os
import sys
import copy
import logging
logger = logging.getLogger(__name__)

import simplejson
import termcolor


DEFAULTS = {
    'platform': 'https://www.beat-eu.org/platform/',
    'user': None,
    'token': None,
    'cache': 'cache', #relative path to <prefix>
}

COLOR_THEMES = {

  'none': {
    'color_critical': '',
    'color_error': '',
    'color_warn': '',
    'color_info': '',
    'color_debug': '',
    },

  'dark': {
    'color_critical': 'bold_red',
    'color_error': 'fg_red',
    'color_warn': 'bold_yellow',
    'color_info': 'fg_green',
    'color_debug': 'fg_white',
    },

  'light': {
    'color_critical': 'bold_red',
    'color_error': 'fg_red',
    'color_warn': 'bold_blue',
    'color_info': 'fg_green',
    'color_debug': 'fg_grey',
    },

  }

DEFAULTS.update(COLOR_THEMES['none'])

DOC = {
    'platform': 'Web address of the BEAT platform',
    'user': 'User name for operations that create, delete or edit objects',
    'token': 'Secret key of the user on the BEAT platform',
    'cache': 'Path to the directory to use for data caching',
    'color_critical': 'Color of critical messages in the terminal',
    'color_error': 'Color of error messages in the terminal',
    'color_warn': 'Color of warning messages in the terminal',
    'color_info': 'Color of informational messages in the terminal',
    'color_debug': 'Color of debug messages in the terminal',
}


def colorlog_to_termcolor(color):
  '''Returns the termcolor configuration tuple (color, on_color, attrs)'''

  info = [t for t in color.split(',') if t.strip()]
  color = None
  on_color = None
  attrs = []
  for i in info:
    c = i.split('_')
    if c[0] in ('bold', 'fg'): # text color
      color = c[1]
      if c[0] == 'bold': attrs.append('bold')
    if c[0] in ('bg'): # background color
      on_color = 'on_%s' % c[1]

  return color, on_color, attrs


class Configuration(object):
  '''Keeps track of configuration elements'''

  def __init__(self, args):

    self.path = args.get('--prefix', '.')
    self.load() #loads defaults and local configuration, if one exists

    #overwrites preferences, if the user has set any
    self.__data['cache'] = args.get('--cache') or self.__data['cache']
    self.__data['platform'] = args.get('--platform') or self.__data['platform']
    self.__data['user'] = args.get('--user') or self.__data['user']
    self.__data['token'] = args.get('--token') or self.__data['token']

    if args.get('--color'):
      if args['--color'] not in COLOR_THEMES:
        print("ERROR: color theme must be one of `%s' - `%s' is invalid" % \
                (','.join(COLOR_THEMES.keys()), args['--color']))
        sys.exit(1)
      self.__data.update(COLOR_THEMES[args['--color']])


  def __config_file(self):
    return os.path.join(self.path, '.beat', 'config.json')


  def load(self):
    '''Loads contents from file'''

    self.__data = copy.deepcopy(DEFAULTS)

    try:

      c = self.__config_file()
      if not os.path.exists(c): return
      with open(c, 'rt') as f:
        user_data = simplejson.load(f)
        for k in DEFAULTS:
          if k in user_data: self.__data[k] = user_data[k]

    except simplejson.JSONDecodeError:
      print("WARNING: invalid state file at `%s' - removing and " \
              "re-starting..." % c)
      from beat.core.utils import safe_rmfile
      safe_rmfile(c)


  @property
  def cache(self):
    '''The directory for the cache'''

    if not os.path.isabs(self.__data['cache']):
      return os.path.join(self.path, self.__data['cache'])
    return self.__data['cache']


  def set(self, key, value):
    '''Sets or resets a field in the configuration'''

    if key not in DEFAULTS:
      print("ERROR: don't know about parameter `%s'" % key)
      sys.exit(1)

    if value is not None:
      self.__data[key] = value
    else:
      self.__data[key] = DEFAULTS[key]

    self.save()


  def color(self, value):
    '''Sets the color theme'''

    if value is None:
      value = 'none'

    elif value not in COLOR_THEMES:
      print("ERROR: color theme must be one of `%s' - `%s' is invalid" % \
              (','.join(COLOR_THEMES.keys()), value))
      sys.exit(1)

    self.__data.update(COLOR_THEMES[value])
    self.save()


  def save(self):
    '''Saves contents to file'''

    c = self.__config_file()
    dirname = os.path.dirname(c)
    if not os.path.exists(dirname): os.makedirs(dirname)
    with os.fdopen(os.open(c, os.O_WRONLY | os.O_CREAT, 0600), 'wt') as f:
      simplejson.dump(self.__data, f, indent=4)


  def __str__(self):

    retval = []

    c = self.__config_file()
    if os.path.exists(c):
      retval.append("-> loaded configuration file `%s'" % c)
    else:
      retval.append("-> configuration file `%s' does *not* exist" % c)

    for key in sorted([k for k in DOC if not k.startswith('color')]):
      value = self.__data[key]
      value = "`%s'" % value if value is not None else '<unset>'
      retval.append(" * %-15s: %s" % (key, value))
    for key in sorted([k for k in DOC if k.startswith('color')]):
      value = self.__data[key]
      color, on_color, attrs = colorlog_to_termcolor(value)
      example = termcolor.colored('example', color, on_color, attrs)
      retval.append(" * %-15s: `%s' (%s)" % (key, value, example))

    return '\n'.join(retval)


  def __getattr__(self, key):

    return self.__data[key]


def process(args):

  # Must display the list of options?
  if args['save']:
    args['config'].save()
    return 0

  elif args['list']:
    print args['config']
    return 0

  elif args['set']:
    for k,v in zip(args['<key>'], args['<value>']):
      args['config'].set(k, v)
    return 0

  elif args['get']:
    for k in args['<key>']: print(getattr(args['config'], k))
    return 0

  elif args['color']:

    if args['--list']:
      for k in COLOR_THEMES:
        print("`%s' theme:" % k)
        for par in COLOR_THEMES[k]:
          value = COLOR_THEMES[k][par]
          color, on_color, attrs = colorlog_to_termcolor(value)
          example = termcolor.colored('example', color, on_color, attrs)
          print(" * %-15s: `%s' (%s)" % (par, value, example))
      return 0

    args['config'].color(args['<theme>'])
    return 0

  # Should not happen
  logger.error("unrecognized `config' subcommand")
  return 1