You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LocalDiskRepositoryTestCase.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. package org.eclipse.jgit.junit;
  46. import static org.junit.Assert.assertFalse;
  47. import static org.junit.Assert.fail;
  48. import java.io.File;
  49. import java.io.IOException;
  50. import java.util.*;
  51. import org.eclipse.jgit.dircache.DirCache;
  52. import org.eclipse.jgit.dircache.DirCacheEntry;
  53. import org.eclipse.jgit.internal.storage.file.FileRepository;
  54. import org.eclipse.jgit.lib.*;
  55. import org.eclipse.jgit.storage.file.FileBasedConfig;
  56. import org.eclipse.jgit.storage.file.WindowCacheConfig;
  57. import org.eclipse.jgit.util.FS;
  58. import org.eclipse.jgit.util.FileUtils;
  59. import org.eclipse.jgit.util.SystemReader;
  60. import org.junit.After;
  61. import org.junit.Before;
  62. /**
  63. * JUnit TestCase with specialized support for temporary local repository.
  64. * <p>
  65. * A temporary directory is created for each test, allowing each test to use a
  66. * fresh environment. The temporary directory is cleaned up after the test ends.
  67. * <p>
  68. * Callers should not use {@link RepositoryCache} from within these tests as it
  69. * may wedge file descriptors open past the end of the test.
  70. * <p>
  71. * A system property {@code jgit.junit.usemmap} defines whether memory mapping
  72. * is used. Memory mapping has an effect on the file system, in that memory
  73. * mapped files in Java cannot be deleted as long as the mapped arrays have not
  74. * been reclaimed by the garbage collector. The programmer cannot control this
  75. * with precision, so temporary files may hang around longer than desired during
  76. * a test, or tests may fail altogether if there is insufficient file
  77. * descriptors or address space for the test process.
  78. */
  79. public abstract class LocalDiskRepositoryTestCase {
  80. private static final boolean useMMAP = "true".equals(System
  81. .getProperty("jgit.junit.usemmap"));
  82. /** A fake (but stable) identity for author fields in the test. */
  83. protected PersonIdent author;
  84. /** A fake (but stable) identity for committer fields in the test. */
  85. protected PersonIdent committer;
  86. /**
  87. * A {@link SystemReader} used to coordinate time, envars, etc.
  88. * @since 4.2
  89. */
  90. protected MockSystemReader mockSystemReader;
  91. private final List<Repository> toClose = new ArrayList<Repository>();
  92. private File tmp;
  93. @Before
  94. public void setUp() throws Exception {
  95. tmp = File.createTempFile("jgit_test_", "_tmp");
  96. CleanupThread.deleteOnShutdown(tmp);
  97. if (!tmp.delete() || !tmp.mkdir())
  98. throw new IOException("Cannot create " + tmp);
  99. mockSystemReader = new MockSystemReader();
  100. mockSystemReader.userGitConfig = new FileBasedConfig(new File(tmp,
  101. "usergitconfig"), FS.DETECTED);
  102. ceilTestDirectories(getCeilings());
  103. SystemReader.setInstance(mockSystemReader);
  104. final long now = mockSystemReader.getCurrentTime();
  105. final int tz = mockSystemReader.getTimezone(now);
  106. author = new PersonIdent("J. Author", "jauthor@example.com");
  107. author = new PersonIdent(author, now, tz);
  108. committer = new PersonIdent("J. Committer", "jcommitter@example.com");
  109. committer = new PersonIdent(committer, now, tz);
  110. final WindowCacheConfig c = new WindowCacheConfig();
  111. c.setPackedGitLimit(128 * WindowCacheConfig.KB);
  112. c.setPackedGitWindowSize(8 * WindowCacheConfig.KB);
  113. c.setPackedGitMMAP(useMMAP);
  114. c.setDeltaBaseCacheLimit(8 * WindowCacheConfig.KB);
  115. c.install();
  116. }
  117. protected File getTemporaryDirectory() {
  118. return tmp.getAbsoluteFile();
  119. }
  120. protected List<File> getCeilings() {
  121. return Collections.singletonList(getTemporaryDirectory());
  122. }
  123. private void ceilTestDirectories(List<File> ceilings) {
  124. mockSystemReader.setProperty(Constants.GIT_CEILING_DIRECTORIES_KEY, makePath(ceilings));
  125. }
  126. private static String makePath(List<?> objects) {
  127. final StringBuilder stringBuilder = new StringBuilder();
  128. for (Object object : objects) {
  129. if (stringBuilder.length() > 0)
  130. stringBuilder.append(File.pathSeparatorChar);
  131. stringBuilder.append(object.toString());
  132. }
  133. return stringBuilder.toString();
  134. }
  135. @After
  136. public void tearDown() throws Exception {
  137. RepositoryCache.clear();
  138. for (Repository r : toClose)
  139. r.close();
  140. toClose.clear();
  141. // Since memory mapping is controlled by the GC we need to
  142. // tell it this is a good time to clean up and unlock
  143. // memory mapped files.
  144. //
  145. if (useMMAP)
  146. System.gc();
  147. if (tmp != null)
  148. recursiveDelete(tmp, false, true);
  149. if (tmp != null && !tmp.exists())
  150. CleanupThread.removed(tmp);
  151. SystemReader.setInstance(null);
  152. }
  153. /** Increment the {@link #author} and {@link #committer} times. */
  154. protected void tick() {
  155. mockSystemReader.tick(5 * 60);
  156. final long now = mockSystemReader.getCurrentTime();
  157. final int tz = mockSystemReader.getTimezone(now);
  158. author = new PersonIdent(author, now, tz);
  159. committer = new PersonIdent(committer, now, tz);
  160. }
  161. /**
  162. * Recursively delete a directory, failing the test if the delete fails.
  163. *
  164. * @param dir
  165. * the recursively directory to delete, if present.
  166. */
  167. protected void recursiveDelete(final File dir) {
  168. recursiveDelete(dir, false, true);
  169. }
  170. private static boolean recursiveDelete(final File dir,
  171. boolean silent, boolean failOnError) {
  172. assert !(silent && failOnError);
  173. if (!dir.exists())
  174. return silent;
  175. final File[] ls = dir.listFiles();
  176. if (ls != null)
  177. for (int k = 0; k < ls.length; k++) {
  178. final File e = ls[k];
  179. if (e.isDirectory())
  180. silent = recursiveDelete(e, silent, failOnError);
  181. else if (!e.delete()) {
  182. if (!silent)
  183. reportDeleteFailure(failOnError, e);
  184. silent = !failOnError;
  185. }
  186. }
  187. if (!dir.delete()) {
  188. if (!silent)
  189. reportDeleteFailure(failOnError, dir);
  190. silent = !failOnError;
  191. }
  192. return silent;
  193. }
  194. private static void reportDeleteFailure(boolean failOnError, File e) {
  195. String severity = failOnError ? "ERROR" : "WARNING";
  196. String msg = severity + ": Failed to delete " + e;
  197. if (failOnError)
  198. fail(msg);
  199. else
  200. System.err.println(msg);
  201. }
  202. public static final int MOD_TIME = 1;
  203. public static final int SMUDGE = 2;
  204. public static final int LENGTH = 4;
  205. public static final int CONTENT_ID = 8;
  206. public static final int CONTENT = 16;
  207. public static final int ASSUME_UNCHANGED = 32;
  208. /**
  209. * Represent the state of the index in one String. This representation is
  210. * useful when writing tests which do assertions on the state of the index.
  211. * By default information about path, mode, stage (if different from 0) is
  212. * included. A bitmask controls which additional info about
  213. * modificationTimes, smudge state and length is included.
  214. * <p>
  215. * The format of the returned string is described with this BNF:
  216. *
  217. * <pre>
  218. * result = ( "[" path mode stage? time? smudge? length? sha1? content? "]" )* .
  219. * mode = ", mode:" number .
  220. * stage = ", stage:" number .
  221. * time = ", time:t" timestamp-index .
  222. * smudge = "" | ", smudged" .
  223. * length = ", length:" number .
  224. * sha1 = ", sha1:" hex-sha1 .
  225. * content = ", content:" blob-data .
  226. * </pre>
  227. *
  228. * 'stage' is only presented when the stage is different from 0. All
  229. * reported time stamps are mapped to strings like "t0", "t1", ... "tn". The
  230. * smallest reported time-stamp will be called "t0". This allows to write
  231. * assertions against the string although the concrete value of the time
  232. * stamps is unknown.
  233. *
  234. * @param repo
  235. * the repository the index state should be determined for
  236. *
  237. * @param includedOptions
  238. * a bitmask constructed out of the constants {@link #MOD_TIME},
  239. * {@link #SMUDGE}, {@link #LENGTH}, {@link #CONTENT_ID} and
  240. * {@link #CONTENT} controlling which info is present in the
  241. * resulting string.
  242. * @return a string encoding the index state
  243. * @throws IllegalStateException
  244. * @throws IOException
  245. */
  246. public static String indexState(Repository repo, int includedOptions)
  247. throws IllegalStateException, IOException {
  248. DirCache dc = repo.readDirCache();
  249. StringBuilder sb = new StringBuilder();
  250. TreeSet<Long> timeStamps = new TreeSet<Long>();
  251. // iterate once over the dircache just to collect all time stamps
  252. if (0 != (includedOptions & MOD_TIME)) {
  253. for (int i=0; i<dc.getEntryCount(); ++i)
  254. timeStamps.add(Long.valueOf(dc.getEntry(i).getLastModified()));
  255. }
  256. // iterate again, now produce the result string
  257. for (int i=0; i<dc.getEntryCount(); ++i) {
  258. DirCacheEntry entry = dc.getEntry(i);
  259. sb.append("["+entry.getPathString()+", mode:" + entry.getFileMode());
  260. int stage = entry.getStage();
  261. if (stage != 0)
  262. sb.append(", stage:" + stage);
  263. if (0 != (includedOptions & MOD_TIME)) {
  264. sb.append(", time:t"+
  265. timeStamps.headSet(Long.valueOf(entry.getLastModified())).size());
  266. }
  267. if (0 != (includedOptions & SMUDGE))
  268. if (entry.isSmudged())
  269. sb.append(", smudged");
  270. if (0 != (includedOptions & LENGTH))
  271. sb.append(", length:"
  272. + Integer.toString(entry.getLength()));
  273. if (0 != (includedOptions & CONTENT_ID))
  274. sb.append(", sha1:" + ObjectId.toString(entry.getObjectId()));
  275. if (0 != (includedOptions & CONTENT)) {
  276. sb.append(", content:"
  277. + new String(repo.open(entry.getObjectId(),
  278. Constants.OBJ_BLOB).getCachedBytes(), "UTF-8"));
  279. }
  280. if (0 != (includedOptions & ASSUME_UNCHANGED))
  281. sb.append(", assume-unchanged:"
  282. + Boolean.toString(entry.isAssumeValid()));
  283. sb.append("]");
  284. }
  285. return sb.toString();
  286. }
  287. /**
  288. * Creates a new empty bare repository.
  289. *
  290. * @return the newly created repository, opened for access
  291. * @throws IOException
  292. * the repository could not be created in the temporary area
  293. */
  294. protected FileRepository createBareRepository() throws IOException {
  295. return createRepository(true /* bare */);
  296. }
  297. /**
  298. * Creates a new empty repository within a new empty working directory.
  299. *
  300. * @return the newly created repository, opened for access
  301. * @throws IOException
  302. * the repository could not be created in the temporary area
  303. */
  304. protected FileRepository createWorkRepository() throws IOException {
  305. return createRepository(false /* not bare */);
  306. }
  307. /**
  308. * Creates a new empty repository.
  309. *
  310. * @param bare
  311. * true to create a bare repository; false to make a repository
  312. * within its working directory
  313. * @return the newly created repository, opened for access
  314. * @throws IOException
  315. * the repository could not be created in the temporary area
  316. */
  317. private FileRepository createRepository(boolean bare) throws IOException {
  318. File gitdir = createUniqueTestGitDir(bare);
  319. FileRepository db = new FileRepository(gitdir);
  320. assertFalse(gitdir.exists());
  321. db.create(bare);
  322. toClose.add(db);
  323. return db;
  324. }
  325. /**
  326. * Adds a repository to the list of repositories which is closed at the end
  327. * of the tests
  328. *
  329. * @param r
  330. * the repository to be closed
  331. */
  332. public void addRepoToClose(Repository r) {
  333. toClose.add(r);
  334. }
  335. /**
  336. * Creates a unique directory for a test
  337. *
  338. * @param name
  339. * a subdirectory
  340. * @return a unique directory for a test
  341. * @throws IOException
  342. */
  343. protected File createTempDirectory(String name) throws IOException {
  344. File directory = new File(createTempFile(), name);
  345. FileUtils.mkdirs(directory);
  346. return directory.getCanonicalFile();
  347. }
  348. /**
  349. * Creates a new unique directory for a test repository
  350. *
  351. * @param bare
  352. * true for a bare repository; false for a repository with a
  353. * working directory
  354. * @return a unique directory for a test repository
  355. * @throws IOException
  356. */
  357. protected File createUniqueTestGitDir(boolean bare) throws IOException {
  358. String gitdirName = createTempFile().getPath();
  359. if (!bare)
  360. gitdirName += "/";
  361. return new File(gitdirName + Constants.DOT_GIT);
  362. }
  363. /**
  364. * Allocates a new unique file path that does not exist.
  365. * <p>
  366. * Unlike the standard {@code File.createTempFile} the returned path does
  367. * not exist, but may be created by another thread in a race with the
  368. * caller. Good luck.
  369. * <p>
  370. * This method is inherently unsafe due to a race condition between creating
  371. * the name and the first use that reserves it.
  372. *
  373. * @return a unique path that does not exist.
  374. * @throws IOException
  375. */
  376. protected File createTempFile() throws IOException {
  377. File p = File.createTempFile("tmp_", "", tmp);
  378. if (!p.delete()) {
  379. throw new IOException("Cannot obtain unique path " + tmp);
  380. }
  381. return p;
  382. }
  383. /**
  384. * Run a hook script in the repository, returning the exit status.
  385. *
  386. * @param db
  387. * repository the script should see in GIT_DIR environment
  388. * @param hook
  389. * path of the hook script to execute, must be executable file
  390. * type on this platform
  391. * @param args
  392. * arguments to pass to the hook script
  393. * @return exit status code of the invoked hook
  394. * @throws IOException
  395. * the hook could not be executed
  396. * @throws InterruptedException
  397. * the caller was interrupted before the hook completed
  398. */
  399. protected int runHook(final Repository db, final File hook,
  400. final String... args) throws IOException, InterruptedException {
  401. final String[] argv = new String[1 + args.length];
  402. argv[0] = hook.getAbsolutePath();
  403. System.arraycopy(args, 0, argv, 1, args.length);
  404. final Map<String, String> env = cloneEnv();
  405. env.put("GIT_DIR", db.getDirectory().getAbsolutePath());
  406. putPersonIdent(env, "AUTHOR", author);
  407. putPersonIdent(env, "COMMITTER", committer);
  408. final File cwd = db.getWorkTree();
  409. final Process p = Runtime.getRuntime().exec(argv, toEnvArray(env), cwd);
  410. p.getOutputStream().close();
  411. p.getErrorStream().close();
  412. p.getInputStream().close();
  413. return p.waitFor();
  414. }
  415. private static void putPersonIdent(final Map<String, String> env,
  416. final String type, final PersonIdent who) {
  417. final String ident = who.toExternalString();
  418. final String date = ident.substring(ident.indexOf("> ") + 2);
  419. env.put("GIT_" + type + "_NAME", who.getName());
  420. env.put("GIT_" + type + "_EMAIL", who.getEmailAddress());
  421. env.put("GIT_" + type + "_DATE", date);
  422. }
  423. /**
  424. * Create a string to a UTF-8 temporary file and return the path.
  425. *
  426. * @param body
  427. * complete content to write to the file. If the file should end
  428. * with a trailing LF, the string should end with an LF.
  429. * @return path of the temporary file created within the trash area.
  430. * @throws IOException
  431. * the file could not be written.
  432. */
  433. protected File write(final String body) throws IOException {
  434. final File f = File.createTempFile("temp", "txt", tmp);
  435. try {
  436. write(f, body);
  437. return f;
  438. } catch (Error e) {
  439. f.delete();
  440. throw e;
  441. } catch (RuntimeException e) {
  442. f.delete();
  443. throw e;
  444. } catch (IOException e) {
  445. f.delete();
  446. throw e;
  447. }
  448. }
  449. /**
  450. * Write a string as a UTF-8 file.
  451. *
  452. * @param f
  453. * file to write the string to. Caller is responsible for making
  454. * sure it is in the trash directory or will otherwise be cleaned
  455. * up at the end of the test. If the parent directory does not
  456. * exist, the missing parent directories are automatically
  457. * created.
  458. * @param body
  459. * content to write to the file.
  460. * @throws IOException
  461. * the file could not be written.
  462. */
  463. protected void write(final File f, final String body) throws IOException {
  464. JGitTestUtil.write(f, body);
  465. }
  466. protected String read(final File f) throws IOException {
  467. return JGitTestUtil.read(f);
  468. }
  469. private static String[] toEnvArray(final Map<String, String> env) {
  470. final String[] envp = new String[env.size()];
  471. int i = 0;
  472. for (Map.Entry<String, String> e : env.entrySet())
  473. envp[i++] = e.getKey() + "=" + e.getValue();
  474. return envp;
  475. }
  476. private static HashMap<String, String> cloneEnv() {
  477. return new HashMap<String, String>(System.getenv());
  478. }
  479. private static final class CleanupThread extends Thread {
  480. private static final CleanupThread me;
  481. static {
  482. me = new CleanupThread();
  483. Runtime.getRuntime().addShutdownHook(me);
  484. }
  485. static void deleteOnShutdown(File tmp) {
  486. synchronized (me) {
  487. me.toDelete.add(tmp);
  488. }
  489. }
  490. static void removed(File tmp) {
  491. synchronized (me) {
  492. me.toDelete.remove(tmp);
  493. }
  494. }
  495. private final List<File> toDelete = new ArrayList<File>();
  496. @Override
  497. public void run() {
  498. // On windows accidentally open files or memory
  499. // mapped regions may prevent files from being deleted.
  500. // Suggesting a GC increases the likelihood that our
  501. // test repositories actually get removed after the
  502. // tests, even in the case of failure.
  503. System.gc();
  504. synchronized (this) {
  505. boolean silent = false;
  506. boolean failOnError = false;
  507. for (File tmp : toDelete)
  508. recursiveDelete(tmp, silent, failOnError);
  509. }
  510. }
  511. }
  512. }