Cope better if no GUI is available
[zeroinstall.git] / zeroinstall / cmd / config.py
blob40ab988b9c043d4cfc597264a87faf441d261979
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 from __future__ import print_function
10 import os
12 from zeroinstall import SafeException, _
13 from zeroinstall.injector import model
14 from zeroinstall.cmd import UsageError
16 syntax = "[NAME [VALUE]]"
18 def add_options(parser):
19 pass
21 class String:
22 @staticmethod
23 def format(value):
24 return value
26 @staticmethod
27 def parse(value):
28 return value
30 class TimeInterval:
31 @staticmethod
32 def format(value):
33 def s(v):
34 if int(v) == v:
35 return str(int(v))
36 else:
37 return str(v)
38 value = float(value)
39 if value < 60:
40 return s(value) + "s"
41 value /= 60
42 if value < 60:
43 return s(value) + "m"
44 value /= 60
45 if value < 24:
46 return s(value) + "h"
47 value /= 24
48 return s(value) + "d"
50 @staticmethod
51 def parse(value):
52 v = float(value[:-1])
53 unit = value[-1]
54 if unit == 's':
55 return int(v)
56 v *= 60
57 if unit == 'm':
58 return int(v)
59 v *= 60
60 if unit == 'h':
61 return int(v)
62 v *= 24
63 if unit == 'd':
64 return int(v)
65 raise SafeException(_('Unknown unit "%s" - use e.g. 5d for 5 days') % unit)
67 class Boolean:
68 @staticmethod
69 def format(value):
70 return value
72 @staticmethod
73 def parse(value):
74 if value.lower() == 'true':
75 return True
76 elif value.lower() == 'false':
77 return False
78 else:
79 raise SafeException(_('Must be True or False, not "%s"') % value)
81 settings = {
82 'network_use': String,
83 'freshness': TimeInterval,
84 'help_with_testing': Boolean,
85 'auto_approve_keys': Boolean,
88 def handle(config, options, args):
89 if len(args) == 0:
90 from zeroinstall import helpers
91 if helpers.get_selections_gui(None, [], use_gui = options.gui) == helpers.DontUseGUI:
92 for key, setting_type in settings.items():
93 value = getattr(config, key)
94 print(key, "=", setting_type.format(value))
95 # (else we displayed the preferences dialog in the GUI)
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()