def subrelpath(sub):
    """return path to this subrepo as seen from outermost repo"""
    if util.safehasattr(sub, '_relpath'):
        return sub._relpath
    if not util.safehasattr(sub, '_repo'):
        return sub._path
    return reporelpath(sub._repo)
def json(obj):
    if obj is None or obj is False or obj is True:
        return {None: 'null', False: 'false', True: 'true'}[obj]
    elif isinstance(obj, int) or isinstance(obj, float):
        return str(obj)
    elif isinstance(obj, str):
        u = unicode(obj, encoding.encoding, 'replace')
        return '"%s"' % jsonescape(u)
    elif isinstance(obj, unicode):
        return '"%s"' % jsonescape(obj)
    elif util.safehasattr(obj, 'keys'):
        out = []
        for k, v in sorted(obj.iteritems()):
            s = '%s: %s' % (json(k), json(v))
            out.append(s)
        return '{' + ', '.join(out) + '}'
    elif util.safehasattr(obj, '__iter__'):
        out = []
        for i in obj:
            out.append(json(i))
        return '[' + ', '.join(out) + ']'
    elif util.safehasattr(obj, '__call__'):
        return json(obj())
    else:
        raise TypeError('cannot encode type %s' % obj.__class__.__name__)
Beispiel #3
0
def makefileobj(repo, pat, node=None, desc=None, total=None,
                seqno=None, revwidth=None, mode='wb', pathname=None):

    writable = mode not in ('r', 'rb')

    if not pat or pat == '-':
        fp = writable and repo.ui.fout or repo.ui.fin
        if util.safehasattr(fp, 'fileno'):
            return os.fdopen(os.dup(fp.fileno()), mode)
        else:
            # if this fp can't be duped properly, return
            # a dummy object that can be closed
            class wrappedfileobj(object):
                noop = lambda x: None
                def __init__(self, f):
                    self.f = f
                def __getattr__(self, attr):
                    if attr == 'close':
                        return self.noop
                    else:
                        return getattr(self.f, attr)

            return wrappedfileobj(fp)
    if util.safehasattr(pat, 'write') and writable:
        return pat
    if util.safehasattr(pat, 'read') and 'r' in mode:
        return pat
    return open(makefilename(repo, pat, node, desc, total, seqno, revwidth,
                              pathname),
                mode)
Beispiel #4
0
def subrelpath(sub):
    """return path to this subrepo as seen from outermost repo"""
    if util.safehasattr(sub, '_relpath'):
        return sub._relpath
    if not util.safehasattr(sub, '_repo'):
        return sub._path
    return reporelpath(sub._repo)
def json(obj):
    if obj is None or obj is False or obj is True:
        return {None: "null", False: "false", True: "true"}[obj]
    elif isinstance(obj, int) or isinstance(obj, float):
        return str(obj)
    elif isinstance(obj, str):
        u = unicode(obj, encoding.encoding, "replace")
        return '"%s"' % jsonescape(u)
    elif isinstance(obj, unicode):
        return '"%s"' % jsonescape(obj)
    elif util.safehasattr(obj, "keys"):
        out = []
        for k, v in sorted(obj.iteritems()):
            s = "%s: %s" % (json(k), json(v))
            out.append(s)
        return "{" + ", ".join(out) + "}"
    elif util.safehasattr(obj, "__iter__"):
        out = []
        for i in obj:
            out.append(json(i))
        return "[" + ", ".join(out) + "]"
    elif util.safehasattr(obj, "__call__"):
        return json(obj())
    else:
        raise TypeError("cannot encode type %s" % obj.__class__.__name__)
def _abssource(repo, push=False, abort=True):
    """return pull/push path of repo - either based on parent repo .hgsub info
    or on the top repo config. Abort or return None if no source found."""
    if util.safehasattr(repo, '_subparent'):
        source = util.url(repo._subsource)
        if source.isabs():
            return str(source)
        source.path = posixpath.normpath(source.path)
        parent = _abssource(repo._subparent, push, abort=False)
        if parent:
            parent = util.url(util.pconvert(parent))
            parent.path = posixpath.join(parent.path or '', source.path)
            parent.path = posixpath.normpath(parent.path)
            return str(parent)
    else:  # recursion reached top repo
        if util.safehasattr(repo, '_subtoppath'):
            return repo._subtoppath
        if push and repo.ui.config('paths', 'default-push'):
            return repo.ui.config('paths', 'default-push')
        if repo.ui.config('paths', 'default'):
            return repo.ui.config('paths', 'default')
    if abort:
        raise util.Abort(
            _("default path for subrepository %s not found") %
            reporelpath(repo))
Beispiel #7
0
def json(obj):
    if obj is None or obj is False or obj is True:
        return {None: 'null', False: 'false', True: 'true'}[obj]
    elif isinstance(obj, int) or isinstance(obj, float):
        return str(obj)
    elif isinstance(obj, str):
        u = unicode(obj, encoding.encoding, 'replace')
        return '"%s"' % jsonescape(u)
    elif isinstance(obj, unicode):
        return '"%s"' % jsonescape(obj)
    elif util.safehasattr(obj, 'keys'):
        out = []
        for k, v in sorted(obj.iteritems()):
            s = '%s: %s' % (json(k), json(v))
            out.append(s)
        return '{' + ', '.join(out) + '}'
    elif util.safehasattr(obj, '__iter__'):
        out = []
        for i in obj:
            out.append(json(i))
        return '[' + ', '.join(out) + ']'
    elif util.safehasattr(obj, '__call__'):
        return json(obj())
    else:
        raise TypeError('cannot encode type %s' % obj.__class__.__name__)
def makefileobj(repo, pat, node=None, desc=None, total=None,
                seqno=None, revwidth=None, mode='wb', pathname=None):

    writable = mode not in ('r', 'rb')

    if not pat or pat == '-':
        fp = writable and repo.ui.fout or repo.ui.fin
        if util.safehasattr(fp, 'fileno'):
            return os.fdopen(os.dup(fp.fileno()), mode)
        else:
            # if this fp can't be duped properly, return
            # a dummy object that can be closed
            class wrappedfileobj(object):
                noop = lambda x: None
                def __init__(self, f):
                    self.f = f
                def __getattr__(self, attr):
                    if attr == 'close':
                        return self.noop
                    else:
                        return getattr(self.f, attr)

            return wrappedfileobj(fp)
    if util.safehasattr(pat, 'write') and writable:
        return pat
    if util.safehasattr(pat, 'read') and 'r' in mode:
        return pat
    return open(makefilename(repo, pat, node, desc, total, seqno, revwidth,
                              pathname),
                mode)
Beispiel #9
0
def moduleversion(module):
    '''return version information from given module as a string'''
    if (util.safehasattr(module, 'getversion')
          and callable(module.getversion)):
        version = module.getversion()
    elif util.safehasattr(module, '__version__'):
        version = module.__version__
    else:
        version = ''
    if isinstance(version, (list, tuple)):
        version = '.'.join(str(o) for o in version)
    return version
Beispiel #10
0
def moduleversion(module):
    '''return version information from given module as a string'''
    if (util.safehasattr(module, 'getversion')
            and callable(module.getversion)):
        version = module.getversion()
    elif util.safehasattr(module, '__version__'):
        version = module.__version__
    else:
        version = ''
    if isinstance(version, (list, tuple)):
        version = '.'.join(str(o) for o in version)
    return version
Beispiel #11
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
Beispiel #12
0
 def copies(self, c2):
     if not util.safehasattr(self, "_copycache"):
         self._copycache = {}
     sc2 = str(c2)
     if sc2 not in self._copycache:
         self._copycache[sc2] = copies.pathcopies(c2)
     return self._copycache[sc2]
Beispiel #13
0
def unbundle(repo, cg, heads, source, url):
    """Apply a bundle to a repo.

    this function makes sure the repo is locked during the application and have
    mechanism to check that no push race occurred between the creation of the
    bundle and its application.

    If the push was raced as PushRaced exception is raised."""
    r = 0
    # need a transaction when processing a bundle2 stream
    tr = None
    lock = repo.lock()
    try:
        check_heads(repo, heads, 'uploading changes')
        # push can proceed
        if util.safehasattr(cg, 'params'):
            try:
                tr = repo.transaction('unbundle')
                tr.hookargs['bundle2-exp'] = '1'
                r = bundle2.processbundle(repo, cg, lambda: tr).reply
                cl = repo.unfiltered().changelog
                p = cl.writepending() and repo.root or ""
                repo.hook('b2x-pretransactionclose', throw=True, source=source,
                          url=url, pending=p, **tr.hookargs)
                tr.close()
                repo.hook('b2x-transactionclose', source=source, url=url,
                          **tr.hookargs)
            except Exception, exc:
                exc.duringunbundle2 = True
                raise
        else:
Beispiel #14
0
def runsymbol(context, mapping, key):
    v = mapping.get(key)
    if v is None:
        v = context._defaults.get(key, '')
    if util.safehasattr(v, '__call__'):
        return v(**mapping)
    return v
Beispiel #15
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
Beispiel #16
0
def remoteui(src, opts):
    "build a remote ui from ui or repo and opts"
    if util.safehasattr(src, "baseui"):  # looks like a repository
        dst = src.baseui.copy()  # drop repo-specific config
        src = src.ui  # copy target options from repo
    else:  # assume it's a global ui object
        dst = src.copy()  # keep all global options

    # copy ssh-specific options
    for o in "ssh", "remotecmd":
        v = opts.get(o) or src.config("ui", o)
        if v:
            dst.setconfig("ui", o, v, "copied")

    # copy bundle-specific options
    r = src.config("bundle", "mainreporoot")
    if r:
        dst.setconfig("bundle", "mainreporoot", r, "copied")

    # copy selected local settings to the remote ui
    for sect in ("auth", "hostfingerprints", "http_proxy"):
        for key, val in src.configitems(sect):
            dst.setconfig(sect, key, val, "copied")
    v = src.config("web", "cacerts")
    if v:
        dst.setconfig("web", "cacerts", util.expandpath(v), "copied")

    return dst
Beispiel #17
0
def unbundle(repo, proto, heads):
    their_heads = decodelist(heads)

    try:
        proto.redirect()

        exchange.check_heads(repo, their_heads, 'preparing changes')

        # write bundle data to temporary file because it can be big
        fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
        fp = os.fdopen(fd, 'wb+')
        r = 0
        try:
            proto.getfile(fp)
            fp.seek(0)
            gen = exchange.readbundle(repo.ui, fp, None)
            r = exchange.unbundle(repo, gen, their_heads, 'serve',
                                  proto._client())
            if util.safehasattr(r, 'addpart'):
                # The return looks streameable, we are in the bundle2 case and
                # should return a stream.
                return streamres(r.getchunks())
            return pushres(r)

        finally:
            fp.close()
            os.unlink(tempname)
    except bundle2.UnknownPartError, exc:
            bundler = bundle2.bundle20(repo.ui)
            part = bundle2.bundlepart('B2X:ERROR:UNKNOWNPART',
                                      [('parttype', str(exc))])
            bundler.addpart(part)
            return streamres(bundler.getchunks())
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
Beispiel #19
0
def unbundle(repo, proto, heads):
    their_heads = decodelist(heads)

    try:
        proto.redirect()

        exchange.check_heads(repo, their_heads, 'preparing changes')

        # write bundle data to temporary file because it can be big
        fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
        fp = os.fdopen(fd, 'wb+')
        r = 0
        try:
            proto.getfile(fp)
            fp.seek(0)
            gen = exchange.readbundle(repo.ui, fp, None)
            r = exchange.unbundle(repo, gen, their_heads, 'serve',
                                  proto._client())
            if util.safehasattr(r, 'addpart'):
                # The return looks streameable, we are in the bundle2 case and
                # should return a stream.
                return streamres(r.getchunks())
            return pushres(r)

        finally:
            fp.close()
            os.unlink(tempname)
    except bundle2.UnknownPartError, exc:
        bundler = bundle2.bundle20(repo.ui)
        part = bundle2.bundlepart('B2X:ERROR:UNKNOWNPART',
                                  [('parttype', str(exc))])
        bundler.addpart(part)
        return streamres(bundler.getchunks())
Beispiel #20
0
def reporelpath(repo):
    """return path to this (sub)repo as seen from outermost repo"""
    parent = repo
    while util.safehasattr(parent, '_subparent'):
        parent = parent._subparent
    p = parent.root.rstrip(os.sep)
    return repo.root[len(p) + 1:]
Beispiel #21
0
    def unbundle(self, cg, heads, source):
        '''Send cg (a readable file-like object representing the
        changegroup to push, typically a chunkbuffer object) to the
        remote server as a bundle.

        When pushing a bundle10 stream, return an integer indicating the
        result of the push (see localrepository.addchangegroup()).

        When pushing a bundle20 stream, return a bundle20 stream.'''

        if heads != ['force'] and self.capable('unbundlehash'):
            heads = encodelist(['hashed',
                                util.sha1(''.join(sorted(heads))).digest()])
        else:
            heads = encodelist(heads)

        if util.safehasattr(cg, 'deltaheader'):
            # this a bundle10, do the old style call sequence
            ret, output = self._callpush("unbundle", cg, heads=heads)
            if ret == "":
                raise error.ResponseError(
                    _('push failed:'), output)
            try:
                ret = int(ret)
            except ValueError:
                raise error.ResponseError(
                    _('push failed (unexpected response):'), ret)

            for l in output.splitlines(True):
                self.ui.status(_('remote: '), l)
        else:
            # bundle2 push. Send a stream, fetch a stream.
            stream = self._calltwowaystream('unbundle', cg, heads=heads)
            ret = bundle2.unbundle20(self.ui, stream)
        return ret
Beispiel #22
0
def _exthook(ui, repo, name, cmd, args, throw):
    ui.note(_("running hook %s: %s\n") % (name, cmd))

    env = {}
    for k, v in args.iteritems():
        if util.safehasattr(v, '__call__'):
            v = v()
        if isinstance(v, dict):
            # make the dictionary element order stable across Python
            # implementations
            v = ('{' + ', '.join('%r: %r' % i
                                 for i in sorted(v.iteritems())) + '}')
        env['HG_' + k.upper()] = v

    if repo:
        cwd = repo.root
    else:
        cwd = os.getcwd()
    if 'HG_URL' in env and env['HG_URL'].startswith('remote:http'):
        r = util.system(cmd, environ=env, cwd=cwd, out=ui)
    else:
        r = util.system(cmd, environ=env, cwd=cwd, out=ui.fout)
    if r:
        desc, r = util.explainexit(r)
        if throw:
            raise util.Abort(_('%s hook %s') % (name, desc))
        ui.warn(_('warning: %s hook %s\n') % (name, desc))
    return r
 def copies(self, c2):
     if not util.safehasattr(self, "_copycache"):
         self._copycache = {}
     sc2 = str(c2)
     if sc2 not in self._copycache:
         self._copycache[sc2] = copies.pathcopies(c2)
     return self._copycache[sc2]
Beispiel #24
0
def pushkey(repo, proto, namespace, key, old, new):
    # compatibility with pre-1.8 clients which were accidentally
    # sending raw binary nodes rather than utf-8-encoded hex
    if len(new) == 20 and new.encode('string-escape') != new:
        # looks like it could be a binary node
        try:
            new.decode('utf-8')
            new = encoding.tolocal(new)  # but cleanly decodes as UTF-8
        except UnicodeDecodeError:
            pass  # binary, leave unmodified
    else:
        new = encoding.tolocal(new)  # normal path

    if util.safehasattr(proto, 'restore'):

        proto.redirect()

        try:
            r = repo.pushkey(
                encoding.tolocal(namespace), encoding.tolocal(key),
                encoding.tolocal(old), new) or False
        except util.Abort:
            r = False

        output = proto.restore()

        return '%s\n%s' % (int(r), output)

    r = repo.pushkey(encoding.tolocal(namespace), encoding.tolocal(key),
                     encoding.tolocal(old), new)
    return '%s\n' % int(r)
def unbundle(repo, proto, heads):
    their_heads = decodelist(heads)

    try:
        proto.redirect()

        exchange.check_heads(repo, their_heads, "preparing changes")

        # write bundle data to temporary file because it can be big
        fd, tempname = tempfile.mkstemp(prefix="hg-unbundle-")
        fp = os.fdopen(fd, "wb+")
        r = 0
        try:
            proto.getfile(fp)
            fp.seek(0)
            gen = exchange.readbundle(repo.ui, fp, None)
            r = exchange.unbundle(repo, gen, their_heads, "serve", proto._client())
            if util.safehasattr(r, "addpart"):
                # The return looks streameable, we are in the bundle2 case and
                # should return a stream.
                return streamres(r.getchunks())
            return pushres(r)

        finally:
            fp.close()
            os.unlink(tempname)
    except error.BundleValueError, exc:
        bundler = bundle2.bundle20(repo.ui)
        errpart = bundler.newpart("B2X:ERROR:UNSUPPORTEDCONTENT")
        if exc.parttype is not None:
            errpart.addparam("parttype", exc.parttype)
        if exc.params:
            errpart.addparam("params", "\0".join(exc.params))
        return streamres(bundler.getchunks())
Beispiel #26
0
def stringify(thing):
    """:stringify: Any type. Turns the value into text by converting values into
    text and concatenating them.
    """
    if util.safehasattr(thing, '__iter__') and not isinstance(thing, str):
        return "".join([stringify(t) for t in thing if t is not None])
    return str(thing)
def stringify(thing):
    """:stringify: Any type. Turns the value into text by converting values into
    text and concatenating them.
    """
    if util.safehasattr(thing, '__iter__') and not isinstance(thing, str):
        return "".join([stringify(t) for t in thing if t is not None])
    return str(thing)
Beispiel #28
0
def reporelpath(repo):
    """return path to this (sub)repo as seen from outermost repo"""
    parent = repo
    while util.safehasattr(parent, '_subparent'):
        parent = parent._subparent
    p = parent.root.rstrip(os.sep)
    return repo.root[len(p) + 1:]
Beispiel #29
0
def remoteui(src, opts):
    'build a remote ui from ui or repo and opts'
    if util.safehasattr(src, 'baseui'):  # looks like a repository
        dst = src.baseui.copy()  # drop repo-specific config
        src = src.ui  # copy target options from repo
    else:  # assume it's a global ui object
        dst = src.copy()  # keep all global options

    # copy ssh-specific options
    for o in 'ssh', 'remotecmd':
        v = opts.get(o) or src.config('ui', o)
        if v:
            dst.setconfig("ui", o, v, 'copied')

    # copy bundle-specific options
    r = src.config('bundle', 'mainreporoot')
    if r:
        dst.setconfig('bundle', 'mainreporoot', r, 'copied')

    # copy selected local settings to the remote ui
    for sect in ('auth', 'hostfingerprints', 'http_proxy'):
        for key, val in src.configitems(sect):
            dst.setconfig(sect, key, val, 'copied')
    v = src.config('web', 'cacerts')
    if v == '!':
        dst.setconfig('web', 'cacerts', v, 'copied')
    elif v:
        dst.setconfig('web', 'cacerts', util.expandpath(v), 'copied')

    return dst
Beispiel #30
0
def remoteui(src, opts):
    'build a remote ui from ui or repo and opts'
    if util.safehasattr(src, 'baseui'): # looks like a repository
        dst = src.baseui.copy() # drop repo-specific config
        src = src.ui # copy target options from repo
    else: # assume it's a global ui object
        dst = src.copy() # keep all global options

    # copy ssh-specific options
    for o in 'ssh', 'remotecmd':
        v = opts.get(o) or src.config('ui', o)
        if v:
            dst.setconfig("ui", o, v)

    # copy bundle-specific options
    r = src.config('bundle', 'mainreporoot')
    if r:
        dst.setconfig('bundle', 'mainreporoot', r)

    # copy selected local settings to the remote ui
    for sect in ('auth', 'hostfingerprints', 'http_proxy'):
        for key, val in src.configitems(sect):
            dst.setconfig(sect, key, val)
    v = src.config('web', 'cacerts')
    if v:
        dst.setconfig('web', 'cacerts', util.expandpath(v))

    return dst
def unbundle(repo, cg, heads, source, url):
    """Apply a bundle to a repo.

    this function makes sure the repo is locked during the application and have
    mechanism to check that no push race occurred between the creation of the
    bundle and its application.

    If the push was raced as PushRaced exception is raised."""
    r = 0
    # need a transaction when processing a bundle2 stream
    tr = None
    lock = repo.lock()
    try:
        check_heads(repo, heads, 'uploading changes')
        # push can proceed
        if util.safehasattr(cg, 'params'):
            try:
                tr = repo.transaction('unbundle')
                tr.hookargs['source'] = source
                tr.hookargs['url'] = url
                tr.hookargs['bundle2-exp'] = '1'
                r = bundle2.processbundle(repo, cg, lambda: tr).reply
                cl = repo.unfiltered().changelog
                p = cl.writepending() and repo.root or ""
                repo.hook('b2x-pretransactionclose', throw=True, pending=p,
                          **tr.hookargs)
                tr.close()
                hookargs = dict(tr.hookargs)
                def runhooks():
                    repo.hook('b2x-transactionclose', **hookargs)
                repo._afterlock(runhooks)
            except Exception, exc:
                exc.duringunbundle2 = True
                raise
        else:
Beispiel #32
0
def _exthook(ui, repo, name, cmd, args, throw):
    ui.note(_("running hook %s: %s\n") % (name, cmd))

    starttime = time.time()
    env = {}
    for k, v in args.iteritems():
        if util.safehasattr(v, '__call__'):
            v = v()
        if isinstance(v, dict):
            # make the dictionary element order stable across Python
            # implementations
            v = ('{' +
                 ', '.join('%r: %r' % i for i in sorted(v.iteritems())) +
                 '}')
        env['HG_' + k.upper()] = v

    if repo:
        cwd = repo.root
    else:
        cwd = os.getcwd()
    if 'HG_URL' in env and env['HG_URL'].startswith('remote:http'):
        r = util.system(cmd, environ=env, cwd=cwd, out=ui)
    else:
        r = util.system(cmd, environ=env, cwd=cwd, out=ui.fout)

    duration = time.time() - starttime
    ui.log('exthook', 'exthook-%s: %s finished in %0.2f seconds\n',
           name, cmd, duration)
    if r:
        desc, r = util.explainexit(r)
        if throw:
            raise util.Abort(_('%s hook %s') % (name, desc))
        ui.warn(_('warning: %s hook %s\n') % (name, desc))
    return r
Beispiel #33
0
def pushkey(repo, proto, namespace, key, old, new):
    # compatibility with pre-1.8 clients which were accidentally
    # sending raw binary nodes rather than utf-8-encoded hex
    if len(new) == 20 and new.encode('string-escape') != new:
        # looks like it could be a binary node
        try:
            new.decode('utf-8')
            new = encoding.tolocal(new) # but cleanly decodes as UTF-8
        except UnicodeDecodeError:
            pass # binary, leave unmodified
    else:
        new = encoding.tolocal(new) # normal path

    if util.safehasattr(proto, 'restore'):

        proto.redirect()

        try:
            r = repo.pushkey(encoding.tolocal(namespace), encoding.tolocal(key),
                             encoding.tolocal(old), new) or False
        except util.Abort:
            r = False

        output = proto.restore()

        return '%s\n%s' % (int(r), output)

    r = repo.pushkey(encoding.tolocal(namespace), encoding.tolocal(key),
                     encoding.tolocal(old), new)
    return '%s\n' % int(r)
Beispiel #34
0
def _smtp(ui):
    '''build an smtp connection and return a function to send mail'''
    local_hostname = ui.config('smtp', 'local_hostname')
    tls = ui.config('smtp', 'tls', 'none')
    # backward compatible: when tls = true, we use starttls.
    starttls = tls == 'starttls' or util.parsebool(tls)
    smtps = tls == 'smtps'
    if (starttls or smtps) and not util.safehasattr(socket, 'ssl'):
        raise util.Abort(_("can't use TLS: Python SSL support not installed"))
    if smtps:
        ui.note(_('(using smtps)\n'))
        s = smtplib.SMTP_SSL(local_hostname=local_hostname)
    else:
        s = smtplib.SMTP(local_hostname=local_hostname)
    mailhost = ui.config('smtp', 'host')
    if not mailhost:
        raise util.Abort(_('smtp.host not configured - cannot send mail'))
    mailport = util.getport(ui.config('smtp', 'port', 25))
    ui.note(_('sending mail: smtp host %s, port %s\n') % (mailhost, mailport))
    s.connect(host=mailhost, port=mailport)
    if starttls:
        ui.note(_('(using starttls)\n'))
        s.ehlo()
        s.starttls()
        s.ehlo()
    username = ui.config('smtp', 'username')
    password = ui.config('smtp', 'password')
    if username and not password:
        password = ui.getpass()
    if username and password:
        ui.note(_('(authenticating to mail server as %s)\n') % (username))
        try:
            s.login(username, password)
        except smtplib.SMTPException, inst:
            raise util.Abort(inst)
Beispiel #35
0
def unbundle(repo, proto, heads):
    their_heads = decodelist(heads)

    try:
        proto.redirect()

        exchange.check_heads(repo, their_heads, 'preparing changes')

        # write bundle data to temporary file because it can be big
        fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
        fp = os.fdopen(fd, 'wb+')
        r = 0
        try:
            proto.getfile(fp)
            fp.seek(0)
            gen = exchange.readbundle(repo.ui, fp, None)
            r = exchange.unbundle(repo, gen, their_heads, 'serve',
                                  proto._client())
            if util.safehasattr(r, 'addpart'):
                # The return looks streamable, we are in the bundle2 case and
                # should return a stream.
                return streamres(r.getchunks())
            return pushres(r)

        finally:
            fp.close()
            os.unlink(tempname)
    except error.BundleValueError, exc:
            bundler = bundle2.bundle20(repo.ui)
            errpart = bundler.newpart('b2x:error:unsupportedcontent')
            if exc.parttype is not None:
                errpart.addparam('parttype', exc.parttype)
            if exc.params:
                errpart.addparam('params', '\0'.join(exc.params))
            return streamres(bundler.getchunks())
Beispiel #36
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
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
Beispiel #39
0
def _flatten(thing):
    '''yield a single stream from a possibly nested set of iterators'''
    if isinstance(thing, str):
        yield thing
    elif not util.safehasattr(thing, '__iter__'):
        if thing is not None:
            yield str(thing)
    else:
        for i in thing:
            if isinstance(i, str):
                yield i
            elif not util.safehasattr(i, '__iter__'):
                if i is not None:
                    yield str(i)
            elif i is not None:
                for j in _flatten(i):
                    yield j
def _flatten(thing):
    '''yield a single stream from a possibly nested set of iterators'''
    if isinstance(thing, str):
        yield thing
    elif not util.safehasattr(thing, '__iter__'):
        if thing is not None:
            yield str(thing)
    else:
        for i in thing:
            if isinstance(i, str):
                yield i
            elif not util.safehasattr(i, '__iter__'):
                if i is not None:
                    yield str(i)
            elif i is not None:
                for j in _flatten(i):
                    yield j
Beispiel #41
0
    def copy(self):
        """return a copy of the part

        The new part have the very same content but no partid assigned yet.
        Parts with generated data cannot be copied."""
        assert not util.safehasattr(self.data, 'next')
        return self.__class__(self.type, self._mandatoryparams,
                              self._advisoryparams, self._data, self.mandatory)
 def __init__(self, ui, repo, opts):
     self.ui = ui
     self.repo = repo
     self.address = opts['address']
     if not util.safehasattr(SocketServer, 'UnixStreamServer'):
         raise error.Abort(_('unsupported platform'))
     if not self.address:
         raise error.Abort(_('no socket path specified with --address'))
Beispiel #43
0
 def __init__(self, ui, repo, opts):
     self.ui = ui
     self.repo = repo
     self.address = opts['address']
     if not util.safehasattr(SocketServer, 'UnixStreamServer'):
         raise error.Abort(_('unsupported platform'))
     if not self.address:
         raise error.Abort(_('no socket path specified with --address'))
Beispiel #44
0
def _smtp(ui):
    '''build an smtp connection and return a function to send mail'''
    local_hostname = ui.config('smtp', 'local_hostname')
    tls = ui.config('smtp', 'tls', 'none')
    # backward compatible: when tls = true, we use starttls.
    starttls = tls == 'starttls' or util.parsebool(tls)
    smtps = tls == 'smtps'
    if (starttls or smtps) and not util.safehasattr(socket, 'ssl'):
        raise util.Abort(_("can't use TLS: Python SSL support not installed"))
    mailhost = ui.config('smtp', 'host')
    if not mailhost:
        raise util.Abort(_('smtp.host not configured - cannot send mail'))
    verifycert = ui.config('smtp', 'verifycert', 'strict')
    if verifycert not in ['strict', 'loose']:
        if util.parsebool(verifycert) is not False:
            raise util.Abort(_('invalid smtp.verifycert configuration: %s')
                             % (verifycert))
        verifycert = False
    if (starttls or smtps) and verifycert:
        sslkwargs = sslutil.sslkwargs(ui, mailhost)
    else:
        sslkwargs = {}
    if smtps:
        ui.note(_('(using smtps)\n'))
        s = SMTPS(sslkwargs, local_hostname=local_hostname)
    elif starttls:
        s = STARTTLS(sslkwargs, local_hostname=local_hostname)
    else:
        s = smtplib.SMTP(local_hostname=local_hostname)
    if smtps:
        defaultport = 465
    else:
        defaultport = 25
    mailport = util.getport(ui.config('smtp', 'port', defaultport))
    ui.note(_('sending mail: smtp host %s, port %s\n') %
            (mailhost, mailport))
    s.connect(host=mailhost, port=mailport)
    if starttls:
        ui.note(_('(using starttls)\n'))
        s.ehlo()
        s.starttls()
        s.ehlo()
    if (starttls or smtps) and verifycert:
        ui.note(_('(verifying remote certificate)\n'))
        sslutil.validator(ui, mailhost)(s.sock, verifycert == 'strict')
    username = ui.config('smtp', 'username')
    password = ui.config('smtp', 'password')
    if username and not password:
        password = ui.getpass()
    if username and password:
        ui.note(_('(authenticating to mail server as %s)\n') %
                  (username))
        try:
            s.login(username, password)
        except smtplib.SMTPException, inst:
            raise util.Abort(inst)
Beispiel #45
0
 def __init__(self, map, skip=None):
     self._dirs = {}
     addpath = self.addpath
     if util.safehasattr(map, 'iteritems') and skip is not None:
         for f, s in map.iteritems():
             if s[0] != skip:
                 addpath(f)
     else:
         for f in map:
             addpath(f)
Beispiel #46
0
 def __init__(self, map, skip=None):
     self._dirs = {}
     addpath = self.addpath
     if util.safehasattr(map, "iteritems") and skip is not None:
         for f, s in map.iteritems():
             if s[0] != skip:
                 addpath(f)
     else:
         for f in map:
             addpath(f)
def wrapfunction(container, funcname, wrapper):
    """Wrap the function named funcname in container

    Replace the funcname member in the given container with the specified
    wrapper. The container is typically a module, class, or instance.

    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.

    Wrapping methods of the repository object is not recommended since
    it conflicts with extensions that extend the repository by
    subclassing. All extensions that need to extend methods of
    localrepository should use this subclassing trick: namely,
    reposetup() should look like

      def reposetup(ui, repo):
          class myrepo(repo.__class__):
              def whatever(self, *args, **kwargs):
                  [...extension stuff...]
                  super(myrepo, self).whatever(*args, **kwargs)
                  [...extension stuff...]

          repo.__class__ = myrepo

    In general, combining wrapfunction() with subclassing does not
    work. Since you cannot control what other extensions are loaded by
    your end users, you should play nicely with others by using the
    subclass trick.
    """
    assert util.safehasattr(wrapper, "__call__")

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

    origfn = getattr(container, funcname)
    assert util.safehasattr(origfn, "__call__")
    setattr(container, funcname, wrap)
    return origfn
def wrapfunction(container, funcname, wrapper):
    '''Wrap the function named funcname in container

    Replace the funcname member in the given container with the specified
    wrapper. The container is typically a module, class, or instance.

    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.

    Wrapping methods of the repository object is not recommended since
    it conflicts with extensions that extend the repository by
    subclassing. All extensions that need to extend methods of
    localrepository should use this subclassing trick: namely,
    reposetup() should look like

      def reposetup(ui, repo):
          class myrepo(repo.__class__):
              def whatever(self, *args, **kwargs):
                  [...extension stuff...]
                  super(myrepo, self).whatever(*args, **kwargs)
                  [...extension stuff...]

          repo.__class__ = myrepo

    In general, combining wrapfunction() with subclassing does not
    work. Since you cannot control what other extensions are loaded by
    your end users, you should play nicely with others by using the
    subclass trick.
    '''
    assert util.safehasattr(wrapper, '__call__')

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

    origfn = getattr(container, funcname)
    assert util.safehasattr(origfn, '__call__')
    setattr(container, funcname, wrap)
    return origfn
def runsymbol(context, mapping, key):
    v = mapping.get(key)
    if v is None:
        v = context._defaults.get(key, '')
    if util.safehasattr(v, '__call__'):
        return v(**mapping)
    if isinstance(v, types.GeneratorType):
        v = list(v)
        mapping[key] = v
        return v
    return v
Beispiel #50
0
def runsymbol(context, mapping, key):
    v = mapping.get(key)
    if v is None:
        v = context._defaults.get(key, '')
    if util.safehasattr(v, '__call__'):
        return v(**mapping)
    if isinstance(v, types.GeneratorType):
        v = list(v)
        mapping[key] = v
        return v
    return v
def _smtp(ui):
    '''build an smtp connection and return a function to send mail'''
    local_hostname = ui.config('smtp', 'local_hostname')
    tls = ui.config('smtp', 'tls', 'none')
    # backward compatible: when tls = true, we use starttls.
    starttls = tls == 'starttls' or util.parsebool(tls)
    smtps = tls == 'smtps'
    if (starttls or smtps) and not util.safehasattr(socket, 'ssl'):
        raise util.Abort(_("can't use TLS: Python SSL support not installed"))
    mailhost = ui.config('smtp', 'host')
    if not mailhost:
        raise util.Abort(_('smtp.host not configured - cannot send mail'))
    verifycert = ui.config('smtp', 'verifycert', 'strict')
    if verifycert not in ['strict', 'loose']:
        if util.parsebool(verifycert) is not False:
            raise util.Abort(
                _('invalid smtp.verifycert configuration: %s') % (verifycert))
        verifycert = False
    if (starttls or smtps) and verifycert:
        sslkwargs = sslutil.sslkwargs(ui, mailhost)
    else:
        sslkwargs = {}
    if smtps:
        ui.note(_('(using smtps)\n'))
        s = SMTPS(sslkwargs, local_hostname=local_hostname)
    elif starttls:
        s = STARTTLS(sslkwargs, local_hostname=local_hostname)
    else:
        s = smtplib.SMTP(local_hostname=local_hostname)
    if smtps:
        defaultport = 465
    else:
        defaultport = 25
    mailport = util.getport(ui.config('smtp', 'port', defaultport))
    ui.note(_('sending mail: smtp host %s, port %s\n') % (mailhost, mailport))
    s.connect(host=mailhost, port=mailport)
    if starttls:
        ui.note(_('(using starttls)\n'))
        s.ehlo()
        s.starttls()
        s.ehlo()
    if (starttls or smtps) and verifycert:
        ui.note(_('(verifying remote certificate)\n'))
        sslutil.validator(ui, mailhost)(s.sock, verifycert == 'strict')
    username = ui.config('smtp', 'username')
    password = ui.config('smtp', 'password')
    if username and not password:
        password = ui.getpass()
    if username and password:
        ui.note(_('(authenticating to mail server as %s)\n') % (username))
        try:
            s.login(username, password)
        except smtplib.SMTPException, inst:
            raise util.Abort(inst)
Beispiel #52
0
def unbundle(repo, proto, heads):
    their_heads = decodelist(heads)

    try:
        proto.redirect()

        exchange.check_heads(repo, their_heads, 'preparing changes')

        # write bundle data to temporary file because it can be big
        fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
        fp = os.fdopen(fd, 'wb+')
        r = 0
        try:
            proto.getfile(fp)
            fp.seek(0)
            gen = exchange.readbundle(repo.ui, fp, None)
            r = exchange.unbundle(repo, gen, their_heads, 'serve',
                                  proto._client())
            if util.safehasattr(r, 'addpart'):
                # The return looks streamable, we are in the bundle2 case and
                # should return a stream.
                return streamres(r.getchunks())
            return pushres(r)

        finally:
            fp.close()
            os.unlink(tempname)

    except (error.BundleValueError, util.Abort, error.PushRaced), exc:
        # handle non-bundle2 case first
        if not getattr(exc, 'duringunbundle2', False):
            try:
                raise
            except util.Abort:
                # The old code we moved used sys.stderr directly.
                # We did not change it to minimise code change.
                # This need to be moved to something proper.
                # Feel free to do it.
                sys.stderr.write("abort: %s\n" % exc)
                return pushres(0)
            except error.PushRaced:
                return pusherr(str(exc))

        bundler = bundle2.bundle20(repo.ui)
        for out in getattr(exc, '_bundle2salvagedoutput', ()):
            bundler.addpart(out)
        try:
            raise
        except error.BundleValueError, exc:
            errpart = bundler.newpart('error:unsupportedcontent')
            if exc.parttype is not None:
                errpart.addparam('parttype', exc.parttype)
            if exc.params:
                errpart.addparam('params', '\0'.join(exc.params))
Beispiel #53
0
def _peerlookup(path):
    u = util.url(path)
    scheme = u.scheme or 'file'
    thing = schemes.get(scheme) or schemes['file']
    try:
        return thing(path)
    except TypeError:
        # we can't test callable(thing) because 'thing' can be an unloaded
        # module that implements __call__
        if not util.safehasattr(thing, 'instance'):
            raise
        return thing
def get(context, mapping, args):
    if len(args) != 2:
        # i18n: "get" is a keyword
        raise error.ParseError(_("get() expects two arguments"))

    dictarg = args[0][0](context, mapping, args[0][1])
    if not util.safehasattr(dictarg, 'get'):
        # i18n: "get" is a keyword
        raise error.ParseError(_("get() expects a dict as first argument"))

    key = args[1][0](context, mapping, args[1][1])
    yield dictarg.get(key)
def get(context, mapping, args):
    if len(args) != 2:
        # i18n: "get" is a keyword
        raise error.ParseError(_("get() expects two arguments"))

    dictarg = args[0][0](context, mapping, args[0][1])
    if not util.safehasattr(dictarg, 'get'):
        # i18n: "get" is a keyword
        raise error.ParseError(_("get() expects a dict as first argument"))

    key = args[1][0](context, mapping, args[1][1])
    yield dictarg.get(key)
Beispiel #56
0
    def _callstream(self, cmd, **args):
        if cmd == 'pushkey':
            args['data'] = ''
        data = args.pop('data', None)
        size = 0
        if util.safehasattr(data, 'length'):
            size = data.length
        elif data is not None:
            size = len(data)
        headers = args.pop('headers', {})
        if data is not None and 'Content-Type' not in headers:
            headers['Content-Type'] = 'application/mercurial-0.1'


        if size and self.ui.configbool('ui', 'usehttp2', False):
            headers['Expect'] = '100-Continue'
            headers['X-HgHttp2'] = '1'

        self.ui.debug("sending %s command\n" % cmd)
        q = [('cmd', cmd)]
        headersize = 0
        if len(args) > 0:
            httpheader = self.capable('httpheader')
            if httpheader:
                headersize = int(httpheader.split(',')[0])
        if headersize > 0:
            # The headers can typically carry more data than the URL.
            encargs = urllib.urlencode(sorted(args.items()))
            headerfmt = 'X-HgArg-%s'
            contentlen = headersize - len(headerfmt % '000' + ': \r\n')
            headernum = 0
            for i in xrange(0, len(encargs), contentlen):
                headernum += 1
                header = headerfmt % str(headernum)
                headers[header] = encargs[i:i + contentlen]
            varyheaders = [headerfmt % str(h) for h in range(1, headernum + 1)]
            headers['Vary'] = ','.join(varyheaders)
        else:
            q += sorted(args.items())
        qs = '?%s' % urllib.urlencode(q)
        cu = "%s%s" % (self._url, qs)
        req = urllib2.Request(cu, data, headers)
        if data is not None:
            self.ui.debug("sending %s bytes\n" % size)
            req.add_unredirected_header('Content-Length', '%d' % size)
        try:
            resp = self.urlopener.open(req)
        except urllib2.HTTPError, inst:
            if inst.code == 401:
                raise util.Abort(_('authorization failed'))
            raise
Beispiel #57
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()