View Javadoc
1   /*
2    * Copyright (C) 2009-2010, Google Inc.
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  
44  package org.eclipse.jgit.junit;
45  
46  import static java.nio.charset.StandardCharsets.UTF_8;
47  import static org.junit.Assert.assertEquals;
48  import static org.junit.Assert.fail;
49  
50  import java.io.BufferedOutputStream;
51  import java.io.File;
52  import java.io.FileOutputStream;
53  import java.io.IOException;
54  import java.io.OutputStream;
55  import java.security.MessageDigest;
56  import java.util.ArrayList;
57  import java.util.Arrays;
58  import java.util.Collections;
59  import java.util.Date;
60  import java.util.HashSet;
61  import java.util.List;
62  import java.util.Set;
63  import java.util.TimeZone;
64  
65  import org.eclipse.jgit.api.Git;
66  import org.eclipse.jgit.dircache.DirCache;
67  import org.eclipse.jgit.dircache.DirCacheBuilder;
68  import org.eclipse.jgit.dircache.DirCacheEditor;
69  import org.eclipse.jgit.dircache.DirCacheEditor.DeletePath;
70  import org.eclipse.jgit.dircache.DirCacheEditor.DeleteTree;
71  import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
72  import org.eclipse.jgit.dircache.DirCacheEntry;
73  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
74  import org.eclipse.jgit.errors.MissingObjectException;
75  import org.eclipse.jgit.errors.ObjectWritingException;
76  import org.eclipse.jgit.internal.storage.file.FileRepository;
77  import org.eclipse.jgit.internal.storage.file.LockFile;
78  import org.eclipse.jgit.internal.storage.file.ObjectDirectory;
79  import org.eclipse.jgit.internal.storage.file.PackFile;
80  import org.eclipse.jgit.internal.storage.file.PackIndex.MutableEntry;
81  import org.eclipse.jgit.internal.storage.pack.PackWriter;
82  import org.eclipse.jgit.lib.AnyObjectId;
83  import org.eclipse.jgit.lib.Constants;
84  import org.eclipse.jgit.lib.FileMode;
85  import org.eclipse.jgit.lib.NullProgressMonitor;
86  import org.eclipse.jgit.lib.ObjectChecker;
87  import org.eclipse.jgit.lib.ObjectId;
88  import org.eclipse.jgit.lib.ObjectInserter;
89  import org.eclipse.jgit.lib.PersonIdent;
90  import org.eclipse.jgit.lib.Ref;
91  import org.eclipse.jgit.lib.RefUpdate;
92  import org.eclipse.jgit.lib.RefWriter;
93  import org.eclipse.jgit.lib.Repository;
94  import org.eclipse.jgit.lib.TagBuilder;
95  import org.eclipse.jgit.merge.MergeStrategy;
96  import org.eclipse.jgit.merge.ThreeWayMerger;
97  import org.eclipse.jgit.revwalk.ObjectWalk;
98  import org.eclipse.jgit.revwalk.RevBlob;
99  import org.eclipse.jgit.revwalk.RevCommit;
100 import org.eclipse.jgit.revwalk.RevObject;
101 import org.eclipse.jgit.revwalk.RevTag;
102 import org.eclipse.jgit.revwalk.RevTree;
103 import org.eclipse.jgit.revwalk.RevWalk;
104 import org.eclipse.jgit.treewalk.TreeWalk;
105 import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
106 import org.eclipse.jgit.util.ChangeIdUtil;
107 import org.eclipse.jgit.util.FileUtils;
108 
109 /**
110  * Wrapper to make creating test data easier.
111  *
112  * @param <R>
113  *            type of Repository the test data is stored on.
114  */
115 public class TestRepository<R extends Repository> implements AutoCloseable {
116 
117 	/** Constant <code>AUTHOR="J. Author"</code> */
118 	public static final String AUTHOR = "J. Author";
119 
120 	/** Constant <code>AUTHOR_EMAIL="jauthor@example.com"</code> */
121 	public static final String AUTHOR_EMAIL = "jauthor@example.com";
122 
123 	/** Constant <code>COMMITTER="J. Committer"</code> */
124 	public static final String COMMITTER = "J. Committer";
125 
126 	/** Constant <code>COMMITTER_EMAIL="jcommitter@example.com"</code> */
127 	public static final String COMMITTER_EMAIL = "jcommitter@example.com";
128 
129 	private final PersonIdent defaultAuthor;
130 
131 	private final PersonIdent defaultCommitter;
132 
133 	private final R db;
134 
135 	private final Git git;
136 
137 	private final RevWalk pool;
138 
139 	private final ObjectInserter inserter;
140 
141 	private final MockSystemReader mockSystemReader;
142 
143 	/**
144 	 * Wrap a repository with test building tools.
145 	 *
146 	 * @param db
147 	 *            the test repository to write into.
148 	 * @throws IOException
149 	 */
150 	public TestRepository(R db) throws IOException {
151 		this(db, new RevWalk(db), new MockSystemReader());
152 	}
153 
154 	/**
155 	 * Wrap a repository with test building tools.
156 	 *
157 	 * @param db
158 	 *            the test repository to write into.
159 	 * @param rw
160 	 *            the RevObject pool to use for object lookup.
161 	 * @throws IOException
162 	 */
163 	public TestRepository(R db, RevWalk rw) throws IOException {
164 		this(db, rw, new MockSystemReader());
165 	}
166 
167 	/**
168 	 * Wrap a repository with test building tools.
169 	 *
170 	 * @param db
171 	 *            the test repository to write into.
172 	 * @param rw
173 	 *            the RevObject pool to use for object lookup.
174 	 * @param reader
175 	 *            the MockSystemReader to use for clock and other system
176 	 *            operations.
177 	 * @throws IOException
178 	 * @since 4.2
179 	 */
180 	public TestRepository(R db, RevWalk rw, MockSystemReader reader)
181 			throws IOException {
182 		this.db = db;
183 		this.git = Git.wrap(db);
184 		this.pool = rw;
185 		this.inserter = db.newObjectInserter();
186 		this.mockSystemReader = reader;
187 		long now = mockSystemReader.getCurrentTime();
188 		int tz = mockSystemReader.getTimezone(now);
189 		defaultAuthor = new PersonIdent(AUTHOR, AUTHOR_EMAIL, now, tz);
190 		defaultCommitter = new PersonIdent(COMMITTER, COMMITTER_EMAIL, now, tz);
191 	}
192 
193 	/**
194 	 * Get repository
195 	 *
196 	 * @return the repository this helper class operates against.
197 	 */
198 	public R getRepository() {
199 		return db;
200 	}
201 
202 	/**
203 	 * Get RevWalk
204 	 *
205 	 * @return get the RevWalk pool all objects are allocated through.
206 	 */
207 	public RevWalk getRevWalk() {
208 		return pool;
209 	}
210 
211 	/**
212 	 * Return Git API wrapper
213 	 *
214 	 * @return an API wrapper for the underlying repository. This wrapper does
215 	 *         not allocate any new resources and need not be closed (but
216 	 *         closing it is harmless).
217 	 */
218 	public Git git() {
219 		return git;
220 	}
221 
222 	/**
223 	 * Get date
224 	 *
225 	 * @return current date.
226 	 * @since 4.2
227 	 */
228 	public Date getDate() {
229 		return new Date(mockSystemReader.getCurrentTime());
230 	}
231 
232 	/**
233 	 * Get timezone
234 	 *
235 	 * @return timezone used for default identities.
236 	 */
237 	public TimeZone getTimeZone() {
238 		return mockSystemReader.getTimeZone();
239 	}
240 
241 	/**
242 	 * Adjust the current time that will used by the next commit.
243 	 *
244 	 * @param secDelta
245 	 *            number of seconds to add to the current time.
246 	 */
247 	public void tick(int secDelta) {
248 		mockSystemReader.tick(secDelta);
249 	}
250 
251 	/**
252 	 * Set the author and committer using {@link #getDate()}.
253 	 *
254 	 * @param c
255 	 *            the commit builder to store.
256 	 */
257 	public void setAuthorAndCommitter(org.eclipse.jgit.lib.CommitBuilder c) {
258 		c.setAuthor(new PersonIdent(defaultAuthor, getDate()));
259 		c.setCommitter(new PersonIdent(defaultCommitter, getDate()));
260 	}
261 
262 	/**
263 	 * Create a new blob object in the repository.
264 	 *
265 	 * @param content
266 	 *            file content, will be UTF-8 encoded.
267 	 * @return reference to the blob.
268 	 * @throws Exception
269 	 */
270 	public RevBlob blob(String content) throws Exception {
271 		return blob(content.getBytes(UTF_8));
272 	}
273 
274 	/**
275 	 * Create a new blob object in the repository.
276 	 *
277 	 * @param content
278 	 *            binary file content.
279 	 * @return the new, fully parsed blob.
280 	 * @throws Exception
281 	 */
282 	public RevBlob blob(byte[] content) throws Exception {
283 		ObjectId id;
284 		try (ObjectInserter ins = inserter) {
285 			id = ins.insert(Constants.OBJ_BLOB, content);
286 			ins.flush();
287 		}
288 		return (RevBlob) pool.parseAny(id);
289 	}
290 
291 	/**
292 	 * Construct a regular file mode tree entry.
293 	 *
294 	 * @param path
295 	 *            path of the file.
296 	 * @param blob
297 	 *            a blob, previously constructed in the repository.
298 	 * @return the entry.
299 	 * @throws Exception
300 	 */
301 	public DirCacheEntry file(String path, RevBlob blob)
302 			throws Exception {
303 		final DirCacheEntryacheEntry.html#DirCacheEntry">DirCacheEntry e = new DirCacheEntry(path);
304 		e.setFileMode(FileMode.REGULAR_FILE);
305 		e.setObjectId(blob);
306 		return e;
307 	}
308 
309 	/**
310 	 * Construct a tree from a specific listing of file entries.
311 	 *
312 	 * @param entries
313 	 *            the files to include in the tree. The collection does not need
314 	 *            to be sorted properly and may be empty.
315 	 * @return the new, fully parsed tree specified by the entry list.
316 	 * @throws Exception
317 	 */
318 	public RevTree tree(DirCacheEntry... entries) throws Exception {
319 		final DirCache dc = DirCache.newInCore();
320 		final DirCacheBuilder b = dc.builder();
321 		for (DirCacheEntry e : entries) {
322 			b.add(e);
323 		}
324 		b.finish();
325 		ObjectId root;
326 		try (ObjectInserter ins = inserter) {
327 			root = dc.writeTree(ins);
328 			ins.flush();
329 		}
330 		return pool.parseTree(root);
331 	}
332 
333 	/**
334 	 * Lookup an entry stored in a tree, failing if not present.
335 	 *
336 	 * @param tree
337 	 *            the tree to search.
338 	 * @param path
339 	 *            the path to find the entry of.
340 	 * @return the parsed object entry at this path, never null.
341 	 * @throws Exception
342 	 */
343 	public RevObject get(RevTree tree, String path)
344 			throws Exception {
345 		try (TreeWalkTreeWalk.html#TreeWalk">TreeWalk tw = new TreeWalk(pool.getObjectReader())) {
346 			tw.setFilter(PathFilterGroup.createFromStrings(Collections
347 					.singleton(path)));
348 			tw.reset(tree);
349 			while (tw.next()) {
350 				if (tw.isSubtree() && !path.equals(tw.getPathString())) {
351 					tw.enterSubtree();
352 					continue;
353 				}
354 				final ObjectId entid = tw.getObjectId(0);
355 				final FileMode entmode = tw.getFileMode(0);
356 				return pool.lookupAny(entid, entmode.getObjectType());
357 			}
358 		}
359 		fail("Can't find " + path + " in tree " + tree.name());
360 		return null; // never reached.
361 	}
362 
363 	/**
364 	 * Create a new commit.
365 	 * <p>
366 	 * See {@link #commit(int, RevTree, RevCommit...)}. The tree is the empty
367 	 * tree (no files or subdirectories).
368 	 *
369 	 * @param parents
370 	 *            zero or more parents of the commit.
371 	 * @return the new commit.
372 	 * @throws Exception
373 	 */
374 	public RevCommit commit(RevCommit... parents) throws Exception {
375 		return commit(1, tree(), parents);
376 	}
377 
378 	/**
379 	 * Create a new commit.
380 	 * <p>
381 	 * See {@link #commit(int, RevTree, RevCommit...)}.
382 	 *
383 	 * @param tree
384 	 *            the root tree for the commit.
385 	 * @param parents
386 	 *            zero or more parents of the commit.
387 	 * @return the new commit.
388 	 * @throws Exception
389 	 */
390 	public RevCommit commit(RevTree tree, RevCommit... parents)
391 			throws Exception {
392 		return commit(1, tree, parents);
393 	}
394 
395 	/**
396 	 * Create a new commit.
397 	 * <p>
398 	 * See {@link #commit(int, RevTree, RevCommit...)}. The tree is the empty
399 	 * tree (no files or subdirectories).
400 	 *
401 	 * @param secDelta
402 	 *            number of seconds to advance {@link #tick(int)} by.
403 	 * @param parents
404 	 *            zero or more parents of the commit.
405 	 * @return the new commit.
406 	 * @throws Exception
407 	 */
408 	public RevCommit commit(int secDelta, RevCommit... parents)
409 			throws Exception {
410 		return commit(secDelta, tree(), parents);
411 	}
412 
413 	/**
414 	 * Create a new commit.
415 	 * <p>
416 	 * The author and committer identities are stored using the current
417 	 * timestamp, after being incremented by {@code secDelta}. The message body
418 	 * is empty.
419 	 *
420 	 * @param secDelta
421 	 *            number of seconds to advance {@link #tick(int)} by.
422 	 * @param tree
423 	 *            the root tree for the commit.
424 	 * @param parents
425 	 *            zero or more parents of the commit.
426 	 * @return the new, fully parsed commit.
427 	 * @throws Exception
428 	 */
429 	public RevCommit commit(final int secDelta, final RevTree tree,
430 			final RevCommit... parents) throws Exception {
431 		tick(secDelta);
432 
433 		final org.eclipse.jgit.lib.CommitBuilder c;
434 
435 		c = new org.eclipse.jgit.lib.CommitBuilder();
436 		c.setTreeId(tree);
437 		c.setParentIds(parents);
438 		c.setAuthor(new PersonIdent(defaultAuthor, getDate()));
439 		c.setCommitter(new PersonIdent(defaultCommitter, getDate()));
440 		c.setMessage("");
441 		ObjectId id;
442 		try (ObjectInserter ins = inserter) {
443 			id = ins.insert(c);
444 			ins.flush();
445 		}
446 		return pool.parseCommit(id);
447 	}
448 
449 	/**
450 	 * Create commit builder
451 	 *
452 	 * @return a new commit builder.
453 	 */
454 	public CommitBuilder commit() {
455 		return new CommitBuilder();
456 	}
457 
458 	/**
459 	 * Construct an annotated tag object pointing at another object.
460 	 * <p>
461 	 * The tagger is the committer identity, at the current time as specified by
462 	 * {@link #tick(int)}. The time is not increased.
463 	 * <p>
464 	 * The tag message is empty.
465 	 *
466 	 * @param name
467 	 *            name of the tag. Traditionally a tag name should not start
468 	 *            with {@code refs/tags/}.
469 	 * @param dst
470 	 *            object the tag should be pointed at.
471 	 * @return the new, fully parsed annotated tag object.
472 	 * @throws Exception
473 	 */
474 	public RevTag tag(String name, RevObject dst) throws Exception {
475 		final TagBuilderlder.html#TagBuilder">TagBuilder t = new TagBuilder();
476 		t.setObjectId(dst);
477 		t.setTag(name);
478 		t.setTagger(new PersonIdent(defaultCommitter, getDate()));
479 		t.setMessage("");
480 		ObjectId id;
481 		try (ObjectInserter ins = inserter) {
482 			id = ins.insert(t);
483 			ins.flush();
484 		}
485 		return pool.parseTag(id);
486 	}
487 
488 	/**
489 	 * Update a reference to point to an object.
490 	 *
491 	 * @param ref
492 	 *            the name of the reference to update to. If {@code ref} does
493 	 *            not start with {@code refs/} and is not the magic names
494 	 *            {@code HEAD} {@code FETCH_HEAD} or {@code MERGE_HEAD}, then
495 	 *            {@code refs/heads/} will be prefixed in front of the given
496 	 *            name, thereby assuming it is a branch.
497 	 * @param to
498 	 *            the target object.
499 	 * @return the target object.
500 	 * @throws Exception
501 	 */
502 	public RevCommit update(String ref, CommitBuilder to) throws Exception {
503 		return update(ref, to.create());
504 	}
505 
506 	/**
507 	 * Amend an existing ref.
508 	 *
509 	 * @param ref
510 	 *            the name of the reference to amend, which must already exist.
511 	 *            If {@code ref} does not start with {@code refs/} and is not the
512 	 *            magic names {@code HEAD} {@code FETCH_HEAD} or {@code
513 	 *            MERGE_HEAD}, then {@code refs/heads/} will be prefixed in front
514 	 *            of the given name, thereby assuming it is a branch.
515 	 * @return commit builder that amends the branch on commit.
516 	 * @throws Exception
517 	 */
518 	public CommitBuilder amendRef(String ref) throws Exception {
519 		String name = normalizeRef(ref);
520 		Ref r = db.exactRef(name);
521 		if (r == null)
522 			throw new IOException("Not a ref: " + ref);
523 		return amend(pool.parseCommit(r.getObjectId()), branch(name).commit());
524 	}
525 
526 	/**
527 	 * Amend an existing commit.
528 	 *
529 	 * @param id
530 	 *            the id of the commit to amend.
531 	 * @return commit builder.
532 	 * @throws Exception
533 	 */
534 	public CommitBuilder amend(AnyObjectId id) throws Exception {
535 		return amend(pool.parseCommit(id), commit());
536 	}
537 
538 	private CommitBuilderlipse/jgit/lib/CommitBuilder.html#CommitBuilder">CommitBuilder amend(RevCommit old, CommitBuilder b) throws Exception {
539 		pool.parseBody(old);
540 		b.author(old.getAuthorIdent());
541 		b.committer(old.getCommitterIdent());
542 		b.message(old.getFullMessage());
543 		// Use the committer name from the old commit, but update it after ticking
544 		// the clock in CommitBuilder#create().
545 		b.updateCommitterTime = true;
546 
547 		// Reset parents to original parents.
548 		b.noParents();
549 		for (int i = 0; i < old.getParentCount(); i++)
550 			b.parent(old.getParent(i));
551 
552 		// Reset tree to original tree; resetting parents reset tree contents to the
553 		// first parent.
554 		b.tree.clear();
555 		try (TreeWalkTreeWalk.html#TreeWalk">TreeWalk tw = new TreeWalk(db)) {
556 			tw.reset(old.getTree());
557 			tw.setRecursive(true);
558 			while (tw.next()) {
559 				b.edit(new PathEdit(tw.getPathString()) {
560 					@Override
561 					public void apply(DirCacheEntry ent) {
562 						ent.setFileMode(tw.getFileMode(0));
563 						ent.setObjectId(tw.getObjectId(0));
564 					}
565 				});
566 			}
567 		}
568 
569 		return b;
570 	}
571 
572 	/**
573 	 * Update a reference to point to an object.
574 	 *
575 	 * @param <T>
576 	 *            type of the target object.
577 	 * @param ref
578 	 *            the name of the reference to update to. If {@code ref} does
579 	 *            not start with {@code refs/} and is not the magic names
580 	 *            {@code HEAD} {@code FETCH_HEAD} or {@code MERGE_HEAD}, then
581 	 *            {@code refs/heads/} will be prefixed in front of the given
582 	 *            name, thereby assuming it is a branch.
583 	 * @param obj
584 	 *            the target object.
585 	 * @return the target object.
586 	 * @throws Exception
587 	 */
588 	public <T extends AnyObjectId> T update(String ref, T obj) throws Exception {
589 		ref = normalizeRef(ref);
590 		RefUpdate u = db.updateRef(ref);
591 		u.setNewObjectId(obj);
592 		switch (u.forceUpdate()) {
593 		case FAST_FORWARD:
594 		case FORCED:
595 		case NEW:
596 		case NO_CHANGE:
597 			updateServerInfo();
598 			return obj;
599 
600 		default:
601 			throw new IOException("Cannot write " + ref + " " + u.getResult());
602 		}
603 	}
604 
605 	/**
606 	 * Delete a reference.
607 	 *
608 	 * @param ref
609 	 *	      the name of the reference to delete. This is normalized
610 	 *	      in the same way as {@link #update(String, AnyObjectId)}.
611 	 * @throws Exception
612 	 * @since 4.4
613 	 */
614 	public void delete(String ref) throws Exception {
615 		ref = normalizeRef(ref);
616 		RefUpdate u = db.updateRef(ref);
617 		u.setForceUpdate(true);
618 		switch (u.delete()) {
619 		case FAST_FORWARD:
620 		case FORCED:
621 		case NEW:
622 		case NO_CHANGE:
623 			updateServerInfo();
624 			return;
625 
626 		default:
627 			throw new IOException("Cannot delete " + ref + " " + u.getResult());
628 		}
629 	}
630 
631 	private static String normalizeRef(String ref) {
632 		if (Constants.HEAD.equals(ref)) {
633 			// nothing
634 		} else if ("FETCH_HEAD".equals(ref)) {
635 			// nothing
636 		} else if ("MERGE_HEAD".equals(ref)) {
637 			// nothing
638 		} else if (ref.startsWith(Constants.R_REFS)) {
639 			// nothing
640 		} else
641 			ref = Constants.R_HEADS + ref;
642 		return ref;
643 	}
644 
645 	/**
646 	 * Soft-reset HEAD to a detached state.
647 	 *
648 	 * @param id
649 	 *            ID of detached head.
650 	 * @throws Exception
651 	 * @see #reset(String)
652 	 */
653 	public void reset(AnyObjectId id) throws Exception {
654 		RefUpdate ru = db.updateRef(Constants.HEAD, true);
655 		ru.setNewObjectId(id);
656 		RefUpdate.Result result = ru.forceUpdate();
657 		switch (result) {
658 			case FAST_FORWARD:
659 			case FORCED:
660 			case NEW:
661 			case NO_CHANGE:
662 				break;
663 			default:
664 				throw new IOException(String.format(
665 						"Checkout \"%s\" failed: %s", id.name(), result));
666 		}
667 	}
668 
669 	/**
670 	 * Soft-reset HEAD to a different commit.
671 	 * <p>
672 	 * This is equivalent to {@code git reset --soft} in that it modifies HEAD but
673 	 * not the index or the working tree of a non-bare repository.
674 	 *
675 	 * @param name
676 	 *            revision string; either an existing ref name, or something that
677 	 *            can be parsed to an object ID.
678 	 * @throws Exception
679 	 */
680 	public void reset(String name) throws Exception {
681 		RefUpdate.Result result;
682 		ObjectId id = db.resolve(name);
683 		if (id == null)
684 			throw new IOException("Not a revision: " + name);
685 		RefUpdate ru = db.updateRef(Constants.HEAD, false);
686 		ru.setNewObjectId(id);
687 		result = ru.forceUpdate();
688 		switch (result) {
689 			case FAST_FORWARD:
690 			case FORCED:
691 			case NEW:
692 			case NO_CHANGE:
693 				break;
694 			default:
695 				throw new IOException(String.format(
696 						"Checkout \"%s\" failed: %s", name, result));
697 		}
698 	}
699 
700 	/**
701 	 * Cherry-pick a commit onto HEAD.
702 	 * <p>
703 	 * This differs from {@code git cherry-pick} in that it works in a bare
704 	 * repository. As a result, any merge failure results in an exception, as
705 	 * there is no way to recover.
706 	 *
707 	 * @param id
708 	 *            commit-ish to cherry-pick.
709 	 * @return the new, fully parsed commit, or null if no work was done due to
710 	 *         the resulting tree being identical.
711 	 * @throws Exception
712 	 */
713 	public RevCommit cherryPick(AnyObjectId id) throws Exception {
714 		RevCommit commit = pool.parseCommit(id);
715 		pool.parseBody(commit);
716 		if (commit.getParentCount() != 1)
717 			throw new IOException(String.format(
718 					"Expected 1 parent for %s, found: %s",
719 					id.name(), Arrays.asList(commit.getParents())));
720 		RevCommit parent = commit.getParent(0);
721 		pool.parseHeaders(parent);
722 
723 		Ref headRef = db.exactRef(Constants.HEAD);
724 		if (headRef == null)
725 			throw new IOException("Missing HEAD");
726 		RevCommit head = pool.parseCommit(headRef.getObjectId());
727 
728 		ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(db, true);
729 		merger.setBase(parent.getTree());
730 		if (merger.merge(head, commit)) {
731 			if (AnyObjectId.equals(head.getTree(), merger.getResultTreeId()))
732 				return null;
733 			tick(1);
734 			org.eclipse.jgit.lib.CommitBuilder b =
735 					new org.eclipse.jgit.lib.CommitBuilder();
736 			b.setParentId(head);
737 			b.setTreeId(merger.getResultTreeId());
738 			b.setAuthor(commit.getAuthorIdent());
739 			b.setCommitter(new PersonIdent(defaultCommitter, getDate()));
740 			b.setMessage(commit.getFullMessage());
741 			ObjectId result;
742 			try (ObjectInserter ins = inserter) {
743 				result = ins.insert(b);
744 				ins.flush();
745 			}
746 			update(Constants.HEAD, result);
747 			return pool.parseCommit(result);
748 		} else {
749 			throw new IOException("Merge conflict");
750 		}
751 	}
752 
753 	/**
754 	 * Update the dumb client server info files.
755 	 *
756 	 * @throws Exception
757 	 */
758 	public void updateServerInfo() throws Exception {
759 		if (db instanceof FileRepository) {
760 			final FileRepository./../../org/eclipse/jgit/internal/storage/file/FileRepository.html#FileRepository">FileRepository fr = (FileRepository) db;
761 			RefWriter rw = new RefWriter(fr.getRefDatabase().getRefs()) {
762 				@Override
763 				protected void writeFile(String name, byte[] bin)
764 						throws IOException {
765 					File path = new File(fr.getDirectory(), name);
766 					TestRepository.this.writeFile(path, bin);
767 				}
768 			};
769 			rw.writePackedRefs();
770 			rw.writeInfoRefs();
771 
772 			final StringBuilder w = new StringBuilder();
773 			for (PackFile p : fr.getObjectDatabase().getPacks()) {
774 				w.append("P ");
775 				w.append(p.getPackFile().getName());
776 				w.append('\n');
777 			}
778 			writeFile(new File(new File(fr.getObjectDatabase().getDirectory(),
779 					"info"), "packs"), Constants.encodeASCII(w.toString()));
780 		}
781 	}
782 
783 	/**
784 	 * Ensure the body of the given object has been parsed.
785 	 *
786 	 * @param <T>
787 	 *            type of object, e.g. {@link org.eclipse.jgit.revwalk.RevTag}
788 	 *            or {@link org.eclipse.jgit.revwalk.RevCommit}.
789 	 * @param object
790 	 *            reference to the (possibly unparsed) object to force body
791 	 *            parsing of.
792 	 * @return {@code object}
793 	 * @throws Exception
794 	 */
795 	public <T extends RevObject> T parseBody(T object) throws Exception {
796 		pool.parseBody(object);
797 		return object;
798 	}
799 
800 	/**
801 	 * Create a new branch builder for this repository.
802 	 *
803 	 * @param ref
804 	 *            name of the branch to be constructed. If {@code ref} does not
805 	 *            start with {@code refs/} the prefix {@code refs/heads/} will
806 	 *            be added.
807 	 * @return builder for the named branch.
808 	 */
809 	public BranchBuilder branch(String ref) {
810 		if (Constants.HEAD.equals(ref)) {
811 			// nothing
812 		} else if (ref.startsWith(Constants.R_REFS)) {
813 			// nothing
814 		} else
815 			ref = Constants.R_HEADS + ref;
816 		return new BranchBuilder(ref);
817 	}
818 
819 	/**
820 	 * Tag an object using a lightweight tag.
821 	 *
822 	 * @param name
823 	 *            the tag name. The /refs/tags/ prefix will be added if the name
824 	 *            doesn't start with it
825 	 * @param obj
826 	 *            the object to tag
827 	 * @return the tagged object
828 	 * @throws Exception
829 	 */
830 	public ObjectIdpse/jgit/lib/ObjectId.html#ObjectId">ObjectId lightweightTag(String name, ObjectId obj) throws Exception {
831 		if (!name.startsWith(Constants.R_TAGS))
832 			name = Constants.R_TAGS + name;
833 		return update(name, obj);
834 	}
835 
836 	/**
837 	 * Run consistency checks against the object database.
838 	 * <p>
839 	 * This method completes silently if the checks pass. A temporary revision
840 	 * pool is constructed during the checking.
841 	 *
842 	 * @param tips
843 	 *            the tips to start checking from; if not supplied the refs of
844 	 *            the repository are used instead.
845 	 * @throws MissingObjectException
846 	 * @throws IncorrectObjectTypeException
847 	 * @throws IOException
848 	 */
849 	public void fsck(RevObject... tips) throws MissingObjectException,
850 			IncorrectObjectTypeException, IOException {
851 		try (ObjectWalkectWalk.html#ObjectWalk">ObjectWalk ow = new ObjectWalk(db)) {
852 			if (tips.length != 0) {
853 				for (RevObject o : tips)
854 					ow.markStart(ow.parseAny(o));
855 			} else {
856 				for (Ref r : db.getRefDatabase().getRefs())
857 					ow.markStart(ow.parseAny(r.getObjectId()));
858 			}
859 
860 			ObjectChecker oc = new ObjectChecker();
861 			for (;;) {
862 				final RevCommit o = ow.next();
863 				if (o == null)
864 					break;
865 
866 				final byte[] bin = db.open(o, o.getType()).getCachedBytes();
867 				oc.checkCommit(o, bin);
868 				assertHash(o, bin);
869 			}
870 
871 			for (;;) {
872 				final RevObject o = ow.nextObject();
873 				if (o == null)
874 					break;
875 
876 				final byte[] bin = db.open(o, o.getType()).getCachedBytes();
877 				oc.check(o, o.getType(), bin);
878 				assertHash(o, bin);
879 			}
880 		}
881 	}
882 
883 	private static void assertHash(RevObject id, byte[] bin) {
884 		MessageDigest md = Constants.newMessageDigest();
885 		md.update(Constants.encodedTypeString(id.getType()));
886 		md.update((byte) ' ');
887 		md.update(Constants.encodeASCII(bin.length));
888 		md.update((byte) 0);
889 		md.update(bin);
890 		assertEquals(id, ObjectId.fromRaw(md.digest()));
891 	}
892 
893 	/**
894 	 * Pack all reachable objects in the repository into a single pack file.
895 	 * <p>
896 	 * All loose objects are automatically pruned. Existing packs however are
897 	 * not removed.
898 	 *
899 	 * @throws Exception
900 	 */
901 	public void packAndPrune() throws Exception {
902 		if (db.getObjectDatabase() instanceof ObjectDirectory) {
903 			ObjectDirectory odb = (ObjectDirectory) db.getObjectDatabase();
904 			NullProgressMonitor m = NullProgressMonitor.INSTANCE;
905 
906 			final File pack, idx;
907 			try (PackWriterorage/pack/PackWriter.html#PackWriter">PackWriter pw = new PackWriter(db)) {
908 				Set<ObjectId> all = new HashSet<>();
909 				for (Ref r : db.getRefDatabase().getRefs())
910 					all.add(r.getObjectId());
911 				pw.preparePack(m, all, PackWriter.NONE);
912 
913 				final ObjectId name = pw.computeName();
914 
915 				pack = nameFor(odb, name, ".pack");
916 				try (OutputStream out =
917 						new BufferedOutputStream(new FileOutputStream(pack))) {
918 					pw.writePack(m, m, out);
919 				}
920 				pack.setReadOnly();
921 
922 				idx = nameFor(odb, name, ".idx");
923 				try (OutputStream out =
924 						new BufferedOutputStream(new FileOutputStream(idx))) {
925 					pw.writeIndex(out);
926 				}
927 				idx.setReadOnly();
928 			}
929 
930 			odb.openPack(pack);
931 			updateServerInfo();
932 			prunePacked(odb);
933 		}
934 	}
935 
936 	/**
937 	 * Closes the underlying {@link Repository} object and any other internal
938 	 * resources.
939 	 * <p>
940 	 * {@link AutoCloseable} resources that may escape this object, such as
941 	 * those returned by the {@link #git} and {@link #getRevWalk()} methods are
942 	 * not closed.
943 	 */
944 	@Override
945 	public void close() {
946 		try {
947 			inserter.close();
948 		} finally {
949 			db.close();
950 		}
951 	}
952 
953 	private static void prunePacked(ObjectDirectory odb) throws IOException {
954 		for (PackFile p : odb.getPacks()) {
955 			for (MutableEntry e : p)
956 				FileUtils.delete(odb.fileFor(e.toObjectId()));
957 		}
958 	}
959 
960 	private static File nameFor(ObjectDirectory odb, ObjectId name, String t) {
961 		File packdir = odb.getPackDirectory();
962 		return new File(packdir, "pack-" + name.name() + t);
963 	}
964 
965 	private void writeFile(File p, byte[] bin) throws IOException,
966 			ObjectWritingException {
967 		final LockFiletorage/file/LockFile.html#LockFile">LockFile lck = new LockFile(p);
968 		if (!lck.lock())
969 			throw new ObjectWritingException("Can't write " + p);
970 		try {
971 			lck.write(bin);
972 		} catch (IOException ioe) {
973 			throw new ObjectWritingException("Can't write " + p);
974 		}
975 		if (!lck.commit())
976 			throw new ObjectWritingException("Can't write " + p);
977 	}
978 
979 	/** Helper to build a branch with one or more commits */
980 	public class BranchBuilder {
981 		private final String ref;
982 
983 		BranchBuilder(String ref) {
984 			this.ref = ref;
985 		}
986 
987 		/**
988 		 * @return construct a new commit builder that updates this branch. If
989 		 *         the branch already exists, the commit builder will have its
990 		 *         first parent as the current commit and its tree will be
991 		 *         initialized to the current files.
992 		 * @throws Exception
993 		 *             the commit builder can't read the current branch state
994 		 */
995 		public CommitBuilder commit() throws Exception {
996 			return new CommitBuilder(this);
997 		}
998 
999 		/**
1000 		 * Forcefully update this branch to a particular commit.
1001 		 *
1002 		 * @param to
1003 		 *            the commit to update to.
1004 		 * @return {@code to}.
1005 		 * @throws Exception
1006 		 */
1007 		public RevCommit update(CommitBuilder to) throws Exception {
1008 			return update(to.create());
1009 		}
1010 
1011 		/**
1012 		 * Forcefully update this branch to a particular commit.
1013 		 *
1014 		 * @param to
1015 		 *            the commit to update to.
1016 		 * @return {@code to}.
1017 		 * @throws Exception
1018 		 */
1019 		public RevCommit../../../../org/eclipse/jgit/revwalk/RevCommit.html#RevCommit">RevCommit update(RevCommit to) throws Exception {
1020 			return TestRepository.this.update(ref, to);
1021 		}
1022 
1023 		/**
1024 		 * Delete this branch.
1025 		 * @throws Exception
1026 		 * @since 4.4
1027 		 */
1028 		public void delete() throws Exception {
1029 			TestRepository.this.delete(ref);
1030 		}
1031 	}
1032 
1033 	/** Helper to generate a commit. */
1034 	public class CommitBuilder {
1035 		private final BranchBuilder branch;
1036 
1037 		private final DirCache tree = DirCache.newInCore();
1038 
1039 		private ObjectId topLevelTree;
1040 
1041 		private final List<RevCommit> parents = new ArrayList<>(2);
1042 
1043 		private int tick = 1;
1044 
1045 		private String message = "";
1046 
1047 		private RevCommit self;
1048 
1049 		private PersonIdent author;
1050 		private PersonIdent committer;
1051 
1052 		private String changeId;
1053 
1054 		private boolean updateCommitterTime;
1055 
1056 		CommitBuilder() {
1057 			branch = null;
1058 		}
1059 
1060 		CommitBuilder(BranchBuilder b) throws Exception {
1061 			branch = b;
1062 
1063 			Ref ref = db.exactRef(branch.ref);
1064 			if (ref != null && ref.getObjectId() != null)
1065 				parent(pool.parseCommit(ref.getObjectId()));
1066 		}
1067 
1068 		CommitBuilder(CommitBuilder prior) throws Exception {
1069 			branch = prior.branch;
1070 
1071 			DirCacheBuilder b = tree.builder();
1072 			for (int i = 0; i < prior.tree.getEntryCount(); i++)
1073 				b.add(prior.tree.getEntry(i));
1074 			b.finish();
1075 
1076 			parents.add(prior.create());
1077 		}
1078 
1079 		public CommitBuilder parent(RevCommit p) throws Exception {
1080 			if (parents.isEmpty()) {
1081 				DirCacheBuilder b = tree.builder();
1082 				parseBody(p);
1083 				b.addTree(new byte[0], DirCacheEntry.STAGE_0, pool
1084 						.getObjectReader(), p.getTree());
1085 				b.finish();
1086 			}
1087 			parents.add(p);
1088 			return this;
1089 		}
1090 
1091 		public List<RevCommit> parents() {
1092 			return Collections.unmodifiableList(parents);
1093 		}
1094 
1095 		public CommitBuilder noParents() {
1096 			parents.clear();
1097 			return this;
1098 		}
1099 
1100 		public CommitBuilder noFiles() {
1101 			tree.clear();
1102 			return this;
1103 		}
1104 
1105 		public CommitBuilder setTopLevelTree(ObjectId treeId) {
1106 			topLevelTree = treeId;
1107 			return this;
1108 		}
1109 
1110 		public CommitBuilder add(String path, String content) throws Exception {
1111 			return add(path, blob(content));
1112 		}
1113 
1114 		public CommitBuilder add(String path, RevBlob id)
1115 				throws Exception {
1116 			return edit(new PathEdit(path) {
1117 				@Override
1118 				public void apply(DirCacheEntry ent) {
1119 					ent.setFileMode(FileMode.REGULAR_FILE);
1120 					ent.setObjectId(id);
1121 				}
1122 			});
1123 		}
1124 
1125 		public CommitBuilder edit(PathEdit edit) {
1126 			DirCacheEditor e = tree.editor();
1127 			e.add(edit);
1128 			e.finish();
1129 			return this;
1130 		}
1131 
1132 		public CommitBuilder rm(String path) {
1133 			DirCacheEditor e = tree.editor();
1134 			e.add(new DeletePath(path));
1135 			e.add(new DeleteTree(path));
1136 			e.finish();
1137 			return this;
1138 		}
1139 
1140 		public CommitBuilder message(String m) {
1141 			message = m;
1142 			return this;
1143 		}
1144 
1145 		public String message() {
1146 			return message;
1147 		}
1148 
1149 		public CommitBuilder tick(int secs) {
1150 			tick = secs;
1151 			return this;
1152 		}
1153 
1154 		public CommitBuilder ident(PersonIdent ident) {
1155 			author = ident;
1156 			committer = ident;
1157 			return this;
1158 		}
1159 
1160 		public CommitBuilder author(PersonIdent a) {
1161 			author = a;
1162 			return this;
1163 		}
1164 
1165 		public PersonIdent author() {
1166 			return author;
1167 		}
1168 
1169 		public CommitBuilder committer(PersonIdent c) {
1170 			committer = c;
1171 			return this;
1172 		}
1173 
1174 		public PersonIdent committer() {
1175 			return committer;
1176 		}
1177 
1178 		public CommitBuilder insertChangeId() {
1179 			changeId = "";
1180 			return this;
1181 		}
1182 
1183 		public CommitBuilder insertChangeId(String c) {
1184 			// Validate, but store as a string so we can use "" as a sentinel.
1185 			ObjectId.fromString(c);
1186 			changeId = c;
1187 			return this;
1188 		}
1189 
1190 		public RevCommit create() throws Exception {
1191 			if (self == null) {
1192 				TestRepository.this.tick(tick);
1193 
1194 				final org.eclipse.jgit.lib.CommitBuilder c;
1195 
1196 				c = new org.eclipse.jgit.lib.CommitBuilder();
1197 				c.setParentIds(parents);
1198 				setAuthorAndCommitter(c);
1199 				if (author != null)
1200 					c.setAuthor(author);
1201 				if (committer != null) {
1202 					if (updateCommitterTime)
1203 						committer = new PersonIdent(committer, getDate());
1204 					c.setCommitter(committer);
1205 				}
1206 
1207 				ObjectId commitId;
1208 				try (ObjectInserter ins = inserter) {
1209 					if (topLevelTree != null)
1210 						c.setTreeId(topLevelTree);
1211 					else
1212 						c.setTreeId(tree.writeTree(ins));
1213 					insertChangeId(c);
1214 					c.setMessage(message);
1215 					commitId = ins.insert(c);
1216 					ins.flush();
1217 				}
1218 				self = pool.parseCommit(commitId);
1219 
1220 				if (branch != null)
1221 					branch.update(self);
1222 			}
1223 			return self;
1224 		}
1225 
1226 		private void insertChangeId(org.eclipse.jgit.lib.CommitBuilder c) {
1227 			if (changeId == null)
1228 				return;
1229 			int idx = ChangeIdUtil.indexOfChangeId(message, "\n");
1230 			if (idx >= 0)
1231 				return;
1232 
1233 			ObjectId firstParentId = null;
1234 			if (!parents.isEmpty())
1235 				firstParentId = parents.get(0);
1236 
1237 			ObjectId cid;
1238 			if (changeId.isEmpty())
1239 				cid = ChangeIdUtil.computeChangeId(c.getTreeId(), firstParentId,
1240 						c.getAuthor(), c.getCommitter(), message);
1241 			else
1242 				cid = ObjectId.fromString(changeId);
1243 			message = ChangeIdUtil.insertId(message, cid);
1244 			if (cid != null)
1245 				message = message.replaceAll("\nChange-Id: I" //$NON-NLS-1$
1246 						+ ObjectId.zeroId().getName() + "\n", "\nChange-Id: I" //$NON-NLS-1$ //$NON-NLS-2$
1247 						+ cid.getName() + "\n"); //$NON-NLS-1$
1248 		}
1249 
1250 		public CommitBuilder child() throws Exception {
1251 			return new CommitBuilder(this);
1252 		}
1253 	}
1254 }