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 19KB

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