Made a proper Config object
[zeroinstall.git] / zeroinstall / cmd / config.py
blob3a32adc69989d6d1054b678152d646ef7f2f30ba
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, sys
9 import logging
10 import ConfigParser
12 from zeroinstall import cmd, SafeException, _
13 from zeroinstall.support import basedir
14 from zeroinstall.injector import policy, namespaces, model
15 from zeroinstall.cmd import UsageError
17 syntax = "[NAME [VALUE]]"
19 def add_options(parser):
20 pass
22 class String:
23 @staticmethod
24 def format(value):
25 return value
27 @staticmethod
28 def parse(value):
29 return value
31 class TimeInterval:
32 @staticmethod
33 def format(value):
34 value = float(value)
35 if value < 60:
36 return str(value) + "s"
37 value /= 60
38 if value < 60:
39 return str(value) + "m"
40 value /= 60
41 if value < 24:
42 return str(value) + "h"
43 value /= 24
44 return str(value) + "d"
46 @staticmethod
47 def parse(value):
48 v = float(value[:-1])
49 unit = value[-1]
50 if unit == 's':
51 return int(v)
52 v *= 60
53 if unit == 'm':
54 return int(v)
55 v *= 60
56 if unit == 'h':
57 return int(v)
58 v *= 24
59 if unit == 'd':
60 return int(v)
61 raise SafeException(_('Unknown unit "%s" - use e.g. 5d for 5 days') % unit)
63 class Boolean:
64 @staticmethod
65 def format(value):
66 return value
68 @staticmethod
69 def parse(value):
70 if value.lower() == 'true':
71 return True
72 elif value.lower() == 'false':
73 return False
74 else:
75 raise SafeException(_('Must be True or False, not "%s"') % value)
77 settings = {
78 'network_use': String,
79 'freshness': TimeInterval,
80 'help_with_testing': Boolean,
83 def handle(config, options, args):
84 if len(args) == 0:
85 if options.gui is None and os.environ.get('DISPLAY', None):
86 options.gui = True
87 if options.gui:
88 from zeroinstall import helpers
89 return helpers.get_selections_gui(None, [])
90 else:
91 for key, setting_type in settings.iteritems():
92 value = getattr(config, key)
93 print key, "=", setting_type.format(value)
94 return
95 elif len(args) > 2:
96 raise UsageError()
98 option = args[0]
99 if option not in settings:
100 raise SafeException(_('Unknown option "%s"') % option)
102 if len(args) == 1:
103 value = getattr(config, option)
104 print settings[option].format(value)
105 else:
106 value = settings[option].parse(args[1])
107 if option == 'network_use' and value not in model.network_levels:
108 raise SafeException(_("Must be one of %s") % list(model.network_levels))
109 setattr(config, option, value)
111 config.save_globals()