def __init__(self, root, callback=None):
     self.audited = set()
     self.auditeddir = set()
     self.root = root
     self.callback = callback
     if os.path.lexists(root) and not util.checkcase(root):
         self.normcase = util.normcase
     else:
         self.normcase = lambda x: x
示例#2
0
 def __init__(self, root, callback=None):
     self.audited = set()
     self.auditeddir = set()
     self.root = root
     self.callback = callback
     if os.path.lexists(root) and not util.checkcase(root):
         self.normcase = util.normcase
     else:
         self.normcase = lambda x: x
 def _checkcase(self):
     return not util.checkcase(self._join('.hg'))
示例#4
0
def manifestmerge(repo, wctx, p2, pa, branchmerge, force, partial,
                  acceptremote, followcopies):
    """
    Merge p1 and p2 with ancestor pa and generate merge action list

    branchmerge and force are as passed in to update
    partial = function to filter file lists
    acceptremote = accept the incoming changes without prompting
    """

    actions = dict((m, []) for m in 'a f g cd dc r dm dg m dr e rd k'.split())
    copy, movewithdir = {}, {}

    # manifests fetched in order are going to be faster, so prime the caches
    [
        x.manifest()
        for x in sorted(wctx.parents() + [p2, pa], key=lambda x: x.rev())
    ]

    if followcopies:
        ret = copies.mergecopies(repo, wctx, p2, pa)
        copy, movewithdir, diverge, renamedelete = ret
        for of, fl in diverge.iteritems():
            actions['dr'].append((of, (fl, ), "divergent renames"))
        for of, fl in renamedelete.iteritems():
            actions['rd'].append((of, (fl, ), "rename and delete"))

    repo.ui.note(_("resolving manifests\n"))
    repo.ui.debug(" branchmerge: %s, force: %s, partial: %s\n" %
                  (bool(branchmerge), bool(force), bool(partial)))
    repo.ui.debug(" ancestor: %s, local: %s, remote: %s\n" % (pa, wctx, p2))

    m1, m2, ma = wctx.manifest(), p2.manifest(), pa.manifest()
    copied = set(copy.values())
    copied.update(movewithdir.values())

    if '.hgsubstate' in m1:
        # check whether sub state is modified
        for s in sorted(wctx.substate):
            if wctx.sub(s).dirty():
                m1['.hgsubstate'] += "+"
                break

    aborts = []
    # Compare manifests
    diff = m1.diff(m2)

    for f, ((n1, fl1), (n2, fl2)) in diff.iteritems():
        if partial and not partial(f):
            continue
        if n1 and n2:
            fa = f
            a = ma.get(f, nullid)
            if a == nullid:
                fa = copy.get(f, f)
                # Note: f as default is wrong - we can't really make a 3-way
                # merge without an ancestor file.
            fla = ma.flags(fa)
            nol = 'l' not in fl1 + fl2 + fla
            if n2 == a and fl2 == fla:
                actions['k'].append((f, (), "keep"))  # remote unchanged
            elif n1 == a and fl1 == fla:  # local unchanged - use remote
                if n1 == n2:  # optimization: keep local content
                    actions['e'].append((f, (fl2, ), "update permissions"))
                else:
                    actions['g'].append((f, (fl2, ), "remote is newer"))
            elif nol and n2 == a:  # remote only changed 'x'
                actions['e'].append((f, (fl2, ), "update permissions"))
            elif nol and n1 == a:  # local only changed 'x'
                actions['g'].append((f, (fl1, ), "remote is newer"))
            else:  # both changed something
                actions['m'].append(
                    (f, (f, f, fa, False, pa.node()), "versions differ"))
        elif f in copied:  # files we'll deal with on m2 side
            pass
        elif n1 and f in movewithdir:  # directory rename, move local
            f2 = movewithdir[f]
            actions['dm'].append(
                (f2, (f, fl1), "remote directory rename - move from " + f))
        elif n1 and f in copy:
            f2 = copy[f]
            actions['m'].append((f, (f, f2, f2, False, pa.node()),
                                 "local copied/moved from " + f2))
        elif n1 and f in ma:  # clean, a different, no remote
            if n1 != ma[f]:
                if acceptremote:
                    actions['r'].append((f, None, "remote delete"))
                else:
                    actions['cd'].append((f, None, "prompt changed/deleted"))
            elif n1[20:] == "a":  # added, no remote
                actions['f'].append((f, None, "remote deleted"))
            else:
                actions['r'].append((f, None, "other deleted"))
        elif n2 and f in movewithdir:
            f2 = movewithdir[f]
            actions['dg'].append(
                (f2, (f, fl2), "local directory rename - get from " + f))
        elif n2 and f in copy:
            f2 = copy[f]
            if f2 in m2:
                actions['m'].append((f, (f2, f, f2, False, pa.node()),
                                     "remote copied from " + f2))
            else:
                actions['m'].append((f, (f2, f, f2, True, pa.node()),
                                     "remote moved from " + f2))
        elif n2 and f not in ma:
            # local unknown, remote created: the logic is described by the
            # following table:
            #
            # force  branchmerge  different  |  action
            #   n         *           n      |    get
            #   n         *           y      |   abort
            #   y         n           *      |    get
            #   y         y           n      |    get
            #   y         y           y      |   merge
            #
            # Checking whether the files are different is expensive, so we
            # don't do that when we can avoid it.
            if force and not branchmerge:
                actions['g'].append((f, (fl2, ), "remote created"))
            else:
                different = _checkunknownfile(repo, wctx, p2, f)
                if force and branchmerge and different:
                    # FIXME: This is wrong - f is not in ma ...
                    actions['m'].append(
                        (f, (f, f, f, False, pa.node()),
                         "remote differs from untracked local"))
                elif not force and different:
                    aborts.append((f, "ud"))
                else:
                    actions['g'].append((f, (fl2, ), "remote created"))
        elif n2 and n2 != ma[f]:
            different = _checkunknownfile(repo, wctx, p2, f)
            if not force and different:
                aborts.append((f, "ud"))
            else:
                # if different: old untracked f may be overwritten and lost
                if acceptremote:
                    actions['g'].append(
                        (f, (m2.flags(f), ), "remote recreating"))
                else:
                    actions['dc'].append(
                        (f, (m2.flags(f), ), "prompt deleted/changed"))

    for f, m in sorted(aborts):
        if m == "ud":
            repo.ui.warn(_("%s: untracked file differs\n") % f)
        else:
            assert False, m
    if aborts:
        raise util.Abort(
            _("untracked files in working directory differ "
              "from files in requested revision"))

    if not util.checkcase(repo.path):
        # check collision between files only in p2 for clean update
        if (not branchmerge
                and (force or not wctx.dirty(missing=True, branch=False))):
            _checkcollision(repo, m2, None)
        else:
            _checkcollision(repo, m1, actions)

    return actions
示例#5
0
 def _checkcase(self):
     return not util.checkcase(self._join('.hg'))
示例#6
0
文件: merge.py 项目: as/9front-work
def update(repo, node, branchmerge, force, partial):
    """
    Perform a merge between the working directory and the given node

    branchmerge = whether to merge between branches
    force = whether to force branch merging or file overwriting
    partial = a function to filter file lists (dirstate not updated)
    """

    wlock = repo.wlock()
    try:
        wc = repo[None]
        if node is None:
            # tip of current branch
            try:
                node = repo.branchtags()[wc.branch()]
            except KeyError:
                if wc.branch() == "default":  # no default branch!
                    node = repo.lookup("tip")  # update to tip
                else:
                    raise util.Abort(_("branch %s not found") % wc.branch())
        overwrite = force and not branchmerge
        pl = wc.parents()
        p1, p2 = pl[0], repo[node]
        pa = p1.ancestor(p2)
        fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
        fastforward = False

        ### check phase
        if not overwrite and len(pl) > 1:
            raise util.Abort(_("outstanding uncommitted merges"))
        if branchmerge:
            if pa == p2:
                raise util.Abort(_("can't merge with ancestor"))
            elif pa == p1:
                if p1.branch() != p2.branch():
                    fastforward = True
                else:
                    raise util.Abort(
                        _("nothing to merge (use 'hg update'"
                          " or check 'hg heads')"))
            if not force and (wc.files() or wc.deleted()):
                raise util.Abort(
                    _("outstanding uncommitted changes "
                      "(use 'hg status' to list changes)"))
        elif not overwrite:
            if pa == p1 or pa == p2:  # linear
                pass  # all good
            elif p1.branch() == p2.branch():
                if wc.files() or wc.deleted():
                    raise util.Abort(
                        _("crosses branches (use 'hg merge' or "
                          "'hg update -C' to discard changes)"))
                raise util.Abort(
                    _("crosses branches (use 'hg merge' "
                      "or 'hg update -C')"))
            elif wc.files() or wc.deleted():
                raise util.Abort(
                    _("crosses named branches (use "
                      "'hg update -C' to discard changes)"))
            else:
                # Allow jumping branches if there are no changes
                overwrite = True

        ### calculate phase
        action = []
        if not force:
            _checkunknown(wc, p2)
        if not util.checkcase(repo.path):
            _checkcollision(p2)
        action += _forgetremoved(wc, p2, branchmerge)
        action += manifestmerge(repo, wc, p2, pa, overwrite, partial)

        ### apply phase
        if not branchmerge:  # just jump to the new rev
            fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
        if not partial:
            repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)

        stats = applyupdates(repo, action, wc, p2)

        if not partial:
            recordupdates(repo, action, branchmerge)
            repo.dirstate.setparents(fp1, fp2)
            if not branchmerge and not fastforward:
                repo.dirstate.setbranch(p2.branch())
            repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])

        return stats
    finally:
        wlock.release()
示例#7
0
文件: merge.py 项目: helloandre/cr48
def update(repo, node, branchmerge, force, partial):
    """
    Perform a merge between the working directory and the given node

    node = the node to update to, or None if unspecified
    branchmerge = whether to merge between branches
    force = whether to force branch merging or file overwriting
    partial = a function to filter file lists (dirstate not updated)

    The table below shows all the behaviors of the update command
    given the -c and -C or no options, whether the working directory
    is dirty, whether a revision is specified, and the relationship of
    the parent rev to the target rev (linear, on the same named
    branch, or on another named branch).

    This logic is tested by test-update-branches.t.

    -c  -C  dirty  rev  |  linear   same  cross
     n   n    n     n   |    ok     (1)     x
     n   n    n     y   |    ok     ok     ok
     n   n    y     *   |   merge   (2)    (2)
     n   y    *     *   |    ---  discard  ---
     y   n    y     *   |    ---    (3)    ---
     y   n    n     *   |    ---    ok     ---
     y   y    *     *   |    ---    (4)    ---

    x = can't happen
    * = don't-care
    1 = abort: crosses branches (use 'hg merge' or 'hg update -c')
    2 = abort: crosses branches (use 'hg merge' to merge or
                 use 'hg update -C' to discard changes)
    3 = abort: uncommitted local changes
    4 = incompatible options (checked in commands.py)
    """

    onode = node
    wlock = repo.wlock()
    try:
        wc = repo[None]
        if node is None:
            # tip of current branch
            try:
                node = repo.branchtags()[wc.branch()]
            except KeyError:
                if wc.branch() == "default": # no default branch!
                    node = repo.lookup("tip") # update to tip
                else:
                    raise util.Abort(_("branch %s not found") % wc.branch())
        overwrite = force and not branchmerge
        pl = wc.parents()
        p1, p2 = pl[0], repo[node]
        pa = p1.ancestor(p2)
        fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
        fastforward = False

        ### check phase
        if not overwrite and len(pl) > 1:
            raise util.Abort(_("outstanding uncommitted merges"))
        if branchmerge:
            if pa == p2:
                raise util.Abort(_("merging with a working directory ancestor"
                                   " has no effect"))
            elif pa == p1:
                if p1.branch() != p2.branch():
                    fastforward = True
                else:
                    raise util.Abort(_("nothing to merge (use 'hg update'"
                                       " or check 'hg heads')"))
            if not force and (wc.files() or wc.deleted()):
                raise util.Abort(_("outstanding uncommitted changes "
                                   "(use 'hg status' to list changes)"))
        elif not overwrite:
            if pa == p1 or pa == p2: # linear
                pass # all good
            elif wc.files() or wc.deleted():
                raise util.Abort(_("crosses branches (merge branches or use"
                                   " --clean to discard changes)"))
            elif onode is None:
                raise util.Abort(_("crosses branches (merge branches or use"
                                   " --check to force update)"))
            else:
                # Allow jumping branches if clean and specific rev given
                overwrite = True

        ### calculate phase
        action = []
        wc.status(unknown=True) # prime cache
        if not force:
            _checkunknown(wc, p2)
        if not util.checkcase(repo.path):
            _checkcollision(p2)
        action += _forgetremoved(wc, p2, branchmerge)
        action += manifestmerge(repo, wc, p2, pa, overwrite, partial)

        ### apply phase
        if not branchmerge: # just jump to the new rev
            fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
        if not partial:
            repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)

        stats = applyupdates(repo, action, wc, p2, pa, overwrite)

        if not partial:
            repo.dirstate.setparents(fp1, fp2)
            recordupdates(repo, action, branchmerge)
            if not branchmerge and not fastforward:
                repo.dirstate.setbranch(p2.branch())
    finally:
        wlock.release()

    if not partial:
        repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])
    return stats
示例#8
0
def manifestmerge(repo, wctx, p2, pa, branchmerge, force, partial,
                  acceptremote=False):
    """
    Merge p1 and p2 with ancestor pa and generate merge action list

    branchmerge and force are as passed in to update
    partial = function to filter file lists
    acceptremote = accept the incoming changes without prompting
    """

    overwrite = force and not branchmerge
    actions, copy, movewithdir = [], {}, {}

    followcopies = False
    if overwrite:
        pa = wctx
    elif pa == p2: # backwards
        pa = wctx.p1()
    elif not branchmerge and not wctx.dirty(missing=True):
        pass
    elif pa and repo.ui.configbool("merge", "followcopies", True):
        followcopies = True

    # manifests fetched in order are going to be faster, so prime the caches
    [x.manifest() for x in
     sorted(wctx.parents() + [p2, pa], key=lambda x: x.rev())]

    if followcopies:
        ret = copies.mergecopies(repo, wctx, p2, pa)
        copy, movewithdir, diverge, renamedelete = ret
        for of, fl in diverge.iteritems():
            actions.append((of, "dr", (fl,), "divergent renames"))
        for of, fl in renamedelete.iteritems():
            actions.append((of, "rd", (fl,), "rename and delete"))

    repo.ui.note(_("resolving manifests\n"))
    repo.ui.debug(" branchmerge: %s, force: %s, partial: %s\n"
                  % (bool(branchmerge), bool(force), bool(partial)))
    repo.ui.debug(" ancestor: %s, local: %s, remote: %s\n" % (pa, wctx, p2))

    m1, m2, ma = wctx.manifest(), p2.manifest(), pa.manifest()
    copied = set(copy.values())
    copied.update(movewithdir.values())

    if '.hgsubstate' in m1:
        # check whether sub state is modified
        for s in sorted(wctx.substate):
            if wctx.sub(s).dirty():
                m1['.hgsubstate'] += "+"
                break

    aborts, prompts = [], []
    # Compare manifests
    fdiff = dicthelpers.diff(m1, m2)
    flagsdiff = m1.flagsdiff(m2)
    diff12 = dicthelpers.join(fdiff, flagsdiff)

    for f, (n12, fl12) in diff12.iteritems():
        if n12:
            n1, n2 = n12
        else: # file contents didn't change, but flags did
            n1 = n2 = m1.get(f, None)
            if n1 is None:
                # Since n1 == n2, the file isn't present in m2 either. This
                # means that the file was removed or deleted locally and
                # removed remotely, but that residual entries remain in flags.
                # This can happen in manifests generated by workingctx.
                continue
        if fl12:
            fl1, fl2 = fl12
        else: # flags didn't change, file contents did
            fl1 = fl2 = m1.flags(f)

        if partial and not partial(f):
            continue
        if n1 and n2:
            fla = ma.flags(f)
            nol = 'l' not in fl1 + fl2 + fla
            a = ma.get(f, nullid)
            if n2 == a and fl2 == fla:
                pass # remote unchanged - keep local
            elif n1 == a and fl1 == fla: # local unchanged - use remote
                if n1 == n2: # optimization: keep local content
                    actions.append((f, "e", (fl2,), "update permissions"))
                else:
                    actions.append((f, "g", (fl2,), "remote is newer"))
            elif nol and n2 == a: # remote only changed 'x'
                actions.append((f, "e", (fl2,), "update permissions"))
            elif nol and n1 == a: # local only changed 'x'
                actions.append((f, "g", (fl1,), "remote is newer"))
            else: # both changed something
                actions.append((f, "m", (f, f, False), "versions differ"))
        elif f in copied: # files we'll deal with on m2 side
            pass
        elif n1 and f in movewithdir: # directory rename
            f2 = movewithdir[f]
            actions.append((f, "d", (None, f2, fl1),
                            "remote renamed directory to " + f2))
        elif n1 and f in copy:
            f2 = copy[f]
            actions.append((f, "m", (f2, f, False),
                            "local copied/moved to " + f2))
        elif n1 and f in ma: # clean, a different, no remote
            if n1 != ma[f]:
                prompts.append((f, "cd")) # prompt changed/deleted
            elif n1[20:] == "a": # added, no remote
                actions.append((f, "f", None, "remote deleted"))
            else:
                actions.append((f, "r", None, "other deleted"))
        elif n2 and f in movewithdir:
            f2 = movewithdir[f]
            actions.append((None, "d", (f, f2, fl2),
                            "local renamed directory to " + f2))
        elif n2 and f in copy:
            f2 = copy[f]
            if f2 in m2:
                actions.append((f2, "m", (f, f, False),
                                "remote copied to " + f))
            else:
                actions.append((f2, "m", (f, f, True),
                                "remote moved to " + f))
        elif n2 and f not in ma:
            # local unknown, remote created: the logic is described by the
            # following table:
            #
            # force  branchmerge  different  |  action
            #   n         *           n      |    get
            #   n         *           y      |   abort
            #   y         n           *      |    get
            #   y         y           n      |    get
            #   y         y           y      |   merge
            #
            # Checking whether the files are different is expensive, so we
            # don't do that when we can avoid it.
            if force and not branchmerge:
                actions.append((f, "g", (fl2,), "remote created"))
            else:
                different = _checkunknownfile(repo, wctx, p2, f)
                if force and branchmerge and different:
                    actions.append((f, "m", (f, f, False),
                                    "remote differs from untracked local"))
                elif not force and different:
                    aborts.append((f, "ud"))
                else:
                    actions.append((f, "g", (fl2,), "remote created"))
        elif n2 and n2 != ma[f]:
            prompts.append((f, "dc")) # prompt deleted/changed

    for f, m in sorted(aborts):
        if m == "ud":
            repo.ui.warn(_("%s: untracked file differs\n") % f)
        else: assert False, m
    if aborts:
        raise util.Abort(_("untracked files in working directory differ "
                           "from files in requested revision"))

    if not util.checkcase(repo.path):
        # check collision between files only in p2 for clean update
        if (not branchmerge and
            (force or not wctx.dirty(missing=True, branch=False))):
            _checkcollision(repo, m2, [], [])
        else:
            _checkcollision(repo, m1, actions, prompts)

    for f, m in sorted(prompts):
        if m == "cd":
            if acceptremote:
                actions.append((f, "r", None, "remote delete"))
            elif repo.ui.promptchoice(
                _("local changed %s which remote deleted\n"
                  "use (c)hanged version or (d)elete?"
                  "$$ &Changed $$ &Delete") % f, 0):
                actions.append((f, "r", None, "prompt delete"))
            else:
                actions.append((f, "a", None, "prompt keep"))
        elif m == "dc":
            if acceptremote:
                actions.append((f, "g", (m2.flags(f),), "remote recreating"))
            elif repo.ui.promptchoice(
                _("remote changed %s which local deleted\n"
                  "use (c)hanged version or leave (d)eleted?"
                  "$$ &Changed $$ &Deleted") % f, 0) == 0:
                actions.append((f, "g", (m2.flags(f),), "prompt recreating"))
        else: assert False, m
    return actions
示例#9
0
def update(repo, node, branchmerge, force, partial, ancestor=None):
    """
    Perform a merge between the working directory and the given node

    node = the node to update to, or None if unspecified
    branchmerge = whether to merge between branches
    force = whether to force branch merging or file overwriting
    partial = a function to filter file lists (dirstate not updated)

    The table below shows all the behaviors of the update command
    given the -c and -C or no options, whether the working directory
    is dirty, whether a revision is specified, and the relationship of
    the parent rev to the target rev (linear, on the same named
    branch, or on another named branch).

    This logic is tested by test-update-branches.t.

    -c  -C  dirty  rev  |  linear   same  cross
     n   n    n     n   |    ok     (1)     x
     n   n    n     y   |    ok     ok     ok
     n   n    y     *   |   merge   (2)    (2)
     n   y    *     *   |    ---  discard  ---
     y   n    y     *   |    ---    (3)    ---
     y   n    n     *   |    ---    ok     ---
     y   y    *     *   |    ---    (4)    ---

    x = can't happen
    * = don't-care
    1 = abort: crosses branches (use 'hg merge' or 'hg update -c')
    2 = abort: crosses branches (use 'hg merge' to merge or
                 use 'hg update -C' to discard changes)
    3 = abort: uncommitted local changes
    4 = incompatible options (checked in commands.py)

    Return the same tuple as applyupdates().
    """

    onode = node
    wlock = repo.wlock()
    try:
        wc = repo[None]
        if node is None:
            # tip of current branch
            try:
                node = repo.branchtags()[wc.branch()]
            except KeyError:
                if wc.branch() == "default":  # no default branch!
                    node = repo.lookup("tip")  # update to tip
                else:
                    raise util.Abort(_("branch %s not found") % wc.branch())
        overwrite = force and not branchmerge
        pl = wc.parents()
        p1, p2 = pl[0], repo[node]
        if ancestor:
            pa = repo[ancestor]
        else:
            pa = p1.ancestor(p2)

        fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)

        ### check phase
        if not overwrite and len(pl) > 1:
            raise util.Abort(_("outstanding uncommitted merges"))
        if branchmerge:
            if pa == p2:
                raise util.Abort(
                    _("merging with a working directory ancestor"
                      " has no effect"))
            elif pa == p1:
                if p1.branch() == p2.branch():
                    raise util.Abort(_("nothing to merge"),
                                     hint=_("use 'hg update' "
                                            "or check 'hg heads'"))
            if not force and (wc.files() or wc.deleted()):
                raise util.Abort(_("outstanding uncommitted changes"),
                                 hint=_("use 'hg status' to list changes"))
            for s in wc.substate:
                if wc.sub(s).dirty():
                    raise util.Abort(
                        _("outstanding uncommitted changes in "
                          "subrepository '%s'") % s)

        elif not overwrite:
            if pa == p1 or pa == p2:  # linear
                pass  # all good
            elif wc.dirty(missing=True):
                raise util.Abort(
                    _("crosses branches (merge branches or use"
                      " --clean to discard changes)"))
            elif onode is None:
                raise util.Abort(
                    _("crosses branches (merge branches or update"
                      " --check to force update)"))
            else:
                # Allow jumping branches if clean and specific rev given
                overwrite = True

        ### calculate phase
        action = []
        wc.status(unknown=True)  # prime cache
        folding = not util.checkcase(repo.path)
        if not force:
            _checkunknown(wc, p2, folding)
        if folding:
            _checkcollision(p2, branchmerge and p1)
        action += _forgetremoved(wc, p2, branchmerge)
        action += manifestmerge(repo, wc, p2, pa, overwrite, partial)

        ### apply phase
        if not branchmerge:  # just jump to the new rev
            fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
        if not partial:
            repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)

        stats = applyupdates(repo, action, wc, p2, pa, overwrite)

        if not partial:
            repo.dirstate.setparents(fp1, fp2)
            recordupdates(repo, action, branchmerge)
            if not branchmerge:
                repo.dirstate.setbranch(p2.branch())
    finally:
        wlock.release()

    if not partial:
        repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])
    return stats
示例#10
0
def manifestmerge(repo, wctx, p2, pa, branchmerge, force, partial,
                  acceptremote, followcopies):
    """
    Merge p1 and p2 with ancestor pa and generate merge action list

    branchmerge and force are as passed in to update
    partial = function to filter file lists
    acceptremote = accept the incoming changes without prompting
    """

    actions = dict((m, []) for m in 'a f g cd dc r dm dg m dr e rd k'.split())
    copy, movewithdir = {}, {}

    # manifests fetched in order are going to be faster, so prime the caches
    [x.manifest() for x in
     sorted(wctx.parents() + [p2, pa], key=lambda x: x.rev())]

    if followcopies:
        ret = copies.mergecopies(repo, wctx, p2, pa)
        copy, movewithdir, diverge, renamedelete = ret
        for of, fl in diverge.iteritems():
            actions['dr'].append((of, (fl,), "divergent renames"))
        for of, fl in renamedelete.iteritems():
            actions['rd'].append((of, (fl,), "rename and delete"))

    repo.ui.note(_("resolving manifests\n"))
    repo.ui.debug(" branchmerge: %s, force: %s, partial: %s\n"
                  % (bool(branchmerge), bool(force), bool(partial)))
    repo.ui.debug(" ancestor: %s, local: %s, remote: %s\n" % (pa, wctx, p2))

    m1, m2, ma = wctx.manifest(), p2.manifest(), pa.manifest()
    copied = set(copy.values())
    copied.update(movewithdir.values())

    if '.hgsubstate' in m1:
        # check whether sub state is modified
        for s in sorted(wctx.substate):
            if wctx.sub(s).dirty():
                m1['.hgsubstate'] += "+"
                break

    aborts = []
    # Compare manifests
    diff = m1.diff(m2)

    for f, ((n1, fl1), (n2, fl2)) in diff.iteritems():
        if partial and not partial(f):
            continue
        if n1 and n2:
            fa = f
            a = ma.get(f, nullid)
            if a == nullid:
                fa = copy.get(f, f)
                # Note: f as default is wrong - we can't really make a 3-way
                # merge without an ancestor file.
            fla = ma.flags(fa)
            nol = 'l' not in fl1 + fl2 + fla
            if n2 == a and fl2 == fla:
                actions['k'].append((f, (), "keep")) # remote unchanged
            elif n1 == a and fl1 == fla: # local unchanged - use remote
                if n1 == n2: # optimization: keep local content
                    actions['e'].append((f, (fl2,), "update permissions"))
                else:
                    actions['g'].append((f, (fl2,), "remote is newer"))
            elif nol and n2 == a: # remote only changed 'x'
                actions['e'].append((f, (fl2,), "update permissions"))
            elif nol and n1 == a: # local only changed 'x'
                actions['g'].append((f, (fl1,), "remote is newer"))
            else: # both changed something
                actions['m'].append((f, (f, f, fa, False, pa.node()),
                               "versions differ"))
        elif f in copied: # files we'll deal with on m2 side
            pass
        elif n1 and f in movewithdir: # directory rename, move local
            f2 = movewithdir[f]
            actions['dm'].append((f2, (f, fl1),
                            "remote directory rename - move from " + f))
        elif n1 and f in copy:
            f2 = copy[f]
            actions['m'].append((f, (f, f2, f2, False, pa.node()),
                            "local copied/moved from " + f2))
        elif n1 and f in ma: # clean, a different, no remote
            if n1 != ma[f]:
                if acceptremote:
                    actions['r'].append((f, None, "remote delete"))
                else:
                    actions['cd'].append((f, None, "prompt changed/deleted"))
            elif n1[20:] == "a": # added, no remote
                actions['f'].append((f, None, "remote deleted"))
            else:
                actions['r'].append((f, None, "other deleted"))
        elif n2 and f in movewithdir:
            f2 = movewithdir[f]
            actions['dg'].append((f2, (f, fl2),
                            "local directory rename - get from " + f))
        elif n2 and f in copy:
            f2 = copy[f]
            if f2 in m2:
                actions['m'].append((f, (f2, f, f2, False, pa.node()),
                                "remote copied from " + f2))
            else:
                actions['m'].append((f, (f2, f, f2, True, pa.node()),
                                "remote moved from " + f2))
        elif n2 and f not in ma:
            # local unknown, remote created: the logic is described by the
            # following table:
            #
            # force  branchmerge  different  |  action
            #   n         *           n      |    get
            #   n         *           y      |   abort
            #   y         n           *      |    get
            #   y         y           n      |    get
            #   y         y           y      |   merge
            #
            # Checking whether the files are different is expensive, so we
            # don't do that when we can avoid it.
            if force and not branchmerge:
                actions['g'].append((f, (fl2,), "remote created"))
            else:
                different = _checkunknownfile(repo, wctx, p2, f)
                if force and branchmerge and different:
                    # FIXME: This is wrong - f is not in ma ...
                    actions['m'].append((f, (f, f, f, False, pa.node()),
                                    "remote differs from untracked local"))
                elif not force and different:
                    aborts.append((f, "ud"))
                else:
                    actions['g'].append((f, (fl2,), "remote created"))
        elif n2 and n2 != ma[f]:
            different = _checkunknownfile(repo, wctx, p2, f)
            if not force and different:
                aborts.append((f, "ud"))
            else:
                # if different: old untracked f may be overwritten and lost
                if acceptremote:
                    actions['g'].append((f, (m2.flags(f),),
                                   "remote recreating"))
                else:
                    actions['dc'].append((f, (m2.flags(f),),
                                   "prompt deleted/changed"))

    for f, m in sorted(aborts):
        if m == "ud":
            repo.ui.warn(_("%s: untracked file differs\n") % f)
        else: assert False, m
    if aborts:
        raise util.Abort(_("untracked files in working directory differ "
                           "from files in requested revision"))

    if not util.checkcase(repo.path):
        # check collision between files only in p2 for clean update
        if (not branchmerge and
            (force or not wctx.dirty(missing=True, branch=False))):
            _checkcollision(repo, m2, None)
        else:
            _checkcollision(repo, m1, actions)

    return actions
示例#11
0
文件: merge.py 项目: RayFerr000/PLTL
def update(repo, node, branchmerge, force, partial, ancestor=None,
           mergeancestor=False, labels=None):
    """
    Perform a merge between the working directory and the given node

    node = the node to update to, or None if unspecified
    branchmerge = whether to merge between branches
    force = whether to force branch merging or file overwriting
    partial = a function to filter file lists (dirstate not updated)
    mergeancestor = whether it is merging with an ancestor. If true,
      we should accept the incoming changes for any prompts that occur.
      If false, merging with an ancestor (fast-forward) is only allowed
      between different named branches. This flag is used by rebase extension
      as a temporary fix and should be avoided in general.

    The table below shows all the behaviors of the update command
    given the -c and -C or no options, whether the working directory
    is dirty, whether a revision is specified, and the relationship of
    the parent rev to the target rev (linear, on the same named
    branch, or on another named branch).

    This logic is tested by test-update-branches.t.

    -c  -C  dirty  rev  |  linear   same  cross
     n   n    n     n   |    ok     (1)     x
     n   n    n     y   |    ok     ok     ok
     n   n    y     n   |   merge   (2)    (2)
     n   n    y     y   |   merge   (3)    (3)
     n   y    *     *   |    ---  discard  ---
     y   n    y     *   |    ---    (4)    ---
     y   n    n     *   |    ---    ok     ---
     y   y    *     *   |    ---    (5)    ---

    x = can't happen
    * = don't-care
    1 = abort: not a linear update (merge or update --check to force update)
    2 = abort: uncommitted changes (commit and merge, or update --clean to
                 discard changes)
    3 = abort: uncommitted changes (commit or update --clean to discard changes)
    4 = abort: uncommitted changes (checked in commands.py)
    5 = incompatible options (checked in commands.py)

    Return the same tuple as applyupdates().
    """

    onode = node
    wlock = repo.wlock()
    try:
        wc = repo[None]
        pl = wc.parents()
        p1 = pl[0]
        pas = [None]
        if ancestor is not None:
            pas = [repo[ancestor]]

        if node is None:
            # Here is where we should consider bookmarks, divergent bookmarks,
            # foreground changesets (successors), and tip of current branch;
            # but currently we are only checking the branch tips.
            try:
                node = repo.branchtip(wc.branch())
            except errormod.RepoLookupError:
                if wc.branch() == 'default': # no default branch!
                    node = repo.lookup('tip') # update to tip
                else:
                    raise util.Abort(_("branch %s not found") % wc.branch())

            if p1.obsolete() and not p1.children():
                # allow updating to successors
                successors = obsolete.successorssets(repo, p1.node())

                # behavior of certain cases is as follows,
                #
                # divergent changesets: update to highest rev, similar to what
                #     is currently done when there are more than one head
                #     (i.e. 'tip')
                #
                # replaced changesets: same as divergent except we know there
                # is no conflict
                #
                # pruned changeset: no update is done; though, we could
                #     consider updating to the first non-obsolete parent,
                #     similar to what is current done for 'hg prune'

                if successors:
                    # flatten the list here handles both divergent (len > 1)
                    # and the usual case (len = 1)
                    successors = [n for sub in successors for n in sub]

                    # get the max revision for the given successors set,
                    # i.e. the 'tip' of a set
                    node = repo.revs('max(%ln)', successors).first()
                    pas = [p1]

        overwrite = force and not branchmerge

        p2 = repo[node]
        if pas[0] is None:
            if repo.ui.config('merge', 'preferancestor', '*') == '*':
                cahs = repo.changelog.commonancestorsheads(p1.node(), p2.node())
                pas = [repo[anc] for anc in (sorted(cahs) or [nullid])]
            else:
                pas = [p1.ancestor(p2, warn=branchmerge)]

        fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)

        ### check phase
        if not overwrite and len(pl) > 1:
            raise util.Abort(_("outstanding uncommitted merge"))
        if branchmerge:
            if pas == [p2]:
                raise util.Abort(_("merging with a working directory ancestor"
                                   " has no effect"))
            elif pas == [p1]:
                if not mergeancestor and p1.branch() == p2.branch():
                    raise util.Abort(_("nothing to merge"),
                                     hint=_("use 'hg update' "
                                            "or check 'hg heads'"))
            if not force and (wc.files() or wc.deleted()):
                raise util.Abort(_("uncommitted changes"),
                                 hint=_("use 'hg status' to list changes"))
            for s in sorted(wc.substate):
                wc.sub(s).bailifchanged()

        elif not overwrite:
            if p1 == p2: # no-op update
                # call the hooks and exit early
                repo.hook('preupdate', throw=True, parent1=xp2, parent2='')
                repo.hook('update', parent1=xp2, parent2='', error=0)
                return 0, 0, 0, 0

            if pas not in ([p1], [p2]):  # nonlinear
                dirty = wc.dirty(missing=True)
                if dirty or onode is None:
                    # Branching is a bit strange to ensure we do the minimal
                    # amount of call to obsolete.background.
                    foreground = obsolete.foreground(repo, [p1.node()])
                    # note: the <node> variable contains a random identifier
                    if repo[node].node() in foreground:
                        pas = [p1]  # allow updating to successors
                    elif dirty:
                        msg = _("uncommitted changes")
                        if onode is None:
                            hint = _("commit and merge, or update --clean to"
                                     " discard changes")
                        else:
                            hint = _("commit or update --clean to discard"
                                     " changes")
                        raise util.Abort(msg, hint=hint)
                    else:  # node is none
                        msg = _("not a linear update")
                        hint = _("merge or update --check to force update")
                        raise util.Abort(msg, hint=hint)
                else:
                    # Allow jumping branches if clean and specific rev given
                    pas = [p1]

        followcopies = False
        if overwrite:
            pas = [wc]
        elif pas == [p2]: # backwards
            pas = [wc.p1()]
        elif not branchmerge and not wc.dirty(missing=True):
            pass
        elif pas[0] and repo.ui.configbool('merge', 'followcopies', True):
            followcopies = True

        ### calculate phase
        actionbyfile, diverge, renamedelete = calculateupdates(
            repo, wc, p2, pas, branchmerge, force, partial, mergeancestor,
            followcopies)
        # Convert to dictionary-of-lists format
        actions = dict((m, []) for m in 'a f g cd dc r dm dg m e k'.split())
        for f, (m, args, msg) in actionbyfile.iteritems():
            if m not in actions:
                actions[m] = []
            actions[m].append((f, args, msg))

        if not util.checkcase(repo.path):
            # check collision between files only in p2 for clean update
            if (not branchmerge and
                (force or not wc.dirty(missing=True, branch=False))):
                _checkcollision(repo, p2.manifest(), None)
            else:
                _checkcollision(repo, wc.manifest(), actions)

        # Prompt and create actions. TODO: Move this towards resolve phase.
        for f, args, msg in sorted(actions['cd']):
            if repo.ui.promptchoice(
                _("local changed %s which remote deleted\n"
                  "use (c)hanged version or (d)elete?"
                  "$$ &Changed $$ &Delete") % f, 0):
                actions['r'].append((f, None, "prompt delete"))
            else:
                actions['a'].append((f, None, "prompt keep"))
        del actions['cd'][:]

        for f, args, msg in sorted(actions['dc']):
            flags, = args
            if repo.ui.promptchoice(
                _("remote changed %s which local deleted\n"
                  "use (c)hanged version or leave (d)eleted?"
                  "$$ &Changed $$ &Deleted") % f, 0) == 0:
                actions['g'].append((f, (flags,), "prompt recreating"))
        del actions['dc'][:]

        ### apply phase
        if not branchmerge: # just jump to the new rev
            fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
        if not partial:
            repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)
            # note that we're in the middle of an update
            repo.vfs.write('updatestate', p2.hex())

        stats = applyupdates(repo, actions, wc, p2, overwrite, labels=labels)

        # divergent renames
        for f, fl in sorted(diverge.iteritems()):
            repo.ui.warn(_("note: possible conflict - %s was renamed "
                           "multiple times to:\n") % f)
            for nf in fl:
                repo.ui.warn(" %s\n" % nf)

        # rename and delete
        for f, fl in sorted(renamedelete.iteritems()):
            repo.ui.warn(_("note: possible conflict - %s was deleted "
                           "and renamed to:\n") % f)
            for nf in fl:
                repo.ui.warn(" %s\n" % nf)

        if not partial:
            repo.dirstate.beginparentchange()
            repo.setparents(fp1, fp2)
            recordupdates(repo, actions, branchmerge)
            # update completed, clear state
            util.unlink(repo.join('updatestate'))

            if not branchmerge:
                repo.dirstate.setbranch(p2.branch())
            repo.dirstate.endparentchange()
    finally:
        wlock.release()

    if not partial:
        def updatehook(parent1=xp1, parent2=xp2, error=stats[3]):
            repo.hook('update', parent1=parent1, parent2=parent2, error=error)
        repo._afterlock(updatehook)
    return stats
示例#12
0
def manifestmerge(repo,
                  wctx,
                  p2,
                  pa,
                  branchmerge,
                  force,
                  partial,
                  acceptremote=False):
    """
    Merge p1 and p2 with ancestor pa and generate merge action list

    branchmerge and force are as passed in to update
    partial = function to filter file lists
    acceptremote = accept the incoming changes without prompting
    """

    overwrite = force and not branchmerge
    actions, copy, movewithdir = [], {}, {}

    followcopies = False
    if overwrite:
        pa = wctx
    elif pa == p2:  # backwards
        pa = wctx.p1()
    elif not branchmerge and not wctx.dirty(missing=True):
        pass
    elif pa and repo.ui.configbool("merge", "followcopies", True):
        followcopies = True

    # manifests fetched in order are going to be faster, so prime the caches
    [
        x.manifest()
        for x in sorted(wctx.parents() + [p2, pa], key=lambda x: x.rev())
    ]

    if followcopies:
        ret = copies.mergecopies(repo, wctx, p2, pa)
        copy, movewithdir, diverge, renamedelete = ret
        for of, fl in diverge.iteritems():
            actions.append((of, "dr", (fl, ), "divergent renames"))
        for of, fl in renamedelete.iteritems():
            actions.append((of, "rd", (fl, ), "rename and delete"))

    repo.ui.note(_("resolving manifests\n"))
    repo.ui.debug(" branchmerge: %s, force: %s, partial: %s\n" %
                  (bool(branchmerge), bool(force), bool(partial)))
    repo.ui.debug(" ancestor: %s, local: %s, remote: %s\n" % (pa, wctx, p2))

    m1, m2, ma = wctx.manifest(), p2.manifest(), pa.manifest()
    copied = set(copy.values())
    copied.update(movewithdir.values())

    if '.hgsubstate' in m1:
        # check whether sub state is modified
        for s in sorted(wctx.substate):
            if wctx.sub(s).dirty():
                m1['.hgsubstate'] += "+"
                break

    aborts, prompts = [], []
    # Compare manifests
    fdiff = dicthelpers.diff(m1, m2)
    flagsdiff = m1.flagsdiff(m2)
    diff12 = dicthelpers.join(fdiff, flagsdiff)

    for f, (n12, fl12) in diff12.iteritems():
        if n12:
            n1, n2 = n12
        else:  # file contents didn't change, but flags did
            n1 = n2 = m1.get(f, None)
            if n1 is None:
                # Since n1 == n2, the file isn't present in m2 either. This
                # means that the file was removed or deleted locally and
                # removed remotely, but that residual entries remain in flags.
                # This can happen in manifests generated by workingctx.
                continue
        if fl12:
            fl1, fl2 = fl12
        else:  # flags didn't change, file contents did
            fl1 = fl2 = m1.flags(f)

        if partial and not partial(f):
            continue
        if n1 and n2:
            fla = ma.flags(f)
            nol = 'l' not in fl1 + fl2 + fla
            a = ma.get(f, nullid)
            if n2 == a and fl2 == fla:
                pass  # remote unchanged - keep local
            elif n1 == a and fl1 == fla:  # local unchanged - use remote
                if n1 == n2:  # optimization: keep local content
                    actions.append((f, "e", (fl2, ), "update permissions"))
                else:
                    actions.append((f, "g", (fl2, ), "remote is newer"))
            elif nol and n2 == a:  # remote only changed 'x'
                actions.append((f, "e", (fl2, ), "update permissions"))
            elif nol and n1 == a:  # local only changed 'x'
                actions.append((f, "g", (fl1, ), "remote is newer"))
            else:  # both changed something
                actions.append((f, "m", (f, f, False), "versions differ"))
        elif f in copied:  # files we'll deal with on m2 side
            pass
        elif n1 and f in movewithdir:  # directory rename
            f2 = movewithdir[f]
            actions.append(
                (f, "d", (None, f2, fl1), "remote renamed directory to " + f2))
        elif n1 and f in copy:
            f2 = copy[f]
            actions.append(
                (f, "m", (f2, f, False), "local copied/moved to " + f2))
        elif n1 and f in ma:  # clean, a different, no remote
            if n1 != ma[f]:
                prompts.append((f, "cd"))  # prompt changed/deleted
            elif n1[20:] == "a":  # added, no remote
                actions.append((f, "f", None, "remote deleted"))
            else:
                actions.append((f, "r", None, "other deleted"))
        elif n2 and f in movewithdir:
            f2 = movewithdir[f]
            actions.append(
                (None, "d", (f, f2, fl2), "local renamed directory to " + f2))
        elif n2 and f in copy:
            f2 = copy[f]
            if f2 in m2:
                actions.append(
                    (f2, "m", (f, f, False), "remote copied to " + f))
            else:
                actions.append((f2, "m", (f, f, True), "remote moved to " + f))
        elif n2 and f not in ma:
            # local unknown, remote created: the logic is described by the
            # following table:
            #
            # force  branchmerge  different  |  action
            #   n         *           n      |    get
            #   n         *           y      |   abort
            #   y         n           *      |    get
            #   y         y           n      |    get
            #   y         y           y      |   merge
            #
            # Checking whether the files are different is expensive, so we
            # don't do that when we can avoid it.
            if force and not branchmerge:
                actions.append((f, "g", (fl2, ), "remote created"))
            else:
                different = _checkunknownfile(repo, wctx, p2, f)
                if force and branchmerge and different:
                    actions.append((f, "m", (f, f, False),
                                    "remote differs from untracked local"))
                elif not force and different:
                    aborts.append((f, "ud"))
                else:
                    actions.append((f, "g", (fl2, ), "remote created"))
        elif n2 and n2 != ma[f]:
            prompts.append((f, "dc"))  # prompt deleted/changed

    for f, m in sorted(aborts):
        if m == "ud":
            repo.ui.warn(_("%s: untracked file differs\n") % f)
        else:
            assert False, m
    if aborts:
        raise util.Abort(
            _("untracked files in working directory differ "
              "from files in requested revision"))

    if not util.checkcase(repo.path):
        # check collision between files only in p2 for clean update
        if (not branchmerge
                and (force or not wctx.dirty(missing=True, branch=False))):
            _checkcollision(repo, m2, [], [])
        else:
            _checkcollision(repo, m1, actions, prompts)

    for f, m in sorted(prompts):
        if m == "cd":
            if acceptremote:
                actions.append((f, "r", None, "remote delete"))
            elif repo.ui.promptchoice(
                    _("local changed %s which remote deleted\n"
                      "use (c)hanged version or (d)elete?"
                      "$$ &Changed $$ &Delete") % f, 0):
                actions.append((f, "r", None, "prompt delete"))
            else:
                actions.append((f, "a", None, "prompt keep"))
        elif m == "dc":
            if acceptremote:
                actions.append((f, "g", (m2.flags(f), ), "remote recreating"))
            elif repo.ui.promptchoice(
                    _("remote changed %s which local deleted\n"
                      "use (c)hanged version or leave (d)eleted?"
                      "$$ &Changed $$ &Deleted") % f, 0) == 0:
                actions.append((f, "g", (m2.flags(f), ), "prompt recreating"))
        else:
            assert False, m
    return actions
示例#13
0
 def _checkcase(self):
     return not util.checkcase(self._join(".hg"))
示例#14
0
def update(repo, node, branchmerge, force, partial):
    """
    Perform a merge between the working directory and the given node

    branchmerge = whether to merge between branches
    force = whether to force branch merging or file overwriting
    partial = a function to filter file lists (dirstate not updated)
    """

    wlock = repo.wlock()
    try:
        wc = repo[None]
        if node is None:
            # tip of current branch
            try:
                node = repo.branchtags()[wc.branch()]
            except KeyError:
                if wc.branch() == "default": # no default branch!
                    node = repo.lookup("tip") # update to tip
                else:
                    raise util.Abort(_("branch %s not found") % wc.branch())
        overwrite = force and not branchmerge
        pl = wc.parents()
        p1, p2 = pl[0], repo[node]
        pa = p1.ancestor(p2)
        fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
        fastforward = False

        ### check phase
        if not overwrite and len(pl) > 1:
            raise util.Abort(_("outstanding uncommitted merges"))
        if branchmerge:
            if pa == p2:
                raise util.Abort(_("can't merge with ancestor"))
            elif pa == p1:
                if p1.branch() != p2.branch():
                    fastforward = True
                else:
                    raise util.Abort(_("nothing to merge (use 'hg update'"
                                       " or check 'hg heads')"))
            if not force and (wc.files() or wc.deleted()):
                raise util.Abort(_("outstanding uncommitted changes "
                                   "(use 'hg status' to list changes)"))
        elif not overwrite:
            if pa == p1 or pa == p2: # linear
                pass # all good
            elif p1.branch() == p2.branch():
                if wc.files() or wc.deleted():
                    raise util.Abort(_("crosses branches (use 'hg merge' or "
                                       "'hg update -C' to discard changes)"))
                raise util.Abort(_("crosses branches (use 'hg merge' "
                                   "or 'hg update -C')"))
            elif wc.files() or wc.deleted():
                raise util.Abort(_("crosses named branches (use "
                                   "'hg update -C' to discard changes)"))
            else:
                # Allow jumping branches if there are no changes
                overwrite = True

        ### calculate phase
        action = []
        if not force:
            _checkunknown(wc, p2)
        if not util.checkcase(repo.path):
            _checkcollision(p2)
        action += _forgetremoved(wc, p2, branchmerge)
        action += manifestmerge(repo, wc, p2, pa, overwrite, partial)

        ### apply phase
        if not branchmerge: # just jump to the new rev
            fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
        if not partial:
            repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)

        stats = applyupdates(repo, action, wc, p2)

        if not partial:
            recordupdates(repo, action, branchmerge)
            repo.dirstate.setparents(fp1, fp2)
            if not branchmerge and not fastforward:
                repo.dirstate.setbranch(p2.branch())
            repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])

        return stats
    finally:
        wlock.release()
示例#15
0
            for name, path in self._ui.configitems("ui"):
                if name == 'ignore' or name.startswith('ignore.'):
                    files.append(os.path.expanduser(path))
            self._ignore = ignore.ignore(self._root, files, self._ui.warn)
            return self._ignore
        elif name == '_slash':
            self._slash = self._ui.configbool('ui', 'slash') and os.sep != '/'
            return self._slash
        elif name == '_checklink':
            self._checklink = util.checklink(self._root)
            return self._checklink
        elif name == '_checkexec':
            self._checkexec = util.checkexec(self._root)
            return self._checkexec
        elif name == '_checkcase':
            self._checkcase = not util.checkcase(self._join('.hg'))
            return self._checkcase
        elif name == 'normalize':
            if self._checkcase:
                self.normalize = self._normalize
            else:
                self.normalize = lambda x, y=False: x
            return self.normalize
        else:
            raise AttributeError(name)

    def _join(self, f):
        # much faster than os.path.join()
        # it's safe because f is always a relative path
        return self._rootdir + f
示例#16
0
def update(repo,
           node,
           branchmerge,
           force,
           partial,
           ancestor=None,
           mergeancestor=False,
           labels=None):
    """
    Perform a merge between the working directory and the given node

    node = the node to update to, or None if unspecified
    branchmerge = whether to merge between branches
    force = whether to force branch merging or file overwriting
    partial = a function to filter file lists (dirstate not updated)
    mergeancestor = whether it is merging with an ancestor. If true,
      we should accept the incoming changes for any prompts that occur.
      If false, merging with an ancestor (fast-forward) is only allowed
      between different named branches. This flag is used by rebase extension
      as a temporary fix and should be avoided in general.

    The table below shows all the behaviors of the update command
    given the -c and -C or no options, whether the working directory
    is dirty, whether a revision is specified, and the relationship of
    the parent rev to the target rev (linear, on the same named
    branch, or on another named branch).

    This logic is tested by test-update-branches.t.

    -c  -C  dirty  rev  |  linear   same  cross
     n   n    n     n   |    ok     (1)     x
     n   n    n     y   |    ok     ok     ok
     n   n    y     n   |   merge   (2)    (2)
     n   n    y     y   |   merge   (3)    (3)
     n   y    *     *   |    ---  discard  ---
     y   n    y     *   |    ---    (4)    ---
     y   n    n     *   |    ---    ok     ---
     y   y    *     *   |    ---    (5)    ---

    x = can't happen
    * = don't-care
    1 = abort: not a linear update (merge or update --check to force update)
    2 = abort: uncommitted changes (commit and merge, or update --clean to
                 discard changes)
    3 = abort: uncommitted changes (commit or update --clean to discard changes)
    4 = abort: uncommitted changes (checked in commands.py)
    5 = incompatible options (checked in commands.py)

    Return the same tuple as applyupdates().
    """

    onode = node
    wlock = repo.wlock()
    try:
        wc = repo[None]
        pl = wc.parents()
        p1 = pl[0]
        pas = [None]
        if ancestor is not None:
            pas = [repo[ancestor]]

        if node is None:
            # Here is where we should consider bookmarks, divergent bookmarks,
            # foreground changesets (successors), and tip of current branch;
            # but currently we are only checking the branch tips.
            try:
                node = repo.branchtip(wc.branch())
            except errormod.RepoLookupError:
                if wc.branch() == 'default':  # no default branch!
                    node = repo.lookup('tip')  # update to tip
                else:
                    raise util.Abort(_("branch %s not found") % wc.branch())

            if p1.obsolete() and not p1.children():
                # allow updating to successors
                successors = obsolete.successorssets(repo, p1.node())

                # behavior of certain cases is as follows,
                #
                # divergent changesets: update to highest rev, similar to what
                #     is currently done when there are more than one head
                #     (i.e. 'tip')
                #
                # replaced changesets: same as divergent except we know there
                # is no conflict
                #
                # pruned changeset: no update is done; though, we could
                #     consider updating to the first non-obsolete parent,
                #     similar to what is current done for 'hg prune'

                if successors:
                    # flatten the list here handles both divergent (len > 1)
                    # and the usual case (len = 1)
                    successors = [n for sub in successors for n in sub]

                    # get the max revision for the given successors set,
                    # i.e. the 'tip' of a set
                    node = repo.revs('max(%ln)', successors).first()
                    pas = [p1]

        overwrite = force and not branchmerge

        p2 = repo[node]
        if pas[0] is None:
            if repo.ui.config('merge', 'preferancestor', '*') == '*':
                cahs = repo.changelog.commonancestorsheads(
                    p1.node(), p2.node())
                pas = [repo[anc] for anc in (sorted(cahs) or [nullid])]
            else:
                pas = [p1.ancestor(p2, warn=branchmerge)]

        fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)

        ### check phase
        if not overwrite and len(pl) > 1:
            raise util.Abort(_("outstanding uncommitted merge"))
        if branchmerge:
            if pas == [p2]:
                raise util.Abort(
                    _("merging with a working directory ancestor"
                      " has no effect"))
            elif pas == [p1]:
                if not mergeancestor and p1.branch() == p2.branch():
                    raise util.Abort(_("nothing to merge"),
                                     hint=_("use 'hg update' "
                                            "or check 'hg heads'"))
            if not force and (wc.files() or wc.deleted()):
                raise util.Abort(_("uncommitted changes"),
                                 hint=_("use 'hg status' to list changes"))
            for s in sorted(wc.substate):
                wc.sub(s).bailifchanged()

        elif not overwrite:
            if p1 == p2:  # no-op update
                # call the hooks and exit early
                repo.hook('preupdate', throw=True, parent1=xp2, parent2='')
                repo.hook('update', parent1=xp2, parent2='', error=0)
                return 0, 0, 0, 0

            if pas not in ([p1], [p2]):  # nonlinear
                dirty = wc.dirty(missing=True)
                if dirty or onode is None:
                    # Branching is a bit strange to ensure we do the minimal
                    # amount of call to obsolete.background.
                    foreground = obsolete.foreground(repo, [p1.node()])
                    # note: the <node> variable contains a random identifier
                    if repo[node].node() in foreground:
                        pas = [p1]  # allow updating to successors
                    elif dirty:
                        msg = _("uncommitted changes")
                        if onode is None:
                            hint = _("commit and merge, or update --clean to"
                                     " discard changes")
                        else:
                            hint = _("commit or update --clean to discard"
                                     " changes")
                        raise util.Abort(msg, hint=hint)
                    else:  # node is none
                        msg = _("not a linear update")
                        hint = _("merge or update --check to force update")
                        raise util.Abort(msg, hint=hint)
                else:
                    # Allow jumping branches if clean and specific rev given
                    pas = [p1]

        followcopies = False
        if overwrite:
            pas = [wc]
        elif pas == [p2]:  # backwards
            pas = [wc.p1()]
        elif not branchmerge and not wc.dirty(missing=True):
            pass
        elif pas[0] and repo.ui.configbool('merge', 'followcopies', True):
            followcopies = True

        ### calculate phase
        actionbyfile, diverge, renamedelete = calculateupdates(
            repo, wc, p2, pas, branchmerge, force, partial, mergeancestor,
            followcopies)
        # Convert to dictionary-of-lists format
        actions = dict((m, []) for m in 'a f g cd dc r dm dg m e k'.split())
        for f, (m, args, msg) in actionbyfile.iteritems():
            if m not in actions:
                actions[m] = []
            actions[m].append((f, args, msg))

        if not util.checkcase(repo.path):
            # check collision between files only in p2 for clean update
            if (not branchmerge
                    and (force or not wc.dirty(missing=True, branch=False))):
                _checkcollision(repo, p2.manifest(), None)
            else:
                _checkcollision(repo, wc.manifest(), actions)

        # Prompt and create actions. TODO: Move this towards resolve phase.
        for f, args, msg in sorted(actions['cd']):
            if repo.ui.promptchoice(
                    _("local changed %s which remote deleted\n"
                      "use (c)hanged version or (d)elete?"
                      "$$ &Changed $$ &Delete") % f, 0):
                actions['r'].append((f, None, "prompt delete"))
            else:
                actions['a'].append((f, None, "prompt keep"))
        del actions['cd'][:]

        for f, args, msg in sorted(actions['dc']):
            flags, = args
            if repo.ui.promptchoice(
                    _("remote changed %s which local deleted\n"
                      "use (c)hanged version or leave (d)eleted?"
                      "$$ &Changed $$ &Deleted") % f, 0) == 0:
                actions['g'].append((f, (flags, ), "prompt recreating"))
        del actions['dc'][:]

        ### apply phase
        if not branchmerge:  # just jump to the new rev
            fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
        if not partial:
            repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)
            # note that we're in the middle of an update
            repo.vfs.write('updatestate', p2.hex())

        stats = applyupdates(repo, actions, wc, p2, overwrite, labels=labels)

        # divergent renames
        for f, fl in sorted(diverge.iteritems()):
            repo.ui.warn(
                _("note: possible conflict - %s was renamed "
                  "multiple times to:\n") % f)
            for nf in fl:
                repo.ui.warn(" %s\n" % nf)

        # rename and delete
        for f, fl in sorted(renamedelete.iteritems()):
            repo.ui.warn(
                _("note: possible conflict - %s was deleted "
                  "and renamed to:\n") % f)
            for nf in fl:
                repo.ui.warn(" %s\n" % nf)

        if not partial:
            repo.dirstate.beginparentchange()
            repo.setparents(fp1, fp2)
            recordupdates(repo, actions, branchmerge)
            # update completed, clear state
            util.unlink(repo.join('updatestate'))

            if not branchmerge:
                repo.dirstate.setbranch(p2.branch())
            repo.dirstate.endparentchange()
    finally:
        wlock.release()

    if not partial:

        def updatehook(parent1=xp1, parent2=xp2, error=stats[3]):
            repo.hook('update', parent1=parent1, parent2=parent2, error=error)

        repo._afterlock(updatehook)
    return stats