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