View Javadoc
1   /*
2    * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  package org.eclipse.jgit.api;
44  
45  import static org.junit.Assert.assertEquals;
46  import static org.junit.Assert.assertFalse;
47  import static org.junit.Assert.assertNotNull;
48  import static org.junit.Assert.assertTrue;
49  import static org.junit.Assert.fail;
50  
51  import java.io.File;
52  import java.io.IOException;
53  import java.util.Iterator;
54  
55  import org.eclipse.jgit.api.CherryPickResult.CherryPickStatus;
56  import org.eclipse.jgit.api.ResetCommand.ResetType;
57  import org.eclipse.jgit.api.errors.GitAPIException;
58  import org.eclipse.jgit.api.errors.JGitInternalException;
59  import org.eclipse.jgit.api.errors.MultipleParentsNotAllowedException;
60  import org.eclipse.jgit.dircache.DirCache;
61  import org.eclipse.jgit.junit.RepositoryTestCase;
62  import org.eclipse.jgit.lib.ConfigConstants;
63  import org.eclipse.jgit.lib.Constants;
64  import org.eclipse.jgit.lib.FileMode;
65  import org.eclipse.jgit.lib.ObjectId;
66  import org.eclipse.jgit.lib.ReflogReader;
67  import org.eclipse.jgit.lib.RepositoryState;
68  import org.eclipse.jgit.merge.ResolveMerger.MergeFailureReason;
69  import org.eclipse.jgit.revwalk.RevCommit;
70  import org.junit.Test;
71  
72  /**
73   * Test cherry-pick command
74   */
75  public class CherryPickCommandTest extends RepositoryTestCase {
76  	@Test
77  	public void testCherryPick() throws IOException, JGitInternalException,
78  			GitAPIException {
79  		doTestCherryPick(false);
80  	}
81  
82  	@Test
83  	public void testCherryPickNoCommit() throws IOException,
84  			JGitInternalException, GitAPIException {
85  		doTestCherryPick(true);
86  	}
87  
88  	private void doTestCherryPick(boolean noCommit) throws IOException,
89  			JGitInternalException,
90  			GitAPIException {
91  		try (Git git = new Git(db)) {
92  			writeTrashFile("a", "first line\nsec. line\nthird line\n");
93  			git.add().addFilepattern("a").call();
94  			RevCommit firstCommit = git.commit().setMessage("create a").call();
95  
96  			writeTrashFile("b", "content\n");
97  			git.add().addFilepattern("b").call();
98  			git.commit().setMessage("create b").call();
99  
100 			writeTrashFile("a", "first line\nsec. line\nthird line\nfourth line\n");
101 			git.add().addFilepattern("a").call();
102 			git.commit().setMessage("enlarged a").call();
103 
104 			writeTrashFile("a",
105 					"first line\nsecond line\nthird line\nfourth line\n");
106 			git.add().addFilepattern("a").call();
107 			RevCommit fixingA = git.commit().setMessage("fixed a").call();
108 
109 			git.branchCreate().setName("side").setStartPoint(firstCommit).call();
110 			checkoutBranch("refs/heads/side");
111 
112 			writeTrashFile("a", "first line\nsec. line\nthird line\nfeature++\n");
113 			git.add().addFilepattern("a").call();
114 			git.commit().setMessage("enhanced a").call();
115 
116 			CherryPickResult pickResult = git.cherryPick().include(fixingA)
117 					.setNoCommit(noCommit).call();
118 
119 			assertEquals(CherryPickStatus.OK, pickResult.getStatus());
120 			assertFalse(new File(db.getWorkTree(), "b").exists());
121 			checkFile(new File(db.getWorkTree(), "a"),
122 					"first line\nsecond line\nthird line\nfeature++\n");
123 			Iterator<RevCommit> history = git.log().call().iterator();
124 			if (!noCommit)
125 				assertEquals("fixed a", history.next().getFullMessage());
126 			assertEquals("enhanced a", history.next().getFullMessage());
127 			assertEquals("create a", history.next().getFullMessage());
128 			assertFalse(history.hasNext());
129 		}
130 	}
131 
132     @Test
133     public void testSequentialCherryPick() throws IOException, JGitInternalException,
134             GitAPIException {
135         try (Git git = new Git(db)) {
136 	        writeTrashFile("a", "first line\nsec. line\nthird line\n");
137 	        git.add().addFilepattern("a").call();
138 	        RevCommit firstCommit = git.commit().setMessage("create a").call();
139 
140 	        writeTrashFile("a", "first line\nsec. line\nthird line\nfourth line\n");
141 	        git.add().addFilepattern("a").call();
142 	        RevCommit enlargingA = git.commit().setMessage("enlarged a").call();
143 
144 	        writeTrashFile("a",
145 	                "first line\nsecond line\nthird line\nfourth line\n");
146 	        git.add().addFilepattern("a").call();
147 	        RevCommit fixingA = git.commit().setMessage("fixed a").call();
148 
149 	        git.branchCreate().setName("side").setStartPoint(firstCommit).call();
150 	        checkoutBranch("refs/heads/side");
151 
152 	        writeTrashFile("b", "nothing to do with a");
153 	        git.add().addFilepattern("b").call();
154 	        git.commit().setMessage("create b").call();
155 
156 	        CherryPickResult result = git.cherryPick().include(enlargingA).include(fixingA).call();
157 	        assertEquals(CherryPickResult.CherryPickStatus.OK, result.getStatus());
158 
159 	        Iterator<RevCommit> history = git.log().call().iterator();
160 	        assertEquals("fixed a", history.next().getFullMessage());
161 	        assertEquals("enlarged a", history.next().getFullMessage());
162 	        assertEquals("create b", history.next().getFullMessage());
163 	        assertEquals("create a", history.next().getFullMessage());
164 	        assertFalse(history.hasNext());
165         }
166     }
167 
168 	@Test
169 	public void testCherryPickDirtyIndex() throws Exception {
170 		try (Git git = new Git(db)) {
171 			RevCommit sideCommit = prepareCherryPick(git);
172 
173 			// modify and add file a
174 			writeTrashFile("a", "a(modified)");
175 			git.add().addFilepattern("a").call();
176 			// do not commit
177 
178 			doCherryPickAndCheckResult(git, sideCommit,
179 					MergeFailureReason.DIRTY_INDEX);
180 		}
181 	}
182 
183 	@Test
184 	public void testCherryPickDirtyWorktree() throws Exception {
185 		try (Git git = new Git(db)) {
186 			RevCommit sideCommit = prepareCherryPick(git);
187 
188 			// modify file a
189 			writeTrashFile("a", "a(modified)");
190 			// do not add and commit
191 
192 			doCherryPickAndCheckResult(git, sideCommit,
193 					MergeFailureReason.DIRTY_WORKTREE);
194 		}
195 	}
196 
197 	@Test
198 	public void testCherryPickConflictResolution() throws Exception {
199 		try (Git git = new Git(db)) {
200 			RevCommit sideCommit = prepareCherryPick(git);
201 
202 			CherryPickResult result = git.cherryPick().include(sideCommit.getId())
203 					.call();
204 
205 			assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());
206 			assertTrue(new File(db.getDirectory(), Constants.MERGE_MSG).exists());
207 			assertEquals("side\n\nConflicts:\n\ta\n", db.readMergeCommitMsg());
208 			assertTrue(new File(db.getDirectory(), Constants.CHERRY_PICK_HEAD)
209 					.exists());
210 			assertEquals(sideCommit.getId(), db.readCherryPickHead());
211 			assertEquals(RepositoryState.CHERRY_PICKING, db.getRepositoryState());
212 
213 			// Resolve
214 			writeTrashFile("a", "a");
215 			git.add().addFilepattern("a").call();
216 
217 			assertEquals(RepositoryState.CHERRY_PICKING_RESOLVED,
218 					db.getRepositoryState());
219 
220 			git.commit().setOnly("a").setMessage("resolve").call();
221 
222 			assertEquals(RepositoryState.SAFE, db.getRepositoryState());
223 		}
224 	}
225 
226 	@Test
227 	public void testCherryPickConflictResolutionNoCOmmit() throws Exception {
228 		Git git = new Git(db);
229 		RevCommit sideCommit = prepareCherryPick(git);
230 
231 		CherryPickResult result = git.cherryPick().include(sideCommit.getId())
232 				.setNoCommit(true).call();
233 
234 		assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());
235 		assertTrue(db.readDirCache().hasUnmergedPaths());
236 		String expected = "<<<<<<< master\na(master)\n=======\na(side)\n>>>>>>> 527460a side\n";
237 		assertEquals(expected, read("a"));
238 		assertTrue(new File(db.getDirectory(), Constants.MERGE_MSG).exists());
239 		assertEquals("side\n\nConflicts:\n\ta\n", db.readMergeCommitMsg());
240 		assertFalse(new File(db.getDirectory(), Constants.CHERRY_PICK_HEAD)
241 				.exists());
242 		assertEquals(RepositoryState.SAFE, db.getRepositoryState());
243 
244 		// Resolve
245 		writeTrashFile("a", "a");
246 		git.add().addFilepattern("a").call();
247 
248 		assertEquals(RepositoryState.SAFE, db.getRepositoryState());
249 
250 		git.commit().setOnly("a").setMessage("resolve").call();
251 
252 		assertEquals(RepositoryState.SAFE, db.getRepositoryState());
253 	}
254 
255 	@Test
256 	public void testCherryPickConflictReset() throws Exception {
257 		try (Git git = new Git(db)) {
258 			RevCommit sideCommit = prepareCherryPick(git);
259 
260 			CherryPickResult result = git.cherryPick().include(sideCommit.getId())
261 					.call();
262 
263 			assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());
264 			assertEquals(RepositoryState.CHERRY_PICKING, db.getRepositoryState());
265 			assertTrue(new File(db.getDirectory(), Constants.CHERRY_PICK_HEAD)
266 					.exists());
267 
268 			git.reset().setMode(ResetType.MIXED).setRef("HEAD").call();
269 
270 			assertEquals(RepositoryState.SAFE, db.getRepositoryState());
271 			assertFalse(new File(db.getDirectory(), Constants.CHERRY_PICK_HEAD)
272 					.exists());
273 		}
274 	}
275 
276 	@Test
277 	public void testCherryPickOverExecutableChangeOnNonExectuableFileSystem()
278 			throws Exception {
279 		try (Git git = new Git(db)) {
280 			File file = writeTrashFile("test.txt", "a");
281 			assertNotNull(git.add().addFilepattern("test.txt").call());
282 			assertNotNull(git.commit().setMessage("commit1").call());
283 
284 			assertNotNull(git.checkout().setCreateBranch(true).setName("a").call());
285 
286 			writeTrashFile("test.txt", "b");
287 			assertNotNull(git.add().addFilepattern("test.txt").call());
288 			RevCommit commit2 = git.commit().setMessage("commit2").call();
289 			assertNotNull(commit2);
290 
291 			assertNotNull(git.checkout().setName(Constants.MASTER).call());
292 
293 			DirCache cache = db.lockDirCache();
294 			cache.getEntry("test.txt").setFileMode(FileMode.EXECUTABLE_FILE);
295 			cache.write();
296 			assertTrue(cache.commit());
297 			cache.unlock();
298 
299 			assertNotNull(git.commit().setMessage("commit3").call());
300 
301 			db.getFS().setExecute(file, false);
302 			git.getRepository()
303 					.getConfig()
304 					.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
305 							ConfigConstants.CONFIG_KEY_FILEMODE, false);
306 
307 			CherryPickResult result = git.cherryPick().include(commit2).call();
308 			assertNotNull(result);
309 			assertEquals(CherryPickStatus.OK, result.getStatus());
310 		}
311 	}
312 
313 	@Test
314 	public void testCherryPickConflictMarkers() throws Exception {
315 		try (Git git = new Git(db)) {
316 			RevCommit sideCommit = prepareCherryPick(git);
317 
318 			CherryPickResult result = git.cherryPick().include(sideCommit.getId())
319 					.call();
320 			assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());
321 
322 			String expected = "<<<<<<< master\na(master)\n=======\na(side)\n>>>>>>> 527460a side\n";
323 			checkFile(new File(db.getWorkTree(), "a"), expected);
324 		}
325 	}
326 
327 	@Test
328 	public void testCherryPickOurCommitName() throws Exception {
329 		try (Git git = new Git(db)) {
330 			RevCommit sideCommit = prepareCherryPick(git);
331 
332 			CherryPickResult result = git.cherryPick().include(sideCommit.getId())
333 					.setOurCommitName("custom name").call();
334 			assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());
335 
336 			String expected = "<<<<<<< custom name\na(master)\n=======\na(side)\n>>>>>>> 527460a side\n";
337 			checkFile(new File(db.getWorkTree(), "a"), expected);
338 		}
339 	}
340 
341 	private RevCommit prepareCherryPick(final Git git) throws Exception {
342 		// create, add and commit file a
343 		writeTrashFile("a", "a");
344 		git.add().addFilepattern("a").call();
345 		RevCommit firstMasterCommit = git.commit().setMessage("first master")
346 				.call();
347 
348 		// create and checkout side branch
349 		createBranch(firstMasterCommit, "refs/heads/side");
350 		checkoutBranch("refs/heads/side");
351 		// modify, add and commit file a
352 		writeTrashFile("a", "a(side)");
353 		git.add().addFilepattern("a").call();
354 		RevCommit sideCommit = git.commit().setMessage("side").call();
355 
356 		// checkout master branch
357 		checkoutBranch("refs/heads/master");
358 		// modify, add and commit file a
359 		writeTrashFile("a", "a(master)");
360 		git.add().addFilepattern("a").call();
361 		git.commit().setMessage("second master").call();
362 		return sideCommit;
363 	}
364 
365 	private void doCherryPickAndCheckResult(final Git git,
366 			final RevCommit sideCommit, final MergeFailureReason reason)
367 			throws Exception {
368 		// get current index state
369 		String indexState = indexState(CONTENT);
370 
371 		// cherry-pick
372 		CherryPickResult result = git.cherryPick().include(sideCommit.getId())
373 				.call();
374 		assertEquals(CherryPickStatus.FAILED, result.getStatus());
375 		// staged file a causes DIRTY_INDEX
376 		assertEquals(1, result.getFailingPaths().size());
377 		assertEquals(reason, result.getFailingPaths().get("a"));
378 		assertEquals("a(modified)", read(new File(db.getWorkTree(), "a")));
379 		// index shall be unchanged
380 		assertEquals(indexState, indexState(CONTENT));
381 		assertEquals(RepositoryState.SAFE, db.getRepositoryState());
382 
383 		if (reason == null) {
384 			ReflogReader reader = db.getReflogReader(Constants.HEAD);
385 			assertTrue(reader.getLastEntry().getComment()
386 					.startsWith("cherry-pick: "));
387 			reader = db.getReflogReader(db.getBranch());
388 			assertTrue(reader.getLastEntry().getComment()
389 					.startsWith("cherry-pick: "));
390 		}
391 	}
392 
393 	/**
394 	 * Cherry-picking merge commit M onto T
395 	 * <pre>
396 	 *    M
397 	 *    |\
398 	 *    C D
399 	 *    |/
400 	 * T  B
401 	 * | /
402 	 * A
403 	 * </pre>
404 	 * @throws Exception
405 	 */
406 	@Test
407 	public void testCherryPickMerge() throws Exception {
408 		try (Git git = new Git(db)) {
409 			commitFile("file", "1\n2\n3\n", "master");
410 			commitFile("file", "1\n2\n3\n", "side");
411 			checkoutBranch("refs/heads/side");
412 			RevCommit commitD = commitFile("file", "1\n2\n3\n4\n5\n", "side2");
413 			commitFile("file", "a\n2\n3\n", "side");
414 			MergeResult mergeResult = git.merge().include(commitD).call();
415 			ObjectId commitM = mergeResult.getNewHead();
416 			checkoutBranch("refs/heads/master");
417 			RevCommit commitT = commitFile("another", "t", "master");
418 
419 			try {
420 				git.cherryPick().include(commitM).call();
421 				fail("merges should not be cherry-picked by default");
422 			} catch (MultipleParentsNotAllowedException e) {
423 				// expected
424 			}
425 			try {
426 				git.cherryPick().include(commitM).setMainlineParentNumber(3).call();
427 				fail("specifying a non-existent parent should fail");
428 			} catch (JGitInternalException e) {
429 				// expected
430 				assertTrue(e.getMessage().endsWith(
431 						"does not have a parent number 3."));
432 			}
433 
434 			CherryPickResult result = git.cherryPick().include(commitM)
435 					.setMainlineParentNumber(1).call();
436 			assertEquals(CherryPickStatus.OK, result.getStatus());
437 			checkFile(new File(db.getWorkTree(), "file"), "1\n2\n3\n4\n5\n");
438 
439 			git.reset().setMode(ResetType.HARD).setRef(commitT.getName()).call();
440 
441 			CherryPickResult result2 = git.cherryPick().include(commitM)
442 					.setMainlineParentNumber(2).call();
443 			assertEquals(CherryPickStatus.OK, result2.getStatus());
444 			checkFile(new File(db.getWorkTree(), "file"), "a\n2\n3\n");
445 		}
446 	}
447 }