예제 #1
0
    def helptopic(name):
        for names, header, doc in helptable:
            if name in names:
                break
        else:
            raise error.UnknownCommand(name)

        rst = [minirst.section(header)]

        # description
        if not doc:
            rst.append("    %s\n" % _("(no help text available)"))
        if callable(doc):
            rst += ["    %s\n" % l for l in doc().splitlines()]

        if not ui.verbose:
            omitted = _('(some details hidden, use --verbose'
                         ' to show complete help)')
            indicateomitted(rst, omitted)

        try:
            cmdutil.findcmd(name, commands.table)
            rst.append(_('\nuse "hg help -c %s" to see help for '
                       'the %s command\n') % (name, name))
        except error.UnknownCommand:
            pass
        return rst
예제 #2
0
    def helptopic(name):
        for names, header, doc in helptable:
            if name in names:
                break
        else:
            raise error.UnknownCommand(name)

        rst = [minirst.section(header)]

        # description
        if not doc:
            rst.append("    %s\n" % _("(no help text available)"))
        if util.safehasattr(doc, '__call__'):
            rst += ["    %s\n" % l for l in doc().splitlines()]

        if not ui.verbose:
            omitted = (_('use "hg help -v %s" to show more complete help') %
                       name)
            indicateomitted(rst, omitted)

        try:
            cmdutil.findcmd(name, commands.table)
            rst.append(_('\nuse "hg help -c %s" to see help for '
                       'the %s command\n') % (name, name))
        except error.UnknownCommand:
            pass
        return rst
예제 #3
0
    def helptopic(name):
        for names, header, doc in helptable:
            if name in names:
                break
        else:
            raise error.UnknownCommand(name)

        rst = [minirst.section(header)]

        # description
        if not doc:
            rst.append("    %s\n" % _("(no help text available)"))
        if callable(doc):
            rst += ["    %s\n" % l for l in doc().splitlines()]

        if not ui.verbose:
            omitted = _('(some details hidden, use --verbose'
                         ' to show complete help)')
            indicateomitted(rst, omitted)

        try:
            cmdutil.findcmd(name, commands.table)
            rst.append(_('\nuse "hg help -c %s" to see help for '
                       'the %s command\n') % (name, name))
        except error.UnknownCommand:
            pass
        return rst
예제 #4
0
    def helptopic(name):
        for names, header, doc in helptable:
            if name in names:
                break
        else:
            raise error.UnknownCommand(name)

        rst = [minirst.section(header)]

        # description
        if not doc:
            rst.append("    %s\n" % _("(no help text available)"))
        if util.safehasattr(doc, '__call__'):
            rst += ["    %s\n" % l for l in doc().splitlines()]

        if not ui.verbose:
            omitted = (_('use "hg help -v %s" to show more complete help') %
                       name)
            indicateomitted(rst, omitted)

        try:
            cmdutil.findcmd(name, commands.table)
            rst.append(
                _('\nuse "hg help -c %s" to see help for '
                  'the %s command\n') % (name, name))
        except error.UnknownCommand:
            pass
        return rst
예제 #5
0
    def __init__(self, name, definition, cmdtable):
        self.name = name
        self.definition = definition
        self.args = []
        self.opts = []
        self.help = ''
        self.norepo = True

        try:
            cmdutil.findcmd(self.name, cmdtable, True)
            self.shadows = True
        except error.UnknownCommand:
            self.shadows = False

        if not self.definition:

            def fn(ui, *args):
                ui.warn(_("no definition for alias '%s'\n") % self.name)
                return 1

            self.fn = fn

            return

        args = shlex.split(self.definition)
        cmd = args.pop(0)
        opts = []
        help = ''

        try:
            self.fn, self.opts, self.help = cmdutil.findcmd(
                cmd, cmdtable, False)[1]
            self.args = aliasargs(self.fn) + args
            if cmd not in commands.norepo.split(' '):
                self.norepo = False
        except error.UnknownCommand:

            def fn(ui, *args):
                ui.warn(_("alias '%s' resolves to unknown command '%s'\n") \
                            % (self.name, cmd))
                return 1

            self.fn = fn
        except error.AmbiguousCommand:

            def fn(ui, *args):
                ui.warn(_("alias '%s' resolves to ambiguous command '%s'\n") \
                            % (self.name, cmd))
                return 1

            self.fn = fn
예제 #6
0
def _checkshellalias(lui, ui, args):
    norepo = commands.norepo
    options = {}

    try:
        args = fancyopts.fancyopts(args, commands.globalopts, options)
    except fancyopts.getopt.GetoptError:
        return

    if not args:
        return

    cmdtable = commands.table.copy()
    addaliases(lui, cmdtable)

    cmd = args[0]
    try:
        aliases, entry = cmdutil.findcmd(cmd, cmdtable,
                                         lui.config("ui", "strict"))
    except (error.AmbiguousCommand, error.UnknownCommand):
        commands.norepo = norepo
        return

    cmd = aliases[0]
    fn = entry[0]

    if cmd and util.safehasattr(fn, 'shell'):
        d = lambda: fn(ui, *args[1:])
        return lambda: runcommand(lui, None, cmd, args[:1], ui, options, d, [],
                                  {})

    commands.norepo = norepo
예제 #7
0
파일: dispatch.py 프로젝트: mortonfox/cr48
def _checkshellalias(lui, ui, args):
    norepo = commands.norepo
    options = {}

    try:
        args = fancyopts.fancyopts(args, commands.globalopts, options)
    except fancyopts.getopt.GetoptError:
        return

    if not args:
        return

    cmdtable = commands.table.copy()
    addaliases(lui, cmdtable)

    cmd = args[0]
    try:
        aliases, entry = cmdutil.findcmd(cmd, cmdtable, lui.config("ui", "strict"))
    except (error.AmbiguousCommand, error.UnknownCommand):
        commands.norepo = norepo
        return

    cmd = aliases[0]
    fn = entry[0]

    if cmd and util.safehasattr(fn, 'shell'):
        d = lambda: fn(ui, *args[1:])
        return lambda: runcommand(lui, None, cmd, args[:1], ui, options, d, [], {})

    commands.norepo = norepo
예제 #8
0
def wrapcommand(table, command, wrapper):
    '''Wrap the command named `command' in table

    Replace command in the command table with wrapper. The wrapped command will
    be inserted into the command table specified by the table argument.

    The wrapper will be called like

      wrapper(orig, *args, **kwargs)

    where orig is the original (wrapped) function, and *args, **kwargs
    are the arguments passed to it.
    '''
    assert util.safehasattr(wrapper, '__call__')
    aliases, entry = cmdutil.findcmd(command, table)
    for alias, e in table.iteritems():
        if e is entry:
            key = alias
            break

    origfn = entry[0]
    def wrap(*args, **kwargs):
        return util.checksignature(wrapper)(
            util.checksignature(origfn), *args, **kwargs)

    wrap.__doc__ = getattr(origfn, '__doc__')
    wrap.__module__ = getattr(origfn, '__module__')

    newentry = list(entry)
    newentry[0] = wrap
    table[key] = tuple(newentry)
    return entry
def wrapcommand(table, command, wrapper):
    '''Wrap the command named `command' in table

    Replace command in the command table with wrapper. The wrapped command will
    be inserted into the command table specified by the table argument.

    The wrapper will be called like

      wrapper(orig, *args, **kwargs)

    where orig is the original (wrapped) function, and *args, **kwargs
    are the arguments passed to it.
    '''
    assert util.safehasattr(wrapper, '__call__')
    aliases, entry = cmdutil.findcmd(command, table)
    for alias, e in table.iteritems():
        if e is entry:
            key = alias
            break

    origfn = entry[0]

    def wrap(*args, **kwargs):
        return util.checksignature(wrapper)(util.checksignature(origfn), *args,
                                            **kwargs)

    wrap.__doc__ = getattr(origfn, '__doc__')
    wrap.__module__ = getattr(origfn, '__module__')

    newentry = list(entry)
    newentry[0] = wrap
    table[key] = tuple(newentry)
    return entry
예제 #10
0
    def __init__(self, name, definition, cmdtable):
        self.name = self.cmd = name
        self.cmdname = ''
        self.definition = definition
        self.fn = None
        self.args = []
        self.opts = []
        self.help = ''
        self.norepo = True
        self.optionalrepo = False
        self.badalias = None
        self.unknowncmd = False

        try:
            aliases, entry = cmdutil.findcmd(self.name, cmdtable)
            for alias, e in cmdtable.iteritems():
                if e is entry:
                    self.cmd = alias
                    break
            self.shadows = True
        except error.UnknownCommand:
            self.shadows = False

        if not self.definition:
            self.badalias = _("no definition for alias '%s'") % self.name
            return

        if self.definition.startswith('!'):
            self.shell = True

            def fn(ui, *args):
                env = {'HG_ARGS': ' '.join((self.name, ) + args)}

                def _checkvar(m):
                    if m.groups()[0] == '$':
                        return m.group()
                    elif int(m.groups()[0]) <= len(args):
                        return m.group()
                    else:
                        ui.debug("No argument found for substitution "
                                 "of %i variable in alias '%s' definition." %
                                 (int(m.groups()[0]), self.name))
                        return ''

                cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
                cmd = aliasinterpolate(self.name, args, cmd)
                return util.system(cmd, environ=env, out=ui.fout)

            self.fn = fn
            return

        try:
            args = shlex.split(self.definition)
        except ValueError, inst:
            self.badalias = (_("error in definition for alias '%s': %s") %
                             (self.name, inst))
            return
예제 #11
0
    def __init__(self, name, definition, cmdtable):
        self.name = name
        self.definition = definition
        self.args = []
        self.opts = []
        self.help = ''
        self.norepo = True

        try:
            cmdutil.findcmd(self.name, cmdtable, True)
            self.shadows = True
        except error.UnknownCommand:
            self.shadows = False

        if not self.definition:
            def fn(ui, *args):
                ui.warn(_("no definition for alias '%s'\n") % self.name)
                return 1
            self.fn = fn

            return

        args = shlex.split(self.definition)
        cmd = args.pop(0)
        opts = []
        help = ''

        try:
            self.fn, self.opts, self.help = cmdutil.findcmd(cmd, cmdtable, False)[1]
            self.args = aliasargs(self.fn) + args
            if cmd not in commands.norepo.split(' '):
                self.norepo = False
        except error.UnknownCommand:
            def fn(ui, *args):
                ui.warn(_("alias '%s' resolves to unknown command '%s'\n") \
                            % (self.name, cmd))
                return 1
            self.fn = fn
        except error.AmbiguousCommand:
            def fn(ui, *args):
                ui.warn(_("alias '%s' resolves to ambiguous command '%s'\n") \
                            % (self.name, cmd))
                return 1
            self.fn = fn
def wrapcommand(table, command, wrapper, synopsis=None, docstring=None):
    '''Wrap the command named `command' in table

    Replace command in the command table with wrapper. The wrapped command will
    be inserted into the command table specified by the table argument.

    The wrapper will be called like

      wrapper(orig, *args, **kwargs)

    where orig is the original (wrapped) function, and *args, **kwargs
    are the arguments passed to it.

    Optionally append to the command synopsis and docstring, used for help.
    For example, if your extension wraps the ``bookmarks`` command to add the
    flags ``--remote`` and ``--all`` you might call this function like so:

      synopsis = ' [-a] [--remote]'
      docstring = """

      The ``remotenames`` extension adds the ``--remote`` and ``--all`` (``-a``)
      flags to the bookmarks command. Either flag will show the remote bookmarks
      known to the repository; ``--remote`` will also supress the output of the
      local bookmarks.
      """

      extensions.wrapcommand(commands.table, 'bookmarks', exbookmarks,
                             synopsis, docstring)
    '''
    assert callable(wrapper)
    aliases, entry = cmdutil.findcmd(command, table)
    for alias, e in table.iteritems():
        if e is entry:
            key = alias
            break

    origfn = entry[0]
    def wrap(*args, **kwargs):
        return util.checksignature(wrapper)(
            util.checksignature(origfn), *args, **kwargs)

    wrap.__module__ = getattr(origfn, '__module__')

    doc = getattr(origfn, '__doc__')
    if docstring is not None:
        doc += docstring
    wrap.__doc__ = doc

    newentry = list(entry)
    newentry[0] = wrap
    if synopsis is not None:
        newentry[2] += synopsis
    table[key] = tuple(newentry)
    return entry
예제 #13
0
 def helpcmd(name):
     try:
         aliases, entry = cmdutil.findcmd(name, commands.table,
                                          strict=unknowncmd)
     except error.AmbiguousCommand, inst:
         # py3k fix: except vars can't be used outside the scope of the
         # except block, nor can be used inside a lambda. python issue4617
         prefix = inst.args[0]
         select = lambda c: c.lstrip('^').startswith(prefix)
         rst = helplist(select)
         return rst
예제 #14
0
 def helpcmd(name):
     try:
         aliases, entry = cmdutil.findcmd(name, commands.table,
                                          strict=unknowncmd)
     except error.AmbiguousCommand, inst:
         # py3k fix: except vars can't be used outside the scope of the
         # except block, nor can be used inside a lambda. python issue4617
         prefix = inst.args[0]
         select = lambda c: c.lstrip('^').startswith(prefix)
         rst = helplist(select)
         return rst
예제 #15
0
파일: dispatch.py 프로젝트: RayFerr000/PLTL
    def __init__(self, name, definition, cmdtable):
        self.name = self.cmd = name
        self.cmdname = ''
        self.definition = definition
        self.fn = None
        self.args = []
        self.opts = []
        self.help = ''
        self.norepo = True
        self.optionalrepo = False
        self.badalias = None
        self.unknowncmd = False

        try:
            aliases, entry = cmdutil.findcmd(self.name, cmdtable)
            for alias, e in cmdtable.iteritems():
                if e is entry:
                    self.cmd = alias
                    break
            self.shadows = True
        except error.UnknownCommand:
            self.shadows = False

        if not self.definition:
            self.badalias = _("no definition for alias '%s'") % self.name
            return

        if self.definition.startswith('!'):
            self.shell = True
            def fn(ui, *args):
                env = {'HG_ARGS': ' '.join((self.name,) + args)}
                def _checkvar(m):
                    if m.groups()[0] == '$':
                        return m.group()
                    elif int(m.groups()[0]) <= len(args):
                        return m.group()
                    else:
                        ui.debug("No argument found for substitution "
                                 "of %i variable in alias '%s' definition."
                                 % (int(m.groups()[0]), self.name))
                        return ''
                cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
                cmd = aliasinterpolate(self.name, args, cmd)
                return ui.system(cmd, environ=env)
            self.fn = fn
            return

        try:
            args = shlex.split(self.definition)
        except ValueError, inst:
            self.badalias = (_("error in definition for alias '%s': %s")
                             % (self.name, inst))
            return
예제 #16
0
def wrapcommand(table, command, wrapper, synopsis=None, docstring=None):
    '''Wrap the command named `command' in table

    Replace command in the command table with wrapper. The wrapped command will
    be inserted into the command table specified by the table argument.

    The wrapper will be called like

      wrapper(orig, *args, **kwargs)

    where orig is the original (wrapped) function, and *args, **kwargs
    are the arguments passed to it.

    Optionally append to the command synopsis and docstring, used for help.
    For example, if your extension wraps the ``bookmarks`` command to add the
    flags ``--remote`` and ``--all`` you might call this function like so:

      synopsis = ' [-a] [--remote]'
      docstring = """

      The ``remotenames`` extension adds the ``--remote`` and ``--all`` (``-a``)
      flags to the bookmarks command. Either flag will show the remote bookmarks
      known to the repository; ``--remote`` will also supress the output of the
      local bookmarks.
      """

      extensions.wrapcommand(commands.table, 'bookmarks', exbookmarks,
                             synopsis, docstring)
    '''
    assert callable(wrapper)
    aliases, entry = cmdutil.findcmd(command, table)
    for alias, e in table.iteritems():
        if e is entry:
            key = alias
            break

    origfn = entry[0]
    wrap = bind(util.checksignature(wrapper), util.checksignature(origfn))

    wrap.__module__ = getattr(origfn, '__module__')

    doc = getattr(origfn, '__doc__')
    if docstring is not None:
        doc += docstring
    wrap.__doc__ = doc

    newentry = list(entry)
    newentry[0] = wrap
    if synopsis is not None:
        newentry[2] += synopsis
    table[key] = tuple(newentry)
    return entry
예제 #17
0
def _checkshellalias(lui, ui, args, precheck=True):
    """Return the function to run the shell alias, if it is required

    'precheck' is whether this function is invoked before adding
    aliases or not.
    """
    options = {}

    try:
        args = fancyopts.fancyopts(args, commands.globalopts, options)
    except fancyopts.getopt.GetoptError:
        return

    if not args:
        return

    if precheck:
        strict = True
        norepo = commands.norepo
        optionalrepo = commands.optionalrepo

        def restorecommands():
            commands.norepo = norepo
            commands.optionalrepo = optionalrepo

        cmdtable = commands.table.copy()
        addaliases(lui, cmdtable)
    else:
        strict = False

        def restorecommands():
            pass

        cmdtable = commands.table

    cmd = args[0]
    try:
        aliases, entry = cmdutil.findcmd(cmd, cmdtable, strict)
    except (error.AmbiguousCommand, error.UnknownCommand):
        restorecommands()
        return

    cmd = aliases[0]
    fn = entry[0]

    if cmd and util.safehasattr(fn, 'shell'):
        d = lambda: fn(ui, *args[1:])
        return lambda: runcommand(lui, None, cmd, args[:1], ui, options, d, [],
                                  {})

    restorecommands()
예제 #18
0
파일: dispatch.py 프로젝트: RayFerr000/PLTL
def _checkshellalias(lui, ui, args, precheck=True):
    """Return the function to run the shell alias, if it is required

    'precheck' is whether this function is invoked before adding
    aliases or not.
    """
    options = {}

    try:
        args = fancyopts.fancyopts(args, commands.globalopts, options)
    except fancyopts.getopt.GetoptError:
        return

    if not args:
        return

    if precheck:
        strict = True
        norepo = commands.norepo
        optionalrepo = commands.optionalrepo
        def restorecommands():
            commands.norepo = norepo
            commands.optionalrepo = optionalrepo
        cmdtable = commands.table.copy()
        addaliases(lui, cmdtable)
    else:
        strict = False
        def restorecommands():
            pass
        cmdtable = commands.table

    cmd = args[0]
    try:
        aliases, entry = cmdutil.findcmd(cmd, cmdtable, strict)
    except (error.AmbiguousCommand, error.UnknownCommand):
        restorecommands()
        return

    cmd = aliases[0]
    fn = entry[0]

    if cmd and util.safehasattr(fn, 'shell'):
        d = lambda: fn(ui, *args[1:])
        return lambda: runcommand(lui, None, cmd, args[:1], ui, options, d,
                                  [], {})

    restorecommands()
예제 #19
0
 def findcmd(cmd, name, path):
     try:
         mod = loadpath(path, 'hgext.%s' % name)
     except Exception:
         return
     try:
         aliases, entry = cmdutil.findcmd(cmd, getattr(mod, 'cmdtable', {}),
                                          strict)
     except (error.AmbiguousCommand, error.UnknownCommand):
         return
     for c in aliases:
         if c.startswith(cmd):
             cmd = c
             break
     else:
         cmd = aliases[0]
     return (cmd, name, mod)
예제 #20
0
 def findcmd(cmd, name, path):
     try:
         mod = loadpath(path, 'hgext.%s' % name)
     except Exception:
         return
     try:
         aliases, entry = cmdutil.findcmd(cmd,
             getattr(mod, 'cmdtable', {}), strict)
     except (error.AmbiguousCommand, error.UnknownCommand):
         return
     for c in aliases:
         if c.startswith(cmd):
             cmd = c
             break
     else:
         cmd = aliases[0]
     return (cmd, name, mod)
예제 #21
0
def wrapcommand(table, command, wrapper):
    aliases, entry = cmdutil.findcmd(command, table)
    for alias, e in table.iteritems():
        if e is entry:
            key = alias
            break

    origfn = entry[0]
    def wrap(*args, **kwargs):
        return util.checksignature(wrapper)(
            util.checksignature(origfn), *args, **kwargs)

    wrap.__doc__ = getattr(origfn, '__doc__')
    wrap.__module__ = getattr(origfn, '__module__')

    newentry = list(entry)
    newentry[0] = wrap
    table[key] = tuple(newentry)
    return entry
예제 #22
0
 def findcmd(cmd, name, path):
     try:
         mod = loadpath(path, "hgext.%s" % name)
     except Exception:
         return
     try:
         aliases, entry = cmdutil.findcmd(cmd, getattr(mod, "cmdtable", {}), strict)
     except (error.AmbiguousCommand, error.UnknownCommand):
         return
     except Exception:
         ui.warn(_("warning: error finding commands in %s\n") % path)
         ui.traceback()
         return
     for c in aliases:
         if c.startswith(cmd):
             cmd = c
             break
     else:
         cmd = aliases[0]
     return (cmd, name, mod)
예제 #23
0
def wrapcommand(table, command, wrapper):
    aliases, entry = cmdutil.findcmd(command, table)
    for alias, e in table.iteritems():
        if e is entry:
            key = alias
            break

    origfn = entry[0]

    def wrap(*args, **kwargs):
        return util.checksignature(wrapper)(util.checksignature(origfn), *args,
                                            **kwargs)

    wrap.__doc__ = getattr(origfn, '__doc__')
    wrap.__module__ = getattr(origfn, '__module__')

    newentry = list(entry)
    newentry[0] = wrap
    table[key] = tuple(newentry)
    return entry
예제 #24
0
파일: dispatch.py 프로젝트: ezc/mercurial
def _checkshellalias(ui, args):
    cwd = os.getcwd()
    norepo = commands.norepo
    options = {}

    try:
        args = fancyopts.fancyopts(args, commands.globalopts, options)
    except fancyopts.getopt.GetoptError:
        return

    if not args:
        return

    _parseconfig(ui, options['config'])
    if options['cwd']:
        os.chdir(options['cwd'])

    path, lui = _getlocal(ui, [options['repository']])

    cmdtable = commands.table.copy()
    addaliases(lui, cmdtable)

    cmd = args[0]
    try:
        aliases, entry = cmdutil.findcmd(cmd, cmdtable,
                                         lui.config("ui", "strict"))
    except (error.AmbiguousCommand, error.UnknownCommand):
        commands.norepo = norepo
        os.chdir(cwd)
        return

    cmd = aliases[0]
    fn = entry[0]

    if cmd and hasattr(fn, 'shell'):
        d = lambda: fn(ui, *args[1:])
        return lambda: runcommand(lui, None, cmd, args[:1], ui, options, d, [],
                                  {})

    commands.norepo = norepo
    os.chdir(cwd)
예제 #25
0
def _parse(ui, args):
    options = {}
    cmdoptions = {}

    try:
        args = fancyopts.fancyopts(args, commands.globalopts, options)
    except fancyopts.getopt.GetoptError as inst:
        raise error.CommandError(None, inst)

    if args:
        cmd, args = args[0], args[1:]
        aliases, entry = cmdutil.findcmd(cmd, commands.table,
                                         ui.configbool("ui", "strict"))
        cmd = aliases[0]
        args = aliasargs(entry[0], args)
        defaults = ui.config("defaults", cmd)
        if defaults:
            args = map(util.expandpath, shlex.split(defaults)) + args
        c = list(entry[1])
    else:
        cmd = None
        c = []

    # combine global options into local
    for o in commands.globalopts:
        c.append((o[0], o[1], options[o[1]], o[3]))

    try:
        args = fancyopts.fancyopts(args, c, cmdoptions, True)
    except fancyopts.getopt.GetoptError as inst:
        raise error.CommandError(cmd, inst)

    # separate global options back out
    for o in commands.globalopts:
        n = o[1]
        options[n] = cmdoptions[n]
        del cmdoptions[n]

    return (cmd, cmd and entry[0] or None, args, options, cmdoptions)
예제 #26
0
def _checkshellalias(ui, args):
    cwd = os.getcwd()
    norepo = commands.norepo
    options = {}

    try:
        args = fancyopts.fancyopts(args, commands.globalopts, options)
    except fancyopts.getopt.GetoptError:
        return

    if not args:
        return

    _parseconfig(ui, options['config'])
    if options['cwd']:
        os.chdir(options['cwd'])

    path, lui = _getlocal(ui, [options['repository']])

    cmdtable = commands.table.copy()
    addaliases(lui, cmdtable)

    cmd = args[0]
    try:
        aliases, entry = cmdutil.findcmd(cmd, cmdtable, lui.config("ui", "strict"))
    except (error.AmbiguousCommand, error.UnknownCommand):
        commands.norepo = norepo
        os.chdir(cwd)
        return

    cmd = aliases[0]
    fn = entry[0]

    if cmd and hasattr(fn, 'shell'):
        d = lambda: fn(ui, *args[1:])
        return lambda: runcommand(lui, None, cmd, args[:1], ui, options, d, [], {})

    commands.norepo = norepo
    os.chdir(cwd)
예제 #27
0
    def helpcmd(name):
        try:
            aliases, entry = cmdutil.findcmd(name,
                                             commands.table,
                                             strict=unknowncmd)
        except error.AmbiguousCommand as inst:
            # py3k fix: except vars can't be used outside the scope of the
            # except block, nor can be used inside a lambda. python issue4617
            prefix = inst.args[0]
            select = lambda c: c.lstrip('^').startswith(prefix)
            rst = helplist(select)
            return rst

        rst = []

        # check if it's an invalid alias and display its error if it is
        if getattr(entry[0], 'badalias', None):
            rst.append(entry[0].badalias + '\n')
            if entry[0].unknowncmd:
                try:
                    rst.extend(helpextcmd(entry[0].cmdname))
                except error.UnknownCommand:
                    pass
            return rst

        # synopsis
        if len(entry) > 2:
            if entry[2].startswith('hg'):
                rst.append("%s\n" % entry[2])
            else:
                rst.append('hg %s %s\n' % (aliases[0], entry[2]))
        else:
            rst.append('hg %s\n' % aliases[0])
        # aliases
        if full and not ui.quiet and len(aliases) > 1:
            rst.append(_("\naliases: %s\n") % ', '.join(aliases[1:]))
        rst.append('\n')

        # description
        doc = gettext(entry[0].__doc__)
        if not doc:
            doc = _("(no help text available)")
        if util.safehasattr(entry[0], 'definition'):  # aliased command
            if entry[0].definition.startswith('!'):  # shell alias
                doc = _(
                    'shell alias for::\n\n    %s') % entry[0].definition[1:]
            else:
                doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
        doc = doc.splitlines(True)
        if ui.quiet or not full:
            rst.append(doc[0])
        else:
            rst.extend(doc)
        rst.append('\n')

        # check if this command shadows a non-trivial (multi-line)
        # extension help text
        try:
            mod = extensions.find(name)
            doc = gettext(mod.__doc__) or ''
            if '\n' in doc.strip():
                msg = _('(use "hg help -e %s" to show help for '
                        'the %s extension)') % (name, name)
                rst.append('\n%s\n' % msg)
        except KeyError:
            pass

        # options
        if not ui.quiet and entry[1]:
            rst.append(optrst(_("options"), entry[1], ui.verbose))

        if ui.verbose:
            rst.append(
                optrst(_("global options"), commands.globalopts, ui.verbose))

        if not ui.verbose:
            if not full:
                rst.append(_('\n(use "hg %s -h" to show more help)\n') % name)
            elif not ui.quiet:
                rst.append(
                    _('\n(some details hidden, use --verbose '
                      'to show complete help)'))

        return rst
예제 #28
0
class cmdalias(object):
    def __init__(self, name, definition, cmdtable):
        self.name = self.cmd = name
        self.cmdname = ''
        self.definition = definition
        self.fn = None
        self.args = []
        self.opts = []
        self.help = ''
        self.norepo = True
        self.optionalrepo = False
        self.badalias = None
        self.unknowncmd = False

        try:
            aliases, entry = cmdutil.findcmd(self.name, cmdtable)
            for alias, e in cmdtable.iteritems():
                if e is entry:
                    self.cmd = alias
                    break
            self.shadows = True
        except error.UnknownCommand:
            self.shadows = False

        if not self.definition:
            self.badalias = _("no definition for alias '%s'") % self.name
            return

        if self.definition.startswith('!'):
            self.shell = True

            def fn(ui, *args):
                env = {'HG_ARGS': ' '.join((self.name, ) + args)}

                def _checkvar(m):
                    if m.groups()[0] == '$':
                        return m.group()
                    elif int(m.groups()[0]) <= len(args):
                        return m.group()
                    else:
                        ui.debug("No argument found for substitution "
                                 "of %i variable in alias '%s' definition." %
                                 (int(m.groups()[0]), self.name))
                        return ''

                cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
                cmd = aliasinterpolate(self.name, args, cmd)
                return util.system(cmd, environ=env, out=ui.fout)

            self.fn = fn
            return

        try:
            args = shlex.split(self.definition)
        except ValueError, inst:
            self.badalias = (_("error in definition for alias '%s': %s") %
                             (self.name, inst))
            return
        self.cmdname = cmd = args.pop(0)
        args = map(util.expandpath, args)

        for invalidarg in ("--cwd", "-R", "--repository", "--repo",
                           "--config"):
            if _earlygetopt([invalidarg], args):
                self.badalias = (
                    _("error in definition for alias '%s': %s may "
                      "only be given on the command line") %
                    (self.name, invalidarg))
                return

        try:
            tableentry = cmdutil.findcmd(cmd, cmdtable, False)[1]
            if len(tableentry) > 2:
                self.fn, self.opts, self.help = tableentry
            else:
                self.fn, self.opts = tableentry

            self.args = aliasargs(self.fn, args)
            if cmd not in commands.norepo.split(' '):
                self.norepo = False
            if cmd in commands.optionalrepo.split(' '):
                self.optionalrepo = True
            if self.help.startswith("hg " + cmd):
                # drop prefix in old-style help lines so hg shows the alias
                self.help = self.help[4 + len(cmd):]
            self.__doc__ = self.fn.__doc__

        except error.UnknownCommand:
            self.badalias = (_("alias '%s' resolves to unknown command '%s'") %
                             (self.name, cmd))
            self.unknowncmd = True
        except error.AmbiguousCommand:
            self.badalias = (
                _("alias '%s' resolves to ambiguous command '%s'") %
                (self.name, cmd))
예제 #29
0
        if aliasdef.optionalrepo:
            commands.optionalrepo += ' %s' % alias


def _parse(ui, args):
    options = {}
    cmdoptions = {}

    try:
        args = fancyopts.fancyopts(args, commands.globalopts, options)
    except fancyopts.getopt.GetoptError, inst:
        raise error.CommandError(None, inst)

    if args:
        cmd, args = args[0], args[1:]
        aliases, entry = cmdutil.findcmd(cmd, commands.table,
                                         ui.configbool("ui", "strict"))
        cmd = aliases[0]
        args = aliasargs(entry[0], args)
        defaults = ui.config("defaults", cmd)
        if defaults:
            args = map(util.expandpath, shlex.split(defaults)) + args
        c = list(entry[1])
    else:
        cmd = None
        c = []

    # combine global options into local
    for o in commands.globalopts:
        c.append((o[0], o[1], options[o[1]], o[3]))

    try:
예제 #30
0
    def __init__(self, name, definition, cmdtable):
        self.name = name
        self.definition = definition
        self.args = []
        self.opts = []
        self.help = ''
        self.norepo = True
        self.badalias = False

        try:
            cmdutil.findcmd(self.name, cmdtable, True)
            self.shadows = True
        except error.UnknownCommand:
            self.shadows = False

        if not self.definition:

            def fn(ui, *args):
                ui.warn(_("no definition for alias '%s'\n") % self.name)
                return 1

            self.fn = fn
            self.badalias = True

            return

        args = shlex.split(self.definition)
        cmd = args.pop(0)

        try:
            tableentry = cmdutil.findcmd(cmd, cmdtable, False)[1]
            if len(tableentry) > 2:
                self.fn, self.opts, self.help = tableentry
            else:
                self.fn, self.opts = tableentry

            self.args = aliasargs(self.fn) + args
            if cmd not in commands.norepo.split(' '):
                self.norepo = False
            if self.help.startswith("hg " + cmd):
                # drop prefix in old-style help lines so hg shows the alias
                self.help = self.help[4 + len(cmd):]
            self.__doc__ = _("alias for: hg %s\n\n%s") \
                               % (definition, self.fn.__doc__)

        except error.UnknownCommand:

            def fn(ui, *args):
                ui.warn(_("alias '%s' resolves to unknown command '%s'\n") \
                            % (self.name, cmd))
                try:
                    # check if the command is in a disabled extension
                    commands.help_(ui, cmd, unknowncmd=True)
                except error.UnknownCommand:
                    pass
                return 1

            self.fn = fn
            self.badalias = True
        except error.AmbiguousCommand:

            def fn(ui, *args):
                ui.warn(_("alias '%s' resolves to ambiguous command '%s'\n") \
                            % (self.name, cmd))
                return 1

            self.fn = fn
            self.badalias = True
예제 #31
0
            return None

    return p

def _parse(ui, args):
    options = {}
    cmdoptions = {}

    try:
        args = fancyopts.fancyopts(args, commands.globalopts, options)
    except fancyopts.getopt.GetoptError, inst:
        raise ParseError(None, inst)

    if args:
        cmd, args = args[0], args[1:]
        aliases, i = cmdutil.findcmd(ui, cmd, commands.table)
        cmd = aliases[0]
        defaults = ui.config("defaults", cmd)
        if defaults:
            args = shlex.split(defaults) + args
        c = list(i[1])
    else:
        cmd = None
        c = []

    # combine global options into local
    for o in commands.globalopts:
        c.append((o[0], o[1], options[o[1]], o[3]))

    try:
        args = fancyopts.fancyopts(args, c, cmdoptions)
예제 #32
0
    def __init__(self, name, definition, cmdtable):
        self.name = self.cmd = name
        self.cmdname = ''
        self.definition = definition
        self.args = []
        self.opts = []
        self.help = ''
        self.norepo = True
        self.badalias = False

        try:
            aliases, entry = cmdutil.findcmd(self.name, cmdtable)
            for alias, e in cmdtable.iteritems():
                if e is entry:
                    self.cmd = alias
                    break
            self.shadows = True
        except error.UnknownCommand:
            self.shadows = False

        if not self.definition:
            def fn(ui, *args):
                ui.warn(_("no definition for alias '%s'\n") % self.name)
                return 1
            self.fn = fn
            self.badalias = True

            return

        if self.definition.startswith('!'):
            self.shell = True
            def fn(ui, *args):
                env = {'HG_ARGS': ' '.join((self.name,) + args)}
                def _checkvar(m):
                    if int(m.groups()[0]) <= len(args):
                        return m.group()
                    else:
                        return ''
                cmd = re.sub(r'\$(\d+)', _checkvar, self.definition[1:])
                replace = dict((str(i + 1), arg) for i, arg in enumerate(args))
                replace['0'] = self.name
                replace['@'] = ' '.join(args)
                cmd = util.interpolate(r'\$', replace, cmd)
                return util.system(cmd, environ=env)
            self.fn = fn
            return

        args = shlex.split(self.definition)
        self.cmdname = cmd = args.pop(0)
        args = map(util.expandpath, args)

        for invalidarg in ("--cwd", "-R", "--repository", "--repo"):
            if _earlygetopt([invalidarg], args):
                def fn(ui, *args):
                    ui.warn(_("error in definition for alias '%s': %s may only "
                              "be given on the command line\n")
                            % (self.name, invalidarg))
                    return 1

                self.fn = fn
                self.badalias = True
                return

        try:
            tableentry = cmdutil.findcmd(cmd, cmdtable, False)[1]
            if len(tableentry) > 2:
                self.fn, self.opts, self.help = tableentry
            else:
                self.fn, self.opts = tableentry

            self.args = aliasargs(self.fn) + args
            if cmd not in commands.norepo.split(' '):
                self.norepo = False
            if self.help.startswith("hg " + cmd):
                # drop prefix in old-style help lines so hg shows the alias
                self.help = self.help[4 + len(cmd):]
            self.__doc__ = self.fn.__doc__

        except error.UnknownCommand:
            def fn(ui, *args):
                ui.warn(_("alias '%s' resolves to unknown command '%s'\n") \
                            % (self.name, cmd))
                try:
                    # check if the command is in a disabled extension
                    commands.help_(ui, cmd, unknowncmd=True)
                except error.UnknownCommand:
                    pass
                return 1
            self.fn = fn
            self.badalias = True
        except error.AmbiguousCommand:
            def fn(ui, *args):
                ui.warn(_("alias '%s' resolves to ambiguous command '%s'\n") \
                            % (self.name, cmd))
                return 1
            self.fn = fn
            self.badalias = True
예제 #33
0
        cmdtable[aliasdef.cmd] = (aliasdef, aliasdef.opts, aliasdef.help)
        if aliasdef.norepo:
            commands.norepo += ' %s' % alias

def _parse(ui, args):
    options = {}
    cmdoptions = {}

    try:
        args = fancyopts.fancyopts(args, commands.globalopts, options)
    except fancyopts.getopt.GetoptError, inst:
        raise error.CommandError(None, inst)

    if args:
        cmd, args = args[0], args[1:]
        aliases, entry = cmdutil.findcmd(cmd, commands.table,
                                     ui.config("ui", "strict"))
        cmd = aliases[0]
        args = aliasargs(entry[0], args)
        defaults = ui.config("defaults", cmd)
        if defaults:
            args = map(util.expandpath, shlex.split(defaults)) + args
        c = list(entry[1])
    else:
        cmd = None
        c = []

    # combine global options into local
    for o in commands.globalopts:
        c.append((o[0], o[1], options[o[1]], o[3]))

    try:
예제 #34
0
        if aliasdef.norepo:
            commands.norepo += ' %s' % alias


def _parse(ui, args):
    options = {}
    cmdoptions = {}

    try:
        args = fancyopts.fancyopts(args, commands.globalopts, options)
    except fancyopts.getopt.GetoptError, inst:
        raise error.ParseError(None, inst)

    if args:
        cmd, args = args[0], args[1:]
        aliases, i = cmdutil.findcmd(cmd, commands.table,
                                     ui.config("ui", "strict"))
        cmd = aliases[0]
        args = aliasargs(i[0]) + args
        defaults = ui.config("defaults", cmd)
        if defaults:
            args = shlex.split(defaults) + args
        c = list(i[1])
    else:
        cmd = None
        c = []

    # combine global options into local
    for o in commands.globalopts:
        c.append((o[0], o[1], options[o[1]], o[3]))

    try:
예제 #35
0
    def helpcmd(name):
        try:
            aliases, entry = cmdutil.findcmd(name, commands.table,
                                             strict=unknowncmd)
        except error.AmbiguousCommand as inst:
            # py3k fix: except vars can't be used outside the scope of the
            # except block, nor can be used inside a lambda. python issue4617
            prefix = inst.args[0]
            select = lambda c: c.lstrip('^').startswith(prefix)
            rst = helplist(select)
            return rst

        rst = []

        # check if it's an invalid alias and display its error if it is
        if getattr(entry[0], 'badalias', None):
            rst.append(entry[0].badalias + '\n')
            if entry[0].unknowncmd:
                try:
                    rst.extend(helpextcmd(entry[0].cmdname))
                except error.UnknownCommand:
                    pass
            return rst

        # synopsis
        if len(entry) > 2:
            if entry[2].startswith('hg'):
                rst.append("%s\n" % entry[2])
            else:
                rst.append('hg %s %s\n' % (aliases[0], entry[2]))
        else:
            rst.append('hg %s\n' % aliases[0])
        # aliases
        if full and not ui.quiet and len(aliases) > 1:
            rst.append(_("\naliases: %s\n") % ', '.join(aliases[1:]))
        rst.append('\n')

        # description
        doc = gettext(entry[0].__doc__)
        if not doc:
            doc = _("(no help text available)")
        if util.safehasattr(entry[0], 'definition'):  # aliased command
            if entry[0].definition.startswith('!'):  # shell alias
                doc = _('shell alias for::\n\n    %s') % entry[0].definition[1:]
            else:
                doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
        doc = doc.splitlines(True)
        if ui.quiet or not full:
            rst.append(doc[0])
        else:
            rst.extend(doc)
        rst.append('\n')

        # check if this command shadows a non-trivial (multi-line)
        # extension help text
        try:
            mod = extensions.find(name)
            doc = gettext(mod.__doc__) or ''
            if '\n' in doc.strip():
                msg = _('(use "hg help -e %s" to show help for '
                        'the %s extension)') % (name, name)
                rst.append('\n%s\n' % msg)
        except KeyError:
            pass

        # options
        if not ui.quiet and entry[1]:
            rst.append(optrst(_("options"), entry[1], ui.verbose))

        if ui.verbose:
            rst.append(optrst(_("global options"),
                              commands.globalopts, ui.verbose))

        if not ui.verbose:
            if not full:
                rst.append(_('\n(use "hg %s -h" to show more help)\n')
                           % name)
            elif not ui.quiet:
                rst.append(_('\n(some details hidden, use --verbose '
                               'to show complete help)'))

        return rst
예제 #36
0
    def __init__(self, name, definition, cmdtable):
        self.name = self.cmd = name
        self.cmdname = ''
        self.definition = definition
        self.args = []
        self.opts = []
        self.help = ''
        self.norepo = True
        self.badalias = False

        try:
            aliases, entry = cmdutil.findcmd(self.name, cmdtable)
            for alias, e in cmdtable.iteritems():
                if e is entry:
                    self.cmd = alias
                    break
            self.shadows = True
        except error.UnknownCommand:
            self.shadows = False

        if not self.definition:
            def fn(ui, *args):
                ui.warn(_("no definition for alias '%s'\n") % self.name)
                return 1
            self.fn = fn
            self.badalias = True

            return

        if self.definition.startswith('!'):
            self.shell = True
            def fn(ui, *args):
                env = {'HG_ARGS': ' '.join((self.name,) + args)}
                def _checkvar(m):
                    if m.groups()[0] == '$':
                        return m.group()
                    elif int(m.groups()[0]) <= len(args):
                        return m.group()
                    else:
                        ui.debug("No argument found for substitution "
                                 "of %i variable in alias '%s' definition."
                                 % (int(m.groups()[0]), self.name))
                        return ''
                cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
                replace = dict((str(i + 1), arg) for i, arg in enumerate(args))
                replace['0'] = self.name
                replace['@'] = ' '.join(args)
                cmd = util.interpolate(r'\$', replace, cmd, escape_prefix=True)
                return util.system(cmd, environ=env, out=ui.fout)
            self.fn = fn
            return

        args = shlex.split(self.definition)
        self.cmdname = cmd = args.pop(0)
        args = map(util.expandpath, args)

        for invalidarg in ("--cwd", "-R", "--repository", "--repo"):
            if _earlygetopt([invalidarg], args):
                def fn(ui, *args):
                    ui.warn(_("error in definition for alias '%s': %s may only "
                              "be given on the command line\n")
                            % (self.name, invalidarg))
                    return 1

                self.fn = fn
                self.badalias = True
                return

        try:
            tableentry = cmdutil.findcmd(cmd, cmdtable, False)[1]
            if len(tableentry) > 2:
                self.fn, self.opts, self.help = tableentry
            else:
                self.fn, self.opts = tableentry

            self.args = aliasargs(self.fn, args)
            if cmd not in commands.norepo.split(' '):
                self.norepo = False
            if self.help.startswith("hg " + cmd):
                # drop prefix in old-style help lines so hg shows the alias
                self.help = self.help[4 + len(cmd):]
            self.__doc__ = self.fn.__doc__

        except error.UnknownCommand:
            def fn(ui, *args):
                ui.warn(_("alias '%s' resolves to unknown command '%s'\n") \
                            % (self.name, cmd))
                try:
                    # check if the command is in a disabled extension
                    commands.help_(ui, cmd, unknowncmd=True)
                except error.UnknownCommand:
                    pass
                return 1
            self.fn = fn
            self.badalias = True
        except error.AmbiguousCommand:
            def fn(ui, *args):
                ui.warn(_("alias '%s' resolves to ambiguous command '%s'\n") \
                            % (self.name, cmd))
                return 1
            self.fn = fn
            self.badalias = True
예제 #37
0
    def __init__(self, name, definition, cmdtable):
        self.name = name
        self.definition = definition
        self.args = []
        self.opts = []
        self.help = ''
        self.norepo = True
        self.badalias = False

        try:
            cmdutil.findcmd(self.name, cmdtable, True)
            self.shadows = True
        except error.UnknownCommand:
            self.shadows = False

        if not self.definition:
            def fn(ui, *args):
                ui.warn(_("no definition for alias '%s'\n") % self.name)
                return 1
            self.fn = fn
            self.badalias = True

            return

        args = shlex.split(self.definition)
        cmd = args.pop(0)
        args = map(util.expandpath, args)

        try:
            tableentry = cmdutil.findcmd(cmd, cmdtable, False)[1]
            if len(tableentry) > 2:
                self.fn, self.opts, self.help = tableentry
            else:
                self.fn, self.opts = tableentry

            self.args = aliasargs(self.fn) + args
            if cmd not in commands.norepo.split(' '):
                self.norepo = False
            if self.help.startswith("hg " + cmd):
                # drop prefix in old-style help lines so hg shows the alias
                self.help = self.help[4 + len(cmd):]
            self.__doc__ = self.fn.__doc__

        except error.UnknownCommand:
            def fn(ui, *args):
                ui.warn(_("alias '%s' resolves to unknown command '%s'\n") \
                            % (self.name, cmd))
                try:
                    # check if the command is in a disabled extension
                    commands.help_(ui, cmd, unknowncmd=True)
                except error.UnknownCommand:
                    pass
                return 1
            self.fn = fn
            self.badalias = True
        except error.AmbiguousCommand:
            def fn(ui, *args):
                ui.warn(_("alias '%s' resolves to ambiguous command '%s'\n") \
                            % (self.name, cmd))
                return 1
            self.fn = fn
            self.badalias = True
예제 #38
0
    def __init__(self, name, definition, cmdtable):
        self.name = self.cmd = name
        self.cmdname = ''
        self.definition = definition
        self.args = []
        self.opts = []
        self.help = ''
        self.norepo = True
        self.optionalrepo = False
        self.badalias = False

        try:
            aliases, entry = cmdutil.findcmd(self.name, cmdtable)
            for alias, e in cmdtable.iteritems():
                if e is entry:
                    self.cmd = alias
                    break
            self.shadows = True
        except error.UnknownCommand:
            self.shadows = False

        if not self.definition:
            def fn(ui, *args):
                ui.warn(_("no definition for alias '%s'\n") % self.name)
                return -1
            self.fn = fn
            self.badalias = True
            return

        if self.definition.startswith('!'):
            self.shell = True
            def fn(ui, *args):
                env = {'HG_ARGS': ' '.join((self.name,) + args)}
                def _checkvar(m):
                    if m.groups()[0] == '$':
                        return m.group()
                    elif int(m.groups()[0]) <= len(args):
                        return m.group()
                    else:
                        ui.debug("No argument found for substitution "
                                 "of %i variable in alias '%s' definition."
                                 % (int(m.groups()[0]), self.name))
                        return ''
                cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
                replace = dict((str(i + 1), arg) for i, arg in enumerate(args))
                replace['0'] = self.name
                replace['@'] = ' '.join(args)
                cmd = util.interpolate(r'\$', replace, cmd, escape_prefix=True)
                return util.system(cmd, environ=env, out=ui.fout)
            self.fn = fn
            return

        try:
            args = shlex.split(self.definition)
        except ValueError, inst:
            def fn(ui, *args):
                ui.warn(_("error in definition for alias '%s': %s\n")
                        % (self.name, inst))
                return -1
            self.fn = fn
            self.badalias = True
            return