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

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