chiark / gitweb /
7f8f0c9c74815eb0f79905c5489cda8da7293cc1
[stgit] / stgit / main.py
1 """Basic quilt-like functionality
2 """
3
4 __copyright__ = """
5 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License version 2 as
9 published by the Free Software Foundation.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 """
20
21 import sys, os
22 from optparse import OptionParser
23
24 import stgit.commands
25 from stgit.out import *
26 from stgit import utils
27
28 #
29 # The commands map
30 #
31 class Commands(dict):
32     """Commands class. It performs on-demand module loading
33     """
34     def canonical_cmd(self, key):
35         """Return the canonical name for a possibly-shortenned
36         command name.
37         """
38         candidates = [cmd for cmd in self.keys() if cmd.startswith(key)]
39
40         if not candidates:
41             out.error('Unknown command: %s' % key,
42                       'Try "%s help" for a list of supported commands' % prog)
43             sys.exit(utils.STGIT_GENERAL_ERROR)
44         elif len(candidates) > 1:
45             out.error('Ambiguous command: %s' % key,
46                       'Candidates are: %s' % ', '.join(candidates))
47             sys.exit(utils.STGIT_GENERAL_ERROR)
48
49         return candidates[0]
50         
51     def __getitem__(self, key):
52         """Return the command python module name based.
53         """
54         global prog
55
56         cmd_mod = self.get(key) or self.get(self.canonical_cmd(key))
57             
58         __import__('stgit.commands.' + cmd_mod)
59         return getattr(stgit.commands, cmd_mod)
60
61 commands = Commands({
62     'applied':          'applied',
63     'branch':           'branch',
64     'delete':           'delete',
65     'diff':             'diff',
66     'clean':            'clean',
67     'clone':            'clone',
68     'commit':           'commit',
69     'cp':               'copy',
70     'edit':             'edit',
71     'export':           'export',
72     'files':            'files',
73     'float':            'float',
74     'fold':             'fold',
75     'goto':             'goto',
76     'hide':             'hide',
77     'id':               'id',
78     'import':           'imprt',
79     'init':             'init',
80     'log':              'log',
81     'mail':             'mail',
82     'new':              'new',
83     'patches':          'patches',
84     'pick':             'pick',
85     'pop':              'pop',
86     'pull':             'pull',
87     'push':             'push',
88     'rebase':           'rebase',
89     'refresh':          'refresh',
90     'rename':           'rename',
91     'repair':           'repair',
92     'resolved':         'resolved',
93     'rm':               'rm',
94     'series':           'series',
95     'show':             'show',
96     'sink':             'sink',
97     'status':           'status',
98     'sync':             'sync',
99     'top':              'top',
100     'unapplied':        'unapplied',
101     'uncommit':         'uncommit',
102     'unhide':           'unhide'
103     })
104
105 # classification: repository, stack, patch, working copy
106 repocommands = (
107     'clone',
108     'id',
109     )
110 stackcommands = (
111     'applied',
112     'branch',
113     'clean',
114     'commit',
115     'float',
116     'goto',
117     'hide',
118     'init',
119     'patches',
120     'pop',
121     'pull',
122     'push',
123     'rebase',
124     'repair',
125     'series',
126     'sink',
127     'top',
128     'unapplied',
129     'uncommit',
130     'unhide',
131     )
132 patchcommands = (
133     'delete',
134     'edit',
135     'export',
136     'files',
137     'fold',
138     'import',
139     'log',
140     'mail',
141     'new',
142     'pick',
143     'refresh',
144     'rename',
145     'show',
146     'sync',
147     )
148 wccommands = (
149     'cp',
150     'diff',
151     'resolved',
152     'rm',
153     'status',
154     )
155
156 def _print_helpstring(cmd):
157     print '  ' + cmd + ' ' * (12 - len(cmd)) + commands[cmd].help
158     
159 def print_help():
160     print 'usage: %s <command> [options]' % os.path.basename(sys.argv[0])
161     print
162     print 'Generic commands:'
163     print '  help        print the detailed command usage'
164     print '  version     display version information'
165     print '  copyright   display copyright information'
166     # unclassified commands if any
167     cmds = commands.keys()
168     cmds.sort()
169     for cmd in cmds:
170         if not cmd in repocommands and not cmd in stackcommands \
171                and not cmd in patchcommands and not cmd in wccommands:
172             _print_helpstring(cmd)
173     print
174
175     print 'Repository commands:'
176     for cmd in repocommands:
177         _print_helpstring(cmd)
178     print
179     
180     print 'Stack commands:'
181     for cmd in stackcommands:
182         _print_helpstring(cmd)
183     print
184
185     print 'Patch commands:'
186     for cmd in patchcommands:
187         _print_helpstring(cmd)
188     print
189
190     print 'Working-copy commands:'
191     for cmd in wccommands:
192         _print_helpstring(cmd)
193
194 #
195 # The main function (command dispatcher)
196 #
197 def main():
198     """The main function
199     """
200     global prog
201
202     prog = os.path.basename(sys.argv[0])
203
204     if len(sys.argv) < 2:
205         print >> sys.stderr, 'usage: %s <command>' % prog
206         print >> sys.stderr, \
207               '  Try "%s --help" for a list of supported commands' % prog
208         sys.exit(utils.STGIT_GENERAL_ERROR)
209
210     cmd = sys.argv[1]
211
212     if cmd in ['-h', '--help']:
213         if len(sys.argv) >= 3:
214             cmd = commands.canonical_cmd(sys.argv[2])
215             sys.argv[2] = '--help'
216         else:
217             print_help()
218             sys.exit(utils.STGIT_SUCCESS)
219     if cmd == 'help':
220         if len(sys.argv) == 3 and not sys.argv[2] in ['-h', '--help']:
221             cmd = commands.canonical_cmd(sys.argv[2])
222             if not cmd in commands:
223                 out.error('%s help: "%s" command unknown' % (prog, cmd))
224                 sys.exit(utils.STGIT_GENERAL_ERROR)
225
226             sys.argv[0] += ' %s' % cmd
227             command = commands[cmd]
228             parser = OptionParser(usage = command.usage,
229                                   option_list = command.options)
230             from pydoc import pager
231             pager(parser.format_help())
232         else:
233             print_help()
234         sys.exit(utils.STGIT_SUCCESS)
235     if cmd in ['-v', '--version', 'version']:
236         from stgit.version import version
237         print 'Stacked GIT %s' % version
238         os.system('git --version')
239         print 'Python version %s' % sys.version
240         sys.exit(utils.STGIT_SUCCESS)
241     if cmd in ['copyright']:
242         print __copyright__
243         sys.exit(utils.STGIT_SUCCESS)
244
245     # re-build the command line arguments
246     cmd = commands.canonical_cmd(cmd)
247     sys.argv[0] += ' %s' % cmd
248     del(sys.argv[1])
249
250     command = commands[cmd]
251     usage = command.usage.split('\n')[0].strip()
252     parser = OptionParser(usage = usage, option_list = command.options)
253     options, args = parser.parse_args()
254     directory = command.directory
255
256     # These modules are only used from this point onwards and do not
257     # need to be imported earlier
258     from stgit.exception import StgException
259     from stgit.config import config_setup
260     from ConfigParser import ParsingError, NoSectionError
261     from stgit.stack import Series
262
263     try:
264         debug_level = int(os.environ.get('STGIT_DEBUG_LEVEL', 0))
265     except ValueError:
266         out.error('Invalid STGIT_DEBUG_LEVEL environment variable')
267         sys.exit(utils.STGIT_GENERAL_ERROR)
268
269     try:
270         directory.setup()
271         config_setup()
272
273         # Some commands don't (always) need an initialized series.
274         if directory.needs_current_series:
275             if hasattr(options, 'branch') and options.branch:
276                 command.crt_series = Series(options.branch)
277             else:
278                 command.crt_series = Series()
279
280         command.func(parser, options, args)
281     except (StgException, IOError, ParsingError, NoSectionError), err:
282         out.error(str(err), title = '%s %s' % (prog, cmd))
283         if debug_level > 0:
284             raise
285         else:
286             sys.exit(utils.STGIT_COMMAND_ERROR)
287     except KeyboardInterrupt:
288         sys.exit(utils.STGIT_GENERAL_ERROR)
289
290     sys.exit(utils.STGIT_SUCCESS)