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 WindowCacheConfigowCacheConfig.html#WindowCacheConfig">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(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 	 * @since 5.3
398 	 */
399 	protected FileRepository createRepository(boolean bare)
400 			throws IOException {
401 		return createRepository(bare, false /* auto close */);
402 	}
403 
404 	/**
405 	 * Creates a new empty repository.
406 	 *
407 	 * @param bare
408 	 *            true to create a bare repository; false to make a repository
409 	 *            within its working directory
410 	 * @param autoClose
411 	 *            auto close the repository in {@link #tearDown()}
412 	 * @return the newly created repository, opened for access
413 	 * @throws IOException
414 	 *             the repository could not be created in the temporary area
415 	 * @deprecated use {@link #createRepository(boolean)} instead
416 	 */
417 	@Deprecated
418 	public FileRepository createRepository(boolean bare, boolean autoClose)
419 			throws IOException {
420 		File gitdir = createUniqueTestGitDir(bare);
421 		FileRepository db = new FileRepository(gitdir);
422 		assertFalse(gitdir.exists());
423 		db.create(bare);
424 		if (autoClose) {
425 			addRepoToClose(db);
426 		}
427 		return db;
428 	}
429 
430 	/**
431 	 * Adds a repository to the list of repositories which is closed at the end
432 	 * of the tests
433 	 *
434 	 * @param r
435 	 *            the repository to be closed
436 	 */
437 	public void addRepoToClose(Repository r) {
438 		toClose.add(r);
439 	}
440 
441 	/**
442 	 * Creates a unique directory for a test
443 	 *
444 	 * @param name
445 	 *            a subdirectory
446 	 * @return a unique directory for a test
447 	 * @throws IOException
448 	 */
449 	protected File createTempDirectory(String name) throws IOException {
450 		File directory = new File(createTempFile(), name);
451 		FileUtils.mkdirs(directory);
452 		return directory.getCanonicalFile();
453 	}
454 
455 	/**
456 	 * Creates a new unique directory for a test repository
457 	 *
458 	 * @param bare
459 	 *            true for a bare repository; false for a repository with a
460 	 *            working directory
461 	 * @return a unique directory for a test repository
462 	 * @throws IOException
463 	 */
464 	protected File createUniqueTestGitDir(boolean bare) throws IOException {
465 		String gitdirName = createTempFile().getPath();
466 		if (!bare)
467 			gitdirName += "/";
468 		return new File(gitdirName + Constants.DOT_GIT);
469 	}
470 
471 	/**
472 	 * Allocates a new unique file path that does not exist.
473 	 * <p>
474 	 * Unlike the standard {@code File.createTempFile} the returned path does
475 	 * not exist, but may be created by another thread in a race with the
476 	 * caller. Good luck.
477 	 * <p>
478 	 * This method is inherently unsafe due to a race condition between creating
479 	 * the name and the first use that reserves it.
480 	 *
481 	 * @return a unique path that does not exist.
482 	 * @throws IOException
483 	 */
484 	protected File createTempFile() throws IOException {
485 		File p = File.createTempFile("tmp_", "", tmp);
486 		if (!p.delete()) {
487 			throw new IOException("Cannot obtain unique path " + tmp);
488 		}
489 		return p;
490 	}
491 
492 	/**
493 	 * Run a hook script in the repository, returning the exit status.
494 	 *
495 	 * @param db
496 	 *            repository the script should see in GIT_DIR environment
497 	 * @param hook
498 	 *            path of the hook script to execute, must be executable file
499 	 *            type on this platform
500 	 * @param args
501 	 *            arguments to pass to the hook script
502 	 * @return exit status code of the invoked hook
503 	 * @throws IOException
504 	 *             the hook could not be executed
505 	 * @throws InterruptedException
506 	 *             the caller was interrupted before the hook completed
507 	 */
508 	protected int runHook(final Repository db, final File hook,
509 			final String... args) throws IOException, InterruptedException {
510 		final String[] argv = new String[1 + args.length];
511 		argv[0] = hook.getAbsolutePath();
512 		System.arraycopy(args, 0, argv, 1, args.length);
513 
514 		final Map<String, String> env = cloneEnv();
515 		env.put("GIT_DIR", db.getDirectory().getAbsolutePath());
516 		putPersonIdent(env, "AUTHOR", author);
517 		putPersonIdent(env, "COMMITTER", committer);
518 
519 		final File cwd = db.getWorkTree();
520 		final Process p = Runtime.getRuntime().exec(argv, toEnvArray(env), cwd);
521 		p.getOutputStream().close();
522 		p.getErrorStream().close();
523 		p.getInputStream().close();
524 		return p.waitFor();
525 	}
526 
527 	private static void putPersonIdent(final Map<String, String> env,
528 			final String type, final PersonIdent who) {
529 		final String ident = who.toExternalString();
530 		final String date = ident.substring(ident.indexOf("> ") + 2);
531 		env.put("GIT_" + type + "_NAME", who.getName());
532 		env.put("GIT_" + type + "_EMAIL", who.getEmailAddress());
533 		env.put("GIT_" + type + "_DATE", date);
534 	}
535 
536 	/**
537 	 * Create a string to a UTF-8 temporary file and return the path.
538 	 *
539 	 * @param body
540 	 *            complete content to write to the file. If the file should end
541 	 *            with a trailing LF, the string should end with an LF.
542 	 * @return path of the temporary file created within the trash area.
543 	 * @throws IOException
544 	 *             the file could not be written.
545 	 */
546 	protected File write(String body) throws IOException {
547 		final File f = File.createTempFile("temp", "txt", tmp);
548 		try {
549 			write(f, body);
550 			return f;
551 		} catch (Error e) {
552 			f.delete();
553 			throw e;
554 		} catch (RuntimeException e) {
555 			f.delete();
556 			throw e;
557 		} catch (IOException e) {
558 			f.delete();
559 			throw e;
560 		}
561 	}
562 
563 	/**
564 	 * Write a string as a UTF-8 file.
565 	 *
566 	 * @param f
567 	 *            file to write the string to. Caller is responsible for making
568 	 *            sure it is in the trash directory or will otherwise be cleaned
569 	 *            up at the end of the test. If the parent directory does not
570 	 *            exist, the missing parent directories are automatically
571 	 *            created.
572 	 * @param body
573 	 *            content to write to the file.
574 	 * @throws IOException
575 	 *             the file could not be written.
576 	 */
577 	protected void write(File f, String body) throws IOException {
578 		JGitTestUtil.write(f, body);
579 	}
580 
581 	/**
582 	 * Read a file's content
583 	 *
584 	 * @param f
585 	 *            the file
586 	 * @return the content of the file
587 	 * @throws IOException
588 	 */
589 	protected String read(File f) throws IOException {
590 		return JGitTestUtil.read(f);
591 	}
592 
593 	private static String[] toEnvArray(Map<String, String> env) {
594 		final String[] envp = new String[env.size()];
595 		int i = 0;
596 		for (Map.Entry<String, String> e : env.entrySet())
597 			envp[i++] = e.getKey() + "=" + e.getValue();
598 		return envp;
599 	}
600 
601 	private static HashMap<String, String> cloneEnv() {
602 		return new HashMap<>(System.getenv());
603 	}
604 
605 	private static final class CleanupThread extends Thread {
606 		private static final CleanupThread me;
607 		static {
608 			me = new CleanupThread();
609 			Runtime.getRuntime().addShutdownHook(me);
610 		}
611 
612 		static void deleteOnShutdown(File tmp) {
613 			synchronized (me) {
614 				me.toDelete.add(tmp);
615 			}
616 		}
617 
618 		static void removed(File tmp) {
619 			synchronized (me) {
620 				me.toDelete.remove(tmp);
621 			}
622 		}
623 
624 		private final List<File> toDelete = new ArrayList<>();
625 
626 		@Override
627 		public void run() {
628 			// On windows accidentally open files or memory
629 			// mapped regions may prevent files from being deleted.
630 			// Suggesting a GC increases the likelihood that our
631 			// test repositories actually get removed after the
632 			// tests, even in the case of failure.
633 			System.gc();
634 			synchronized (this) {
635 				boolean silent = false;
636 				boolean failOnError = false;
637 				for (File tmp : toDelete)
638 					recursiveDelete(tmp, silent, failOnError);
639 			}
640 		}
641 	}
642 }