View Javadoc
1   /*
2    * Copyright (C) 2009, Google Inc.
3    * Copyright (C) 2007-2008, Robin Rosenberg <robin.rosenberg@dewire.com>
4    * Copyright (C) 2006-2007, Shawn O. Pearce <spearce@spearce.org>
5    * Copyright (C) 2009, Yann Simon <yann.simon.fr@gmail.com> and others
6    *
7    * This program and the accompanying materials are made available under the
8    * terms of the Eclipse Distribution License v. 1.0 which is available at
9    * https://www.eclipse.org/org/documents/edl-v10.php.
10   *
11   * SPDX-License-Identifier: BSD-3-Clause
12   */
13  
14  package org.eclipse.jgit.junit;
15  
16  import static java.nio.charset.StandardCharsets.UTF_8;
17  import static org.junit.Assert.assertEquals;
18  
19  import java.io.File;
20  import java.io.FileInputStream;
21  import java.io.FileNotFoundException;
22  import java.io.FileOutputStream;
23  import java.io.IOException;
24  import java.io.InputStreamReader;
25  import java.io.Reader;
26  import java.nio.file.Path;
27  import java.time.Instant;
28  import java.util.Map;
29  import java.util.concurrent.TimeUnit;
30  
31  import org.eclipse.jgit.api.Git;
32  import org.eclipse.jgit.api.errors.GitAPIException;
33  import org.eclipse.jgit.dircache.DirCacheBuilder;
34  import org.eclipse.jgit.dircache.DirCacheCheckout;
35  import org.eclipse.jgit.dircache.DirCacheEntry;
36  import org.eclipse.jgit.internal.storage.file.FileRepository;
37  import org.eclipse.jgit.lib.AnyObjectId;
38  import org.eclipse.jgit.lib.Constants;
39  import org.eclipse.jgit.lib.FileMode;
40  import org.eclipse.jgit.lib.ObjectId;
41  import org.eclipse.jgit.lib.ObjectInserter;
42  import org.eclipse.jgit.lib.RefUpdate;
43  import org.eclipse.jgit.lib.Repository;
44  import org.eclipse.jgit.revwalk.RevCommit;
45  import org.eclipse.jgit.revwalk.RevWalk;
46  import org.eclipse.jgit.treewalk.FileTreeIterator;
47  import org.eclipse.jgit.util.FS;
48  import org.eclipse.jgit.util.FileUtils;
49  import org.junit.After;
50  import org.junit.Before;
51  
52  /**
53   * Base class for most JGit unit tests.
54   *
55   * Sets up a predefined test repository and has support for creating additional
56   * repositories and destroying them when the tests are finished.
57   */
58  public abstract class RepositoryTestCase extends LocalDiskRepositoryTestCase {
59  	/**
60  	 * Copy a file
61  	 *
62  	 * @param src
63  	 * @param dst
64  	 * @throws IOException
65  	 */
66  	protected static void copyFile(File src, File dst)
67  			throws IOException {
68  		try (FileInputStream fis = new FileInputStream(src);
69  				FileOutputStream fos = new FileOutputStream(dst)) {
70  			final byte[] buf = new byte[4096];
71  			int r;
72  			while ((r = fis.read(buf)) > 0) {
73  				fos.write(buf, 0, r);
74  			}
75  		}
76  	}
77  
78  	/**
79  	 * Write a trash file
80  	 *
81  	 * @param name
82  	 * @param data
83  	 * @return the trash file
84  	 * @throws IOException
85  	 */
86  	protected File writeTrashFile(String name, String data)
87  			throws IOException {
88  		return JGitTestUtil.writeTrashFile(db, name, data);
89  	}
90  
91  	/**
92  	 * Create a symbolic link
93  	 *
94  	 * @param link
95  	 *            the path of the symbolic link to create
96  	 * @param target
97  	 *            the target of the symbolic link
98  	 * @return the path to the symbolic link
99  	 * @throws Exception
100 	 * @since 4.2
101 	 */
102 	protected Path writeLink(String link, String target)
103 			throws Exception {
104 		return JGitTestUtil.writeLink(db, link, target);
105 	}
106 
107 	/**
108 	 * Write a trash file
109 	 *
110 	 * @param subdir
111 	 * @param name
112 	 * @param data
113 	 * @return the trash file
114 	 * @throws IOException
115 	 */
116 	protected File writeTrashFile(final String subdir, final String name,
117 			final String data)
118 			throws IOException {
119 		return JGitTestUtil.writeTrashFile(db, subdir, name, data);
120 	}
121 
122 	/**
123 	 * Read content of a file
124 	 *
125 	 * @param name
126 	 * @return the file's content
127 	 * @throws IOException
128 	 */
129 	protected String read(String name) throws IOException {
130 		return JGitTestUtil.read(db, name);
131 	}
132 
133 	/**
134 	 * Check if file exists
135 	 *
136 	 * @param name
137 	 *            file name
138 	 * @return if the file exists
139 	 */
140 	protected boolean check(String name) {
141 		return JGitTestUtil.check(db, name);
142 	}
143 
144 	/**
145 	 * Delete a trash file
146 	 *
147 	 * @param name
148 	 *            file name
149 	 * @throws IOException
150 	 */
151 	protected void deleteTrashFile(String name) throws IOException {
152 		JGitTestUtil.deleteTrashFile(db, name);
153 	}
154 
155 	/**
156 	 * Check content of a file.
157 	 *
158 	 * @param f
159 	 * @param checkData
160 	 *            expected content
161 	 * @throws IOException
162 	 */
163 	protected static void checkFile(File f, String checkData)
164 			throws IOException {
165 		try (Reader r = new InputStreamReader(new FileInputStream(f),
166 				UTF_8)) {
167 			if (checkData.length() > 0) {
168 				char[] data = new char[checkData.length()];
169 				assertEquals(data.length, r.read(data));
170 				assertEquals(checkData, new String(data));
171 			}
172 			assertEquals(-1, r.read());
173 		}
174 	}
175 
176 	/** Test repository, initialized for this test case. */
177 	protected FileRepository db;
178 
179 	/** Working directory of {@link #db}. */
180 	protected File trash;
181 
182 	/** {@inheritDoc} */
183 	@Override
184 	@Before
185 	public void setUp() throws Exception {
186 		super.setUp();
187 		db = createWorkRepository();
188 		trash = db.getWorkTree();
189 	}
190 
191 	@Override
192 	@After
193 	public void tearDown() throws Exception {
194 		db.close();
195 		super.tearDown();
196 	}
197 
198 	/**
199 	 * Represent the state of the index in one String. This representation is
200 	 * useful when writing tests which do assertions on the state of the index.
201 	 * By default information about path, mode, stage (if different from 0) is
202 	 * included. A bitmask controls which additional info about
203 	 * modificationTimes, smudge state and length is included.
204 	 * <p>
205 	 * The format of the returned string is described with this BNF:
206 	 *
207 	 * <pre>
208 	 * result = ( "[" path mode stage? time? smudge? length? sha1? content? "]" )* .
209 	 * mode = ", mode:" number .
210 	 * stage = ", stage:" number .
211 	 * time = ", time:t" timestamp-index .
212 	 * smudge = "" | ", smudged" .
213 	 * length = ", length:" number .
214 	 * sha1 = ", sha1:" hex-sha1 .
215 	 * content = ", content:" blob-data .
216 	 * </pre>
217 	 *
218 	 * 'stage' is only presented when the stage is different from 0. All
219 	 * reported time stamps are mapped to strings like "t0", "t1", ... "tn". The
220 	 * smallest reported time-stamp will be called "t0". This allows to write
221 	 * assertions against the string although the concrete value of the time
222 	 * stamps is unknown.
223 	 *
224 	 * @param includedOptions
225 	 *            a bitmask constructed out of the constants {@link #MOD_TIME},
226 	 *            {@link #SMUDGE}, {@link #LENGTH}, {@link #CONTENT_ID} and
227 	 *            {@link #CONTENT} controlling which info is present in the
228 	 *            resulting string.
229 	 * @return a string encoding the index state
230 	 * @throws IllegalStateException
231 	 * @throws IOException
232 	 */
233 	public String indexState(int includedOptions)
234 			throws IllegalStateException, IOException {
235 		return indexState(db, includedOptions);
236 	}
237 
238 	/**
239 	 * Resets the index to represent exactly some filesystem content. E.g. the
240 	 * following call will replace the index with the working tree content:
241 	 * <p>
242 	 * <code>resetIndex(new FileSystemIterator(db))</code>
243 	 * <p>
244 	 * This method can be used by testcases which first prepare a new commit
245 	 * somewhere in the filesystem (e.g. in the working-tree) and then want to
246 	 * have an index which matches their prepared content.
247 	 *
248 	 * @param treeItr
249 	 *            a {@link org.eclipse.jgit.treewalk.FileTreeIterator} which
250 	 *            determines which files should go into the new index
251 	 * @throws FileNotFoundException
252 	 * @throws IOException
253 	 */
254 	protected void resetIndex(FileTreeIterator treeItr)
255 			throws FileNotFoundException, IOException {
256 		try (ObjectInserter inserter = db.newObjectInserter()) {
257 			DirCacheBuilder builder = db.lockDirCache().builder();
258 			DirCacheEntry dce;
259 
260 			while (!treeItr.eof()) {
261 				long len = treeItr.getEntryLength();
262 
263 				dce = new DirCacheEntry(treeItr.getEntryPathString());
264 				dce.setFileMode(treeItr.getEntryFileMode());
265 				dce.setLastModified(treeItr.getEntryLastModifiedInstant());
266 				dce.setLength((int) len);
267 				try (FileInputStream in = new FileInputStream(
268 						treeItr.getEntryFile())) {
269 					dce.setObjectId(
270 							inserter.insert(Constants.OBJ_BLOB, len, in));
271 				}
272 				builder.add(dce);
273 				treeItr.next(1);
274 			}
275 			builder.commit();
276 			inserter.flush();
277 		}
278 	}
279 
280 	/**
281 	 * Helper method to map arbitrary objects to user-defined names. This can be
282 	 * used create short names for objects to produce small and stable debug
283 	 * output. It is guaranteed that when you lookup the same object multiple
284 	 * times even with different nameTemplates this method will always return
285 	 * the same name which was derived from the first nameTemplate.
286 	 * nameTemplates can contain "%n" which will be replaced by a running number
287 	 * before used as a name.
288 	 *
289 	 * @param l
290 	 *            the object to lookup
291 	 * @param lookupTable
292 	 *            a table storing object-name mappings.
293 	 * @param nameTemplate
294 	 *            the name for that object. Can contain "%n" which will be
295 	 *            replaced by a running number before used as a name. If the
296 	 *            lookup table already contains the object this parameter will
297 	 *            be ignored
298 	 * @return a name of that object. Is not guaranteed to be unique. Use
299 	 *         nameTemplates containing "%n" to always have unique names
300 	 */
301 	public static String lookup(Object l, String nameTemplate,
302 			Map<Object, String> lookupTable) {
303 		String name = lookupTable.get(l);
304 		if (name == null) {
305 			name = nameTemplate.replaceAll("%n",
306 					Integer.toString(lookupTable.size()));
307 			lookupTable.put(l, name);
308 		}
309 		return name;
310 	}
311 
312 	/**
313 	 * Replaces '\' by '/'
314 	 *
315 	 * @param str
316 	 *            the string in which backslashes should be replaced
317 	 * @return the resulting string with slashes
318 	 * @since 4.2
319 	 */
320 	public static String slashify(String str) {
321 		str = str.replace('\\', '/');
322 		return str;
323 	}
324 
325 	/**
326 	 * Waits until it is guaranteed that a subsequent file modification has a
327 	 * younger modification timestamp than the modification timestamp of the
328 	 * given file. This is done by touching a temporary file, reading the
329 	 * lastmodified attribute and, if needed, sleeping. After sleeping this loop
330 	 * starts again until the filesystem timer has advanced enough. The
331 	 * temporary file will be created as a sibling of lastFile.
332 	 *
333 	 * @param lastFile
334 	 *            the file on which we want to wait until the filesystem timer
335 	 *            has advanced more than the lastmodification timestamp of this
336 	 *            file
337 	 * @return return the last measured value of the filesystem timer which is
338 	 *         greater than then the lastmodification time of lastfile.
339 	 * @throws InterruptedException
340 	 * @throws IOException
341 	 */
342 	public static Instant fsTick(File lastFile)
343 			throws InterruptedException,
344 			IOException {
345 		File tmp;
346 		FS fs = FS.DETECTED;
347 		if (lastFile == null) {
348 			lastFile = tmp = File
349 					.createTempFile("fsTickTmpFile", null);
350 		} else {
351 			if (!fs.exists(lastFile)) {
352 				throw new FileNotFoundException(lastFile.getPath());
353 			}
354 			tmp = File.createTempFile("fsTickTmpFile", null,
355 					lastFile.getParentFile());
356 		}
357 		long res = FS.getFileStoreAttributes(tmp.toPath())
358 				.getFsTimestampResolution().toNanos();
359 		long sleepTime = res / 10;
360 		try {
361 			Instant startTime = fs.lastModifiedInstant(lastFile);
362 			Instant actTime = fs.lastModifiedInstant(tmp);
363 			while (actTime.compareTo(startTime) <= 0) {
364 				TimeUnit.NANOSECONDS.sleep(sleepTime);
365 				FileUtils.touch(tmp.toPath());
366 				actTime = fs.lastModifiedInstant(tmp);
367 			}
368 			return actTime;
369 		} finally {
370 			FileUtils.delete(tmp);
371 		}
372 	}
373 
374 	/**
375 	 * Create a branch
376 	 *
377 	 * @param objectId
378 	 * @param branchName
379 	 * @throws IOException
380 	 */
381 	protected void createBranch(ObjectId objectId, String branchName)
382 			throws IOException {
383 		RefUpdate updateRef = db.updateRef(branchName);
384 		updateRef.setNewObjectId(objectId);
385 		updateRef.update();
386 	}
387 
388 	/**
389 	 * Checkout a branch
390 	 *
391 	 * @param branchName
392 	 * @throws IllegalStateException
393 	 * @throws IOException
394 	 */
395 	protected void checkoutBranch(String branchName)
396 			throws IllegalStateException, IOException {
397 		try (RevWalkvWalk.html#RevWalk">RevWalk walk = new RevWalk(db)) {
398 			RevCommit head = walk.parseCommit(db.resolve(Constants.HEAD));
399 			RevCommit branch = walk.parseCommit(db.resolve(branchName));
400 			DirCacheCheckout dco = new DirCacheCheckout(db,
401 					head.getTree().getId(), db.lockDirCache(),
402 					branch.getTree().getId());
403 			dco.setFailOnConflict(true);
404 			dco.checkout();
405 		}
406 		// update the HEAD
407 		RefUpdate refUpdate = db.updateRef(Constants.HEAD);
408 		refUpdate.setRefLogMessage("checkout: moving to " + branchName, false);
409 		refUpdate.link(branchName);
410 	}
411 
412 	/**
413 	 * Writes a number of files in the working tree. The first content specified
414 	 * will be written into a file named '0', the second into a file named "1"
415 	 * and so on. If <code>null</code> is specified as content then this file is
416 	 * skipped.
417 	 *
418 	 * @param ensureDistinctTimestamps
419 	 *            if set to <code>true</code> then between two write operations
420 	 *            this method will wait to ensure that the second file will get
421 	 *            a different lastmodification timestamp than the first file.
422 	 * @param contents
423 	 *            the contents which should be written into the files
424 	 * @return the File object associated to the last written file.
425 	 * @throws IOException
426 	 * @throws InterruptedException
427 	 */
428 	protected File writeTrashFiles(boolean ensureDistinctTimestamps,
429 			String... contents)
430 			throws IOException, InterruptedException {
431 				File f = null;
432 				for (int i = 0; i < contents.length; i++)
433 					if (contents[i] != null) {
434 						if (ensureDistinctTimestamps && (f != null))
435 							fsTick(f);
436 						f = writeTrashFile(Integer.toString(i), contents[i]);
437 					}
438 				return f;
439 			}
440 
441 	/**
442 	 * Commit a file with the specified contents on the specified branch,
443 	 * creating the branch if it didn't exist before.
444 	 * <p>
445 	 * It switches back to the original branch after the commit if there was
446 	 * one.
447 	 *
448 	 * @param filename
449 	 * @param contents
450 	 * @param branch
451 	 * @return the created commit
452 	 */
453 	protected RevCommit commitFile(String filename, String contents, String branch) {
454 		try (Gitit.html#Git">Git git = new Git(db)) {
455 			Repository repo = git.getRepository();
456 			String originalBranch = repo.getFullBranch();
457 			boolean empty = repo.resolve(Constants.HEAD) == null;
458 			if (!empty) {
459 				if (repo.findRef(branch) == null)
460 					git.branchCreate().setName(branch).call();
461 				git.checkout().setName(branch).call();
462 			}
463 
464 			writeTrashFile(filename, contents);
465 			git.add().addFilepattern(filename).call();
466 			RevCommit commit = git.commit()
467 					.setMessage(branch + ": " + filename).call();
468 
469 			if (originalBranch != null)
470 				git.checkout().setName(originalBranch).call();
471 			else if (empty)
472 				git.branchCreate().setName(branch).setStartPoint(commit).call();
473 
474 			return commit;
475 		} catch (IOException | GitAPIException e) {
476 			throw new RuntimeException(e);
477 		}
478 	}
479 
480 	/**
481 	 * Create <code>DirCacheEntry</code>
482 	 *
483 	 * @param path
484 	 * @param mode
485 	 * @return the DirCacheEntry
486 	 */
487 	protected DirCacheEntry createEntry(String path, FileMode mode) {
488 		return createEntry(path, mode, DirCacheEntry.STAGE_0, path);
489 	}
490 
491 	/**
492 	 * Create <code>DirCacheEntry</code>
493 	 *
494 	 * @param path
495 	 * @param mode
496 	 * @param content
497 	 * @return the DirCacheEntry
498 	 */
499 	protected DirCacheEntry createEntry(final String path, final FileMode mode,
500 			final String content) {
501 		return createEntry(path, mode, DirCacheEntry.STAGE_0, content);
502 	}
503 
504 	/**
505 	 * Create <code>DirCacheEntry</code>
506 	 *
507 	 * @param path
508 	 * @param mode
509 	 * @param stage
510 	 * @param content
511 	 * @return the DirCacheEntry
512 	 */
513 	protected DirCacheEntry createEntry(final String path, final FileMode mode,
514 			final int stage, final String content) {
515 		final DirCacheEntryEntry.html#DirCacheEntry">DirCacheEntry entry = new DirCacheEntry(path, stage);
516 		entry.setFileMode(mode);
517 		try (ObjectInserter.Formatter formatter = new ObjectInserter.Formatter()) {
518 			entry.setObjectId(formatter.idFor(
519 					Constants.OBJ_BLOB, Constants.encode(content)));
520 		}
521 		return entry;
522 	}
523 
524 	/**
525 	 * Create <code>DirCacheEntry</code>
526 	 *
527 	 * @param path
528 	 * @param objectId
529 	 * @return the DirCacheEntry
530 	 */
531 	protected DirCacheEntry createGitLink(String path, AnyObjectId objectId) {
532 		final DirCacheEntryEntry.html#DirCacheEntry">DirCacheEntry entry = new DirCacheEntry(path,
533 				DirCacheEntry.STAGE_0);
534 		entry.setFileMode(FileMode.GITLINK);
535 		entry.setObjectId(objectId);
536 		return entry;
537 	}
538 
539 	/**
540 	 * Assert files are equal
541 	 *
542 	 * @param expected
543 	 * @param actual
544 	 * @throws IOException
545 	 */
546 	public static void assertEqualsFile(File expected, File actual)
547 			throws IOException {
548 		assertEquals(expected.getCanonicalFile(), actual.getCanonicalFile());
549 	}
550 }