Esempio n. 1
0
def _premerge(repo, toolconf, files, labels=None):
    tool, toolpath, binary, symlink = toolconf
    if symlink:
        return 1
    a, b, c, back = files

    ui = repo.ui

    validkeep = ['keep', 'keep-merge3']

    # do we attempt to simplemerge first?
    try:
        premerge = _toolbool(ui, tool, "premerge", not binary)
    except error.ConfigError:
        premerge = _toolstr(ui, tool, "premerge").lower()
        if premerge not in validkeep:
            _valid = ', '.join(["'" + v + "'" for v in validkeep])
            raise error.ConfigError(
                _("%s.premerge not valid "
                  "('%s' is neither boolean nor %s)") %
                (tool, premerge, _valid))

    if premerge:
        if premerge == 'keep-merge3':
            if not labels:
                labels = _defaultconflictlabels
            if len(labels) < 3:
                labels.append('base')
        r = simplemerge.simplemerge(ui, a, b, c, quiet=True, label=labels)
        if not r:
            ui.debug(" premerge successful\n")
            return 0
        if premerge not in validkeep:
            util.copyfile(back, a)  # restore from backup and try again
    return 1  # continue merging
Esempio n. 2
0
    def configint(self, section, name, default=None, untrusted=False):
        """parse a configuration element as an integer

        >>> u = ui(); s = 'foo'
        >>> u.setconfig(s, 'int1', '42')
        >>> u.configint(s, 'int1')
        42
        >>> u.setconfig(s, 'int2', '-42')
        >>> u.configint(s, 'int2')
        -42
        >>> u.configint(s, 'unknown', 7)
        7
        >>> u.setconfig(s, 'invalid', 'somevalue')
        >>> u.configint(s, 'invalid')
        Traceback (most recent call last):
            ...
        ConfigError: foo.invalid is not an integer ('somevalue')
        """

        v = self.config(section, name, None, untrusted)
        if v is None:
            return default
        try:
            return int(v)
        except ValueError:
            raise error.ConfigError(
                _("%s.%s is not an integer ('%s')") % (section, name, v))
Esempio n. 3
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)')
        emptyre = re.compile(r'(;|#|\s*$)')
        unsetre = re.compile(r'%unset\s+(\S+)')
        includere = re.compile(r'%include\s+(\S.*\S)')
        section = ""
        item = None
        line = 0
        cont = 0

        for l in data.splitlines(1):
            line += 1
            if cont:
                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
            m = includere.match(l)
            if m:
                inc = m.group(1)
                base = os.path.dirname(src)
                inc = os.path.normpath(os.path.join(base, inc))
                if include:
                    include(inc, remap=remap, sections=sections)
                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 = 1
                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) != None:
                    del self._data[section][name]
                continue

            raise error.ConfigError(
                _('config error at %s:%d: \'%s\'') % (src, line, l.rstrip()))
Esempio n. 4
0
    def configbool(self, section, name, default=False, untrusted=False):
        """parse a configuration element as a boolean

        >>> u = ui(); s = 'foo'
        >>> u.setconfig(s, 'true', 'yes')
        >>> u.configbool(s, 'true')
        True
        >>> u.setconfig(s, 'false', 'no')
        >>> u.configbool(s, 'false')
        False
        >>> u.configbool(s, 'unknown')
        False
        >>> u.configbool(s, 'unknown', True)
        True
        >>> u.setconfig(s, 'invalid', 'somevalue')
        >>> u.configbool(s, 'invalid')
        Traceback (most recent call last):
            ...
        ConfigError: foo.invalid is not a boolean ('somevalue')
        """

        v = self.config(section, name, None, untrusted)
        if v is None:
            return default
        if isinstance(v, bool):
            return v
        b = util.parsebool(v)
        if b is None:
            raise error.ConfigError(
                _("%s.%s is not a boolean ('%s')") % (section, name, v))
        return b
Esempio n. 5
0
    def configbytes(self, section, name, default=0, untrusted=False):
        """parse a configuration element as a quantity in bytes

        Units can be specified as b (bytes), k or kb (kilobytes), m or
        mb (megabytes), g or gb (gigabytes).

        >>> u = ui(); s = 'foo'
        >>> u.setconfig(s, 'val1', '42')
        >>> u.configbytes(s, 'val1')
        42
        >>> u.setconfig(s, 'val2', '42.5 kb')
        >>> u.configbytes(s, 'val2')
        43520
        >>> u.configbytes(s, 'unknown', '7 MB')
        7340032
        >>> u.setconfig(s, 'invalid', 'somevalue')
        >>> u.configbytes(s, 'invalid')
        Traceback (most recent call last):
            ...
        ConfigError: foo.invalid is not a byte quantity ('somevalue')
        """

        value = self.config(section, name)
        if value is None:
            if not isinstance(default, str):
                return default
            value = default
        try:
            return util.sizetoint(value)
        except error.ParseError:
            raise error.ConfigError(
                _("%s.%s is not a byte quantity ('%s')") %
                (section, name, value))
Esempio n. 6
0
def _premerge(repo, toolconf, files):
    tool, toolpath, binary, symlink = toolconf
    a, b, c, back = files

    ui = repo.ui

    # do we attempt to simplemerge first?
    try:
        premerge = _toolbool(ui, tool, "premerge", not (binary or symlink))
    except error.ConfigError:
        premerge = _toolstr(ui, tool, "premerge").lower()
        valid = 'keep'.split()
        if premerge not in valid:
            _valid = ', '.join(["'" + v + "'" for v in valid])
            raise error.ConfigError(
                _("%s.premerge not valid "
                  "('%s' is neither boolean nor %s)") %
                (tool, premerge, _valid))

    if premerge:
        r = simplemerge.simplemerge(ui, a, b, c, quiet=True)
        if not r:
            ui.debug(" premerge successful\n")
            return 0
        if premerge != 'keep':
            util.copyfile(back, a)  # restore from backup and try again
    return 1  # continue merging
Esempio n. 7
0
File: ui.py Progetto: as/9front-work
 def configbool(self, section, name, default=False, untrusted=False):
     v = self.config(section, name, None, untrusted)
     if v is None:
         return default
     if v.lower() not in _booleans:
         raise error.ConfigError(_("%s.%s not a boolean ('%s')")
                                 % (section, name, v))
     return _booleans[v.lower()]
 def configbool(self, section, name, default=False, untrusted=False):
     v = self.config(section, name, None, untrusted)
     if v is None:
         return default
     if isinstance(v, bool):
         return v
     b = util.parsebool(v)
     if b is None:
         raise error.ConfigError(
             _("%s.%s not a boolean ('%s')") % (section, name, v))
     return b
Esempio n. 9
0
def checkportabilityalert(ui):
    '''check if the user's config requests nothing, a warning, or abort for
    non-portable filenames'''
    val = ui.config('ui', 'portablefilenames', 'warn')
    lval = val.lower()
    bval = util.parsebool(val)
    abort = os.name == 'nt' or lval == 'abort'
    warn = bval or lval == 'warn'
    if bval is None and not (warn or abort or lval == 'ignore'):
        raise error.ConfigError(
            _("ui.portablefilenames value is invalid ('%s')") % val)
    return abort, warn
Esempio n. 10
0
def newcommitphase(ui):
    """helper to get the target phase of new commit

    Handle all possible values for the phases.new-commit options.

    """
    v = ui.config('phases', 'new-commit', draft)
    try:
        return phasenames.index(v)
    except ValueError:
        try:
            return int(v)
        except ValueError:
            msg = _("phases.new-commit: not a valid phase name ('%s')")
            raise error.ConfigError(msg % v)
Esempio n. 11
0
    def __init__(self):
        self._info  = sys.__stdout__
        self._error = sys.__stderr__ 

        for entry in '_reply', '_request':
            self.__dict__[entry] = {}

        self._arguments = sys.argv[1:]

        if len(self._arguments) < 2:
            try:
                for variable in self._environment_variables:
                    self._arguments.append(os.environ[variable])
            except KeyError:
                raise error.ConfigError("Environment variable `%s' "
                                                 "is not set." % variable)

        self._request_file, self._reply_file = self._arguments

        if len(self._request_file) == 0 or len(self._reply_file) == 0:
            raise error.NotFound("Both request and reply files have to be set.")
Esempio n. 12
0
    def configbytes(self, section, name, default=0, untrusted=False):
        """parse a configuration element as a quantity in bytes

        Units can be specified as b (bytes), k or kb (kilobytes), m or
        mb (megabytes), g or gb (gigabytes).

        >>> u = ui(); s = 'foo'
        >>> u.setconfig(s, 'val1', '42')
        >>> u.configbytes(s, 'val1')
        42
        >>> u.setconfig(s, 'val2', '42.5 kb')
        >>> u.configbytes(s, 'val2')
        43520
        >>> u.configbytes(s, 'unknown', '7 MB')
        7340032
        >>> u.setconfig(s, 'invalid', 'somevalue')
        >>> u.configbytes(s, 'invalid')
        Traceback (most recent call last):
            ...
        ConfigError: foo.invalid is not a byte quantity ('somevalue')
        """

        orig = string = self.config(section, name)
        if orig is None:
            if not isinstance(default, str):
                return default
            orig = string = default
        multiple = 1
        m = re.match(r'([^kmbg]+?)\s*([kmg]?)b?$', string, re.I)
        if m:
            string, key = m.groups()
            key = key.lower()
            multiple = dict(k=1024, m=1048576, g=1073741824).get(key, 1)
        try:
            return int(float(string) * multiple)
        except ValueError:
            raise error.ConfigError(_("%s.%s is not a byte quantity ('%s')")
                                    % (section, name, orig))
Esempio n. 13
0
def filemerge(repo, mynode, orig, fcd, fco, fca):
    """perform a 3-way merge in the working directory

    mynode = parent node before merge
    orig = original local filename before merge
    fco = other file context
    fca = ancestor file context
    fcd = local file context for current/destination file
    """
    def temp(prefix, ctx):
        pre = "%s~%s." % (os.path.basename(ctx.path()), prefix)
        (fd, name) = tempfile.mkstemp(prefix=pre)
        data = repo.wwritedata(ctx.path(), ctx.data())
        f = os.fdopen(fd, "wb")
        f.write(data)
        f.close()
        return name

    def isbin(ctx):
        try:
            return util.binary(ctx.data())
        except IOError:
            return False

    if not fco.cmp(fcd):  # files identical?
        return None

    ui = repo.ui
    fd = fcd.path()
    binary = isbin(fcd) or isbin(fco) or isbin(fca)
    symlink = 'l' in fcd.flags() + fco.flags()
    tool, toolpath = _picktool(repo, ui, fd, binary, symlink)
    ui.debug("picked tool '%s' for %s (binary %s symlink %s)\n" %
             (tool, fd, binary, symlink))

    if not tool or tool == 'internal:prompt':
        tool = "internal:local"
        if ui.promptchoice(
                _(" no tool found to merge %s\n"
                  "keep (l)ocal or take (o)ther?") % fd,
            (_("&Local"), _("&Other")), 0):
            tool = "internal:other"
    if tool == "internal:local":
        return 0
    if tool == "internal:other":
        repo.wwrite(fd, fco.data(), fco.flags())
        return 0
    if tool == "internal:fail":
        return 1

    # do the actual merge
    a = repo.wjoin(fd)
    b = temp("base", fca)
    c = temp("other", fco)
    out = ""
    back = a + ".orig"
    util.copyfile(a, back)

    if orig != fco.path():
        ui.status(_("merging %s and %s to %s\n") % (orig, fco.path(), fd))
    else:
        ui.status(_("merging %s\n") % fd)

    ui.debug("my %s other %s ancestor %s\n" % (fcd, fco, fca))

    # do we attempt to simplemerge first?
    try:
        premerge = _toolbool(ui, tool, "premerge", not (binary or symlink))
    except error.ConfigError:
        premerge = _toolstr(ui, tool, "premerge").lower()
        valid = 'keep'.split()
        if premerge not in valid:
            _valid = ', '.join(["'" + v + "'" for v in valid])
            raise error.ConfigError(
                _("%s.premerge not valid "
                  "('%s' is neither boolean nor %s)") %
                (tool, premerge, _valid))

    if premerge:
        r = simplemerge.simplemerge(ui, a, b, c, quiet=True)
        if not r:
            ui.debug(" premerge successful\n")
            os.unlink(back)
            os.unlink(b)
            os.unlink(c)
            return 0
        if premerge != 'keep':
            util.copyfile(back, a)  # restore from backup and try again

    env = dict(HG_FILE=fd,
               HG_MY_NODE=short(mynode),
               HG_OTHER_NODE=str(fco.changectx()),
               HG_BASE_NODE=str(fca.changectx()),
               HG_MY_ISLINK='l' in fcd.flags(),
               HG_OTHER_ISLINK='l' in fco.flags(),
               HG_BASE_ISLINK='l' in fca.flags())

    if tool == "internal:merge":
        r = simplemerge.simplemerge(ui, a, b, c, label=['local', 'other'])
    elif tool == 'internal:dump':
        a = repo.wjoin(fd)
        util.copyfile(a, a + ".local")
        repo.wwrite(fd + ".other", fco.data(), fco.flags())
        repo.wwrite(fd + ".base", fca.data(), fca.flags())
        return 1  # unresolved
    else:
        args = _toolstr(ui, tool, "args", '$local $base $other')
        if "$output" in args:
            out, a = a, back  # read input from backup, write to original
        replace = dict(local=a, base=b, other=c, output=out)
        args = util.interpolate(r'\$', replace, args,
                                lambda s: '"%s"' % util.localpath(s))
        r = util.system(toolpath + ' ' + args, cwd=repo.root, environ=env)

    if not r and (_toolbool(ui, tool, "checkconflicts")
                  or 'conflicts' in _toollist(ui, tool, "check")):
        if re.search("^(<<<<<<< .*|=======|>>>>>>> .*)$", fcd.data(),
                     re.MULTILINE):
            r = 1

    checked = False
    if 'prompt' in _toollist(ui, tool, "check"):
        checked = True
        if ui.promptchoice(
                _("was merge of '%s' successful (yn)?") % fd,
            (_("&Yes"), _("&No")), 1):
            r = 1

    if not r and not checked and (_toolbool(ui, tool, "checkchanged") or
                                  'changed' in _toollist(ui, tool, "check")):
        if filecmp.cmp(repo.wjoin(fd), back):
            if ui.promptchoice(
                    _(" output file %s appears unchanged\n"
                      "was merge successful (yn)?") % fd,
                (_("&Yes"), _("&No")), 1):
                r = 1

    if _toolbool(ui, tool, "fixeol"):
        _matcheol(repo.wjoin(fd), back)

    if r:
        ui.warn(_("merging %s failed!\n") % fd)
    else:
        os.unlink(back)

    os.unlink(b)
    os.unlink(c)
    return r