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.

RepositoryTestCase.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. /*
  2. * Copyright (C) 2009, Google Inc.
  3. * Copyright (C) 2007-2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2006-2007, Shawn O. Pearce <spearce@spearce.org>
  5. * Copyright (C) 2009, Yann Simon <yann.simon.fr@gmail.com> and others
  6. *
  7. * This program and the accompanying materials are made available under the
  8. * terms of the Eclipse Distribution License v. 1.0 which is available at
  9. * https://www.eclipse.org/org/documents/edl-v10.php.
  10. *
  11. * SPDX-License-Identifier: BSD-3-Clause
  12. */
  13. package org.eclipse.jgit.junit;
  14. import static java.nio.charset.StandardCharsets.UTF_8;
  15. import static org.junit.Assert.assertEquals;
  16. import java.io.File;
  17. import java.io.FileInputStream;
  18. import java.io.FileNotFoundException;
  19. import java.io.FileOutputStream;
  20. import java.io.IOException;
  21. import java.io.InputStreamReader;
  22. import java.io.Reader;
  23. import java.nio.file.Path;
  24. import java.time.Instant;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.concurrent.TimeUnit;
  28. import org.eclipse.jgit.api.Git;
  29. import org.eclipse.jgit.api.errors.GitAPIException;
  30. import org.eclipse.jgit.dircache.DirCacheBuilder;
  31. import org.eclipse.jgit.dircache.DirCacheCheckout;
  32. import org.eclipse.jgit.dircache.DirCacheEntry;
  33. import org.eclipse.jgit.internal.storage.file.FileRepository;
  34. import org.eclipse.jgit.lib.AnyObjectId;
  35. import org.eclipse.jgit.lib.Constants;
  36. import org.eclipse.jgit.lib.FileMode;
  37. import org.eclipse.jgit.lib.ObjectId;
  38. import org.eclipse.jgit.lib.ObjectInserter;
  39. import org.eclipse.jgit.lib.Ref;
  40. import org.eclipse.jgit.lib.RefUpdate;
  41. import org.eclipse.jgit.lib.Repository;
  42. import org.eclipse.jgit.revwalk.RevCommit;
  43. import org.eclipse.jgit.revwalk.RevWalk;
  44. import org.eclipse.jgit.treewalk.FileTreeIterator;
  45. import org.eclipse.jgit.util.FS;
  46. import org.eclipse.jgit.util.FileUtils;
  47. import org.junit.After;
  48. import org.junit.Before;
  49. /**
  50. * Base class for most JGit unit tests.
  51. *
  52. * Sets up a predefined test repository and has support for creating additional
  53. * repositories and destroying them when the tests are finished.
  54. */
  55. public abstract class RepositoryTestCase extends LocalDiskRepositoryTestCase {
  56. /**
  57. * Copy a file
  58. *
  59. * @param src
  60. * @param dst
  61. * @throws IOException
  62. */
  63. protected static void copyFile(File src, File dst)
  64. throws IOException {
  65. try (FileInputStream fis = new FileInputStream(src);
  66. FileOutputStream fos = new FileOutputStream(dst)) {
  67. final byte[] buf = new byte[4096];
  68. int r;
  69. while ((r = fis.read(buf)) > 0) {
  70. fos.write(buf, 0, r);
  71. }
  72. }
  73. }
  74. /**
  75. * Write a trash file
  76. *
  77. * @param name
  78. * @param data
  79. * @return the trash file
  80. * @throws IOException
  81. */
  82. protected File writeTrashFile(String name, String data)
  83. throws IOException {
  84. return JGitTestUtil.writeTrashFile(db, name, data);
  85. }
  86. /**
  87. * Create a symbolic link
  88. *
  89. * @param link
  90. * the path of the symbolic link to create
  91. * @param target
  92. * the target of the symbolic link
  93. * @return the path to the symbolic link
  94. * @throws Exception
  95. * @since 4.2
  96. */
  97. protected Path writeLink(String link, String target)
  98. throws Exception {
  99. return JGitTestUtil.writeLink(db, link, target);
  100. }
  101. /**
  102. * Write a trash file
  103. *
  104. * @param subdir
  105. * @param name
  106. * @param data
  107. * @return the trash file
  108. * @throws IOException
  109. */
  110. protected File writeTrashFile(final String subdir, final String name,
  111. final String data)
  112. throws IOException {
  113. return JGitTestUtil.writeTrashFile(db, subdir, name, data);
  114. }
  115. /**
  116. * Read content of a file
  117. *
  118. * @param name
  119. * @return the file's content
  120. * @throws IOException
  121. */
  122. protected String read(String name) throws IOException {
  123. return JGitTestUtil.read(db, name);
  124. }
  125. /**
  126. * Check if file exists
  127. *
  128. * @param name
  129. * file name
  130. * @return if the file exists
  131. */
  132. protected boolean check(String name) {
  133. return JGitTestUtil.check(db, name);
  134. }
  135. /**
  136. * Delete a trash file
  137. *
  138. * @param name
  139. * file name
  140. * @throws IOException
  141. */
  142. protected void deleteTrashFile(String name) throws IOException {
  143. JGitTestUtil.deleteTrashFile(db, name);
  144. }
  145. /**
  146. * Check content of a file.
  147. *
  148. * @param f
  149. * @param checkData
  150. * expected content
  151. * @throws IOException
  152. */
  153. protected static void checkFile(File f, String checkData)
  154. throws IOException {
  155. try (Reader r = new InputStreamReader(new FileInputStream(f),
  156. UTF_8)) {
  157. if (checkData.length() > 0) {
  158. char[] data = new char[checkData.length()];
  159. assertEquals(data.length, r.read(data));
  160. assertEquals(checkData, new String(data));
  161. }
  162. assertEquals(-1, r.read());
  163. }
  164. }
  165. /** Test repository, initialized for this test case. */
  166. protected FileRepository db;
  167. /** Working directory of {@link #db}. */
  168. protected File trash;
  169. /** {@inheritDoc} */
  170. @Override
  171. @Before
  172. public void setUp() throws Exception {
  173. super.setUp();
  174. db = createWorkRepository();
  175. trash = db.getWorkTree();
  176. }
  177. @Override
  178. @After
  179. public void tearDown() throws Exception {
  180. db.close();
  181. super.tearDown();
  182. }
  183. /**
  184. * Represent the state of the index in one String. This representation is
  185. * useful when writing tests which do assertions on the state of the index.
  186. * By default information about path, mode, stage (if different from 0) is
  187. * included. A bitmask controls which additional info about
  188. * modificationTimes, smudge state and length is included.
  189. * <p>
  190. * The format of the returned string is described with this BNF:
  191. *
  192. * <pre>
  193. * result = ( "[" path mode stage? time? smudge? length? sha1? content? "]" )* .
  194. * mode = ", mode:" number .
  195. * stage = ", stage:" number .
  196. * time = ", time:t" timestamp-index .
  197. * smudge = "" | ", smudged" .
  198. * length = ", length:" number .
  199. * sha1 = ", sha1:" hex-sha1 .
  200. * content = ", content:" blob-data .
  201. * </pre>
  202. *
  203. * 'stage' is only presented when the stage is different from 0. All
  204. * reported time stamps are mapped to strings like "t0", "t1", ... "tn". The
  205. * smallest reported time-stamp will be called "t0". This allows to write
  206. * assertions against the string although the concrete value of the time
  207. * stamps is unknown.
  208. *
  209. * @param includedOptions
  210. * a bitmask constructed out of the constants {@link #MOD_TIME},
  211. * {@link #SMUDGE}, {@link #LENGTH}, {@link #CONTENT_ID} and
  212. * {@link #CONTENT} controlling which info is present in the
  213. * resulting string.
  214. * @return a string encoding the index state
  215. * @throws IllegalStateException
  216. * @throws IOException
  217. */
  218. public String indexState(int includedOptions)
  219. throws IllegalStateException, IOException {
  220. return indexState(db, includedOptions);
  221. }
  222. /**
  223. * Resets the index to represent exactly some filesystem content. E.g. the
  224. * following call will replace the index with the working tree content:
  225. * <p>
  226. * <code>resetIndex(new FileSystemIterator(db))</code>
  227. * <p>
  228. * This method can be used by testcases which first prepare a new commit
  229. * somewhere in the filesystem (e.g. in the working-tree) and then want to
  230. * have an index which matches their prepared content.
  231. *
  232. * @param treeItr
  233. * a {@link org.eclipse.jgit.treewalk.FileTreeIterator} which
  234. * determines which files should go into the new index
  235. * @throws FileNotFoundException
  236. * @throws IOException
  237. */
  238. protected void resetIndex(FileTreeIterator treeItr)
  239. throws FileNotFoundException, IOException {
  240. try (ObjectInserter inserter = db.newObjectInserter()) {
  241. DirCacheBuilder builder = db.lockDirCache().builder();
  242. DirCacheEntry dce;
  243. while (!treeItr.eof()) {
  244. long len = treeItr.getEntryLength();
  245. dce = new DirCacheEntry(treeItr.getEntryPathString());
  246. dce.setFileMode(treeItr.getEntryFileMode());
  247. dce.setLastModified(treeItr.getEntryLastModifiedInstant());
  248. dce.setLength((int) len);
  249. try (FileInputStream in = new FileInputStream(
  250. treeItr.getEntryFile())) {
  251. dce.setObjectId(
  252. inserter.insert(Constants.OBJ_BLOB, len, in));
  253. }
  254. builder.add(dce);
  255. treeItr.next(1);
  256. }
  257. builder.commit();
  258. inserter.flush();
  259. }
  260. }
  261. /**
  262. * Helper method to map arbitrary objects to user-defined names. This can be
  263. * used create short names for objects to produce small and stable debug
  264. * output. It is guaranteed that when you lookup the same object multiple
  265. * times even with different nameTemplates this method will always return
  266. * the same name which was derived from the first nameTemplate.
  267. * nameTemplates can contain "%n" which will be replaced by a running number
  268. * before used as a name.
  269. *
  270. * @param l
  271. * the object to lookup
  272. * @param lookupTable
  273. * a table storing object-name mappings.
  274. * @param nameTemplate
  275. * the name for that object. Can contain "%n" which will be
  276. * replaced by a running number before used as a name. If the
  277. * lookup table already contains the object this parameter will
  278. * be ignored
  279. * @return a name of that object. Is not guaranteed to be unique. Use
  280. * nameTemplates containing "%n" to always have unique names
  281. */
  282. public static String lookup(Object l, String nameTemplate,
  283. Map<Object, String> lookupTable) {
  284. String name = lookupTable.get(l);
  285. if (name == null) {
  286. name = nameTemplate.replaceAll("%n",
  287. Integer.toString(lookupTable.size()));
  288. lookupTable.put(l, name);
  289. }
  290. return name;
  291. }
  292. /**
  293. * Replaces '\' by '/'
  294. *
  295. * @param str
  296. * the string in which backslashes should be replaced
  297. * @return the resulting string with slashes
  298. * @since 4.2
  299. */
  300. public static String slashify(String str) {
  301. str = str.replace('\\', '/');
  302. return str;
  303. }
  304. /**
  305. * Waits until it is guaranteed that a subsequent file modification has a
  306. * younger modification timestamp than the modification timestamp of the
  307. * given file. This is done by touching a temporary file, reading the
  308. * lastmodified attribute and, if needed, sleeping. After sleeping this loop
  309. * starts again until the filesystem timer has advanced enough. The
  310. * temporary file will be created as a sibling of lastFile.
  311. *
  312. * @param lastFile
  313. * the file on which we want to wait until the filesystem timer
  314. * has advanced more than the lastmodification timestamp of this
  315. * file
  316. * @return return the last measured value of the filesystem timer which is
  317. * greater than then the lastmodification time of lastfile.
  318. * @throws InterruptedException
  319. * @throws IOException
  320. */
  321. public static Instant fsTick(File lastFile)
  322. throws InterruptedException,
  323. IOException {
  324. File tmp;
  325. FS fs = FS.DETECTED;
  326. if (lastFile == null) {
  327. lastFile = tmp = File
  328. .createTempFile("fsTickTmpFile", null);
  329. } else {
  330. if (!fs.exists(lastFile)) {
  331. throw new FileNotFoundException(lastFile.getPath());
  332. }
  333. tmp = File.createTempFile("fsTickTmpFile", null,
  334. lastFile.getParentFile());
  335. }
  336. long res = FS.getFileStoreAttributes(tmp.toPath())
  337. .getFsTimestampResolution().toNanos();
  338. long sleepTime = res / 10;
  339. try {
  340. Instant startTime = fs.lastModifiedInstant(lastFile);
  341. Instant actTime = fs.lastModifiedInstant(tmp);
  342. while (actTime.compareTo(startTime) <= 0) {
  343. TimeUnit.NANOSECONDS.sleep(sleepTime);
  344. FileUtils.touch(tmp.toPath());
  345. actTime = fs.lastModifiedInstant(tmp);
  346. }
  347. return actTime;
  348. } finally {
  349. FileUtils.delete(tmp);
  350. }
  351. }
  352. /**
  353. * Create a branch
  354. *
  355. * @param objectId
  356. * @param branchName
  357. * @throws IOException
  358. */
  359. protected void createBranch(ObjectId objectId, String branchName)
  360. throws IOException {
  361. RefUpdate updateRef = db.updateRef(branchName);
  362. updateRef.setNewObjectId(objectId);
  363. updateRef.update();
  364. }
  365. /**
  366. * Get all Refs
  367. *
  368. * @return list of refs
  369. * @throws IOException
  370. */
  371. public List<Ref> getRefs() throws IOException {
  372. return db.getRefDatabase().getRefs();
  373. }
  374. /**
  375. * Checkout a branch
  376. *
  377. * @param branchName
  378. * @throws IllegalStateException
  379. * @throws IOException
  380. */
  381. protected void checkoutBranch(String branchName)
  382. throws IllegalStateException, IOException {
  383. try (RevWalk walk = new RevWalk(db)) {
  384. RevCommit head = walk.parseCommit(db.resolve(Constants.HEAD));
  385. RevCommit branch = walk.parseCommit(db.resolve(branchName));
  386. DirCacheCheckout dco = new DirCacheCheckout(db,
  387. head.getTree().getId(), db.lockDirCache(),
  388. branch.getTree().getId());
  389. dco.setFailOnConflict(true);
  390. dco.checkout();
  391. }
  392. // update the HEAD
  393. RefUpdate refUpdate = db.updateRef(Constants.HEAD);
  394. refUpdate.setRefLogMessage("checkout: moving to " + branchName, false);
  395. refUpdate.link(branchName);
  396. }
  397. /**
  398. * Writes a number of files in the working tree. The first content specified
  399. * will be written into a file named '0', the second into a file named "1"
  400. * and so on. If <code>null</code> is specified as content then this file is
  401. * skipped.
  402. *
  403. * @param ensureDistinctTimestamps
  404. * if set to <code>true</code> then between two write operations
  405. * this method will wait to ensure that the second file will get
  406. * a different lastmodification timestamp than the first file.
  407. * @param contents
  408. * the contents which should be written into the files
  409. * @return the File object associated to the last written file.
  410. * @throws IOException
  411. * @throws InterruptedException
  412. */
  413. protected File writeTrashFiles(boolean ensureDistinctTimestamps,
  414. String... contents)
  415. throws IOException, InterruptedException {
  416. File f = null;
  417. for (int i = 0; i < contents.length; i++)
  418. if (contents[i] != null) {
  419. if (ensureDistinctTimestamps && (f != null))
  420. fsTick(f);
  421. f = writeTrashFile(Integer.toString(i), contents[i]);
  422. }
  423. return f;
  424. }
  425. /**
  426. * Commit a file with the specified contents on the specified branch,
  427. * creating the branch if it didn't exist before.
  428. * <p>
  429. * It switches back to the original branch after the commit if there was
  430. * one.
  431. *
  432. * @param filename
  433. * @param contents
  434. * @param branch
  435. * @return the created commit
  436. */
  437. protected RevCommit commitFile(String filename, String contents, String branch) {
  438. try (Git git = new Git(db)) {
  439. Repository repo = git.getRepository();
  440. String originalBranch = repo.getFullBranch();
  441. boolean empty = repo.resolve(Constants.HEAD) == null;
  442. if (!empty) {
  443. if (repo.findRef(branch) == null)
  444. git.branchCreate().setName(branch).call();
  445. git.checkout().setName(branch).call();
  446. }
  447. writeTrashFile(filename, contents);
  448. git.add().addFilepattern(filename).call();
  449. RevCommit commit = git.commit()
  450. .setMessage(branch + ": " + filename).call();
  451. if (originalBranch != null)
  452. git.checkout().setName(originalBranch).call();
  453. else if (empty)
  454. git.branchCreate().setName(branch).setStartPoint(commit).call();
  455. return commit;
  456. } catch (IOException | GitAPIException e) {
  457. throw new RuntimeException(e);
  458. }
  459. }
  460. /**
  461. * Create <code>DirCacheEntry</code>
  462. *
  463. * @param path
  464. * @param mode
  465. * @return the DirCacheEntry
  466. */
  467. protected DirCacheEntry createEntry(String path, FileMode mode) {
  468. return createEntry(path, mode, DirCacheEntry.STAGE_0, path);
  469. }
  470. /**
  471. * Create <code>DirCacheEntry</code>
  472. *
  473. * @param path
  474. * @param mode
  475. * @param content
  476. * @return the DirCacheEntry
  477. */
  478. protected DirCacheEntry createEntry(final String path, final FileMode mode,
  479. final String content) {
  480. return createEntry(path, mode, DirCacheEntry.STAGE_0, content);
  481. }
  482. /**
  483. * Create <code>DirCacheEntry</code>
  484. *
  485. * @param path
  486. * @param mode
  487. * @param stage
  488. * @param content
  489. * @return the DirCacheEntry
  490. */
  491. protected DirCacheEntry createEntry(final String path, final FileMode mode,
  492. final int stage, final String content) {
  493. final DirCacheEntry entry = new DirCacheEntry(path, stage);
  494. entry.setFileMode(mode);
  495. try (ObjectInserter.Formatter formatter = new ObjectInserter.Formatter()) {
  496. entry.setObjectId(formatter.idFor(
  497. Constants.OBJ_BLOB, Constants.encode(content)));
  498. }
  499. return entry;
  500. }
  501. /**
  502. * Create <code>DirCacheEntry</code>
  503. *
  504. * @param path
  505. * @param objectId
  506. * @return the DirCacheEntry
  507. */
  508. protected DirCacheEntry createGitLink(String path, AnyObjectId objectId) {
  509. final DirCacheEntry entry = new DirCacheEntry(path,
  510. DirCacheEntry.STAGE_0);
  511. entry.setFileMode(FileMode.GITLINK);
  512. entry.setObjectId(objectId);
  513. return entry;
  514. }
  515. /**
  516. * Assert files are equal
  517. *
  518. * @param expected
  519. * @param actual
  520. * @throws IOException
  521. */
  522. public static void assertEqualsFile(File expected, File actual)
  523. throws IOException {
  524. assertEquals(expected.getCanonicalFile(), actual.getCanonicalFile());
  525. }
  526. }