pyflakes
[zeroinstall.git] / zeroinstall / cmd / config.py
blobd2259a9bd664792dc5a83428eb108e8635f62e12
1 """
2 The B{0install config} command-line interface.
3 """
5 # Copyright (C) 2011, Thomas Leonard
6 # See the README file for details, or visit http://0install.net.
8 import os
10 from zeroinstall import SafeException, _
11 from zeroinstall.injector import model
12 from zeroinstall.cmd import UsageError
14 syntax = "[NAME [VALUE]]"
16 def add_options(parser):
17 pass
19 class String:
20 @staticmethod
21 def format(value):
22 return value
24 @staticmethod
25 def parse(value):
26 return value
28 class TimeInterval:
29 @staticmethod
30 def format(value):
31 value = float(value)
32 if value < 60:
33 return str(value) + "s"
34 value /= 60
35 if value < 60:
36 return str(value) + "m"
37 value /= 60
38 if value < 24:
39 return str(value) + "h"
40 value /= 24
41 return str(value) + "d"
43 @staticmethod
44 def parse(value):
45 v = float(value[:-1])
46 unit = value[-1]
47 if unit == 's':
48 return int(v)
49 v *= 60
50 if unit == 'm':
51 return int(v)
52 v *= 60
53 if unit == 'h':
54 return int(v)
55 v *= 24
56 if unit == 'd':
57 return int(v)
58 raise SafeException(_('Unknown unit "%s" - use e.g. 5d for 5 days') % unit)
60 class Boolean:
61 @staticmethod
62 def format(value):
63 return value
65 @staticmethod
66 def parse(value):
67 if value.lower() == 'true':
68 return True
69 elif value.lower() == 'false':
70 return False
71 else:
72 raise SafeException(_('Must be True or False, not "%s"') % value)
74 settings = {
75 'network_use': String,
76 'freshness': TimeInterval,
77 'help_with_testing': Boolean,
80 def handle(config, options, args):
81 if len(args) == 0:
82 if options.gui is None and os.environ.get('DISPLAY', None):
83 options.gui = True
84 if options.gui:
85 from zeroinstall import helpers
86 return helpers.get_selections_gui(None, [])
87 else:
88 for key, setting_type in settings.iteritems():
89 value = getattr(config, key)
90 print key, "=", setting_type.format(value)
91 return
92 elif len(args) > 2:
93 raise UsageError()
95 option = args[0]
96 if option not in settings:
97 raise SafeException(_('Unknown option "%s"') % option)
99 if len(args) == 1:
100 value = getattr(config, option)
101 print settings[option].format(value)
102 else:
103 value = settings[option].parse(args[1])
104 if option == 'network_use' and value not in model.network_levels:
105 raise SafeException(_("Must be one of %s") % list(model.network_levels))
106 setattr(config, option, value)
108 config.save_globals()