mercurial/cmdutil.py
changeset 4551 61e33f1d44a8
parent 4550 6ed91894261e
child 4552 38cdee6b6675
equal deleted inserted replaced
4550:6ed91894261e 4551:61e33f1d44a8
    18 class AmbiguousCommand(Exception):
    18 class AmbiguousCommand(Exception):
    19     """Exception raised if command shortcut matches more than one command."""
    19     """Exception raised if command shortcut matches more than one command."""
    20 class ParseError(Exception):
    20 class ParseError(Exception):
    21     """Exception raised on errors in parsing the command line."""
    21     """Exception raised on errors in parsing the command line."""
    22 
    22 
    23 def runcatch(u, args):
    23 def runcatch(ui, args):
    24     def catchterm(*args):
    24     def catchterm(*args):
    25         raise util.SignalInterrupt
    25         raise util.SignalInterrupt
    26 
    26 
    27     for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
    27     for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
    28         num = getattr(signal, name, None)
    28         num = getattr(signal, name, None)
    32         try:
    32         try:
    33             # enter the debugger before command execution
    33             # enter the debugger before command execution
    34             if '--debugger' in args:
    34             if '--debugger' in args:
    35                 pdb.set_trace()
    35                 pdb.set_trace()
    36             try:
    36             try:
    37                 return dispatch(u, args)
    37                 return dispatch(ui, args)
    38             finally:
    38             finally:
    39                 u.flush()
    39                 ui.flush()
    40         except:
    40         except:
    41             # enter the debugger when we hit an exception
    41             # enter the debugger when we hit an exception
    42             if '--debugger' in args:
    42             if '--debugger' in args:
    43                 pdb.post_mortem(sys.exc_info()[2])
    43                 pdb.post_mortem(sys.exc_info()[2])
    44             u.print_exc()
    44             ui.print_exc()
    45             raise
    45             raise
    46 
    46 
    47     except ParseError, inst:
    47     except ParseError, inst:
    48         if inst.args[0]:
    48         if inst.args[0]:
    49             u.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
    49             ui.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
    50             commands.help_(u, inst.args[0])
    50             commands.help_(ui, inst.args[0])
    51         else:
    51         else:
    52             u.warn(_("hg: %s\n") % inst.args[1])
    52             ui.warn(_("hg: %s\n") % inst.args[1])
    53             commands.help_(u, 'shortlist')
    53             commands.help_(ui, 'shortlist')
    54     except AmbiguousCommand, inst:
    54     except AmbiguousCommand, inst:
    55         u.warn(_("hg: command '%s' is ambiguous:\n    %s\n") %
    55         ui.warn(_("hg: command '%s' is ambiguous:\n    %s\n") %
    56                 (inst.args[0], " ".join(inst.args[1])))
    56                 (inst.args[0], " ".join(inst.args[1])))
    57     except UnknownCommand, inst:
    57     except UnknownCommand, inst:
    58         u.warn(_("hg: unknown command '%s'\n") % inst.args[0])
    58         ui.warn(_("hg: unknown command '%s'\n") % inst.args[0])
    59         commands.help_(u, 'shortlist')
    59         commands.help_(ui, 'shortlist')
    60     except hg.RepoError, inst:
    60     except hg.RepoError, inst:
    61         u.warn(_("abort: %s!\n") % inst)
    61         ui.warn(_("abort: %s!\n") % inst)
    62     except lock.LockHeld, inst:
    62     except lock.LockHeld, inst:
    63         if inst.errno == errno.ETIMEDOUT:
    63         if inst.errno == errno.ETIMEDOUT:
    64             reason = _('timed out waiting for lock held by %s') % inst.locker
    64             reason = _('timed out waiting for lock held by %s') % inst.locker
    65         else:
    65         else:
    66             reason = _('lock held by %s') % inst.locker
    66             reason = _('lock held by %s') % inst.locker
    67         u.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
    67         ui.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
    68     except lock.LockUnavailable, inst:
    68     except lock.LockUnavailable, inst:
    69         u.warn(_("abort: could not lock %s: %s\n") %
    69         ui.warn(_("abort: could not lock %s: %s\n") %
    70                (inst.desc or inst.filename, inst.strerror))
    70                (inst.desc or inst.filename, inst.strerror))
    71     except revlog.RevlogError, inst:
    71     except revlog.RevlogError, inst:
    72         u.warn(_("abort: %s!\n") % inst)
    72         ui.warn(_("abort: %s!\n") % inst)
    73     except util.SignalInterrupt:
    73     except util.SignalInterrupt:
    74         u.warn(_("killed!\n"))
    74         ui.warn(_("killed!\n"))
    75     except KeyboardInterrupt:
    75     except KeyboardInterrupt:
    76         try:
    76         try:
    77             u.warn(_("interrupted!\n"))
    77             ui.warn(_("interrupted!\n"))
    78         except IOError, inst:
    78         except IOError, inst:
    79             if inst.errno == errno.EPIPE:
    79             if inst.errno == errno.EPIPE:
    80                 if u.debugflag:
    80                 if ui.debugflag:
    81                     u.warn(_("\nbroken pipe\n"))
    81                     ui.warn(_("\nbroken pipe\n"))
    82             else:
    82             else:
    83                 raise
    83                 raise
    84     except socket.error, inst:
    84     except socket.error, inst:
    85         u.warn(_("abort: %s\n") % inst[1])
    85         ui.warn(_("abort: %s\n") % inst[1])
    86     except IOError, inst:
    86     except IOError, inst:
    87         if hasattr(inst, "code"):
    87         if hasattr(inst, "code"):
    88             u.warn(_("abort: %s\n") % inst)
    88             ui.warn(_("abort: %s\n") % inst)
    89         elif hasattr(inst, "reason"):
    89         elif hasattr(inst, "reason"):
    90             try: # usually it is in the form (errno, strerror)
    90             try: # usually it is in the form (errno, strerror)
    91                 reason = inst.reason.args[1]
    91                 reason = inst.reason.args[1]
    92             except: # it might be anything, for example a string
    92             except: # it might be anything, for example a string
    93                 reason = inst.reason
    93                 reason = inst.reason
    94             u.warn(_("abort: error: %s\n") % reason)
    94             ui.warn(_("abort: error: %s\n") % reason)
    95         elif hasattr(inst, "args") and inst[0] == errno.EPIPE:
    95         elif hasattr(inst, "args") and inst[0] == errno.EPIPE:
    96             if u.debugflag:
    96             if ui.debugflag:
    97                 u.warn(_("broken pipe\n"))
    97                 ui.warn(_("broken pipe\n"))
    98         elif getattr(inst, "strerror", None):
    98         elif getattr(inst, "strerror", None):
    99             if getattr(inst, "filename", None):
    99             if getattr(inst, "filename", None):
   100                 u.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
   100                 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
   101             else:
   101             else:
   102                 u.warn(_("abort: %s\n") % inst.strerror)
   102                 ui.warn(_("abort: %s\n") % inst.strerror)
   103         else:
   103         else:
   104             raise
   104             raise
   105     except OSError, inst:
   105     except OSError, inst:
   106         if getattr(inst, "filename", None):
   106         if getattr(inst, "filename", None):
   107             u.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
   107             ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
   108         else:
   108         else:
   109             u.warn(_("abort: %s\n") % inst.strerror)
   109             ui.warn(_("abort: %s\n") % inst.strerror)
   110     except util.UnexpectedOutput, inst:
   110     except util.UnexpectedOutput, inst:
   111         u.warn(_("abort: %s") % inst[0])
   111         ui.warn(_("abort: %s") % inst[0])
   112         if not isinstance(inst[1], basestring):
   112         if not isinstance(inst[1], basestring):
   113             u.warn(" %r\n" % (inst[1],))
   113             ui.warn(" %r\n" % (inst[1],))
   114         elif not inst[1]:
   114         elif not inst[1]:
   115             u.warn(_(" empty string\n"))
   115             ui.warn(_(" empty string\n"))
   116         else:
   116         else:
   117             u.warn("\n%r\n" % util.ellipsis(inst[1]))
   117             ui.warn("\n%r\n" % util.ellipsis(inst[1]))
   118     except util.Abort, inst:
   118     except util.Abort, inst:
   119         u.warn(_("abort: %s\n") % inst)
   119         ui.warn(_("abort: %s\n") % inst)
   120     except TypeError, inst:
   120     except TypeError, inst:
   121         # was this an argument error?
   121         # was this an argument error?
   122         tb = traceback.extract_tb(sys.exc_info()[2])
   122         tb = traceback.extract_tb(sys.exc_info()[2])
   123         if len(tb) > 2: # no
   123         if len(tb) > 2: # no
   124             raise
   124             raise
   125         u.debug(inst, "\n")
   125         ui.debug(inst, "\n")
   126         u.warn(_("%s: invalid arguments\n") % cmd)
   126         ui.warn(_("%s: invalid arguments\n") % cmd)
   127         commands.help_(u, cmd)
   127         commands.help_(ui, cmd)
   128     except SystemExit, inst:
   128     except SystemExit, inst:
   129         # Commands shouldn't sys.exit directly, but give a return code.
   129         # Commands shouldn't sys.exit directly, but give a return code.
   130         # Just in case catch this and and pass exit code to caller.
   130         # Just in case catch this and and pass exit code to caller.
   131         return inst.code
   131         return inst.code
   132     except:
   132     except:
   133         u.warn(_("** unknown exception encountered, details follow\n"))
   133         ui.warn(_("** unknown exception encountered, details follow\n"))
   134         u.warn(_("** report bug details to "
   134         ui.warn(_("** report bug details to "
   135                  "http://www.selenic.com/mercurial/bts\n"))
   135                  "http://www.selenic.com/mercurial/bts\n"))
   136         u.warn(_("** or mercurial@selenic.com\n"))
   136         ui.warn(_("** or mercurial@selenic.com\n"))
   137         u.warn(_("** Mercurial Distributed SCM (version %s)\n")
   137         ui.warn(_("** Mercurial Distributed SCM (version %s)\n")
   138                % version.get_version())
   138                % version.get_version())
   139         raise
   139         raise
   140 
   140 
   141     return -1
   141     return -1
   142 
   142 
   236             parsed.append((section, name, value))
   236             parsed.append((section, name, value))
   237         except (IndexError, ValueError):
   237         except (IndexError, ValueError):
   238             raise util.Abort(_('malformed --config option: %s') % cfg)
   238             raise util.Abort(_('malformed --config option: %s') % cfg)
   239     return parsed
   239     return parsed
   240 
   240 
   241 def dispatch(u, args):
   241 def dispatch(ui, args):
   242     extensions.loadall(u)
   242     extensions.loadall(ui)
   243     u.addreadhook(extensions.loadall)
   243     ui.addreadhook(extensions.loadall)
   244 
   244 
   245     cmd, func, args, options, cmdoptions = parse(u, args)
   245     cmd, func, args, options, cmdoptions = parse(ui, args)
   246 
   246 
   247     if options["encoding"]:
   247     if options["encoding"]:
   248         util._encoding = options["encoding"]
   248         util._encoding = options["encoding"]
   249     if options["encodingmode"]:
   249     if options["encodingmode"]:
   250         util._encodingmode = options["encodingmode"]
   250         util._encodingmode = options["encodingmode"]
   255                 t = (t[0], t[1], t[2], t[3], time.clock())
   255                 t = (t[0], t[1], t[2], t[3], time.clock())
   256             return t
   256             return t
   257         s = get_times()
   257         s = get_times()
   258         def print_time():
   258         def print_time():
   259             t = get_times()
   259             t = get_times()
   260             u.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
   260             ui.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
   261                 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
   261                 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
   262         atexit.register(print_time)
   262         atexit.register(print_time)
   263 
   263 
   264     if options['cwd']:
   264     if options['cwd']:
   265         os.chdir(options['cwd'])
   265         os.chdir(options['cwd'])
   266 
   266 
   267     u.updateopts(options["verbose"], options["debug"], options["quiet"],
   267     ui.updateopts(options["verbose"], options["debug"], options["quiet"],
   268                  not options["noninteractive"], options["traceback"],
   268                  not options["noninteractive"], options["traceback"],
   269                  parseconfig(options["config"]))
   269                  parseconfig(options["config"]))
   270 
   270 
   271     path = u.expandpath(options["repository"]) or ""
   271     path = ui.expandpath(options["repository"]) or ""
   272     repo = path and hg.repository(u, path=path) or None
   272     repo = path and hg.repository(ui, path=path) or None
   273     if repo and not repo.local():
   273     if repo and not repo.local():
   274         raise util.Abort(_("repository '%s' is not local") % path)
   274         raise util.Abort(_("repository '%s' is not local") % path)
   275 
   275 
   276     if options['help']:
   276     if options['help']:
   277         return commands.help_(u, cmd, options['version'])
   277         return commands.help_(ui, cmd, options['version'])
   278     elif options['version']:
   278     elif options['version']:
   279         return commands.version_(u)
   279         return commands.version_(ui)
   280     elif not cmd:
   280     elif not cmd:
   281         return commands.help_(u, 'shortlist')
   281         return commands.help_(ui, 'shortlist')
   282 
   282 
   283     if cmd not in commands.norepo.split():
   283     if cmd not in commands.norepo.split():
   284         try:
   284         try:
   285             if not repo:
   285             if not repo:
   286                 repo = hg.repository(u, path=path)
   286                 repo = hg.repository(ui, path=path)
   287             u = repo.ui
   287             ui = repo.ui
   288         except hg.RepoError:
   288         except hg.RepoError:
   289             if cmd not in commands.optionalrepo.split():
   289             if cmd not in commands.optionalrepo.split():
   290                 raise
   290                 raise
   291         d = lambda: func(u, repo, *args, **cmdoptions)
   291         d = lambda: func(ui, repo, *args, **cmdoptions)
   292     else:
   292     else:
   293         d = lambda: func(u, *args, **cmdoptions)
   293         d = lambda: func(ui, *args, **cmdoptions)
   294 
   294 
   295     return runcommand(u, options, d)
   295     return runcommand(ui, options, d)
   296 
   296 
   297 def runcommand(u, options, d):
   297 def runcommand(ui, options, cmdfunc):
   298     if options['profile']:
   298     if options['profile']:
   299         import hotshot, hotshot.stats
   299         import hotshot, hotshot.stats
   300         prof = hotshot.Profile("hg.prof")
   300         prof = hotshot.Profile("hg.prof")
   301         try:
   301         try:
   302             try:
   302             try:
   303                 return prof.runcall(d)
   303                 return prof.runcall(cmdfunc)
   304             except:
   304             except:
   305                 try:
   305                 try:
   306                     u.warn(_('exception raised - generating '
   306                     ui.warn(_('exception raised - generating '
   307                              'profile anyway\n'))
   307                              'profile anyway\n'))
   308                 except:
   308                 except:
   309                     pass
   309                     pass
   310                 raise
   310                 raise
   311         finally:
   311         finally:
   322                 'lsprof not available - install from '
   322                 'lsprof not available - install from '
   323                 'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
   323                 'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
   324         p = lsprof.Profiler()
   324         p = lsprof.Profiler()
   325         p.enable(subcalls=True)
   325         p.enable(subcalls=True)
   326         try:
   326         try:
   327             return d()
   327             return cmdfunc()
   328         finally:
   328         finally:
   329             p.disable()
   329             p.disable()
   330             stats = lsprof.Stats(p.getstats())
   330             stats = lsprof.Stats(p.getstats())
   331             stats.sort()
   331             stats.sort()
   332             stats.pprint(top=10, file=sys.stderr, climit=5)
   332             stats.pprint(top=10, file=sys.stderr, climit=5)
   333     else:
   333     else:
   334         return d()
   334         return cmdfunc()
   335 
   335 
   336 def bail_if_changed(repo):
   336 def bail_if_changed(repo):
   337     modified, added, removed, deleted = repo.status()[:4]
   337     modified, added, removed, deleted = repo.status()[:4]
   338     if modified or added or removed or deleted:
   338     if modified or added or removed or deleted:
   339         raise util.Abort(_("outstanding uncommitted changes"))
   339         raise util.Abort(_("outstanding uncommitted changes"))