diff options
author | Christian Halstrick <christian.halstrick@sap.com> | 2010-10-08 15:39:04 +0200 |
---|---|---|
committer | Christian Halstrick <christian.halstrick@sap.com> | 2010-10-15 16:38:34 +0200 |
commit | 9b4876cedf430e454b99da5410e2a9d624f35129 (patch) | |
tree | 4e2e5b4d42c83019c35a40942daa9b1bb07f8c9f | |
parent | 4c7e100910cb1b40fc3aed0a21abe0806645c02a (diff) | |
download | jgit-9b4876cedf430e454b99da5410e2a9d624f35129.tar.gz jgit-9b4876cedf430e454b99da5410e2a9d624f35129.zip |
Add Cherry-Pick command
Implemented the initial version of a cherry-pick command.
A correct error handling is missing (what happens if the
checkout fails, the cherry-pick leads to conflicts etc).
But straightforward cherry-picks works.
Change-Id: I235c0eb3a7a2d5bdfe40400f1deed06f29d746e1
Signed-off-by: Christian Halstrick <christian.halstrick@sap.com>
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
6 files changed, 403 insertions, 0 deletions
diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CherryPickCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CherryPickCommandTest.java new file mode 100644 index 0000000000..935412e7a6 --- /dev/null +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CherryPickCommandTest.java @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com> + * and other copyright owners as documented in the project's IP log. + * + * This program and the accompanying materials are made available + * under the terms of the Eclipse Distribution License v1.0 which + * accompanies this distribution, is reproduced below, and is + * available at http://www.eclipse.org/org/documents/edl-v10.php + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or + * without modification, are permitted provided that the following + * conditions are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * + * - Neither the name of the Eclipse Foundation, Inc. nor the + * names of its contributors may be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.eclipse.jgit.api; + +import java.io.File; +import java.io.IOException; +import java.util.Iterator; + +import org.eclipse.jgit.api.errors.*; +import org.eclipse.jgit.dircache.DirCacheCheckout; +import org.eclipse.jgit.lib.Constants; +import org.eclipse.jgit.lib.RefUpdate; +import org.eclipse.jgit.lib.RepositoryTestCase; +import org.eclipse.jgit.revwalk.RevCommit; +import org.eclipse.jgit.revwalk.RevWalk; + +/** + * Test cherry-pick command + */ +public class CherryPickCommandTest extends RepositoryTestCase { + public void testCherryPick() throws IOException, JGitInternalException, + GitAPIException { + Git git = new Git(db); + + writeTrashFile("a", "first line\nsec. line\nthird line\n"); + git.add().addFilepattern("a").call(); + RevCommit firstCommit = git.commit().setMessage("create a").call(); + + writeTrashFile("b", "content\n"); + git.add().addFilepattern("b").call(); + git.commit().setMessage("create b").call(); + + writeTrashFile("a", "first line\nsec. line\nthird line\nfourth line\n"); + git.add().addFilepattern("a").call(); + git.commit().setMessage("enlarged a").call(); + + writeTrashFile("a", + "first line\nsecond line\nthird line\nfourth line\n"); + git.add().addFilepattern("a").call(); + RevCommit fixingA = git.commit().setMessage("fixed a").call(); + + git.branchCreate().setName("side").setStartPoint(firstCommit).call(); + checkoutBranch("refs/heads/side"); + + writeTrashFile("a", "first line\nsec. line\nthird line\nfeature++\n"); + git.add().addFilepattern("a").call(); + git.commit().setMessage("enhanced a").call(); + + git.cherryPick().include(fixingA).call(); + + assertFalse(new File(db.getWorkTree(), "b").exists()); + checkFile(new File(db.getWorkTree(), "a"), + "first line\nsecond line\nthird line\nfeature++\n"); + Iterator<RevCommit> history = git.log().call().iterator(); + assertEquals("fixed a", history.next().getFullMessage()); + assertEquals("enhanced a", history.next().getFullMessage()); + assertEquals("create a", history.next().getFullMessage()); + assertFalse(history.hasNext()); + } + + private void checkoutBranch(String branchName) + throws IllegalStateException, IOException { + RevWalk walk = new RevWalk(db); + RevCommit head = walk.parseCommit(db.resolve(Constants.HEAD)); + RevCommit branch = walk.parseCommit(db.resolve(branchName)); + DirCacheCheckout dco = new DirCacheCheckout(db, head.getTree().getId(), + db.lockDirCache(), branch.getTree().getId()); + dco.setFailOnConflict(true); + dco.checkout(); + walk.release(); + // update the HEAD + RefUpdate refUpdate = db.updateRef(Constants.HEAD); + refUpdate.link(branchName); + } + +} diff --git a/org.eclipse.jgit/resources/org/eclipse/jgit/JGitText.properties b/org.eclipse.jgit/resources/org/eclipse/jgit/JGitText.properties index 3cc144a75e..409b43492a 100644 --- a/org.eclipse.jgit/resources/org/eclipse/jgit/JGitText.properties +++ b/org.eclipse.jgit/resources/org/eclipse/jgit/JGitText.properties @@ -70,6 +70,7 @@ cannotResolveLocalTrackingRefForUpdating=Cannot resolve local tracking ref {0} f cannotStoreObjects=cannot store objects cannotUnloadAModifiedTree=Cannot unload a modified tree. cannotWorkWithOtherStagesThanZeroRightNow=Cannot work with other stages than zero right now. Won't write corrupt index. +canOnlyCherryPickCommitsWithOneParent=Can only cherry-pick commits which have exactly one parent cantFindObjectInReversePackIndexForTheSpecifiedOffset=Can't find object in (reverse) pack index for the specified offset {0} cantPassMeATree=Can't pass me a tree! channelMustBeInRange0_255=channel {0} must be in range [0, 255] @@ -156,6 +157,7 @@ errorListing=Error listing {0} errorOccurredDuringUnpackingOnTheRemoteEnd=error occurred during unpacking on the remote end: {0} errorReadingInfoRefs=error reading info/refs exceptionCaughtDuringExecutionOfAddCommand=Exception caught during execution of add command +exceptionCaughtDuringExecutionOfCherryPickCommand=Exception caught during execution of cherry-pick command. {0} exceptionCaughtDuringExecutionOfCommitCommand=Exception caught during execution of commit command exceptionCaughtDuringExecutionOfFetchCommand=Exception caught during execution of fetch command exceptionCaughtDuringExecutionOfMergeCommand=Exception caught during execution of merge command. {0} diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/JGitText.java b/org.eclipse.jgit/src/org/eclipse/jgit/JGitText.java index 93b9700395..d6c6018006 100644 --- a/org.eclipse.jgit/src/org/eclipse/jgit/JGitText.java +++ b/org.eclipse.jgit/src/org/eclipse/jgit/JGitText.java @@ -130,6 +130,7 @@ public class JGitText extends TranslationBundle { /***/ public String cannotStoreObjects; /***/ public String cannotUnloadAModifiedTree; /***/ public String cannotWorkWithOtherStagesThanZeroRightNow; + /***/ public String canOnlyCherryPickCommitsWithOneParent; /***/ public String cantFindObjectInReversePackIndexForTheSpecifiedOffset; /***/ public String cantPassMeATree; /***/ public String channelMustBeInRange0_255; @@ -216,6 +217,7 @@ public class JGitText extends TranslationBundle { /***/ public String errorOccurredDuringUnpackingOnTheRemoteEnd; /***/ public String errorReadingInfoRefs; /***/ public String exceptionCaughtDuringExecutionOfAddCommand; + /***/ public String exceptionCaughtDuringExecutionOfCherryPickCommand; /***/ public String exceptionCaughtDuringExecutionOfCommitCommand; /***/ public String exceptionCaughtDuringExecutionOfFetchCommand; /***/ public String exceptionCaughtDuringExecutionOfMergeCommand; diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/api/CherryPickCommand.java b/org.eclipse.jgit/src/org/eclipse/jgit/api/CherryPickCommand.java new file mode 100644 index 0000000000..2a57b11ac9 --- /dev/null +++ b/org.eclipse.jgit/src/org/eclipse/jgit/api/CherryPickCommand.java @@ -0,0 +1,205 @@ +/* + * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com> + * and other copyright owners as documented in the project's IP log. + * + * This program and the accompanying materials are made available + * under the terms of the Eclipse Distribution License v1.0 which + * accompanies this distribution, is reproduced below, and is + * available at http://www.eclipse.org/org/documents/edl-v10.php + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or + * without modification, are permitted provided that the following + * conditions are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * + * - Neither the name of the Eclipse Foundation, Inc. nor the + * names of its contributors may be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.eclipse.jgit.api; + +import java.io.IOException; +import java.text.MessageFormat; +import java.util.LinkedList; +import java.util.List; + +import org.eclipse.jgit.JGitText; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.api.errors.MultipleParentsNotAllowedException; +import org.eclipse.jgit.api.errors.JGitInternalException; +import org.eclipse.jgit.api.errors.NoHeadException; +import org.eclipse.jgit.dircache.DirCacheCheckout; +import org.eclipse.jgit.lib.AnyObjectId; +import org.eclipse.jgit.lib.Constants; +import org.eclipse.jgit.lib.ObjectId; +import org.eclipse.jgit.lib.ObjectIdRef; +import org.eclipse.jgit.lib.Ref; +import org.eclipse.jgit.lib.Ref.Storage; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.merge.MergeStrategy; +import org.eclipse.jgit.merge.ResolveMerger; +import org.eclipse.jgit.revwalk.RevCommit; +import org.eclipse.jgit.revwalk.RevWalk; +import org.eclipse.jgit.treewalk.FileTreeIterator; + +/** + * A class used to execute a {@code cherry-pick} command. It has setters for all + * supported options and arguments of this command and a {@link #call()} method + * to finally execute the command. Each instance of this class should only be + * used for one invocation of the command (means: one call to {@link #call()}) + * + * @see <a + * href="http://www.kernel.org/pub/software/scm/git/docs/git-cherry-pick.html" + * >Git documentation about cherry-pick</a> + */ +public class CherryPickCommand extends GitCommand<RevCommit> { + private List<Ref> commits = new LinkedList<Ref>(); + + private List<Ref> cherryPickedRefs = new LinkedList<Ref>(); + + /** + * @param repo + */ + protected CherryPickCommand(Repository repo) { + super(repo); + } + + /** + * Executes the {@code Cherry-Pick} command with all the options and + * parameters collected by the setter methods (e.g. {@link #include(Ref)} of + * this class. Each instance of this class should only be used for one + * invocation of the command. Don't call this method twice on an instance. + * + * @return on success the {@link RevCommit} pointed to by the new HEAD is + * returned. If a failure occurred during cherry-pick + * <code>null</code> is returned. The list of successfully + * cherry-picked {@link Ref}'s can be obtained by calling + * {@link #getCherryPickedRefs()} + */ + public RevCommit call() throws GitAPIException { + RevCommit newHead = null; + checkCallable(); + + RevWalk revWalk = new RevWalk(repo); + try { + + // get the head commit + Ref headRef = repo.getRef(Constants.HEAD); + if (headRef == null) + throw new NoHeadException( + JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported); + RevCommit headCommit = revWalk.parseCommit(headRef.getObjectId()); + + // loop through all refs to be cherry-picked + for (Ref src : commits) { + // get the commit to be cherry-picked + // handle annotated tags + ObjectId srcObjectId = src.getPeeledObjectId(); + if (srcObjectId == null) + srcObjectId = src.getObjectId(); + RevCommit srcCommit = revWalk.parseCommit(srcObjectId); + + // get the parent of the commit to cherry-pick + if (srcCommit.getParentCount() != 1) { + throw new MultipleParentsNotAllowedException( + JGitText.get().canOnlyCherryPickCommitsWithOneParent); + } + RevCommit srcParent = srcCommit.getParent(0); + revWalk.parseHeaders(srcParent); + + ResolveMerger merger = (ResolveMerger) MergeStrategy.RESOLVE + .newMerger(repo); + merger.setWorkingTreeIterator(new FileTreeIterator(repo)); + merger.setBase(srcParent.getTree()); + + if (merger.merge(headCommit, srcCommit)) { + DirCacheCheckout dco = new DirCacheCheckout(repo, + headCommit.getTree(), repo.lockDirCache(), + merger.getResultTreeId()); + dco.setFailOnConflict(true); + dco.checkout(); + newHead = new Git(getRepository()).commit() + .setMessage(srcCommit.getFullMessage()) + .setAuthor(srcCommit.getAuthorIdent()).call(); + cherryPickedRefs.add(src); + } else { + return null; + } + } + } catch (IOException e) { + throw new JGitInternalException( + MessageFormat.format( + JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand, + e), e); + } finally { + revWalk.release(); + } + return newHead; + } + + /** + * @param commit + * a reference to a commit which is cherry-picked to the current + * head + * @return {@code this} + */ + public CherryPickCommand include(Ref commit) { + checkCallable(); + commits.add(commit); + return this; + } + + /** + * @param commit + * the Id of a commit which is cherry-picked to the current head + * @return {@code this} + */ + public CherryPickCommand include(AnyObjectId commit) { + return include(commit.getName(), commit); + } + + /** + * @param name + * a name given to the commit + * @param commit + * the Id of a commit which is cherry-picked to the current head + * @return {@code this} + */ + public CherryPickCommand include(String name, AnyObjectId commit) { + return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name, + commit.copy())); + } + + /** + * @return the list of successfully cherry-picked {@link Ref}'s. Never + * <code>null</code> but maybe an empty list if no commit was + * successfully cherry-picked + */ + public List<Ref> getCherryPickedRefs() { + return cherryPickedRefs; + } +} diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/api/Git.java b/org.eclipse.jgit/src/org/eclipse/jgit/api/Git.java index eef5ab98d4..9b6221097a 100644 --- a/org.eclipse.jgit/src/org/eclipse/jgit/api/Git.java +++ b/org.eclipse.jgit/src/org/eclipse/jgit/api/Git.java @@ -231,6 +231,19 @@ public class Git { } /** + * Returns a command object to execute a {@code cherry-pick} command + * + * @see <a + * href="http://www.kernel.org/pub/software/scm/git/docs/git-cherry-pick.html" + * >Git documentation about cherry-pick</a> + * @return a {@link CherryPickCommand} used to collect all optional + * parameters and to finally execute the {@code cherry-pick} command + */ + public CherryPickCommand cherryPick() { + return new CherryPickCommand(repo); + } + + /** * @return the git repository this class is interacting with */ public Repository getRepository() { diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/api/errors/MultipleParentsNotAllowedException.java b/org.eclipse.jgit/src/org/eclipse/jgit/api/errors/MultipleParentsNotAllowedException.java new file mode 100644 index 0000000000..c71cc049d6 --- /dev/null +++ b/org.eclipse.jgit/src/org/eclipse/jgit/api/errors/MultipleParentsNotAllowedException.java @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com> + * and other copyright owners as documented in the project's IP log. + * + * This program and the accompanying materials are made available + * under the terms of the Eclipse Distribution License v1.0 which + * accompanies this distribution, is reproduced below, and is + * available at http://www.eclipse.org/org/documents/edl-v10.php + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or + * without modification, are permitted provided that the following + * conditions are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * + * - Neither the name of the Eclipse Foundation, Inc. nor the + * names of its contributors may be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package org.eclipse.jgit.api.errors; + +/** + * The commit to be cherry-pick'ed did not have exactly one parent + */ +public class MultipleParentsNotAllowedException extends GitAPIException { + private static final long serialVersionUID = 1L; + + /** + * @param message + * @param cause + */ + public MultipleParentsNotAllowedException(String message, Throwable cause) { + super(message, cause); + } + + /** + * @param message + */ + public MultipleParentsNotAllowedException(String message) { + super(message); + } +} |