Preserve stack-traces when re-throwing errors
[zeroinstall.git] / 0store
blob47faee364734152126897b6ca2bd182891732feb
1 #!/usr/bin/env python
3 from __future__ import print_function
5 import locale
6 from logging import warn
7 try:
8 locale.setlocale(locale.LC_ALL, '')
9 except locale.Error:
10 warn('Error setting locale (eg. Invalid locale)')
12 import os, sys
14 ## PATH ##
16 from optparse import OptionParser
17 import logging
18 from zeroinstall import SafeException
20 from zeroinstall.zerostore import cli, BadDigest
22 parser = OptionParser(usage="usage: %prog " +
23 '\n %prog '.join([c.__doc__ for c in cli.commands]))
24 parser.add_option("-v", "--verbose", help="more verbose output", action='count')
25 parser.add_option("-V", "--version", help="display version information", action='store_true')
26 parser.disable_interspersed_args()
28 (options, args) = parser.parse_args()
30 if options.verbose:
31 logger = logging.getLogger()
32 if options.verbose == 1:
33 logger.setLevel(logging.INFO)
34 else:
35 logger.setLevel(logging.DEBUG)
36 hdlr = logging.StreamHandler()
37 fmt = logging.Formatter("%(levelname)s:%(message)s")
38 hdlr.setFormatter(fmt)
39 logger.addHandler(hdlr)
41 if options.version:
42 import zeroinstall
43 print("0store (zero-install) " + zeroinstall.version)
44 print("Copyright (C) 2009 Thomas Leonard")
45 print("This program comes with ABSOLUTELY NO WARRANTY,")
46 print("to the extent permitted by law.")
47 print("You may redistribute copies of this program")
48 print("under the terms of the GNU Lesser General Public License.")
49 print("For more information about these matters, see the file named COPYING.")
50 sys.exit(0)
52 if len(args) < 1:
53 parser.print_help()
54 sys.exit(1)
56 try:
57 cli.init_stores()
59 pattern = args[0].lower()
60 matches = [c for c in cli.commands if c.__name__[3:].startswith(pattern)]
61 if len(matches) == 0:
62 parser.print_help()
63 sys.exit(1)
64 if len(matches) > 1:
65 raise SafeException("What do you mean by '%s'?\n%s" %
66 (pattern, '\n'.join(['- ' + x.__name__[3:] for x in matches])))
67 matches[0](args[1:])
68 except KeyboardInterrupt as ex:
69 print("Interrupted", file=sys.stderr)
70 sys.exit(1)
71 except OSError as ex:
72 if options.verbose: raise
73 print(str(ex), file=sys.stderr)
74 sys.exit(1)
75 except IOError as ex:
76 if options.verbose: raise
77 print(str(ex), file=sys.stderr)
78 sys.exit(1)
79 except cli.UsageError as ex:
80 print(str(ex), file=sys.stderr)
81 print("usage: " + sys.argv[0] + " " + matches[0].__doc__, file=sys.stderr)
82 sys.exit(1)
83 except SafeException as ex:
84 if options.verbose: raise
85 print(str(ex), file=sys.stderr)
86 sys.exit(1)