Updated exception handling to Python 2.6 syntax
[zeroinstall.git] / zeroinstall / cmd / __init__.py
blobd4d4841ac7a3d363c1705842884074193f7ba046
1 """
2 The B{0install} command-line interface.
3 """
5 # Copyright (C) 2011, Thomas Leonard
6 # See the README file for details, or visit http://0install.net.
8 from zeroinstall import _
9 import os, sys
10 from optparse import OptionParser
11 import logging
13 from zeroinstall import SafeException
15 valid_commands = ['select', 'download', 'run', 'update',
16 'config', 'import', 'list', 'add-feed', 'remove-feed', 'list-feeds']
18 class UsageError(Exception): pass
20 def _ensure_standard_fds():
21 "Ensure stdin, stdout and stderr FDs exist, to avoid confusion."
22 for std in (0, 1, 2):
23 try:
24 os.fstat(std)
25 except OSError:
26 fd = os.open('/dev/null', os.O_RDONLY)
27 if fd != std:
28 os.dup2(fd, std)
29 os.close(fd)
31 def _no_command(command_args):
32 """Handle --help and --version"""
33 parser = OptionParser(usage=_("usage: %prog COMMAND\n\nTry --help with one of these:") +
34 "\n\n0install " + '\n0install '.join(valid_commands))
35 parser.add_option("-V", "--version", help=_("display version information"), action='store_true')
37 (options, args) = parser.parse_args(command_args)
38 if options.version:
39 import zeroinstall
40 print "0install (zero-install) " + zeroinstall.version
41 print "Copyright (C) 2011 Thomas Leonard"
42 print _("This program comes with ABSOLUTELY NO WARRANTY,"
43 "\nto the extent permitted by law."
44 "\nYou may redistribute copies of this program"
45 "\nunder the terms of the GNU Lesser General Public License."
46 "\nFor more information about these matters, see the file named COPYING.")
47 sys.exit(0)
48 parser.print_help()
49 sys.exit(2)
51 def main(command_args, config = None):
52 """Act as if 0install was run with the given arguments.
53 @arg command_args: array of arguments (e.g. C{sys.argv[1:]})
54 @type command_args: [str]
55 """
56 _ensure_standard_fds()
58 if config is None:
59 from zeroinstall.injector.config import load_config
60 config = load_config()
62 # The first non-option argument is the command name (or "help" if none is found).
63 command = None
64 for i, arg in enumerate(command_args):
65 if not arg.startswith('-'):
66 command = arg
67 del command_args[i]
68 break
69 elif arg == '--':
70 break
72 verbose = False
73 try:
74 if command is None:
75 return _no_command(command_args)
77 if command not in valid_commands:
78 raise SafeException(_("Unknown sub-command '%s': try --help") % command)
80 # Configure a parser for the given command
81 module_name = command.replace('-', '_')
82 cmd = __import__('zeroinstall.cmd.' + module_name, globals(), locals(), [module_name], 0)
83 parser = OptionParser(usage=_("usage: %%prog %s [OPTIONS] %s") % (command, cmd.syntax))
85 parser.add_option("-c", "--console", help=_("never use GUI"), action='store_false', dest='gui')
86 parser.add_option("", "--dry-run", help=_("just print what would be executed"), action='store_true')
87 parser.add_option("-g", "--gui", help=_("show graphical policy editor"), action='store_true')
88 parser.add_option("-v", "--verbose", help=_("more verbose output"), action='count')
89 parser.add_option("", "--with-store", help=_("add an implementation cache"), action='append', metavar='DIR')
91 cmd.add_options(parser)
92 (options, args) = parser.parse_args(command_args)
94 if options.verbose:
95 logger = logging.getLogger()
96 if options.verbose == 1:
97 logger.setLevel(logging.INFO)
98 else:
99 logger.setLevel(logging.DEBUG)
100 import zeroinstall
101 logging.info(_("Running 0install %(version)s %(args)s; Python %(python_version)s"), {'version': zeroinstall.version, 'args': repr(command_args), 'python_version': sys.version})
103 if options.with_store:
104 from zeroinstall import zerostore
105 for x in options.with_store:
106 config.stores.stores.append(zerostore.Store(os.path.abspath(x)))
107 logging.info(_("Stores search path is now %s"), config.stores.stores)
109 config.handler.dry_run = bool(options.dry_run)
111 cmd.handle(config, options, args)
112 except UsageError:
113 parser.print_help()
114 sys.exit(1)
115 except SafeException as ex:
116 if verbose: raise
117 try:
118 print >>sys.stderr, unicode(ex)
119 except:
120 print >>sys.stderr, repr(ex)
121 sys.exit(1)
122 return