efaa3569ad9d45c1e4dc176b1d4612154f532d93
[scons.git] / bin / Command.py
1 #!/usr/bin/env python
2 #
3 # XXX Python script template
4 #
5 # XXX Describe what the script does here.
6 #
7
8 import getopt
9 import os
10 import shlex
11 import sys
12
13 class Usage(Exception):
14     def __init__(self, msg):
15         self.msg = msg
16
17 class CommandRunner:
18     """
19     Representation of a command to be executed.
20     """
21
22     def __init__(self, dictionary={}):
23         self.subst_dictionary(dictionary)
24
25     def subst_dictionary(self, dictionary):
26         self._subst_dictionary = dictionary
27
28     def subst(self, string, dictionary=None):
29         """
30         Substitutes (via the format operator) the values in the specified
31         dictionary into the specified command.
32
33         The command can be an (action, string) tuple.  In all cases, we
34         perform substitution on strings and don't worry if something isn't
35         a string.  (It's probably a Python function to be executed.)
36         """
37         if dictionary is None:
38             dictionary = self._subst_dictionary
39         if dictionary:
40             try:
41                 string = string % dictionary
42             except TypeError:
43                 pass
44         return string
45
46     def do_display(self, string):
47         if type(string) == type(()):
48             func = string[0]
49             args = string[1:]
50             s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args)))
51         else:
52             s = self.subst(string)
53         if not s.endswith('\n'):
54             s += '\n'
55         sys.stdout.write(s)
56         sys.stdout.flush()
57
58     def do_not_display(self, string):
59         pass
60
61     def do_execute(self, command):
62         if type(command) == type(''):
63             command = self.subst(command)
64             cmdargs = shlex.split(command)
65             if cmdargs[0] == 'cd':
66                  command = (os.chdir,) + tuple(cmdargs[1:])
67             elif cmdargs[0] == 'mkdir':
68                  command = (os.mkdir,) + tuple(cmdargs[1:])
69         if type(command) == type(()):
70             func = command[0]
71             args = command[1:]
72             return func(*args)
73         else:
74             return os.system(command)
75
76     def do_not_execute(self, command):
77         pass
78
79     display = do_display
80     execute = do_execute
81
82     def run(self, command, display=None):
83         """
84         Runs this command, displaying it first.
85
86         The actual display() and execute() methods we call may be
87         overridden if we're printing but not executing, or vice versa.
88         """
89         if display is None:
90             display = command
91         self.display(display)
92         return self.execute(command)
93
94 def main(argv=None):
95     if argv is None:
96         argv = sys.argv
97
98     short_options = 'hnq'
99     long_options = ['help', 'no-exec', 'quiet']
100
101     helpstr = """\
102 Usage:  script-template.py [-hnq] 
103
104   -h, --help                    Print this help and exit
105   -n, --no-exec                 No execute, just print command lines
106   -q, --quiet                   Quiet, don't print command lines
107 """
108
109     try:
110         try:
111             opts, args = getopt.getopt(argv[1:], short_options, long_options)
112         except getopt.error, msg:
113             raise Usage(msg)
114
115         for o, a in opts:
116             if o in ('-h', '--help'):
117                 print helpstr
118                 sys.exit(0)
119             elif o in ('-n', '--no-exec'):
120                 Command.execute = Command.do_not_execute
121             elif o in ('-q', '--quiet'):
122                 Command.display = Command.do_not_display
123     except Usage, err:
124         sys.stderr.write(err.msg)
125         sys.stderr.write('use -h to get help')
126         return 2
127
128     commands = [
129     ]
130
131     for command in [ Command(c) for c in commands ]:
132         status = command.run(command)
133         if status:
134             sys.exit(status)
135
136 if __name__ == "__main__":
137     sys.exit(main())
138
139 # Local Variables:
140 # tab-width:4
141 # indent-tabs-mode:nil
142 # End:
143 # vim: set expandtab tabstop=4 shiftwidth=4: