def __init__(self, ui, path, path2):
        localrepo.localrepository.__init__(self, ui, path)
        self.ui.setconfig('phases', 'publish', False)

        self._url = 'union:%s+%s' % (util.expandpath(path),
                                     util.expandpath(path2))
        self.repo2 = localrepo.localrepository(ui, path2)
Beispiel #2
0
    def __init__(self, ui, path, path2):
        localrepo.localrepository.__init__(self, ui, path)
        self.ui.setconfig('phases', 'publish', False, 'unionrepo')

        self._url = 'union:%s+%s' % (util.expandpath(path),
                                     util.expandpath(path2))
        self.repo2 = localrepo.localrepository(ui, path2)
Beispiel #3
0
    def fixconfig(self, root=None, section=None):
        if section in (None, "paths"):
            # expand vars and ~
            # translate paths relative to root (or home) into absolute paths
            root = root or os.getcwd()
            for c in self._tcfg, self._ucfg, self._ocfg:
                for n, p in c.items("paths"):
                    if not p:
                        continue
                    if "%%" in p:
                        self.warn(
                            _("(deprecated '%%' in path %s=%s from %s)\n") % (n, p, self.configsource("paths", n))
                        )
                        p = p.replace("%%", "%")
                    p = util.expandpath(p)
                    if "://" not in p and not os.path.isabs(p):
                        p = os.path.normpath(os.path.join(root, p))
                    c.set("paths", n, p)

        if section in (None, "ui"):
            # update ui options
            self.debugflag = self.configbool("ui", "debug")
            self.verbose = self.debugflag or self.configbool("ui", "verbose")
            self.quiet = not self.debugflag and self.configbool("ui", "quiet")
            if self.verbose and self.quiet:
                self.quiet = self.verbose = False
            self._reportuntrusted = self.configbool("ui", "report_untrusted", True)
            self.tracebackflag = self.configbool("ui", "traceback", False)

        if section in (None, "trusted"):
            # update trust information
            self._trustusers.update(self.configlist("trusted", "users"))
            self._trustgroups.update(self.configlist("trusted", "groups"))
Beispiel #4
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 #5
0
def readauthforuri(ui, uri):
    # Read configuration
    config = dict()
    for key, val in ui.configitems('auth'):
        if '.' not in key:
            ui.warn(_("ignoring invalid [auth] key '%s'\n") % key)
            continue
        group, setting = key.rsplit('.', 1)
        gdict = config.setdefault(group, dict())
        if setting in ('username', 'cert', 'key'):
            val = util.expandpath(val)
        gdict[setting] = val

    # Find the best match
    scheme, hostpath = uri.split('://', 1)
    bestlen = 0
    bestauth = None
    for group, auth in config.iteritems():
        prefix = auth.get('prefix')
        if not prefix:
            continue
        p = prefix.split('://', 1)
        if len(p) > 1:
            schemes, prefix = [p[0]], p[1]
        else:
            schemes = (auth.get('schemes') or 'https').split()
        if (prefix == '*' or hostpath.startswith(prefix)) and \
            len(prefix) > bestlen and scheme in schemes:
            bestlen = len(prefix)
            bestauth = group, auth
    return bestauth
Beispiel #6
0
    def fixconfig(self, root=None, section=None):
        if section in (None, 'paths'):
            # expand vars and ~
            # translate paths relative to root (or home) into absolute paths
            root = root or os.getcwd()
            for c in self._tcfg, self._ucfg, self._ocfg:
                for n, p in c.items('paths'):
                    if not p:
                        continue
                    if '%%' in p:
                        self.warn(_("(deprecated '%%' in path %s=%s from %s)\n")
                                  % (n, p, self.configsource('paths', n)))
                        p = p.replace('%%', '%')
                    p = util.expandpath(p)
                    if not util.hasscheme(p) and not os.path.isabs(p):
                        p = os.path.normpath(os.path.join(root, p))
                    c.set("paths", n, p)

        if section in (None, 'ui'):
            # update ui options
            self.debugflag = self.configbool('ui', 'debug')
            self.verbose = self.debugflag or self.configbool('ui', 'verbose')
            self.quiet = not self.debugflag and self.configbool('ui', 'quiet')
            if self.verbose and self.quiet:
                self.quiet = self.verbose = False
            self._reportuntrusted = self.debugflag or self.configbool("ui",
                "report_untrusted", True)
            self.tracebackflag = self.configbool('ui', 'traceback', False)

        if section in (None, 'trusted'):
            # update trust information
            self._trustusers.update(self.configlist('trusted', 'users'))
            self._trustgroups.update(self.configlist('trusted', 'groups'))
Beispiel #7
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
Beispiel #8
0
    def readauthtoken(self, uri):
        # Read configuration
        config = dict()
        for key, val in self.ui.configitems('auth'):
            if '.' not in key:
                self.ui.warn(_("ignoring invalid [auth] key '%s'\n") % key)
                continue
            group, setting = key.split('.', 1)
            gdict = config.setdefault(group, dict())
            if setting in ('cert', 'key'):
                val = util.expandpath(val)
            gdict[setting] = val

        # Find the best match
        scheme, hostpath = uri.split('://', 1)
        bestlen = 0
        bestauth = None
        for auth in config.itervalues():
            prefix = auth.get('prefix')
            if not prefix:
                continue
            p = prefix.split('://', 1)
            if len(p) > 1:
                schemes, prefix = [p[0]], p[1]
            else:
                schemes = (auth.get('schemes') or 'https').split()
            if (prefix == '*' or hostpath.startswith(prefix)) and \
                len(prefix) > bestlen and scheme in schemes:
                bestlen = len(prefix)
                bestauth = auth
        return bestauth
Beispiel #9
0
    def fixconfig(self, root=None, section=None):
        if section in (None, 'paths'):
            # expand vars and ~
            # translate paths relative to root (or home) into absolute paths
            root = root or os.getcwd()
            for c in self._tcfg, self._ucfg, self._ocfg:
                for n, p in c.items('paths'):
                    if not p:
                        continue
                    if '%%' in p:
                        self.warn(
                            _("(deprecated '%%' in path %s=%s from %s)\n") %
                            (n, p, self.configsource('paths', n)))
                        p = p.replace('%%', '%')
                    p = util.expandpath(p)
                    if not util.hasscheme(p) and not os.path.isabs(p):
                        p = os.path.normpath(os.path.join(root, p))
                    c.set("paths", n, p)

        if section in (None, 'ui'):
            # update ui options
            self.debugflag = self.configbool('ui', 'debug')
            self.verbose = self.debugflag or self.configbool('ui', 'verbose')
            self.quiet = not self.debugflag and self.configbool('ui', 'quiet')
            if self.verbose and self.quiet:
                self.quiet = self.verbose = False
            self._reportuntrusted = self.debugflag or self.configbool(
                "ui", "report_untrusted", True)
            self.tracebackflag = self.configbool('ui', 'traceback', False)

        if section in (None, 'trusted'):
            # update trust information
            self._trustusers.update(self.configlist('trusted', 'users'))
            self._trustgroups.update(self.configlist('trusted', 'groups'))
Beispiel #10
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 #11
0
 def _ignore(self):
     files = [self._join('.hgignore')]
     for name, path in self._ui.configitems("ui"):
         if name == 'ignore' or name.startswith('ignore.'):
             # we need to use os.path.join here rather than self._join
             # because path is arbitrary and user-specified
             files.append(os.path.join(self._rootdir, util.expandpath(path)))
     return ignore.ignore(self._root, files, self._ui.warn)
Beispiel #12
0
        def connect(self):
            if hasattr(self, 'ui'):
                cacerts = self.ui.config('web', 'cacerts')
                if cacerts:
                    cacerts = util.expandpath(cacerts)
            else:
                cacerts = None

            hostfingerprint = self.ui.config('hostfingerprints', self.host)
            if cacerts and not hostfingerprint:
                sock = _create_connection((self.host, self.port))
                self.sock = _ssl_wrap_socket(sock,
                                             self.key_file,
                                             self.cert_file,
                                             cert_reqs=CERT_REQUIRED,
                                             ca_certs=cacerts)
                msg = _verifycert(self.sock.getpeercert(), self.host)
                if msg:
                    raise util.Abort(
                        _('%s certificate error: %s '
                          '(use --insecure to connect '
                          'insecurely)') % (self.host, msg))
                self.ui.debug('%s certificate successfully verified\n' %
                              self.host)
            else:
                httplib.HTTPSConnection.connect(self)
                if hasattr(self.sock, 'getpeercert'):
                    peercert = self.sock.getpeercert(True)
                    peerfingerprint = util.sha1(peercert).hexdigest()
                    nicefingerprint = ":".join([
                        peerfingerprint[x:x + 2]
                        for x in xrange(0, len(peerfingerprint), 2)
                    ])
                    if hostfingerprint:
                        if peerfingerprint.lower() != \
                                hostfingerprint.replace(':', '').lower():
                            raise util.Abort(
                                _('invalid certificate for %s '
                                  'with fingerprint %s') %
                                (self.host, nicefingerprint))
                        self.ui.debug(
                            '%s certificate matched fingerprint %s\n' %
                            (self.host, nicefingerprint))
                    else:
                        self.ui.warn(
                            _('warning: %s certificate '
                              'with fingerprint %s not verified '
                              '(check hostfingerprints or web.cacerts '
                              'config setting)\n') %
                            (self.host, nicefingerprint))
                else:  # python 2.5 ?
                    if hostfingerprint:
                        raise util.Abort(
                            _('no certificate for %s '
                              'with fingerprint') % self.host)
                    self.ui.warn(
                        _('warning: %s certificate not verified '
                          '(check web.cacerts config setting)\n') % self.host)
Beispiel #13
0
 def _path(self, loc):
     p = self.config('paths', loc)
     if p:
         if '%%' in p:
             self.warn("(deprecated '%%' in path %s=%s from %s)\n" %
                       (loc, p, self.configsource('paths', loc)))
             p = p.replace('%%', '%')
         p = util.expandpath(p)
     return p
Beispiel #14
0
 def __init__(self, base, audit=True, expandpath=False, realpath=False):
     if expandpath:
         base = util.expandpath(base)
     if realpath:
         base = os.path.realpath(base)
     self.base = base
     self._setmustaudit(audit)
     self.createmode = None
     self._trustnlink = None
 def _ignore(self):
     files = [self._join('.hgignore')]
     for name, path in self._ui.configitems("ui"):
         if name == 'ignore' or name.startswith('ignore.'):
             # we need to use os.path.join here rather than self._join
             # because path is arbitrary and user-specified
             files.append(os.path.join(self._rootdir,
                                       util.expandpath(path)))
     return ignore.ignore(self._root, files, self._ui.warn)
Beispiel #16
0
 def __init__(self, base, audit=True, expandpath=False, realpath=False):
     if expandpath:
         base = util.expandpath(base)
     if realpath:
         base = os.path.realpath(base)
     self.base = base
     self._setmustaudit(audit)
     self.createmode = None
     self._trustnlink = None
Beispiel #17
0
 def _path(self, loc):
     p = self.config('paths', loc)
     if p:
         if '%%' in p:
             self.warn("(deprecated '%%' in path %s=%s from %s)\n" %
                       (loc, p, self.configsource('paths', loc)))
             p = p.replace('%%', '%')
         p = util.expandpath(p)
     return p
def loadpath(path, module_name):
    module_name = module_name.replace(".", "_")
    path = util.expandpath(path)
    if os.path.isdir(path):
        # module/__init__.py style
        d, f = os.path.split(path.rstrip("/"))
        fd, fpath, desc = imp.find_module(f, [d])
        return imp.load_module(module_name, fd, fpath, desc)
    else:
        return imp.load_source(module_name, path)
def loadpath(path, module_name):
    module_name = module_name.replace('.', '_')
    path = util.expandpath(path)
    if os.path.isdir(path):
        # module/__init__.py style
        d, f = os.path.split(path.rstrip('/'))
        fd, fpath, desc = imp.find_module(f, [d])
        return imp.load_module(module_name, fd, fpath, desc)
    else:
        return imp.load_source(module_name, path)
    def __init__(self, ui, path, bundlename):
        self._tempparent = None
        try:
            localrepo.localrepository.__init__(self, ui, path)
        except error.RepoError:
            self._tempparent = tempfile.mkdtemp()
            localrepo.instance(ui, self._tempparent, 1)
            localrepo.localrepository.__init__(self, ui, self._tempparent)

        if path:
            self._url = 'bundle:' + util.expandpath(path) + '+' + bundlename
        else:
            self._url = 'bundle:' + bundlename

        self.tempfile = None
        self.bundlefile = open(bundlename, "rb")
        header = self.bundlefile.read(6)
        if not header.startswith("HG"):
            raise util.Abort(_("%s: not a Mercurial bundle file") % bundlename)
        elif not header.startswith("HG10"):
            raise util.Abort(_("%s: unknown bundle version") % bundlename)
        elif (header == "HG10BZ") or (header == "HG10GZ"):
            fdtemp, temp = tempfile.mkstemp(prefix="hg-bundle-",
                                            suffix=".hg10un", dir=self.path)
            self.tempfile = temp
            fptemp = os.fdopen(fdtemp, 'wb')
            def generator(f):
                if header == "HG10BZ":
                    zd = bz2.BZ2Decompressor()
                    zd.decompress("BZ")
                elif header == "HG10GZ":
                    zd = zlib.decompressobj()
                for chunk in f:
                    yield zd.decompress(chunk)
            gen = generator(util.filechunkiter(self.bundlefile, 4096))

            try:
                fptemp.write("HG10UN")
                for chunk in gen:
                    fptemp.write(chunk)
            finally:
                fptemp.close()
                self.bundlefile.close()

            self.bundlefile = open(self.tempfile, "rb")
            # seek right after the header
            self.bundlefile.seek(6)
        elif header == "HG10UN":
            # nothing to do
            pass
        else:
            raise util.Abort(_("%s: unknown bundle compression type")
                             % bundlename)
        # dict with the mapping 'filename' -> position in the bundle
        self.bundlefilespos = {}
Beispiel #21
0
def hook(ui, repo, name, throw=False, **args):
    if not ui.callhooks:
        return False

    r = False
    oldstdout = -1

    try:
        for hname, cmd in _allhooks(ui):
            if hname.split('.')[0] != name or not cmd:
                continue

            if oldstdout == -1 and _redirect:
                try:
                    stdoutno = sys.__stdout__.fileno()
                    stderrno = sys.__stderr__.fileno()
                    # temporarily redirect stdout to stderr, if possible
                    if stdoutno >= 0 and stderrno >= 0:
                        sys.__stdout__.flush()
                        oldstdout = os.dup(stdoutno)
                        os.dup2(stderrno, stdoutno)
                except (OSError, AttributeError):
                    # files seem to be bogus, give up on redirecting (WSGI, etc)
                    pass

            if callable(cmd):
                r = _pythonhook(ui, repo, name, hname, cmd, args, throw) or r
            elif cmd.startswith('python:'):
                if cmd.count(':') >= 2:
                    path, cmd = cmd[7:].rsplit(':', 1)
                    path = util.expandpath(path)
                    if repo:
                        path = os.path.join(repo.root, path)
                    try:
                        mod = extensions.loadpath(path, 'hghook.%s' % hname)
                    except Exception:
                        ui.write(_("loading %s hook failed:\n") % hname)
                        raise
                    hookfn = getattr(mod, cmd)
                else:
                    hookfn = cmd[7:].strip()
                r = _pythonhook(ui, repo, name, hname, hookfn, args, throw) or r
            else:
                r = _exthook(ui, repo, hname, cmd, args, throw) or r

            # The stderr is fully buffered on Windows when connected to a pipe.
            # A forcible flush is required to make small stderr data in the
            # remote side available to the client immediately.
            sys.stderr.flush()
    finally:
        if _redirect and oldstdout >= 0:
            os.dup2(oldstdout, stdoutno)
            os.close(oldstdout)

    return r
Beispiel #22
0
def hook(ui, repo, name, throw=False, **args):
    if not ui.callhooks:
        return False

    r = False
    oldstdout = -1

    try:
        for hname, cmd in _allhooks(ui):
            if hname.split('.')[0] != name or not cmd:
                continue

            if oldstdout == -1 and _redirect:
                try:
                    stdoutno = sys.__stdout__.fileno()
                    stderrno = sys.__stderr__.fileno()
                    # temporarily redirect stdout to stderr, if possible
                    if stdoutno >= 0 and stderrno >= 0:
                        sys.__stdout__.flush()
                        oldstdout = os.dup(stdoutno)
                        os.dup2(stderrno, stdoutno)
                except (OSError, AttributeError):
                    # files seem to be bogus, give up on redirecting (WSGI, etc)
                    pass

            if callable(cmd):
                r = _pythonhook(ui, repo, name, hname, cmd, args, throw) or r
            elif cmd.startswith('python:'):
                if cmd.count(':') >= 2:
                    path, cmd = cmd[7:].rsplit(':', 1)
                    path = util.expandpath(path)
                    if repo:
                        path = os.path.join(repo.root, path)
                    try:
                        mod = extensions.loadpath(path, 'hghook.%s' % hname)
                    except Exception:
                        ui.write(_("loading %s hook failed:\n") % hname)
                        raise
                    hookfn = getattr(mod, cmd)
                else:
                    hookfn = cmd[7:].strip()
                r = _pythonhook(ui, repo, name, hname, hookfn, args, throw) or r
            else:
                r = _exthook(ui, repo, hname, cmd, args, throw) or r

            # The stderr is fully buffered on Windows when connected to a pipe.
            # A forcible flush is required to make small stderr data in the
            # remote side available to the client immediately.
            sys.stderr.flush()
    finally:
        if _redirect and oldstdout >= 0:
            os.dup2(oldstdout, stdoutno)
            os.close(oldstdout)

    return r
Beispiel #23
0
        def connect(self):
            self.sock = _create_connection((self.host, self.port))

            host = self.host
            if self.realhostport: # use CONNECT proxy
                something = _generic_proxytunnel(self)
                host = self.realhostport.rsplit(':', 1)[0]

            cacerts = self.ui.config('web', 'cacerts')
            hostfingerprint = self.ui.config('hostfingerprints', host)

            if cacerts and not hostfingerprint:
                cacerts = util.expandpath(cacerts)
                if not os.path.exists(cacerts):
                    raise util.Abort(_('could not find '
                                       'web.cacerts: %s') % cacerts)
                self.sock = _ssl_wrap_socket(self.sock, self.key_file,
                    self.cert_file, cert_reqs=CERT_REQUIRED,
                    ca_certs=cacerts)
                msg = _verifycert(self.sock.getpeercert(), host)
                if msg:
                    raise util.Abort(_('%s certificate error: %s '
                                       '(use --insecure to connect '
                                       'insecurely)') % (host, msg))
                self.ui.debug('%s certificate successfully verified\n' % host)
            else:
                self.sock = _ssl_wrap_socket(self.sock, self.key_file,
                    self.cert_file)
                if hasattr(self.sock, 'getpeercert'):
                    peercert = self.sock.getpeercert(True)
                    peerfingerprint = util.sha1(peercert).hexdigest()
                    nicefingerprint = ":".join([peerfingerprint[x:x + 2]
                        for x in xrange(0, len(peerfingerprint), 2)])
                    if hostfingerprint:
                        if peerfingerprint.lower() != \
                                hostfingerprint.replace(':', '').lower():
                            raise util.Abort(_('invalid certificate for %s '
                                               'with fingerprint %s') %
                                             (host, nicefingerprint))
                        self.ui.debug('%s certificate matched fingerprint %s\n' %
                                      (host, nicefingerprint))
                    else:
                        self.ui.warn(_('warning: %s certificate '
                                       'with fingerprint %s not verified '
                                       '(check hostfingerprints or web.cacerts '
                                       'config setting)\n') %
                                     (host, nicefingerprint))
                else: # python 2.5 ?
                    if hostfingerprint:
                        raise util.Abort(_('no certificate for %s with '
                                           'configured hostfingerprint') % host)
                    self.ui.warn(_('warning: %s certificate not verified '
                                   '(check web.cacerts config setting)\n') %
                                 host)
Beispiel #24
0
def findexternaltool(ui, tool):
    for kn in ("regkey", "regkeyalt"):
        k = _toolstr(ui, tool, kn)
        if not k:
            continue
        p = util.lookupreg(k, _toolstr(ui, tool, "regname"))
        if p:
            p = util.findexe(p + _toolstr(ui, tool, "regappend"))
            if p:
                return p
    exe = _toolstr(ui, tool, "executable", tool)
    return util.findexe(util.expandpath(exe))
Beispiel #25
0
def findexternaltool(ui, tool):
    for kn in ("regkey", "regkeyalt"):
        k = _toolstr(ui, tool, kn)
        if not k:
            continue
        p = util.lookupreg(k, _toolstr(ui, tool, "regname"))
        if p:
            p = util.findexe(p + _toolstr(ui, tool, "regappend"))
            if p:
                return p
    exe = _toolstr(ui, tool, "executable", tool)
    return util.findexe(util.expandpath(exe))
Beispiel #26
0
def hook(ui, repo, name, throw=False, **args):
    if not ui.callhooks:
        return False

    r = False
    oldstdout = -1

    try:
        for hname, cmd in _allhooks(ui):
            if hname.split('.')[0] != name or not cmd:
                continue

            if oldstdout == -1 and _redirect:
                try:
                    stdoutno = sys.__stdout__.fileno()
                    stderrno = sys.__stderr__.fileno()
                    # temporarily redirect stdout to stderr, if possible
                    if stdoutno >= 0 and stderrno >= 0:
                        sys.__stdout__.flush()
                        oldstdout = os.dup(stdoutno)
                        os.dup2(stderrno, stdoutno)
                except (OSError, AttributeError):
                    # files seem to be bogus, give up on redirecting (WSGI, etc)
                    pass

            if util.safehasattr(cmd, '__call__'):
                r = _pythonhook(ui, repo, name, hname, cmd, args, throw) or r
            elif cmd.startswith('python:'):
                if cmd.count(':') >= 2:
                    path, cmd = cmd[7:].rsplit(':', 1)
                    path = util.expandpath(path)
                    if repo:
                        path = os.path.join(repo.root, path)
                    try:
                        mod = extensions.loadpath(path, 'hghook.%s' % hname)
                    except Exception:
                        ui.write(_("loading %s hook failed:\n") % hname)
                        raise
                    hookfn = getattr(mod, cmd)
                else:
                    hookfn = cmd[7:].strip()
                r = _pythonhook(ui, repo, name, hname, hookfn, args,
                                throw) or r
            else:
                r = _exthook(ui, repo, hname, cmd, args, throw) or r
    finally:
        if _redirect and oldstdout >= 0:
            os.dup2(oldstdout, stdoutno)
            os.close(oldstdout)

    return r
Beispiel #27
0
def hook(ui, repo, name, throw=False, **args):
    if not ui.callhooks:
        return False

    r = False
    oldstdout = -1

    try:
        for hname, cmd in _allhooks(ui):
            if hname.split('.')[0] != name or not cmd:
                continue

            if oldstdout == -1 and _redirect:
                try:
                    stdoutno = sys.__stdout__.fileno()
                    stderrno = sys.__stderr__.fileno()
                    # temporarily redirect stdout to stderr, if possible
                    if stdoutno >= 0 and stderrno >= 0:
                        sys.__stdout__.flush()
                        oldstdout = os.dup(stdoutno)
                        os.dup2(stderrno, stdoutno)
                except (OSError, AttributeError):
                    # files seem to be bogus, give up on redirecting (WSGI, etc)
                    pass

            if util.safehasattr(cmd, '__call__'):
                r = _pythonhook(ui, repo, name, hname, cmd, args, throw) or r
            elif cmd.startswith('python:'):
                if cmd.count(':') >= 2:
                    path, cmd = cmd[7:].rsplit(':', 1)
                    path = util.expandpath(path)
                    if repo:
                        path = os.path.join(repo.root, path)
                    try:
                        mod = extensions.loadpath(path, 'hghook.%s' % hname)
                    except Exception:
                        ui.write(_("loading %s hook failed:\n") % hname)
                        raise
                    hookfn = getattr(mod, cmd)
                else:
                    hookfn = cmd[7:].strip()
                r = _pythonhook(ui, repo, name, hname, hookfn, args, throw) or r
            else:
                r = _exthook(ui, repo, hname, cmd, args, throw) or r
    finally:
        if _redirect and oldstdout >= 0:
            os.dup2(oldstdout, stdoutno)
            os.close(oldstdout)

    return r
Beispiel #28
0
        def connect(self):
            if hasattr(self, 'ui'):
                cacerts = self.ui.config('web', 'cacerts')
                if cacerts:
                    cacerts = util.expandpath(cacerts)
            else:
                cacerts = None

            hostfingerprint = self.ui.config('hostfingerprints', self.host)
            if cacerts and not hostfingerprint:
                sock = _create_connection((self.host, self.port))
                self.sock = _ssl_wrap_socket(sock, self.key_file,
                        self.cert_file, cert_reqs=CERT_REQUIRED,
                        ca_certs=cacerts)
                msg = _verifycert(self.sock.getpeercert(), self.host)
                if msg:
                    raise util.Abort(_('%s certificate error: %s '
                                       '(use --insecure to connect '
                                       'insecurely)') % (self.host, msg))
                self.ui.debug('%s certificate successfully verified\n' %
                              self.host)
            else:
                httplib.HTTPSConnection.connect(self)
                if hasattr(self.sock, 'getpeercert'):
                    peercert = self.sock.getpeercert(True)
                    peerfingerprint = util.sha1(peercert).hexdigest()
                    nicefingerprint = ":".join([peerfingerprint[x:x + 2]
                        for x in xrange(0, len(peerfingerprint), 2)])
                    if hostfingerprint:
                        if peerfingerprint.lower() != \
                                hostfingerprint.replace(':', '').lower():
                            raise util.Abort(_('invalid certificate for %s '
                                               'with fingerprint %s') %
                                             (self.host, nicefingerprint))
                        self.ui.debug('%s certificate matched fingerprint %s\n' %
                                      (self.host, nicefingerprint))
                    else:
                        self.ui.warn(_('warning: %s certificate '
                                       'with fingerprint %s not verified '
                                       '(check hostfingerprints or web.cacerts '
                                       'config setting)\n') %
                                     (self.host, nicefingerprint))
                else: # python 2.5 ?
                    if hostfingerprint:
                        raise util.Abort(_('no certificate for %s '
                                           'with fingerprint') % self.host)
                    self.ui.warn(_('warning: %s certificate not verified '
                                   '(check web.cacerts config setting)\n') %
                                 self.host)
Beispiel #29
0
    def _ignore(self):
        files = []
        if os.path.exists(self._join('.hgignore')):
            files.append(self._join('.hgignore'))
        for name, path in self._ui.configitems("ui"):
            if name == 'ignore' or name.startswith('ignore.'):
                # we need to use os.path.join here rather than self._join
                # because path is arbitrary and user-specified
                files.append(os.path.join(self._rootdir, util.expandpath(path)))

        if not files:
            return util.never

        pats = ['include:%s' % f for f in files]
        return matchmod.match(self._root, '', [], pats, warn=self._ui.warn)
def loadpath(path, module_name):
    module_name = module_name.replace('.', '_')
    path = util.expandpath(path)
    if os.path.isdir(path):
        # module/__init__.py style
        d, f = os.path.split(path.rstrip('/'))
        fd, fpath, desc = imp.find_module(f, [d])
        return imp.load_module(module_name, fd, fpath, desc)
    else:
        try:
            return imp.load_source(module_name, path)
        except IOError, exc:
            if not exc.filename:
                exc.filename = path # python does not fill this
            raise
Beispiel #31
0
def loadpath(path, module_name):
    module_name = module_name.replace('.', '_')
    path = util.normpath(util.expandpath(path))
    if os.path.isdir(path):
        # module/__init__.py style
        d, f = os.path.split(path)
        fd, fpath, desc = imp.find_module(f, [d])
        return imp.load_module(module_name, fd, fpath, desc)
    else:
        try:
            return imp.load_source(module_name, path)
        except IOError as exc:
            if not exc.filename:
                exc.filename = path  # python does not fill this
            raise
Beispiel #32
0
def show_changeset(ui, repo, opts, buffered=False, matchfn=False):
    """show one changeset using template or regular display.

    Display format will be the first non-empty hit of:
    1. option 'template'
    2. option 'style'
    3. [ui] setting 'logtemplate'
    4. [ui] setting 'style'
    If all of these values are either the unset or the empty string,
    regular display via changeset_printer() is done.
    """
    # options
    patch = False
    if opts.get('patch'):
        patch = matchfn or matchall(repo)

    tmpl = opts.get('template')
    style = None
    if tmpl:
        tmpl = templater.parsestring(tmpl, quoted=False)
    else:
        style = opts.get('style')

    # ui settings
    if not (tmpl or style):
        tmpl = ui.config('ui', 'logtemplate')
        if tmpl:
            tmpl = templater.parsestring(tmpl)
        else:
            style = util.expandpath(ui.config('ui', 'style', ''))

    if not (tmpl or style):
        return changeset_printer(ui, repo, patch, opts, buffered)

    mapfile = None
    if style and not tmpl:
        mapfile = style
        if not os.path.split(mapfile)[0]:
            mapname = (templater.templatepath('map-cmdline.' + mapfile)
                       or templater.templatepath(mapfile))
            if mapname:
                mapfile = mapname

    try:
        t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
    except SyntaxError, inst:
        raise util.Abort(inst.args[0])
Beispiel #33
0
def show_changeset(ui, repo, opts, buffered=False):
    """show one changeset using template or regular display.

    Display format will be the first non-empty hit of:
    1. option 'template'
    2. option 'style'
    3. [ui] setting 'logtemplate'
    4. [ui] setting 'style'
    If all of these values are either the unset or the empty string,
    regular display via changeset_printer() is done.
    """
    # options
    patch = False
    if opts.get('patch') or opts.get('stat'):
        patch = matchall(repo)

    tmpl = opts.get('template')
    style = None
    if tmpl:
        tmpl = templater.parsestring(tmpl, quoted=False)
    else:
        style = opts.get('style')

    # ui settings
    if not (tmpl or style):
        tmpl = ui.config('ui', 'logtemplate')
        if tmpl:
            tmpl = templater.parsestring(tmpl)
        else:
            style = util.expandpath(ui.config('ui', 'style', ''))

    if not (tmpl or style):
        return changeset_printer(ui, repo, patch, opts, buffered)

    mapfile = None
    if style and not tmpl:
        mapfile = style
        if not os.path.split(mapfile)[0]:
            mapname = (templater.templatepath('map-cmdline.' + mapfile)
                       or templater.templatepath(mapfile))
            if mapname:
                mapfile = mapname

    try:
        t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
    except SyntaxError, inst:
        raise util.Abort(inst.args[0])
Beispiel #34
0
def hook(ui, repo, name, throw=False, **args):
    if not ui.callhooks:
        return False

    r = False

    oldstdout = -1
    if _redirect:
        try:
            stdoutno = sys.__stdout__.fileno()
            stderrno = sys.__stderr__.fileno()
            # temporarily redirect stdout to stderr, if possible
            if stdoutno >= 0 and stderrno >= 0:
                sys.__stdout__.flush()
                oldstdout = os.dup(stdoutno)
                os.dup2(stderrno, stdoutno)
        except AttributeError:
            # __stdout/err__ doesn't have fileno(), it's not a real file
            pass

    try:
        for hname, cmd in _allhooks(ui):
            if hname.split('.')[0] != name or not cmd:
                continue
            if util.safehasattr(cmd, '__call__'):
                r = _pythonhook(ui, repo, name, hname, cmd, args, throw) or r
            elif cmd.startswith('python:'):
                if cmd.count(':') >= 2:
                    path, cmd = cmd[7:].rsplit(':', 1)
                    path = util.expandpath(path)
                    if repo:
                        path = os.path.join(repo.root, path)
                    mod = extensions.loadpath(path, 'hghook.%s' % hname)
                    hookfn = getattr(mod, cmd)
                else:
                    hookfn = cmd[7:].strip()
                r = _pythonhook(ui, repo, name, hname, hookfn, args,
                                throw) or r
            else:
                r = _exthook(ui, repo, hname, cmd, args, throw) or r
    finally:
        if _redirect and oldstdout >= 0:
            os.dup2(oldstdout, stdoutno)
            os.close(oldstdout)

    return r
Beispiel #35
0
def hook(ui, repo, name, throw=False, **args):
    if not ui.callhooks:
        return False

    r = False

    oldstdout = -1
    if _redirect:
        try:
            stdoutno = sys.__stdout__.fileno()
            stderrno = sys.__stderr__.fileno()
            # temporarily redirect stdout to stderr, if possible
            if stdoutno >= 0 and stderrno >= 0:
                sys.__stdout__.flush()
                oldstdout = os.dup(stdoutno)
                os.dup2(stderrno, stdoutno)
        except AttributeError:
            # __stdout/err__ doesn't have fileno(), it's not a real file
            pass

    try:
        for hname, cmd in _allhooks(ui):
            if hname.split('.')[0] != name or not cmd:
                continue
            if util.safehasattr(cmd, '__call__'):
                r = _pythonhook(ui, repo, name, hname, cmd, args, throw) or r
            elif cmd.startswith('python:'):
                if cmd.count(':') >= 2:
                    path, cmd = cmd[7:].rsplit(':', 1)
                    path = util.expandpath(path)
                    if repo:
                        path = os.path.join(repo.root, path)
                    mod = extensions.loadpath(path, 'hghook.%s' % hname)
                    hookfn = getattr(mod, cmd)
                else:
                    hookfn = cmd[7:].strip()
                r = _pythonhook(ui, repo, name, hname, hookfn, args, throw) or r
            else:
                r = _exthook(ui, repo, hname, cmd, args, throw) or r
    finally:
        if _redirect and oldstdout >= 0:
            os.dup2(oldstdout, stdoutno)
            os.close(oldstdout)

    return r
Beispiel #36
0
    def __init__(self, ui, path, bundlename):
        self._tempparent = None
        try:
            localrepo.localrepository.__init__(self, ui, path)
        except error.RepoError:
            self._tempparent = tempfile.mkdtemp()
            localrepo.instance(ui, self._tempparent, 1)
            localrepo.localrepository.__init__(self, ui, self._tempparent)
        self.ui.setconfig('phases', 'publish', False, 'bundlerepo')

        if path:
            self._url = 'bundle:' + util.expandpath(path) + '+' + bundlename
        else:
            self._url = 'bundle:' + bundlename

        self.tempfile = None
        f = util.posixfile(bundlename, "rb")
        self.bundle = exchange.readbundle(ui, f, bundlename)
        if self.bundle.compressed():
            fdtemp, temp = self.vfs.mkstemp(prefix="hg-bundle-",
                                            suffix=".hg10un")
            self.tempfile = temp
            fptemp = os.fdopen(fdtemp, 'wb')

            try:
                fptemp.write("HG10UN")
                while True:
                    chunk = self.bundle.read(2**18)
                    if not chunk:
                        break
                    fptemp.write(chunk)
            finally:
                fptemp.close()

            f = self.vfs.open(self.tempfile, mode="rb")
            self.bundle = exchange.readbundle(ui, f, bundlename, self.vfs)

        # dict with the mapping 'filename' -> position in the bundle
        self.bundlefilespos = {}

        self.firstnewrev = self.changelog.repotiprev + 1
        phases.retractboundary(self, None, phases.draft,
                               [ctx.node() for ctx in self[self.firstnewrev:]])
Beispiel #37
0
    def __init__(self, ui, path, bundlename):
        self._tempparent = None
        try:
            localrepo.localrepository.__init__(self, ui, path)
        except error.RepoError:
            self._tempparent = tempfile.mkdtemp()
            localrepo.instance(ui, self._tempparent, 1)
            localrepo.localrepository.__init__(self, ui, self._tempparent)
        self.ui.setconfig('phases', 'publish', False)

        if path:
            self._url = 'bundle:' + util.expandpath(path) + '+' + bundlename
        else:
            self._url = 'bundle:' + bundlename

        self.tempfile = None
        f = util.posixfile(bundlename, "rb")
        self.bundle = changegroup.readbundle(f, bundlename)
        if self.bundle.compressed():
            fdtemp, temp = tempfile.mkstemp(prefix="hg-bundle-",
                                            suffix=".hg10un",
                                            dir=self.path)
            self.tempfile = temp
            fptemp = os.fdopen(fdtemp, 'wb')

            try:
                fptemp.write("HG10UN")
                while True:
                    chunk = self.bundle.read(2**18)
                    if not chunk:
                        break
                    fptemp.write(chunk)
            finally:
                fptemp.close()

            f = util.posixfile(self.tempfile, "rb")
            self.bundle = changegroup.readbundle(f, bundlename)

        # dict with the mapping 'filename' -> position in the bundle
        self.bundlefilespos = {}
Beispiel #38
0
    def __init__(self, ui, path, bundlename):
        self._tempparent = None
        try:
            localrepo.localrepository.__init__(self, ui, path)
        except error.RepoError:
            self._tempparent = tempfile.mkdtemp()
            localrepo.instance(ui, self._tempparent, 1)
            localrepo.localrepository.__init__(self, ui, self._tempparent)
        self.ui.setconfig('phases', 'publish', False)

        if path:
            self._url = 'bundle:' + util.expandpath(path) + '+' + bundlename
        else:
            self._url = 'bundle:' + bundlename

        self.tempfile = None
        f = util.posixfile(bundlename, "rb")
        self.bundle = changegroup.readbundle(f, bundlename)
        if self.bundle.compressed():
            fdtemp, temp = tempfile.mkstemp(prefix="hg-bundle-",
                                            suffix=".hg10un", dir=self.path)
            self.tempfile = temp
            fptemp = os.fdopen(fdtemp, 'wb')

            try:
                fptemp.write("HG10UN")
                while True:
                    chunk = self.bundle.read(2**18)
                    if not chunk:
                        break
                    fptemp.write(chunk)
            finally:
                fptemp.close()

            f = util.posixfile(self.tempfile, "rb")
            self.bundle = changegroup.readbundle(f, bundlename)

        # dict with the mapping 'filename' -> position in the bundle
        self.bundlefilespos = {}
Beispiel #39
0
def hook(ui, repo, name, throw=False, **args):
    r = False

    oldstdout = -1
    if _redirect:
        stdoutno = sys.__stdout__.fileno()
        stderrno = sys.__stderr__.fileno()
        # temporarily redirect stdout to stderr, if possible
        if stdoutno >= 0 and stderrno >= 0:
            oldstdout = os.dup(stdoutno)
            os.dup2(stderrno, stdoutno)

    try:
        for hname, cmd in ui.configitems('hooks'):
            if hname.split('.')[0] != name or not cmd:
                continue
            if hasattr(cmd, '__call__'):
                r = _pythonhook(ui, repo, name, hname, cmd, args, throw) or r
            elif cmd.startswith('python:'):
                if cmd.count(':') >= 2:
                    path, cmd = cmd[7:].rsplit(':', 1)
                    path = util.expandpath(path)
                    if repo:
                        path = os.path.join(repo.root, path)
                    mod = extensions.loadpath(path, 'hghook.%s' % hname)
                    hookfn = getattr(mod, cmd)
                else:
                    hookfn = cmd[7:].strip()
                r = _pythonhook(ui, repo, name, hname, hookfn, args,
                                throw) or r
            else:
                r = _exthook(ui, repo, hname, cmd, args, throw) or r
    finally:
        if _redirect and oldstdout >= 0:
            os.dup2(oldstdout, stdoutno)
            os.close(oldstdout)

    return r
    def __init__(self, ui, path, bundlename):
        self._tempparent = None
        try:
            localrepo.localrepository.__init__(self, ui, path)
        except error.RepoError:
            self._tempparent = tempfile.mkdtemp()
            localrepo.instance(ui, self._tempparent, 1)
            localrepo.localrepository.__init__(self, ui, self._tempparent)
        self.ui.setconfig("phases", "publish", False, "bundlerepo")

        if path:
            self._url = "bundle:" + util.expandpath(path) + "+" + bundlename
        else:
            self._url = "bundle:" + bundlename

        self.tempfile = None
        f = util.posixfile(bundlename, "rb")
        self.bundle = exchange.readbundle(ui, f, bundlename)
        if self.bundle.compressed():
            fdtemp, temp = self.vfs.mkstemp(prefix="hg-bundle-", suffix=".hg10un")
            self.tempfile = temp
            fptemp = os.fdopen(fdtemp, "wb")

            try:
                fptemp.write("HG10UN")
                while True:
                    chunk = self.bundle.read(2 ** 18)
                    if not chunk:
                        break
                    fptemp.write(chunk)
            finally:
                fptemp.close()

            f = self.vfs.open(self.tempfile, mode="rb")
            self.bundle = exchange.readbundle(ui, f, bundlename, self.vfs)

        # dict with the mapping 'filename' -> position in the bundle
        self.bundlefilespos = {}
Beispiel #41
0
def rcpath():
    '''return hgrc search path. if env var HGRCPATH is set, use it.
    for each item in path, if directory, use files ending in .rc,
    else use item.
    make HGRCPATH empty to only look in .hg/hgrc of current repo.
    if no HGRCPATH, use default os-specific path.'''
    global _rcpath
    if _rcpath is None:
        if 'HGRCPATH' in os.environ:
            _rcpath = []
            for p in os.environ['HGRCPATH'].split(os.pathsep):
                if not p:
                    continue
                p = util.expandpath(p)
                if os.path.isdir(p):
                    for f, kind in osutil.listdir(p):
                        if f.endswith('.rc'):
                            _rcpath.append(os.path.join(p, f))
                else:
                    _rcpath.append(p)
        else:
            _rcpath = osrcpath()
    return _rcpath
Beispiel #42
0
def rcpath():
    '''return hgrc search path. if env var HGRCPATH is set, use it.
    for each item in path, if directory, use files ending in .rc,
    else use item.
    make HGRCPATH empty to only look in .hg/hgrc of current repo.
    if no HGRCPATH, use default os-specific path.'''
    global _rcpath
    if _rcpath is None:
        if 'HGRCPATH' in os.environ:
            _rcpath = []
            for p in os.environ['HGRCPATH'].split(os.pathsep):
                if not p:
                    continue
                p = util.expandpath(p)
                if os.path.isdir(p):
                    for f, kind in osutil.listdir(p):
                        if f.endswith('.rc'):
                            _rcpath.append(os.path.join(p, f))
                else:
                    _rcpath.append(p)
        else:
            _rcpath = osrcpath()
    return _rcpath
Beispiel #43
0
def hook(ui, repo, name, throw=False, **args):
    r = False

    oldstdout = -1
    if _redirect:
        stdoutno = sys.__stdout__.fileno()
        stderrno = sys.__stderr__.fileno()
        # temporarily redirect stdout to stderr, if possible
        if stdoutno >= 0 and stderrno >= 0:
            oldstdout = os.dup(stdoutno)
            os.dup2(stderrno, stdoutno)

    try:
        for hname, cmd in ui.configitems('hooks'):
            if hname.split('.')[0] != name or not cmd:
                continue
            if hasattr(cmd, '__call__'):
                r = _pythonhook(ui, repo, name, hname, cmd, args, throw) or r
            elif cmd.startswith('python:'):
                if cmd.count(':') >= 2:
                    path, cmd = cmd[7:].rsplit(':', 1)
                    path = util.expandpath(path)
                    if repo:
                        path = os.path.join(repo.root, path)
                    mod = extensions.loadpath(path, 'hghook.%s' % hname)
                    hookfn = getattr(mod, cmd)
                else:
                    hookfn = cmd[7:].strip()
                r = _pythonhook(ui, repo, name, hname, hookfn, args, throw) or r
            else:
                r = _exthook(ui, repo, hname, cmd, args, throw) or r
    finally:
        if _redirect and oldstdout >= 0:
            os.dup2(oldstdout, stdoutno)
            os.close(oldstdout)

    return r
Beispiel #44
0
def _local(path):
    path = util.expandpath(util.drop_scheme('file', path))
    return (os.path.isfile(path) and bundlerepo or localrepo)
Beispiel #45
0
    def parse(self, src, data, sections=None, remap=None, include=None):
        sectionre = util.re.compile(r'\[([^\[]+)\]')
        itemre = util.re.compile(r'([^=\s][^=]*?)\s*=\s*(.*\S|)')
        contre = util.re.compile(r'\s+(\S|\S.*\S)\s*$')
        emptyre = util.re.compile(r'(;|#|\s*$)')
        commentre = util.re.compile(r'(;|#)')
        unsetre = util.re.compile(r'%unset\s+(\S+)')
        includere = util.re.compile(r'%include\s+(\S|\S.*\S)\s*$')
        section = ""
        item = None
        line = 0
        cont = False

        for l in data.splitlines(True):
            line += 1
            if line == 1 and l.startswith('\xef\xbb\xbf'):
                # Someone set us up the BOM
                l = l[3:]
            if cont:
                if commentre.match(l):
                    continue
                m = contre.match(l)
                if m:
                    if sections and section not in sections:
                        continue
                    v = self.get(section, item) + "\n" + m.group(1)
                    self.set(section, item, v, "%s:%d" % (src, line))
                    continue
                item = None
                cont = False
            m = includere.match(l)
            if m:
                inc = util.expandpath(m.group(1))
                base = os.path.dirname(src)
                inc = os.path.normpath(os.path.join(base, inc))
                if include:
                    try:
                        include(inc, remap=remap, sections=sections)
                    except IOError, inst:
                        if inst.errno != errno.ENOENT:
                            raise error.ParseError(
                                _("cannot include %s (%s)") %
                                (inc, inst.strerror), "%s:%s" % (src, line))
                continue
            if emptyre.match(l):
                continue
            m = sectionre.match(l)
            if m:
                section = m.group(1)
                if remap:
                    section = remap.get(section, section)
                if section not in self:
                    self._data[section] = util.sortdict()
                continue
            m = itemre.match(l)
            if m:
                item = m.group(1)
                cont = True
                if sections and section not in sections:
                    continue
                self.set(section, item, m.group(2), "%s:%d" % (src, line))
                continue
            m = unsetre.match(l)
            if m:
                name = m.group(1)
                if sections and section not in sections:
                    continue
                if self.get(section, name) is not None:
                    del self._data[section][name]
                self._unset.append((section, name))
                continue

            raise error.ParseError(l.rstrip(), ("%s:%s" % (src, line)))
Beispiel #46
0
 def _ignore(self):
     files = [self._join('.hgignore')]
     for name, path in self._ui.configitems("ui"):
         if name == 'ignore' or name.startswith('ignore.'):
             files.append(util.expandpath(path))
     return ignore.ignore(self._root, files, self._ui.warn)
Beispiel #47
0
def _local(path):
    path = util.expandpath(util.drop_scheme('file', path))
    return (os.path.isfile(path) and bundlerepo or localrepo)
Beispiel #48
0
    def __init__(self, ui, path, bundlename):
        self._tempparent = None
        try:
            localrepo.localrepository.__init__(self, ui, path)
        except error.RepoError:
            self._tempparent = tempfile.mkdtemp()
            localrepo.instance(ui, self._tempparent, 1)
            localrepo.localrepository.__init__(self, ui, self._tempparent)
        self.ui.setconfig('phases', 'publish', False, 'bundlerepo')

        if path:
            self._url = 'bundle:' + util.expandpath(path) + '+' + bundlename
        else:
            self._url = 'bundle:' + bundlename

        self.tempfile = None
        f = util.posixfile(bundlename, "rb")
        self.bundlefile = self.bundle = exchange.readbundle(ui, f, bundlename)
        if self.bundle.compressed():
            fdtemp, temp = self.vfs.mkstemp(prefix="hg-bundle-",
                                            suffix=".hg10un")
            self.tempfile = temp
            fptemp = os.fdopen(fdtemp, 'wb')

            try:
                fptemp.write("HG10UN")
                while True:
                    chunk = self.bundle.read(2**18)
                    if not chunk:
                        break
                    fptemp.write(chunk)
            finally:
                fptemp.close()

            f = self.vfs.open(self.tempfile, mode="rb")
            self.bundlefile = self.bundle = exchange.readbundle(ui, f,
                                                                bundlename,
                                                                self.vfs)

        if isinstance(self.bundle, bundle2.unbundle20):
            cgparts = [part for part in self.bundle.iterparts()
                       if (part.type == 'changegroup')
                       and (part.params.get('version', '01')
                            in changegroup.packermap)]

            if not cgparts:
                raise util.Abort('No changegroups found')
            version = cgparts[0].params.get('version', '01')
            cgparts = [p for p in cgparts
                       if p.params.get('version', '01') == version]
            if len(cgparts) > 1:
                raise NotImplementedError("Can't process multiple changegroups")
            part = cgparts[0]

            part.seek(0)
            self.bundle = changegroup.packermap[version][1](part, 'UN')

        # dict with the mapping 'filename' -> position in the bundle
        self.bundlefilespos = {}

        self.firstnewrev = self.changelog.repotiprev + 1
        phases.retractboundary(self, None, phases.draft,
                               [ctx.node() for ctx in self[self.firstnewrev:]])
Beispiel #49
0
def _local(path):
    path = util.expandpath(util.urllocalpath(path))
    return (os.path.isfile(path) and bundlerepo or localrepo)
Beispiel #50
0
        def connect(self):
            self.sock = _create_connection((self.host, self.port))

            host = self.host
            if self.realhostport:  # use CONNECT proxy
                something = _generic_proxytunnel(self)
                host = self.realhostport.rsplit(':', 1)[0]

            cacerts = self.ui.config('web', 'cacerts')
            hostfingerprint = self.ui.config('hostfingerprints', host)

            if cacerts and not hostfingerprint:
                cacerts = util.expandpath(cacerts)
                if not os.path.exists(cacerts):
                    raise util.Abort(
                        _('could not find '
                          'web.cacerts: %s') % cacerts)
                self.sock = _ssl_wrap_socket(self.sock,
                                             self.key_file,
                                             self.cert_file,
                                             cert_reqs=CERT_REQUIRED,
                                             ca_certs=cacerts)
                msg = _verifycert(self.sock.getpeercert(), host)
                if msg:
                    raise util.Abort(
                        _('%s certificate error: %s '
                          '(use --insecure to connect '
                          'insecurely)') % (host, msg))
                self.ui.debug('%s certificate successfully verified\n' % host)
            else:
                self.sock = _ssl_wrap_socket(self.sock, self.key_file,
                                             self.cert_file)
                if hasattr(self.sock, 'getpeercert'):
                    peercert = self.sock.getpeercert(True)
                    peerfingerprint = util.sha1(peercert).hexdigest()
                    nicefingerprint = ":".join([
                        peerfingerprint[x:x + 2]
                        for x in xrange(0, len(peerfingerprint), 2)
                    ])
                    if hostfingerprint:
                        if peerfingerprint.lower() != \
                                hostfingerprint.replace(':', '').lower():
                            raise util.Abort(
                                _('invalid certificate for %s '
                                  'with fingerprint %s') %
                                (host, nicefingerprint))
                        self.ui.debug(
                            '%s certificate matched fingerprint %s\n' %
                            (host, nicefingerprint))
                    else:
                        self.ui.warn(
                            _('warning: %s certificate '
                              'with fingerprint %s not verified '
                              '(check hostfingerprints or web.cacerts '
                              'config setting)\n') % (host, nicefingerprint))
                else:  # python 2.5 ?
                    if hostfingerprint:
                        raise util.Abort(
                            _('no certificate for %s with '
                              'configured hostfingerprint') % host)
                    self.ui.warn(
                        _('warning: %s certificate not verified '
                          '(check web.cacerts config setting)\n') % host)
Beispiel #51
0
def _local(path):
    path = util.expandpath(util.urllocalpath(path))
    return (os.path.isfile(path) and bundlerepo or localrepo)
Beispiel #52
0
    def __init__(self, ui, path, bundlename):
        self._tempparent = None
        try:
            localrepo.localrepository.__init__(self, ui, path)
        except error.RepoError:
            self._tempparent = tempfile.mkdtemp()
            localrepo.instance(ui, self._tempparent, 1)
            localrepo.localrepository.__init__(self, ui, self._tempparent)
        self.ui.setconfig('phases', 'publish', False, 'bundlerepo')

        if path:
            self._url = 'bundle:' + util.expandpath(path) + '+' + bundlename
        else:
            self._url = 'bundle:' + bundlename

        self.tempfile = None
        f = util.posixfile(bundlename, "rb")
        self.bundlefile = self.bundle = exchange.readbundle(ui, f, bundlename)
        if self.bundle.compressed():
            fdtemp, temp = self.vfs.mkstemp(prefix="hg-bundle-",
                                            suffix=".hg10un")
            self.tempfile = temp
            fptemp = os.fdopen(fdtemp, 'wb')

            try:
                fptemp.write("HG10UN")
                while True:
                    chunk = self.bundle.read(2**18)
                    if not chunk:
                        break
                    fptemp.write(chunk)
            finally:
                fptemp.close()

            f = self.vfs.open(self.tempfile, mode="rb")
            self.bundlefile = self.bundle = exchange.readbundle(
                ui, f, bundlename, self.vfs)

        if isinstance(self.bundle, bundle2.unbundle20):
            cgparts = [
                part for part in self.bundle.iterparts()
                if (part.type == 'b2x:changegroup') and (
                    part.params.get('version', '01') in changegroup.packermap)
            ]

            if not cgparts:
                raise util.Abort('No changegroups found')
            version = cgparts[0].params.get('version', '01')
            cgparts = [
                p for p in cgparts if p.params.get('version', '01') == version
            ]
            if len(cgparts) > 1:
                raise NotImplementedError(
                    "Can't process multiple changegroups")
            part = cgparts[0]

            part.seek(0)
            self.bundle = changegroup.packermap[version][1](part, 'UN')

        # dict with the mapping 'filename' -> position in the bundle
        self.bundlefilespos = {}

        self.firstnewrev = self.changelog.repotiprev + 1
        phases.retractboundary(self, None, phases.draft,
                               [ctx.node() for ctx in self[self.firstnewrev:]])
Beispiel #53
0
    def parse(self, src, data, sections=None, remap=None, include=None):
        sectionre = re.compile(r'\[([^\[]+)\]')
        itemre = re.compile(r'([^=\s][^=]*?)\s*=\s*(.*\S|)')
        contre = re.compile(r'\s+(\S|\S.*\S)\s*$')
        emptyre = re.compile(r'(;|#|\s*$)')
        commentre = re.compile(r'(;|#)')
        unsetre = re.compile(r'%unset\s+(\S+)')
        includere = re.compile(r'%include\s+(\S|\S.*\S)\s*$')
        section = ""
        item = None
        line = 0
        cont = False

        for l in data.splitlines(True):
            line += 1
            if line == 1 and l.startswith('\xef\xbb\xbf'):
                # Someone set us up the BOM
                l = l[3:]
            if cont:
                if commentre.match(l):
                    continue
                m = contre.match(l)
                if m:
                    if sections and section not in sections:
                        continue
                    v = self.get(section, item) + "\n" + m.group(1)
                    self.set(section, item, v, "%s:%d" % (src, line))
                    continue
                item = None
                cont = False
            m = includere.match(l)
            if m:
                inc = util.expandpath(m.group(1))
                base = os.path.dirname(src)
                inc = os.path.normpath(os.path.join(base, inc))
                if include:
                    try:
                        include(inc, remap=remap, sections=sections)
                    except IOError, inst:
                        if inst.errno != errno.ENOENT:
                            raise error.ParseError(_("cannot include %s (%s)")
                                                   % (inc, inst.strerror),
                                                   "%s:%s" % (src, line))
                continue
            if emptyre.match(l):
                continue
            m = sectionre.match(l)
            if m:
                section = m.group(1)
                if remap:
                    section = remap.get(section, section)
                if section not in self:
                    self._data[section] = sortdict()
                continue
            m = itemre.match(l)
            if m:
                item = m.group(1)
                cont = True
                if sections and section not in sections:
                    continue
                self.set(section, item, m.group(2), "%s:%d" % (src, line))
                continue
            m = unsetre.match(l)
            if m:
                name = m.group(1)
                if sections and section not in sections:
                    continue
                if self.get(section, name) is not None:
                    del self._data[section][name]
                continue

            raise error.ParseError(l.rstrip(), ("%s:%s" % (src, line)))
Beispiel #54
0
 def _ignore(self):
     files = [self._join('.hgignore')]
     for name, path in self._ui.configitems("ui"):
         if name == 'ignore' or name.startswith('ignore.'):
             files.append(util.expandpath(path))
     return ignore.ignore(self._root, files, self._ui.warn)