View Javadoc
1   /*
2    * Copyright (C) 2009-2010, Google Inc.
3    * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
4    * Copyright (C) 2007, Shawn O. Pearce <spearce@spearce.org>
5    * and other copyright owners as documented in the project's IP log.
6    *
7    * This program and the accompanying materials are made available
8    * under the terms of the Eclipse Distribution License v1.0 which
9    * accompanies this distribution, is reproduced below, and is
10   * available at http://www.eclipse.org/org/documents/edl-v10.php
11   *
12   * All rights reserved.
13   *
14   * Redistribution and use in source and binary forms, with or
15   * without modification, are permitted provided that the following
16   * conditions are met:
17   *
18   * - Redistributions of source code must retain the above copyright
19   *   notice, this list of conditions and the following disclaimer.
20   *
21   * - Redistributions in binary form must reproduce the above
22   *   copyright notice, this list of conditions and the following
23   *   disclaimer in the documentation and/or other materials provided
24   *   with the distribution.
25   *
26   * - Neither the name of the Eclipse Foundation, Inc. nor the
27   *   names of its contributors may be used to endorse or promote
28   *   products derived from this software without specific prior
29   *   written permission.
30   *
31   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
32   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
33   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
36   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
39   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
40   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
41   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
42   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
43   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44   */
45  
46  package org.eclipse.jgit.junit;
47  
48  import static java.nio.charset.StandardCharsets.UTF_8;
49  import static org.junit.Assert.assertFalse;
50  import static org.junit.Assert.fail;
51  
52  import java.io.File;
53  import java.io.IOException;
54  import java.util.ArrayList;
55  import java.util.Collections;
56  import java.util.HashMap;
57  import java.util.HashSet;
58  import java.util.List;
59  import java.util.Map;
60  import java.util.Set;
61  import java.util.TreeSet;
62  
63  import org.eclipse.jgit.dircache.DirCache;
64  import org.eclipse.jgit.dircache.DirCacheEntry;
65  import org.eclipse.jgit.internal.storage.file.FileRepository;
66  import org.eclipse.jgit.lib.ConfigConstants;
67  import org.eclipse.jgit.lib.Constants;
68  import org.eclipse.jgit.lib.ObjectId;
69  import org.eclipse.jgit.lib.PersonIdent;
70  import org.eclipse.jgit.lib.Repository;
71  import org.eclipse.jgit.lib.RepositoryCache;
72  import org.eclipse.jgit.storage.file.FileBasedConfig;
73  import org.eclipse.jgit.storage.file.WindowCacheConfig;
74  import org.eclipse.jgit.util.FS;
75  import org.eclipse.jgit.util.FileUtils;
76  import org.eclipse.jgit.util.SystemReader;
77  import org.junit.After;
78  import org.junit.Before;
79  
80  /**
81   * JUnit TestCase with specialized support for temporary local repository.
82   * <p>
83   * A temporary directory is created for each test, allowing each test to use a
84   * fresh environment. The temporary directory is cleaned up after the test ends.
85   * <p>
86   * Callers should not use {@link org.eclipse.jgit.lib.RepositoryCache} from
87   * within these tests as it may wedge file descriptors open past the end of the
88   * test.
89   * <p>
90   * A system property {@code jgit.junit.usemmap} defines whether memory mapping
91   * is used. Memory mapping has an effect on the file system, in that memory
92   * mapped files in Java cannot be deleted as long as the mapped arrays have not
93   * been reclaimed by the garbage collector. The programmer cannot control this
94   * with precision, so temporary files may hang around longer than desired during
95   * a test, or tests may fail altogether if there is insufficient file
96   * descriptors or address space for the test process.
97   */
98  public abstract class LocalDiskRepositoryTestCase {
99  	private static final boolean useMMAP = "true".equals(System
100 			.getProperty("jgit.junit.usemmap"));
101 
102 	/** A fake (but stable) identity for author fields in the test. */
103 	protected PersonIdent author;
104 
105 	/** A fake (but stable) identity for committer fields in the test. */
106 	protected PersonIdent committer;
107 
108 	/**
109 	 * A {@link SystemReader} used to coordinate time, envars, etc.
110 	 * @since 4.2
111 	 */
112 	protected MockSystemReader mockSystemReader;
113 
114 	private final Set<Repository> toClose = new HashSet<>();
115 	private File tmp;
116 
117 	/**
118 	 * Setup test
119 	 *
120 	 * @throws Exception
121 	 */
122 	@Before
123 	public void setUp() throws Exception {
124 		tmp = File.createTempFile("jgit_test_", "_tmp");
125 		CleanupThread.deleteOnShutdown(tmp);
126 		if (!tmp.delete() || !tmp.mkdir())
127 			throw new IOException("Cannot create " + tmp);
128 
129 		mockSystemReader = new MockSystemReader();
130 		mockSystemReader.userGitConfig = new FileBasedConfig(new File(tmp,
131 				"usergitconfig"), FS.DETECTED);
132 		// We have to set autoDetach to false for tests, because tests expect to be able
133 		// to clean up by recursively removing the repository, and background GC might be
134 		// in the middle of writing or deleting files, which would disrupt this.
135 		mockSystemReader.userGitConfig.setBoolean(ConfigConstants.CONFIG_GC_SECTION,
136 				null, ConfigConstants.CONFIG_KEY_AUTODETACH, false);
137 		mockSystemReader.userGitConfig.save();
138 		ceilTestDirectories(getCeilings());
139 		SystemReader.setInstance(mockSystemReader);
140 
141 		author = new PersonIdent("J. Author", "jauthor@example.com");
142 		committer = new PersonIdent("J. Committer", "jcommitter@example.com");
143 
144 		final WindowCacheConfig c = new WindowCacheConfig();
145 		c.setPackedGitLimit(128 * WindowCacheConfig.KB);
146 		c.setPackedGitWindowSize(8 * WindowCacheConfig.KB);
147 		c.setPackedGitMMAP(useMMAP);
148 		c.setDeltaBaseCacheLimit(8 * WindowCacheConfig.KB);
149 		c.install();
150 	}
151 
152 	/**
153 	 * Get temporary directory.
154 	 *
155 	 * @return the temporary directory
156 	 */
157 	protected File getTemporaryDirectory() {
158 		return tmp.getAbsoluteFile();
159 	}
160 
161 	/**
162 	 * Get list of ceiling directories
163 	 *
164 	 * @return list of ceiling directories
165 	 */
166 	protected List<File> getCeilings() {
167 		return Collections.singletonList(getTemporaryDirectory());
168 	}
169 
170 	private void ceilTestDirectories(List<File> ceilings) {
171 		mockSystemReader.setProperty(Constants.GIT_CEILING_DIRECTORIES_KEY, makePath(ceilings));
172 	}
173 
174 	private static String makePath(List<?> objects) {
175 		final StringBuilder stringBuilder = new StringBuilder();
176 		for (Object object : objects) {
177 			if (stringBuilder.length() > 0)
178 				stringBuilder.append(File.pathSeparatorChar);
179 			stringBuilder.append(object.toString());
180 		}
181 		return stringBuilder.toString();
182 	}
183 
184 	/**
185 	 * Tear down the test
186 	 *
187 	 * @throws Exception
188 	 */
189 	@After
190 	public void tearDown() throws Exception {
191 		RepositoryCache.clear();
192 		for (Repository r : toClose)
193 			r.close();
194 		toClose.clear();
195 
196 		// Since memory mapping is controlled by the GC we need to
197 		// tell it this is a good time to clean up and unlock
198 		// memory mapped files.
199 		//
200 		if (useMMAP)
201 			System.gc();
202 		if (tmp != null)
203 			recursiveDelete(tmp, false, true);
204 		if (tmp != null && !tmp.exists())
205 			CleanupThread.removed(tmp);
206 
207 		SystemReader.setInstance(null);
208 	}
209 
210 	/**
211 	 * Increment the {@link #author} and {@link #committer} times.
212 	 */
213 	protected void tick() {
214 		mockSystemReader.tick(5 * 60);
215 		final long now = mockSystemReader.getCurrentTime();
216 		final int tz = mockSystemReader.getTimezone(now);
217 
218 		author = new PersonIdent(author, now, tz);
219 		committer = new PersonIdent(committer, now, tz);
220 	}
221 
222 	/**
223 	 * Recursively delete a directory, failing the test if the delete fails.
224 	 *
225 	 * @param dir
226 	 *            the recursively directory to delete, if present.
227 	 */
228 	protected void recursiveDelete(final File dir) {
229 		recursiveDelete(dir, false, true);
230 	}
231 
232 	private static boolean recursiveDelete(final File dir,
233 			boolean silent, boolean failOnError) {
234 		assert !(silent && failOnError);
235 		if (!dir.exists())
236 			return silent;
237 		final File[] ls = dir.listFiles();
238 		if (ls != null)
239 			for (int k = 0; k < ls.length; k++) {
240 				final File e = ls[k];
241 				if (e.isDirectory())
242 					silent = recursiveDelete(e, silent, failOnError);
243 				else if (!e.delete()) {
244 					if (!silent)
245 						reportDeleteFailure(failOnError, e);
246 					silent = !failOnError;
247 				}
248 			}
249 		if (!dir.delete()) {
250 			if (!silent)
251 				reportDeleteFailure(failOnError, dir);
252 			silent = !failOnError;
253 		}
254 		return silent;
255 	}
256 
257 	private static void reportDeleteFailure(boolean failOnError, File e) {
258 		String severity = failOnError ? "ERROR" : "WARNING";
259 		String msg = severity + ": Failed to delete " + e;
260 		if (failOnError)
261 			fail(msg);
262 		else
263 			System.err.println(msg);
264 	}
265 
266 	/** Constant <code>MOD_TIME=1</code> */
267 	public static final int MOD_TIME = 1;
268 
269 	/** Constant <code>SMUDGE=2</code> */
270 	public static final int SMUDGE = 2;
271 
272 	/** Constant <code>LENGTH=4</code> */
273 	public static final int LENGTH = 4;
274 
275 	/** Constant <code>CONTENT_ID=8</code> */
276 	public static final int CONTENT_ID = 8;
277 
278 	/** Constant <code>CONTENT=16</code> */
279 	public static final int CONTENT = 16;
280 
281 	/** Constant <code>ASSUME_UNCHANGED=32</code> */
282 	public static final int ASSUME_UNCHANGED = 32;
283 
284 	/**
285 	 * Represent the state of the index in one String. This representation is
286 	 * useful when writing tests which do assertions on the state of the index.
287 	 * By default information about path, mode, stage (if different from 0) is
288 	 * included. A bitmask controls which additional info about
289 	 * modificationTimes, smudge state and length is included.
290 	 * <p>
291 	 * The format of the returned string is described with this BNF:
292 	 *
293 	 * <pre>
294 	 * result = ( "[" path mode stage? time? smudge? length? sha1? content? "]" )* .
295 	 * mode = ", mode:" number .
296 	 * stage = ", stage:" number .
297 	 * time = ", time:t" timestamp-index .
298 	 * smudge = "" | ", smudged" .
299 	 * length = ", length:" number .
300 	 * sha1 = ", sha1:" hex-sha1 .
301 	 * content = ", content:" blob-data .
302 	 * </pre>
303 	 *
304 	 * 'stage' is only presented when the stage is different from 0. All
305 	 * reported time stamps are mapped to strings like "t0", "t1", ... "tn". The
306 	 * smallest reported time-stamp will be called "t0". This allows to write
307 	 * assertions against the string although the concrete value of the time
308 	 * stamps is unknown.
309 	 *
310 	 * @param repo
311 	 *            the repository the index state should be determined for
312 	 * @param includedOptions
313 	 *            a bitmask constructed out of the constants {@link #MOD_TIME},
314 	 *            {@link #SMUDGE}, {@link #LENGTH}, {@link #CONTENT_ID} and
315 	 *            {@link #CONTENT} controlling which info is present in the
316 	 *            resulting string.
317 	 * @return a string encoding the index state
318 	 * @throws IllegalStateException
319 	 * @throws IOException
320 	 */
321 	public static String indexState(Repository repo, int includedOptions)
322 			throws IllegalStateException, IOException {
323 		DirCache dc = repo.readDirCache();
324 		StringBuilder sb = new StringBuilder();
325 		TreeSet<Long> timeStamps = new TreeSet<>();
326 
327 		// iterate once over the dircache just to collect all time stamps
328 		if (0 != (includedOptions & MOD_TIME)) {
329 			for (int i=0; i<dc.getEntryCount(); ++i)
330 				timeStamps.add(Long.valueOf(dc.getEntry(i).getLastModified()));
331 		}
332 
333 		// iterate again, now produce the result string
334 		for (int i=0; i<dc.getEntryCount(); ++i) {
335 			DirCacheEntry entry = dc.getEntry(i);
336 			sb.append("["+entry.getPathString()+", mode:" + entry.getFileMode());
337 			int stage = entry.getStage();
338 			if (stage != 0)
339 				sb.append(", stage:" + stage);
340 			if (0 != (includedOptions & MOD_TIME)) {
341 				sb.append(", time:t"+
342 						timeStamps.headSet(Long.valueOf(entry.getLastModified())).size());
343 			}
344 			if (0 != (includedOptions & SMUDGE))
345 				if (entry.isSmudged())
346 					sb.append(", smudged");
347 			if (0 != (includedOptions & LENGTH))
348 				sb.append(", length:"
349 						+ Integer.toString(entry.getLength()));
350 			if (0 != (includedOptions & CONTENT_ID))
351 				sb.append(", sha1:" + ObjectId.toString(entry.getObjectId()));
352 			if (0 != (includedOptions & CONTENT)) {
353 				sb.append(", content:"
354 						+ new String(repo.open(entry.getObjectId(),
355 						Constants.OBJ_BLOB).getCachedBytes(), UTF_8));
356 			}
357 			if (0 != (includedOptions & ASSUME_UNCHANGED))
358 				sb.append(", assume-unchanged:"
359 						+ Boolean.toString(entry.isAssumeValid()));
360 			sb.append("]");
361 		}
362 		return sb.toString();
363 	}
364 
365 
366 	/**
367 	 * Creates a new empty bare repository.
368 	 *
369 	 * @return the newly created repository, opened for access
370 	 * @throws IOException
371 	 *             the repository could not be created in the temporary area
372 	 */
373 	protected FileRepository createBareRepository() throws IOException {
374 		return createRepository(true /* bare */);
375 	}
376 
377 	/**
378 	 * Creates a new empty repository within a new empty working directory.
379 	 *
380 	 * @return the newly created repository, opened for access
381 	 * @throws IOException
382 	 *             the repository could not be created in the temporary area
383 	 */
384 	protected FileRepository createWorkRepository() throws IOException {
385 		return createRepository(false /* not bare */);
386 	}
387 
388 	/**
389 	 * Creates a new empty repository.
390 	 *
391 	 * @param bare
392 	 *            true to create a bare repository; false to make a repository
393 	 *            within its working directory
394 	 * @return the newly created repository, opened for access
395 	 * @throws IOException
396 	 *             the repository could not be created in the temporary area
397 	 */
398 	private FileRepository createRepository(boolean bare)
399 			throws IOException {
400 		return createRepository(bare, true /* auto close */);
401 	}
402 
403 	/**
404 	 * Creates a new empty repository.
405 	 *
406 	 * @param bare
407 	 *            true to create a bare repository; false to make a repository
408 	 *            within its working directory
409 	 * @param autoClose
410 	 *            auto close the repository in #tearDown
411 	 * @return the newly created repository, opened for access
412 	 * @throws IOException
413 	 *             the repository could not be created in the temporary area
414 	 */
415 	public FileRepository createRepository(boolean bare, boolean autoClose)
416 			throws IOException {
417 		File gitdir = createUniqueTestGitDir(bare);
418 		FileRepository db = new FileRepository(gitdir);
419 		assertFalse(gitdir.exists());
420 		db.create(bare);
421 		if (autoClose) {
422 			addRepoToClose(db);
423 		}
424 		return db;
425 	}
426 
427 	/**
428 	 * Adds a repository to the list of repositories which is closed at the end
429 	 * of the tests
430 	 *
431 	 * @param r
432 	 *            the repository to be closed
433 	 */
434 	public void addRepoToClose(Repository r) {
435 		toClose.add(r);
436 	}
437 
438 	/**
439 	 * Creates a unique directory for a test
440 	 *
441 	 * @param name
442 	 *            a subdirectory
443 	 * @return a unique directory for a test
444 	 * @throws IOException
445 	 */
446 	protected File createTempDirectory(String name) throws IOException {
447 		File directory = new File(createTempFile(), name);
448 		FileUtils.mkdirs(directory);
449 		return directory.getCanonicalFile();
450 	}
451 
452 	/**
453 	 * Creates a new unique directory for a test repository
454 	 *
455 	 * @param bare
456 	 *            true for a bare repository; false for a repository with a
457 	 *            working directory
458 	 * @return a unique directory for a test repository
459 	 * @throws IOException
460 	 */
461 	protected File createUniqueTestGitDir(boolean bare) throws IOException {
462 		String gitdirName = createTempFile().getPath();
463 		if (!bare)
464 			gitdirName += "/";
465 		return new File(gitdirName + Constants.DOT_GIT);
466 	}
467 
468 	/**
469 	 * Allocates a new unique file path that does not exist.
470 	 * <p>
471 	 * Unlike the standard {@code File.createTempFile} the returned path does
472 	 * not exist, but may be created by another thread in a race with the
473 	 * caller. Good luck.
474 	 * <p>
475 	 * This method is inherently unsafe due to a race condition between creating
476 	 * the name and the first use that reserves it.
477 	 *
478 	 * @return a unique path that does not exist.
479 	 * @throws IOException
480 	 */
481 	protected File createTempFile() throws IOException {
482 		File p = File.createTempFile("tmp_", "", tmp);
483 		if (!p.delete()) {
484 			throw new IOException("Cannot obtain unique path " + tmp);
485 		}
486 		return p;
487 	}
488 
489 	/**
490 	 * Run a hook script in the repository, returning the exit status.
491 	 *
492 	 * @param db
493 	 *            repository the script should see in GIT_DIR environment
494 	 * @param hook
495 	 *            path of the hook script to execute, must be executable file
496 	 *            type on this platform
497 	 * @param args
498 	 *            arguments to pass to the hook script
499 	 * @return exit status code of the invoked hook
500 	 * @throws IOException
501 	 *             the hook could not be executed
502 	 * @throws InterruptedException
503 	 *             the caller was interrupted before the hook completed
504 	 */
505 	protected int runHook(final Repository db, final File hook,
506 			final String... args) throws IOException, InterruptedException {
507 		final String[] argv = new String[1 + args.length];
508 		argv[0] = hook.getAbsolutePath();
509 		System.arraycopy(args, 0, argv, 1, args.length);
510 
511 		final Map<String, String> env = cloneEnv();
512 		env.put("GIT_DIR", db.getDirectory().getAbsolutePath());
513 		putPersonIdent(env, "AUTHOR", author);
514 		putPersonIdent(env, "COMMITTER", committer);
515 
516 		final File cwd = db.getWorkTree();
517 		final Process p = Runtime.getRuntime().exec(argv, toEnvArray(env), cwd);
518 		p.getOutputStream().close();
519 		p.getErrorStream().close();
520 		p.getInputStream().close();
521 		return p.waitFor();
522 	}
523 
524 	private static void putPersonIdent(final Map<String, String> env,
525 			final String type, final PersonIdent who) {
526 		final String ident = who.toExternalString();
527 		final String date = ident.substring(ident.indexOf("> ") + 2);
528 		env.put("GIT_" + type + "_NAME", who.getName());
529 		env.put("GIT_" + type + "_EMAIL", who.getEmailAddress());
530 		env.put("GIT_" + type + "_DATE", date);
531 	}
532 
533 	/**
534 	 * Create a string to a UTF-8 temporary file and return the path.
535 	 *
536 	 * @param body
537 	 *            complete content to write to the file. If the file should end
538 	 *            with a trailing LF, the string should end with an LF.
539 	 * @return path of the temporary file created within the trash area.
540 	 * @throws IOException
541 	 *             the file could not be written.
542 	 */
543 	protected File write(final String body) throws IOException {
544 		final File f = File.createTempFile("temp", "txt", tmp);
545 		try {
546 			write(f, body);
547 			return f;
548 		} catch (Error e) {
549 			f.delete();
550 			throw e;
551 		} catch (RuntimeException e) {
552 			f.delete();
553 			throw e;
554 		} catch (IOException e) {
555 			f.delete();
556 			throw e;
557 		}
558 	}
559 
560 	/**
561 	 * Write a string as a UTF-8 file.
562 	 *
563 	 * @param f
564 	 *            file to write the string to. Caller is responsible for making
565 	 *            sure it is in the trash directory or will otherwise be cleaned
566 	 *            up at the end of the test. If the parent directory does not
567 	 *            exist, the missing parent directories are automatically
568 	 *            created.
569 	 * @param body
570 	 *            content to write to the file.
571 	 * @throws IOException
572 	 *             the file could not be written.
573 	 */
574 	protected void write(final File f, final String body) throws IOException {
575 		JGitTestUtil.write(f, body);
576 	}
577 
578 	/**
579 	 * Read a file's content
580 	 *
581 	 * @param f
582 	 *            the file
583 	 * @return the content of the file
584 	 * @throws IOException
585 	 */
586 	protected String read(final File f) throws IOException {
587 		return JGitTestUtil.read(f);
588 	}
589 
590 	private static String[] toEnvArray(final Map<String, String> env) {
591 		final String[] envp = new String[env.size()];
592 		int i = 0;
593 		for (Map.Entry<String, String> e : env.entrySet())
594 			envp[i++] = e.getKey() + "=" + e.getValue();
595 		return envp;
596 	}
597 
598 	private static HashMap<String, String> cloneEnv() {
599 		return new HashMap<>(System.getenv());
600 	}
601 
602 	private static final class CleanupThread extends Thread {
603 		private static final CleanupThread me;
604 		static {
605 			me = new CleanupThread();
606 			Runtime.getRuntime().addShutdownHook(me);
607 		}
608 
609 		static void deleteOnShutdown(File tmp) {
610 			synchronized (me) {
611 				me.toDelete.add(tmp);
612 			}
613 		}
614 
615 		static void removed(File tmp) {
616 			synchronized (me) {
617 				me.toDelete.remove(tmp);
618 			}
619 		}
620 
621 		private final List<File> toDelete = new ArrayList<>();
622 
623 		@Override
624 		public void run() {
625 			// On windows accidentally open files or memory
626 			// mapped regions may prevent files from being deleted.
627 			// Suggesting a GC increases the likelihood that our
628 			// test repositories actually get removed after the
629 			// tests, even in the case of failure.
630 			System.gc();
631 			synchronized (this) {
632 				boolean silent = false;
633 				boolean failOnError = false;
634 				for (File tmp : toDelete)
635 					recursiveDelete(tmp, silent, failOnError);
636 			}
637 		}
638 	}
639 }