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

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