Added '0install config' sub-command
[zeroinstall/zeroinstall-afb.git] / zeroinstall / cmd / config.py
blob95a1e61715b7d752fac96f86c55be8d5ee8e7088
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 def handle(options, args):
23 config = policy.load_config()
24 if len(args) == 0:
25 if options.gui is None and os.environ.get('DISPLAY', None):
26 options.gui = True
27 if options.gui:
28 from zeroinstall import helpers
29 return helpers.get_selections_gui(None, [])
30 else:
31 config.write(sys.stdout)
32 return
33 elif len(args) > 2:
34 raise UsageError()
36 if '.' not in args[0]:
37 raise SafeException(_('Missing section name in "%s" (e.g. try "global.freshness")') % args[0])
38 section, option = args[0].split('.', 1)
40 if len(args) == 1:
41 try:
42 print config.get(section, option)
43 except ConfigParser.NoOptionError, ex:
44 raise SafeException(str(ex))
45 except ConfigParser.NoSectionError, ex:
46 raise SafeException(str(ex))
47 else:
48 if section != 'global':
49 raise SafeException(_('Unknown section "%s" (try "global")' % section))
51 value = args[1]
52 if option == 'freshness':
53 int(value)
54 elif option == 'help_with_testing':
55 if value.lower() == 'true':
56 value = 'True'
57 elif value.lower() == 'false':
58 value = 'False'
59 else:
60 raise SafeException(_('Must be True or False, not "%s"') % value)
61 elif option == 'network_use':
62 if value not in model.network_levels:
63 raise SafeException(_("Must be one of %s") % list(model.network_levels))
64 else:
65 raise SafeException(_('Unknown option "%s"') % option)
67 config.set(section, option, value)
68 path = basedir.save_config_path(namespaces.config_site, namespaces.config_prog)
69 path = os.path.join(path, 'global')
70 config.write(file(path + '.new', 'w'))
71 os.rename(path + '.new', path)