chiark / gitweb /
Do not raise an exception if no FETCH_HEAD
[stgit] / stgit / main.py
index 99e083262226fe1345aac30a5dd66fca48acd980..e8242c2783bddd18122b345512f9e155495538f7 100644 (file)
@@ -22,6 +22,7 @@ import sys, os
 from optparse import OptionParser
 
 import stgit.commands
+from stgit.out import *
 
 #
 # The commands map
@@ -29,27 +30,29 @@ import stgit.commands
 class Commands(dict):
     """Commands class. It performs on-demand module loading
     """
+    def canonical_cmd(self, key):
+        """Return the canonical name for a possibly-shortenned
+        command name.
+        """
+        candidates = [cmd for cmd in self.keys() if cmd.startswith(key)]
+
+        if not candidates:
+            out.error('Unknown command: %s' % key,
+                      'Try "%s help" for a list of supported commands' % prog)
+            sys.exit(1)
+        elif len(candidates) > 1:
+            out.error('Ambiguous command: %s' % key,
+                      'Candidates are: %s' % ', '.join(candidates))
+            sys.exit(1)
+
+        return candidates[0]
+        
     def __getitem__(self, key):
         """Return the command python module name based.
         """
         global prog
 
-        cmd_mod = self.get(key)
-        if not cmd_mod:
-            candidates = [cmd for cmd in self.keys() if cmd.startswith(key)]
-
-            if not candidates:
-                print >> sys.stderr, 'Unknown command: %s' % key
-                print >> sys.stderr, '  Try "%s help" for a list of ' \
-                      'supported commands' % prog
-                sys.exit(1)
-            elif len(candidates) > 1:
-                print >> sys.stderr, 'Ambiguous command: %s' % key
-                print >> sys.stderr, '  Candidates are: %s' \
-                      % ', '.join(candidates)
-                sys.exit(1)
-
-            cmd_mod = self.get(candidates[0])
+        cmd_mod = self.get(key) or self.get(self.canonical_cmd(key))
             
         __import__('stgit.commands.' + cmd_mod)
         return getattr(stgit.commands, cmd_mod)
@@ -64,11 +67,14 @@ commands = Commands({
     'clean':            'clean',
     'clone':            'clone',
     'commit':           'commit',
+    'cp':              'copy',
+    'edit':             'edit',
     'export':           'export',
     'files':            'files',
     'float':            'float',
     'fold':             'fold',
     'goto':             'goto',
+    'hide':             'hide',
     'id':               'id',
     'import':           'imprt',
     'init':             'init',
@@ -80,43 +86,52 @@ commands = Commands({
     'pop':              'pop',
     'pull':             'pull',
     'push':             'push',
+    'rebase':           'rebase',
     'refresh':          'refresh',
     'rename':           'rename',
     'resolved':         'resolved',
     'rm':               'rm',
     'series':           'series',
     'show':             'show',
+    'sink':             'sink',
     'status':           'status',
     'sync':             'sync',
     'top':              'top',
     'unapplied':        'unapplied',
-    'uncommit':         'uncommit'
+    'uncommit':         'uncommit',
+    'unhide':           'unhide'
     })
 
 # classification: repository, stack, patch, working copy
 repocommands = (
-    'branch',
     'clone',
     'id',
-    'pull'
     )
 stackcommands = (
     'applied',
     'assimilate',
+    'branch',
     'clean',
     'commit',
     'float',
     'goto',
+    'hide',
     'init',
+    'patches',
     'pop',
+    'pull',
     'push',
+    'rebase',
     'series',
+    'sink',
     'top',
     'unapplied',
-    'uncommit'
+    'uncommit',
+    'unhide',
     )
 patchcommands = (
     'delete',
+    'edit',
     'export',
     'files',
     'fold',
@@ -128,15 +143,15 @@ patchcommands = (
     'refresh',
     'rename',
     'show',
-    'sync'
+    'sync',
     )
 wccommands = (
     'add',
+    'cp',
     'diff',
-    'patches',
     'resolved',
     'rm',
-    'status'
+    'status',
     )
 
 def _print_helpstring(cmd):
@@ -196,18 +211,17 @@ def main():
     cmd = sys.argv[1]
 
     if cmd in ['-h', '--help']:
-        if len(sys.argv) >= 3 and sys.argv[2] in commands:
-            cmd = sys.argv[2]
+        if len(sys.argv) >= 3:
+            cmd = commands.canonical_cmd(sys.argv[2])
             sys.argv[2] = '--help'
         else:
             print_help()
             sys.exit(0)
     if cmd == 'help':
         if len(sys.argv) == 3 and not sys.argv[2] in ['-h', '--help']:
-            cmd = sys.argv[2]
+            cmd = commands.canonical_cmd(sys.argv[2])
             if not cmd in commands:
-                print >> sys.stderr, '%s help: "%s" command unknown' \
-                      % (prog, cmd)
+                out.error('%s help: "%s" command unknown' % (prog, cmd))
                 sys.exit(1)
 
             sys.argv[0] += ' %s' % cmd
@@ -230,6 +244,7 @@ def main():
         sys.exit(0)
 
     # re-build the command line arguments
+    cmd = commands.canonical_cmd(cmd)
     sys.argv[0] += ' %s' % cmd
     del(sys.argv[1])
 
@@ -237,33 +252,39 @@ def main():
     usage = command.usage.split('\n')[0].strip()
     parser = OptionParser(usage = usage, option_list = command.options)
     options, args = parser.parse_args()
+    directory = command.directory
 
     # These modules are only used from this point onwards and do not
     # need to be imported earlier
+    from stgit.exception import StgException
     from stgit.config import config_setup
     from ConfigParser import ParsingError, NoSectionError
-    from stgit.stack import Series, StackException
-    from stgit.git import GitException
-    from stgit.commands.common import CmdException
-    from stgit.gitmergeonefile import GitMergeException
+    from stgit.stack import Series
 
     try:
+        debug_level = int(os.environ.get('STGIT_DEBUG_LEVEL', 0))
+    except ValueError:
+        out.error('Invalid STGIT_DEBUG_LEVEL environment variable')
+        sys.exit(1)
+
+    try:
+        directory.setup()
         config_setup()
 
-        # 'clone' doesn't expect an already initialised GIT tree. A Series
-        # object will be created after the GIT tree is cloned
-        if cmd != 'clone':
+        # Some commands don't (always) need an initialized series.
+        if directory.needs_current_series:
             if hasattr(options, 'branch') and options.branch:
                 command.crt_series = Series(options.branch)
             else:
                 command.crt_series = Series()
-            stgit.commands.common.crt_series = command.crt_series
 
         command.func(parser, options, args)
-    except (IOError, ParsingError, NoSectionError, CmdException,
-            StackException, GitException, GitMergeException), err:
-        print >> sys.stderr, '%s %s: %s' % (prog, cmd, err)
-        sys.exit(2)
+    except (StgException, IOError, ParsingError, NoSectionError), err:
+        out.error(str(err), title = '%s %s' % (prog, cmd))
+        if debug_level > 0:
+            raise
+        else:
+            sys.exit(2)
     except KeyboardInterrupt:
         sys.exit(1)