def domergecmd(ui, repo, *revs, **opts):
    node = (list(revs) + opts.get('rev'))[0]
    originalCtx = repo[None].parents()[0]
    originalRev = originalCtx.rev()

    ui.write('Updating to revision %s \n' % node)
    hg.updaterepo(repo, node, True)
    defaultRev = repo['default'].rev()
    
    ui.write('Merging with default revision %s \n' % defaultRev)
    hg.merge(repo, defaultRev)

    #TODO: handle conflict case
    
    ui.write('Committing after merge... \n')
    commitMsg = getMergeDescription(repo[None].parents()[0].description())
    
    ui.write('   Commit message: %s \n' % commitMsg)
    repo.commit(commitMsg)

    if (originalRev != repo[None].parents()[0].parents()[0].rev()): # update to original rev in case branches are different
        ui.write('Updating to original revision %s \n' % originalRev)
        hg.update(repo, originalRev)

    return 0
Exemplo n.º 2
0
    def test_incremental_fetching_of_repository_with_non_conflict_merge(self):
        # Create Mercurial configuration and override possible definition
        # of external interactive merge tools.
        ui = hgui()
        ui.setconfig("ui", "merge", "internal:merge")

        # Create Mercurial repository and Bazaar branch to import into.
        hgrepo = mercurial.localrepo.localrepository(ui, "hg", create=True)
        hgbranch = Branch.open("hg")
        bzrtree = self.make_branch_and_tree("bzr")

        # Create history graph in Mercurial repository
        # (history flows from left to right):
        #
        # A--B--D
        # |
        # \--C
        self.build_tree_contents([("hg/f1", "f1")])
        hgrepo[None].add(["f1"])
        hgrepo.commit("A (initial commit; first commit to main branch)")
        self.build_tree_contents([("hg/f2", "f2")])
        hgrepo[None].add(["f2"])
        hgrepo.commit("B (second commit to main branch)")
        hg.update(hgrepo, 0)
        self.build_tree_contents([("hg/f3", "f3")])
        hgrepo[None].add(["f3"])
        hgrepo.commit("C (first commit to secondary branch)")
        hg.update(hgrepo, 1)
        self.build_tree_contents([("hg/f4", "f4")])
        hgrepo[None].add(["f4"])
        hgrepo.commit("D (third commit to main branch)")

        # Pull commited changesets to Bazaar branch.
        bzrtree.pull(hgbranch)

        # Continue history graph in Mercurial repository
        # (history flows from up to down):
        #
        # a--b--d--E
        # |       |
        # \--c--F-/
        hg.update(hgrepo, 2)
        self.build_tree_contents([("hg/f5", "f5")])
        hgrepo[None].add(["f5"])
        hgrepo.commit("F (second commit to secondary branch)")
        hg.update(hgrepo, 3)
        hg.merge(hgrepo, 4)
        hgrepo.commit("E (commit merge of main branch with secondary branch)")

        # Pull commited changesets to Bazaar branch.
        bzrtree.pull(hgbranch)

        # Self-assurance check that all changesets was really pulled in.
        for i in range(1, 6):
            file_content = "f%d" % i
            file_path = "bzr/%s" % file_content
            self.assertFileEqual(file_content, file_path)
Exemplo n.º 3
0
def harvest(ui, repo, branch, dest="default", **opts):
    """Close and merge a named branch into the destination branch"""
    if branch not in repo.branchtags():
        ui.warn("Branch %s does not exist! (use 'hg branches' to get a list of branches)\n" % branch)
        return

    if dest not in repo.branchtags():
        ui.warn("Destination branch %s does not exist! (use 'hg branches' to get a list of branches)\n" % branch)
        return

    heads = repo.branchheads(branch)
    if len(heads) == 0:
        ui.warn("Cannot harvest branch %s because it is currently closed. \nUse 'hg merge' to merge it manually.\n" % branch)
        return

    if len(heads) > 1:
        ui.warn("Branch %s has multiple heads. \nUse 'hg merge' to merge it manually.\n" % branch)
        return

    rev = repo.branchtip(branch)
    newrev = context.memctx(repo, [rev, None], "Closed branch %s" % branch, [], None, opts.get('user'), opts.get('date'), extra={'close':1, 'branch':branch})
    newrev.commit()

    #don't need to switch if already on destination branch
    curr = repo[None].branch()
    if dest != curr:
        hg.clean(repo, dest, False)
        ui.status("Switched to branch %s before merging\n" % dest)

    failed = hg.merge(repo, branch, remind = False)
    if not failed:
        repo.commit("Merged %s" % branch, opts.get('user'), opts.get('date'), None)
        ui.status("Completed merge of %s into %s\n" % (branch, dest))
Exemplo n.º 4
0
    def merge(self, initialrevision, working, other):
        self.ui.status(_('merging with %d:%s\n') %
                  (self.repo.changelog.rev(other), short(other)))

        if working != initialrevision: self.updateClean(working)

        if hg.merge(self.repo, other, remind=False):
            if not self.ui.promptchoice(_('Merge failed, do you want to revert [Y/n]: '), ['&Yes', '&No']):
                self.updateClean(initialrevision)
                raise util.Abort('merge failed and reverted, please merge remaining heads manually and sync again')
            else:
                raise util.Abort('merge failed, please resolve remaining merge conflicts manually, commit and sync again')
Exemplo n.º 5
0
def setup():
    global _tmpdir
    _tmpdir = helpers.mktmpdir(__name__)

    # foo0 -- foo1 ---------- foo3 -------------------------- foo7
    #   \       \
    #    \       -------------------- baz4 -- baz5 -- baz6 --------
    #     \                                        /               \
    #      ---------- bar2 ------------------------------------------ bar8
    #       [branch: bar]
    hg = helpers.HgClient(os.path.join(_tmpdir, 'named-branch'))
    hg.init()
    hg.fappend('data', 'foo0')
    hg.commit('-Am', 'foo0')
    hg.fappend('data', 'foo1\n')
    hg.commit('-m', 'foo1')
    hg.update('0')
    hg.branch('bar')
    hg.fappend('data', 'bar2\n')
    hg.commit('-m', 'bar2')
    hg.update('1')
    hg.fappend('data', 'foo3\n')
    hg.commit('-m', 'foo3')
    hg.update('1')
    hg.fappend('data', 'baz4\n')
    hg.commit('-m', 'baz4')
    hg.fappend('data', 'baz5\n')
    hg.commit('-m', 'baz5')
    hg.merge('--tool=internal:local', '2')
    hg.commit('-m', 'baz6')
    hg.update('3')
    hg.fappend('data', 'foo7\n')
    hg.commit('-m', 'foo7')
    hg.update('2')
    hg.merge('--tool=internal:local', '6')
    hg.commit('-m', 'bar8')
Exemplo n.º 6
0
def setup():
    global _tmpdir
    _tmpdir = helpers.mktmpdir(__name__)

    # foo0 -- foo1 ---------- foo3 -------------------------- foo7
    #   \       \
    #    \       -------------------- baz4 -- baz5 -- baz6 --------
    #     \                                        /               \
    #      ---------- bar2 ------------------------------------------ bar8
    #       [branch: bar]
    hg = helpers.HgClient(os.path.join(_tmpdir, 'named-branch'))
    hg.init()
    hg.fappend('data', 'foo0')
    hg.commit('-Am', 'foo0')
    hg.fappend('data', 'foo1\n')
    hg.commit('-m', 'foo1')
    hg.update('0')
    hg.branch('bar')
    hg.fappend('data', 'bar2\n')
    hg.commit('-m', 'bar2')
    hg.update('1')
    hg.fappend('data', 'foo3\n')
    hg.commit('-m', 'foo3')
    hg.update('1')
    hg.fappend('data', 'baz4\n')
    hg.commit('-m', 'baz4')
    hg.fappend('data', 'baz5\n')
    hg.commit('-m', 'baz5')
    hg.merge('--tool=internal:local', '2')
    hg.commit('-m', 'baz6')
    hg.update('3')
    hg.fappend('data', 'foo7\n')
    hg.commit('-m', 'foo7')
    hg.update('2')
    hg.merge('--tool=internal:local', '6')
    hg.commit('-m', 'bar8')
Exemplo n.º 7
0
 def postincoming(other, modheads):
     if modheads == 0:
         return 0
     if modheads == 1:
         return hg.clean(repo, repo.changelog.tip())
     newheads = repo.heads(parent)
     newchildren = [n for n in repo.heads(parent) if n != parent]
     newparent = parent
     if newchildren:
         newparent = newchildren[0]
         hg.clean(repo, newparent)
     newheads = [n for n in repo.heads() if n != newparent]
     if len(newheads) > 1:
         ui.status(_('not merging with %d other new heads '
                     '(use "hg heads" and "hg merge" to merge them)') %
                   (len(newheads) - 1))
         return
     err = False
     if newheads:
         # By default, we consider the repository we're pulling
         # *from* as authoritative, so we merge our changes into
         # theirs.
         if opts['switch_parent']:
             firstparent, secondparent = newparent, newheads[0]
         else:
             firstparent, secondparent = newheads[0], newparent
             ui.status(_('updating to %d:%s\n') %
                       (repo.changelog.rev(firstparent),
                        short(firstparent)))
         hg.clean(repo, firstparent)
         ui.status(_('merging with %d:%s\n') %
                   (repo.changelog.rev(secondparent), short(secondparent)))
         err = hg.merge(repo, secondparent, remind=False)
     if not err:
         mod, add, rem = repo.status()[:3]
         message = (cmdutil.logmessage(opts) or
                    (_('Automated merge with %s') %
                     util.removeauth(other.url())))
         force_editor = opts.get('force_editor') or opts.get('edit')
         n = repo.commit(mod + add + rem, message,
                         opts['user'], opts['date'], force=True,
                         force_editor=force_editor)
         ui.status(_('new changeset %d:%s merges remote changes '
                     'with local\n') % (repo.changelog.rev(n),
                                        short(n)))
Exemplo n.º 8
0
def doMerge(ui, repo, branch):
  """ Merge from the given branch into the working directory. """

  # Try the merge. Don't hide the output as merge sometimes needs to ask the user questions.
  if tryCommand(ui, "merge %s" % quoteBranch(branch), lambda:hg.merge(repo, revsymbol(repo, branch)), showOutput = True):
    res = ui.prompt("Merge failed! Do you want to fix it manually? (if not, will return to clean state):", default="y")
    if res.lower() != "y" and res.lower() != "yes":
      ui.status("Getting back to clean state...\n")
      tryCommand(ui, "update --clean", lambda:hg.clean(repo, repo.dirstate.branch()))
    else:
      ui.status("Ok, leaving directory in partly merged state. To finish:\n")
      ui.status("  $ hg resolve --list        # list conflicting files\n")
      ui.status("  ...fix fix fix...\n")
      ui.status("  $ hg resolve --mark --all  # shortcut: resolve -am\n")
      ui.status("  $ hg commit\n")
      ui.status("Or, to abandon the merge:\n")
      ui.status("  $ hg update --clean\n")
    return 1

  return 0
Exemplo n.º 9
0
    def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
        # first try just applying the patch
        (err, n) = self.apply(repo, [patch], update_status=False,
                              strict=True, merge=rev)

        if err == 0:
            return (err, n)

        if n is None:
            raise util.Abort(_("apply failed for patch %s") % patch)

        self.ui.warn(_("patch didn't work out, merging %s\n") % patch)

        # apply failed, strip away that rev and merge.
        hg.clean(repo, head)
        self.strip(repo, [n], update=False, backup='strip')

        ctx = repo[rev]
        ret = hg.merge(repo, rev)
        if ret:
            raise util.Abort(_("update returned %d") % ret)
        n = newcommit(repo, None, ctx.description(), ctx.user(), force=True)
        if n is None:
            raise util.Abort(_("repo commit failed"))
        try:
            ph = patchheader(mergeq.join(patch), self.plainmode)
        except Exception:
            raise util.Abort(_("unable to read %s") % patch)

        diffopts = self.patchopts(diffopts, patch)
        patchf = self.opener(patch, "w")
        comments = str(ph)
        if comments:
            patchf.write(comments)
        self.printdiff(repo, diffopts, head, n, fp=patchf)
        patchf.close()
        self.removeundo(repo)
        return (0, n)
Exemplo n.º 10
0
def fetch(ui, repo, source=b'default', **opts):
    """pull changes from a remote repository, merge new changes if needed.

    This finds all changes from the repository at the specified path
    or URL and adds them to the local repository.

    If the pulled changes add a new branch head, the head is
    automatically merged, and the result of the merge is committed.
    Otherwise, the working directory is updated to include the new
    changes.

    When a merge is needed, the working directory is first updated to
    the newly pulled changes. Local changes are then merged into the
    pulled changes. To switch the merge order, use --switch-parent.

    See :hg:`help dates` for a list of formats valid for -d/--date.

    Returns 0 on success.
    """

    opts = pycompat.byteskwargs(opts)
    date = opts.get(b'date')
    if date:
        opts[b'date'] = dateutil.parsedate(date)

    parent = repo.dirstate.p1()
    branch = repo.dirstate.branch()
    try:
        branchnode = repo.branchtip(branch)
    except error.RepoLookupError:
        branchnode = None
    if parent != branchnode:
        raise error.Abort(
            _(b'working directory not at branch tip'),
            hint=_(b"use 'hg update' to check out branch tip"),
        )

    wlock = lock = None
    try:
        wlock = repo.wlock()
        lock = repo.lock()

        cmdutil.bailifchanged(repo)

        bheads = repo.branchheads(branch)
        bheads = [head for head in bheads if len(repo[head].children()) == 0]
        if len(bheads) > 1:
            raise error.Abort(
                _(b'multiple heads in this branch '
                  b'(use "hg heads ." and "hg merge" to merge)'))

        other = hg.peer(repo, opts, ui.expandpath(source))
        ui.status(
            _(b'pulling from %s\n') % util.hidepassword(ui.expandpath(source)))
        revs = None
        if opts[b'rev']:
            try:
                revs = [other.lookup(rev) for rev in opts[b'rev']]
            except error.CapabilityError:
                err = _(b"other repository doesn't support revision lookup, "
                        b"so a rev cannot be specified.")
                raise error.Abort(err)

        # Are there any changes at all?
        modheads = exchange.pull(repo, other, heads=revs).cgresult
        if modheads == 0:
            return 0

        # Is this a simple fast-forward along the current branch?
        newheads = repo.branchheads(branch)
        newchildren = repo.changelog.nodesbetween([parent], newheads)[2]
        if len(newheads) == 1 and len(newchildren):
            if newchildren[0] != parent:
                return hg.update(repo, newchildren[0])
            else:
                return 0

        # Are there more than one additional branch heads?
        newchildren = [n for n in newchildren if n != parent]
        newparent = parent
        if newchildren:
            newparent = newchildren[0]
            hg.clean(repo, newparent)
        newheads = [n for n in newheads if n != newparent]
        if len(newheads) > 1:
            ui.status(
                _(b'not merging with %d other new branch heads '
                  b'(use "hg heads ." and "hg merge" to merge them)\n') %
                (len(newheads) - 1))
            return 1

        if not newheads:
            return 0

        # Otherwise, let's merge.
        err = False
        if newheads:
            # By default, we consider the repository we're pulling
            # *from* as authoritative, so we merge our changes into
            # theirs.
            if opts[b'switch_parent']:
                firstparent, secondparent = newparent, newheads[0]
            else:
                firstparent, secondparent = newheads[0], newparent
                ui.status(
                    _(b'updating to %d:%s\n') %
                    (repo.changelog.rev(firstparent), short(firstparent)))
            hg.clean(repo, firstparent)
            p2ctx = repo[secondparent]
            ui.status(
                _(b'merging with %d:%s\n') %
                (p2ctx.rev(), short(secondparent)))
            err = hg.merge(p2ctx, remind=False)

        if not err:
            # we don't translate commit messages
            message = cmdutil.logmessage(
                ui, opts) or (b'Automated merge with %s' %
                              util.removeauth(other.url()))
            editopt = opts.get(b'edit') or opts.get(b'force_editor')
            editor = cmdutil.getcommiteditor(edit=editopt, editform=b'fetch')
            n = repo.commit(message,
                            opts[b'user'],
                            opts[b'date'],
                            editor=editor)
            ui.status(
                _(b'new changeset %d:%s merges remote changes with local\n') %
                (repo.changelog.rev(n), short(n)))

        return err

    finally:
        release(lock, wlock)
Exemplo n.º 11
0
def fetch(ui, repo, source='default', **opts):
    '''pull changes from a remote repository, merge new changes if needed.

    This finds all changes from the repository at the specified path
    or URL and adds them to the local repository.

    If the pulled changes add a new branch head, the head is
    automatically merged, and the result of the merge is committed.
    Otherwise, the working directory is updated to include the new
    changes.

    When a merge occurs, the newly pulled changes are assumed to be
    "authoritative". The head of the new changes is used as the first
    parent, with local changes as the second. To switch the merge
    order, use --switch-parent.

    See 'hg help dates' for a list of formats valid for -d/--date.
    '''

    date = opts.get('date')
    if date:
        opts['date'] = util.parsedate(date)

    parent, p2 = repo.dirstate.parents()
    branch = repo.dirstate.branch()
    branchnode = repo.branchtags().get(branch)
    if parent != branchnode:
        raise util.Abort(_('working dir not at branch tip '
                           '(use "hg update" to check out branch tip)'))

    if p2 != nullid:
        raise util.Abort(_('outstanding uncommitted merge'))

    wlock = lock = None
    try:
        wlock = repo.wlock()
        lock = repo.lock()
        mod, add, rem, del_ = repo.status()[:4]

        if mod or add or rem:
            raise util.Abort(_('outstanding uncommitted changes'))
        if del_:
            raise util.Abort(_('working directory is missing some files'))
        bheads = repo.branchheads(branch)
        bheads = [head for head in bheads if len(repo[head].children()) == 0]
        if len(bheads) > 1:
            raise util.Abort(_('multiple heads in this branch '
                               '(use "hg heads ." and "hg merge" to merge)'))

        other = hg.repository(cmdutil.remoteui(repo, opts),
                              ui.expandpath(source))
        ui.status(_('pulling from %s\n') %
                  url.hidepassword(ui.expandpath(source)))
        revs = None
        if opts['rev']:
            try:
                revs = [other.lookup(rev) for rev in opts['rev']]
            except error.CapabilityError:
                err = _("Other repository doesn't support revision lookup, "
                        "so a rev cannot be specified.")
                raise util.Abort(err)

        # Are there any changes at all?
        modheads = repo.pull(other, heads=revs)
        if modheads == 0:
            return 0

        # Is this a simple fast-forward along the current branch?
        newheads = repo.branchheads(branch)
        newheads = [head for head in newheads if len(repo[head].children()) == 0]
        newchildren = repo.changelog.nodesbetween([parent], newheads)[2]
        if len(newheads) == 1:
            if newchildren[0] != parent:
                return hg.clean(repo, newchildren[0])
            else:
                return

        # Are there more than one additional branch heads?
        newchildren = [n for n in newchildren if n != parent]
        newparent = parent
        if newchildren:
            newparent = newchildren[0]
            hg.clean(repo, newparent)
        newheads = [n for n in newheads if n != newparent]
        if len(newheads) > 1:
            ui.status(_('not merging with %d other new branch heads '
                        '(use "hg heads ." and "hg merge" to merge them)\n') %
                      (len(newheads) - 1))
            return

        # Otherwise, let's merge.
        err = False
        if newheads:
            # By default, we consider the repository we're pulling
            # *from* as authoritative, so we merge our changes into
            # theirs.
            if opts['switch_parent']:
                firstparent, secondparent = newparent, newheads[0]
            else:
                firstparent, secondparent = newheads[0], newparent
                ui.status(_('updating to %d:%s\n') %
                          (repo.changelog.rev(firstparent),
                           short(firstparent)))
            hg.clean(repo, firstparent)
            ui.status(_('merging with %d:%s\n') %
                      (repo.changelog.rev(secondparent), short(secondparent)))
            err = hg.merge(repo, secondparent, remind=False)

        if not err:
            # we don't translate commit messages
            message = (cmdutil.logmessage(opts) or
                       ('Automated merge with %s' %
                        url.removeauth(other.url())))
            editor = cmdutil.commiteditor
            if opts.get('force_editor') or opts.get('edit'):
                editor = cmdutil.commitforceeditor
            n = repo.commit(message, opts['user'], opts['date'], editor=editor)
            ui.status(_('new changeset %d:%s merges remote changes '
                        'with local\n') % (repo.changelog.rev(n),
                                           short(n)))

    finally:
        release(lock, wlock)
Exemplo n.º 12
0
    def _applymerge(self,
                    repo,
                    patchfile,
                    sim,
                    name,
                    parent,
                    force=False,
                    **opts):
        """applies a patch using fancy merge technology."""
        reverse = opts.get('reverse')
        opts['reverse'] = False

        def smwrapper(orig, *args, **opts):
            shelf = 'shelf:%s' % name
            if reverse:
                shelf += ' --reverse'
            opts['label'] = ['local', shelf]
            return orig(*args, **opts)

        def savediff():
            opts = {'git': True}
            fp = opener('.saved', 'w')
            for chunk in patch.diff(repo,
                                    head,
                                    None,
                                    opts=patch.diffopts(self.ui, opts)):
                fp.write(chunk)
            fp.close()

        def applydiff(name):
            files = {}
            patch.patch(self.join(patchfile), self.ui, strip=1, files=files)
            files2 = {}
            for k in files.keys():
                files2[k.strip('\r')] = files[k]
            updatedir(self.ui, repo, files2, similarity=sim / 100.)

        opener = util.opener('.hg/attic')
        smo = extensions.wrapfunction(simplemerge, 'simplemerge', smwrapper)
        quiet = self.ui.quiet
        self.ui.quiet = True
        whead, phead = None, None
        success = False
        try:
            head = repo.dirstate.parents()[0]
            # Save the open changes
            self.ui.note(_("saving open changes\n"))
            n = repo.commit('working', 'hgattic', None, force=1)
            savediff()
            whead = repo.heads(None)[0]
            # Set the workspace to match the base version for patching
            self.ui.note(_("applying diff to version specified in patch\n"))
            hg.clean(repo, parent)
            applydiff(self.join(patchfile))
            n = repo.commit('patched', 'hgattic', None, force=1)
            phead = repo.heads(None)[0]
            if reverse:
                # Merge, using the working copy to avoid conflicts
                self.ui.note(_("applying reverse\n"))
                hgmerge = os.environ.get('HGMERGE')
                os.environ['HGMERGE'] = 'internal:other'
                hg.merge(repo, whead, force=True)
                os.environ['HGMERGE'] = hgmerge
                # Backout the patched version, this is where we want conflicts
                repo.commit('merge', 'hgattic', None, force=1)
                backout_opts = {
                    'rev': phead,
                    'merge': True,
                    'message': 'backout'
                }
                commands.backout(self.ui, repo, **backout_opts)
            else:
                # Merge the working copy with the patched copy
                self.ui.note(_("merging patch forward\n"))
                hg.merge(repo, whead, force=True)
            savediff()
            success = True
        finally:
            simplemerge.simplemerge = smo
            self.ui.note(_("cleanup\n"))
            hg.clean(repo, head)
            strip_opts = {'backup': False, 'nobackup': True, 'force': False}
            if phead and head != phead:
                self.strip(repo, phead)
            if whead and head != whead:
                self.strip(repo, whead)
            if not success:
                applydiff('.saved')
            self.ui.quiet = quiet
        if success:
            self.ui.note(_("applying updated patch\n"))
            success = self._applypatch(repo, '.saved', sim, force, **opts)
        return success
Exemplo n.º 13
0
def fetch(ui, repo, source="default", **opts):
    """pull changes from a remote repository, merge new changes if needed.

    This finds all changes from the repository at the specified path
    or URL and adds them to the local repository.

    If the pulled changes add a new branch head, the head is
    automatically merged, and the result of the merge is committed.
    Otherwise, the working directory is updated to include the new
    changes.

    When a merge is needed, the working directory is first updated to
    the newly pulled changes. Local changes are then merged into the
    pulled changes. To switch the merge order, use --switch-parent.

    See :hg:`help dates` for a list of formats valid for -d/--date.

    Returns 0 on success.
    """

    date = opts.get("date")
    if date:
        opts["date"] = util.parsedate(date)

    parent, p2 = repo.dirstate.parents()
    branch = repo.dirstate.branch()
    try:
        branchnode = repo.branchtip(branch)
    except error.RepoLookupError:
        branchnode = None
    if parent != branchnode:
        raise util.Abort(_("working dir not at branch tip " '(use "hg update" to check out branch tip)'))

    if p2 != nullid:
        raise util.Abort(_("outstanding uncommitted merge"))

    wlock = lock = None
    try:
        wlock = repo.wlock()
        lock = repo.lock()
        mod, add, rem, del_ = repo.status()[:4]

        if mod or add or rem:
            raise util.Abort(_("outstanding uncommitted changes"))
        if del_:
            raise util.Abort(_("working directory is missing some files"))
        bheads = repo.branchheads(branch)
        bheads = [head for head in bheads if len(repo[head].children()) == 0]
        if len(bheads) > 1:
            raise util.Abort(_("multiple heads in this branch " '(use "hg heads ." and "hg merge" to merge)'))

        other = hg.peer(repo, opts, ui.expandpath(source))
        ui.status(_("pulling from %s\n") % util.hidepassword(ui.expandpath(source)))
        revs = None
        if opts["rev"]:
            try:
                revs = [other.lookup(rev) for rev in opts["rev"]]
            except error.CapabilityError:
                err = _("other repository doesn't support revision lookup, " "so a rev cannot be specified.")
                raise util.Abort(err)

        # Are there any changes at all?
        modheads = repo.pull(other, heads=revs)
        if modheads == 0:
            return 0

        # Is this a simple fast-forward along the current branch?
        newheads = repo.branchheads(branch)
        newchildren = repo.changelog.nodesbetween([parent], newheads)[2]
        if len(newheads) == 1 and len(newchildren):
            if newchildren[0] != parent:
                return hg.update(repo, newchildren[0])
            else:
                return 0

        # Are there more than one additional branch heads?
        newchildren = [n for n in newchildren if n != parent]
        newparent = parent
        if newchildren:
            newparent = newchildren[0]
            hg.clean(repo, newparent)
        newheads = [n for n in newheads if n != newparent]
        if len(newheads) > 1:
            ui.status(
                _("not merging with %d other new branch heads " '(use "hg heads ." and "hg merge" to merge them)\n')
                % (len(newheads) - 1)
            )
            return 1

        if not newheads:
            return 0

        # Otherwise, let's merge.
        err = False
        if newheads:
            # By default, we consider the repository we're pulling
            # *from* as authoritative, so we merge our changes into
            # theirs.
            if opts["switch_parent"]:
                firstparent, secondparent = newparent, newheads[0]
            else:
                firstparent, secondparent = newheads[0], newparent
                ui.status(_("updating to %d:%s\n") % (repo.changelog.rev(firstparent), short(firstparent)))
            hg.clean(repo, firstparent)
            ui.status(_("merging with %d:%s\n") % (repo.changelog.rev(secondparent), short(secondparent)))
            err = hg.merge(repo, secondparent, remind=False)

        if not err:
            # we don't translate commit messages
            message = cmdutil.logmessage(ui, opts) or ("Automated merge with %s" % util.removeauth(other.url()))
            editor = cmdutil.commiteditor
            if opts.get("force_editor") or opts.get("edit"):
                editor = cmdutil.commitforceeditor
            n = repo.commit(message, opts["user"], opts["date"], editor=editor)
            ui.status(
                _("new changeset %d:%s merges remote changes " "with local\n") % (repo.changelog.rev(n), short(n))
            )

        return err

    finally:
        release(lock, wlock)
Exemplo n.º 14
0
    def _applymerge(self, repo, patchfile, sim, name, parent, force=False, **opts):
        """applies a patch using fancy merge technology."""
        reverse = opts.get('reverse')
        opts['reverse'] = False

        def smwrapper(orig, *args, **opts):
            shelf = 'shelf:%s' % name
            if reverse:
                shelf += ' --reverse'
            opts['label'] = ['local', shelf]
            return orig(*args, **opts)

        def savediff():
            opts = {'git': True}
            fp = opener('.saved', 'w')
            for chunk in patch.diff(repo, head, None,
                                     opts=patch.diffopts(self.ui, opts)):
                fp.write(chunk)
            fp.close()

        def applydiff(name):
            files = {}
            patch.patch(self.join(patchfile), self.ui, strip=1, files=files)
            files2 = {}
            for k in files.keys():
                files2[k.strip('\r')]=files[k]
            updatedir(self.ui, repo, files2, similarity=sim/100.)
        opener = util.opener('.hg/attic')
        smo = extensions.wrapfunction(simplemerge, 'simplemerge', smwrapper)
        quiet = self.ui.quiet
        self.ui.quiet = True
        whead, phead = None, None
        success = False
        try:
            head = repo.dirstate.parents()[0]
            # Save the open changes
            self.ui.note(_("saving open changes\n"))
            n = repo.commit('working', 'hgattic', None, force=1)
            savediff()
            whead = repo.heads(None)[0]
            # Set the workspace to match the base version for patching
            self.ui.note(_("applying diff to version specified in patch\n"))
            hg.clean(repo, parent)
            applydiff(self.join(patchfile))
            n = repo.commit('patched', 'hgattic', None, force=1)
            phead = repo.heads(None)[0]
            if reverse:
                # Merge, using the working copy to avoid conflicts
                self.ui.note(_("applying reverse\n"))
                hgmerge = os.environ.get('HGMERGE')
                os.environ['HGMERGE'] = 'internal:other'
                hg.merge(repo, whead, force=True)
                os.environ['HGMERGE'] = hgmerge
                # Backout the patched version, this is where we want conflicts
                repo.commit('merge', 'hgattic', None, force=1)
                backout_opts = {'rev': phead, 'merge': True,
                                'message': 'backout'}
                commands.backout(self.ui, repo, **backout_opts)
            else:
                # Merge the working copy with the patched copy
                self.ui.note(_("merging patch forward\n"))
                hg.merge(repo, whead, force=True)
            savediff()
            success = True
        finally:
            simplemerge.simplemerge = smo
            self.ui.note(_("cleanup\n"))
            hg.clean(repo, head)
            strip_opts = {'backup': False, 'nobackup': True, 'force': False}
            if phead and head != phead:
                self.strip(repo, phead)
            if whead and head != whead:
                self.strip(repo, whead)
            if not success:
                applydiff('.saved')
            self.ui.quiet = quiet
        if success:
            self.ui.note(_("applying updated patch\n"))
            success = self._applypatch(repo, '.saved', sim, force, **opts)
        return success
Exemplo n.º 15
0
            gen = changegroup.readbundle(fp, fp.name)
            repo.addchangegroup(gen, 'unshelve', 'bundle:' + fp.name)
            nodes = [ctx.node() for ctx in repo.set('%d:', oldtiprev)]
            phases.retractboundary(repo, phases.secret, nodes)
            tr.close()
        finally:
            fp.close()

        tip = repo['tip']
        wctx = repo['.']
        ancestor = tip.ancestor(wctx)

        wlock = repo.wlock()

        if ancestor.node() != wctx.node():
            conflicts = hg.merge(repo, tip.node(), force=True, remind=False)
            ms = merge.mergestate(repo)
            stripnodes = [repo.changelog.node(rev)
                          for rev in xrange(oldtiprev, len(repo))]
            if conflicts:
                shelvedstate.save(repo, basename, stripnodes)
                # Fix up the dirstate entries of files from the second
                # parent as if we were not merging, except for those
                # with unresolved conflicts.
                parents = repo.parents()
                revertfiles = set(parents[1].files()).difference(ms)
                cmdutil.revert(ui, repo, parents[1],
                               (parents[0].node(), nullid),
                               *revertfiles, **{'no_backup': True})
                raise error.InterventionRequired(
                    _("unresolved conflicts (see 'hg resolve', then "