Large-scale API cleanup
[zeroinstall/zeroinstall-afb.git] / zeroinstall / cmd / config.py
bloba30f7b46529aee06d6435648f177b730973022d3
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 def s(v):
32 if int(v) == v:
33 return str(int(v))
34 else:
35 return str(v)
36 value = float(value)
37 if value < 60:
38 return s(value) + "s"
39 value /= 60
40 if value < 60:
41 return s(value) + "m"
42 value /= 60
43 if value < 24:
44 return s(value) + "h"
45 value /= 24
46 return s(value) + "d"
48 @staticmethod
49 def parse(value):
50 v = float(value[:-1])
51 unit = value[-1]
52 if unit == 's':
53 return int(v)
54 v *= 60
55 if unit == 'm':
56 return int(v)
57 v *= 60
58 if unit == 'h':
59 return int(v)
60 v *= 24
61 if unit == 'd':
62 return int(v)
63 raise SafeException(_('Unknown unit "%s" - use e.g. 5d for 5 days') % unit)
65 class Boolean:
66 @staticmethod
67 def format(value):
68 return value
70 @staticmethod
71 def parse(value):
72 if value.lower() == 'true':
73 return True
74 elif value.lower() == 'false':
75 return False
76 else:
77 raise SafeException(_('Must be True or False, not "%s"') % value)
79 settings = {
80 'network_use': String,
81 'freshness': TimeInterval,
82 'help_with_testing': Boolean,
85 def handle(config, options, args):
86 if len(args) == 0:
87 if options.gui is None and os.environ.get('DISPLAY', None):
88 options.gui = True
89 if options.gui:
90 from zeroinstall import helpers
91 return helpers.get_selections_gui(None, [])
92 else:
93 for key, setting_type in settings.iteritems():
94 value = getattr(config, key)
95 print key, "=", setting_type.format(value)
96 return
97 elif len(args) > 2:
98 raise UsageError()
100 option = args[0]
101 if option not in settings:
102 raise SafeException(_('Unknown option "%s"') % option)
104 if len(args) == 1:
105 value = getattr(config, option)
106 print settings[option].format(value)
107 else:
108 value = settings[option].parse(args[1])
109 if option == 'network_use' and value not in model.network_levels:
110 raise SafeException(_("Must be one of %s") % list(model.network_levels))
111 setattr(config, option, value)
113 config.save_globals()