]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/scripts/runner.py
CLI: simplify argument-passing, use options= for everthing, including stdout
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / scripts / runner.py
1
2 import sys
3 from cStringIO import StringIO
4 from twisted.python import usage
5
6 from allmydata.scripts.common import BaseOptions
7 import debug, create_node, startstop_node, cli, keygen
8
9 _general_commands = ( create_node.subCommands
10                     + keygen.subCommands
11                     + debug.subCommands
12                     + cli.subCommands
13                     )
14
15 class Options(BaseOptions, usage.Options):
16     synopsis = "Usage:  tahoe <command> [command options]"
17
18     subCommands = []
19     subCommands += _general_commands
20     subCommands += startstop_node.subCommands
21
22     def postOptions(self):
23         if not hasattr(self, 'subOptions'):
24             raise usage.UsageError("must specify a command")
25
26 def runner(argv,
27            run_by_human=True,
28            stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr,
29            install_node_control=True, additional_commands=None):
30
31     config = Options()
32     if install_node_control:
33         config.subCommands.extend(startstop_node.subCommands)
34
35     ac_dispatch = {}
36     if additional_commands:
37         for ac in additional_commands:
38             config.subCommands.extend(ac.subCommands)
39             ac_dispatch.update(ac.dispatch)
40
41     try:
42         config.parseOptions(argv)
43     except usage.error, e:
44         if not run_by_human:
45             raise
46         print "%s:  %s" % (sys.argv[0], e)
47         print
48         c = getattr(config, 'subOptions', config)
49         print str(c)
50         return 1
51
52     command = config.subCommand
53     so = config.subOptions
54
55     if config['quiet']:
56         stdout = StringIO()
57
58     so.stdout = stdout
59     so.stderr = stderr
60     so.stdin = stdin
61
62     rc = 0
63     if command in create_node.dispatch:
64         for basedir in so.basedirs:
65             f = create_node.dispatch[command]
66             rc = f(basedir, so, stdout, stderr) or rc
67     elif command in startstop_node.dispatch:
68         rc = startstop_node.dispatch[command](so, stdout, stderr)
69     elif command in debug.dispatch:
70         rc = debug.dispatch[command](so, stdout, stderr)
71     elif command in cli.dispatch:
72         rc = cli.dispatch[command](so)
73     elif command in keygen.dispatch:
74         rc = keygen.dispatch[command](so, stdout, stderr)
75     elif command in ac_dispatch:
76         rc = ac_dispatch[command](so, stdout, stderr)
77     else:
78         raise usage.UsageError()
79
80     return rc
81
82 def run(install_node_control=True):
83     rc = runner(sys.argv[1:])
84     sys.exit(rc)