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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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 org.junit.Assert.assertEquals;
  48. import java.io.File;
  49. import java.io.FileInputStream;
  50. import java.io.FileNotFoundException;
  51. import java.io.FileOutputStream;
  52. import java.io.IOException;
  53. import java.io.InputStreamReader;
  54. import java.io.Reader;
  55. import java.util.Map;
  56. import java.util.TreeSet;
  57. import org.eclipse.jgit.api.Git;
  58. import org.eclipse.jgit.api.errors.GitAPIException;
  59. import org.eclipse.jgit.dircache.DirCache;
  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. protected static void copyFile(final File src, final File dst)
  84. throws IOException {
  85. final FileInputStream fis = new FileInputStream(src);
  86. try {
  87. final FileOutputStream fos = new FileOutputStream(dst);
  88. try {
  89. final byte[] buf = new byte[4096];
  90. int r;
  91. while ((r = fis.read(buf)) > 0) {
  92. fos.write(buf, 0, r);
  93. }
  94. } finally {
  95. fos.close();
  96. }
  97. } finally {
  98. fis.close();
  99. }
  100. }
  101. protected File writeTrashFile(final String name, final String data)
  102. throws IOException {
  103. return JGitTestUtil.writeTrashFile(db, name, data);
  104. }
  105. protected File writeTrashFile(final String subdir, final String name,
  106. final String data)
  107. throws IOException {
  108. return JGitTestUtil.writeTrashFile(db, subdir, name, data);
  109. }
  110. protected String read(final String name) throws IOException {
  111. return JGitTestUtil.read(db, name);
  112. }
  113. protected boolean check(final String name) {
  114. return JGitTestUtil.check(db, name);
  115. }
  116. protected void deleteTrashFile(final String name) throws IOException {
  117. JGitTestUtil.deleteTrashFile(db, name);
  118. }
  119. protected static void checkFile(File f, final String checkData)
  120. throws IOException {
  121. Reader r = new InputStreamReader(new FileInputStream(f), "ISO-8859-1");
  122. try {
  123. char[] data = new char[(int) f.length()];
  124. if (f.length() != r.read(data))
  125. throw new IOException("Internal error reading file data from "+f);
  126. assertEquals(checkData, new String(data));
  127. } finally {
  128. r.close();
  129. }
  130. }
  131. /** Test repository, initialized for this test case. */
  132. protected FileRepository db;
  133. /** Working directory of {@link #db}. */
  134. protected File trash;
  135. @Override
  136. @Before
  137. public void setUp() throws Exception {
  138. super.setUp();
  139. db = createWorkRepository();
  140. trash = db.getWorkTree();
  141. }
  142. public static final int MOD_TIME = 1;
  143. public static final int SMUDGE = 2;
  144. public static final int LENGTH = 4;
  145. public static final int CONTENT_ID = 8;
  146. public static final int CONTENT = 16;
  147. public static final int ASSUME_UNCHANGED = 32;
  148. /**
  149. * Represent the state of the index in one String. This representation is
  150. * useful when writing tests which do assertions on the state of the index.
  151. * By default information about path, mode, stage (if different from 0) is
  152. * included. A bitmask controls which additional info about
  153. * modificationTimes, smudge state and length is included.
  154. * <p>
  155. * The format of the returned string is described with this BNF:
  156. *
  157. * <pre>
  158. * result = ( "[" path mode stage? time? smudge? length? sha1? content? "]" )* .
  159. * mode = ", mode:" number .
  160. * stage = ", stage:" number .
  161. * time = ", time:t" timestamp-index .
  162. * smudge = "" | ", smudged" .
  163. * length = ", length:" number .
  164. * sha1 = ", sha1:" hex-sha1 .
  165. * content = ", content:" blob-data .
  166. * </pre>
  167. *
  168. * 'stage' is only presented when the stage is different from 0. All
  169. * reported time stamps are mapped to strings like "t0", "t1", ... "tn". The
  170. * smallest reported time-stamp will be called "t0". This allows to write
  171. * assertions against the string although the concrete value of the time
  172. * stamps is unknown.
  173. *
  174. * @param repo
  175. * the repository the index state should be determined for
  176. *
  177. * @param includedOptions
  178. * a bitmask constructed out of the constants {@link #MOD_TIME},
  179. * {@link #SMUDGE}, {@link #LENGTH}, {@link #CONTENT_ID} and
  180. * {@link #CONTENT} controlling which info is present in the
  181. * resulting string.
  182. * @return a string encoding the index state
  183. * @throws IllegalStateException
  184. * @throws IOException
  185. */
  186. public String indexState(Repository repo, int includedOptions)
  187. throws IllegalStateException, IOException {
  188. DirCache dc = repo.readDirCache();
  189. StringBuilder sb = new StringBuilder();
  190. TreeSet<Long> timeStamps = null;
  191. // iterate once over the dircache just to collect all time stamps
  192. if (0 != (includedOptions & MOD_TIME)) {
  193. timeStamps = new TreeSet<Long>();
  194. for (int i=0; i<dc.getEntryCount(); ++i)
  195. timeStamps.add(Long.valueOf(dc.getEntry(i).getLastModified()));
  196. }
  197. // iterate again, now produce the result string
  198. for (int i=0; i<dc.getEntryCount(); ++i) {
  199. DirCacheEntry entry = dc.getEntry(i);
  200. sb.append("["+entry.getPathString()+", mode:" + entry.getFileMode());
  201. int stage = entry.getStage();
  202. if (stage != 0)
  203. sb.append(", stage:" + stage);
  204. if (0 != (includedOptions & MOD_TIME)) {
  205. sb.append(", time:t"+
  206. timeStamps.headSet(Long.valueOf(entry.getLastModified())).size());
  207. }
  208. if (0 != (includedOptions & SMUDGE))
  209. if (entry.isSmudged())
  210. sb.append(", smudged");
  211. if (0 != (includedOptions & LENGTH))
  212. sb.append(", length:"
  213. + Integer.toString(entry.getLength()));
  214. if (0 != (includedOptions & CONTENT_ID))
  215. sb.append(", sha1:" + ObjectId.toString(entry.getObjectId()));
  216. if (0 != (includedOptions & CONTENT)) {
  217. sb.append(", content:"
  218. + new String(db.open(entry.getObjectId(),
  219. Constants.OBJ_BLOB).getCachedBytes(), "UTF-8"));
  220. }
  221. if (0 != (includedOptions & ASSUME_UNCHANGED))
  222. sb.append(", assume-unchanged:"
  223. + Boolean.toString(entry.isAssumeValid()));
  224. sb.append("]");
  225. }
  226. return sb.toString();
  227. }
  228. /**
  229. * Represent the state of the index in one String. This representation is
  230. * useful when writing tests which do assertions on the state of the index.
  231. * By default information about path, mode, stage (if different from 0) is
  232. * included. A bitmask controls which additional info about
  233. * modificationTimes, smudge state and length is included.
  234. * <p>
  235. * The format of the returned string is described with this BNF:
  236. *
  237. * <pre>
  238. * result = ( "[" path mode stage? time? smudge? length? sha1? content? "]" )* .
  239. * mode = ", mode:" number .
  240. * stage = ", stage:" number .
  241. * time = ", time:t" timestamp-index .
  242. * smudge = "" | ", smudged" .
  243. * length = ", length:" number .
  244. * sha1 = ", sha1:" hex-sha1 .
  245. * content = ", content:" blob-data .
  246. * </pre>
  247. *
  248. * 'stage' is only presented when the stage is different from 0. All
  249. * reported time stamps are mapped to strings like "t0", "t1", ... "tn". The
  250. * smallest reported time-stamp will be called "t0". This allows to write
  251. * assertions against the string although the concrete value of the time
  252. * stamps is unknown.
  253. *
  254. * @param includedOptions
  255. * a bitmask constructed out of the constants {@link #MOD_TIME},
  256. * {@link #SMUDGE}, {@link #LENGTH}, {@link #CONTENT_ID} and
  257. * {@link #CONTENT} controlling which info is present in the
  258. * resulting string.
  259. * @return a string encoding the index state
  260. * @throws IllegalStateException
  261. * @throws IOException
  262. */
  263. public String indexState(int includedOptions)
  264. throws IllegalStateException, IOException {
  265. return indexState(db, includedOptions);
  266. }
  267. /**
  268. * Resets the index to represent exactly some filesystem content. E.g. the
  269. * following call will replace the index with the working tree content:
  270. * <p>
  271. * <code>resetIndex(new FileSystemIterator(db))</code>
  272. * <p>
  273. * This method can be used by testcases which first prepare a new commit
  274. * somewhere in the filesystem (e.g. in the working-tree) and then want to
  275. * have an index which matches their prepared content.
  276. *
  277. * @param treeItr
  278. * a {@link FileTreeIterator} which determines which files should
  279. * go into the new index
  280. * @throws FileNotFoundException
  281. * @throws IOException
  282. */
  283. protected void resetIndex(FileTreeIterator treeItr)
  284. throws FileNotFoundException, IOException {
  285. try (ObjectInserter inserter = db.newObjectInserter()) {
  286. DirCacheBuilder builder = db.lockDirCache().builder();
  287. DirCacheEntry dce;
  288. while (!treeItr.eof()) {
  289. long len = treeItr.getEntryLength();
  290. dce = new DirCacheEntry(treeItr.getEntryPathString());
  291. dce.setFileMode(treeItr.getEntryFileMode());
  292. dce.setLastModified(treeItr.getEntryLastModified());
  293. dce.setLength((int) len);
  294. FileInputStream in = new FileInputStream(
  295. treeItr.getEntryFile());
  296. dce.setObjectId(inserter.insert(Constants.OBJ_BLOB, len, in));
  297. in.close();
  298. builder.add(dce);
  299. treeItr.next(1);
  300. }
  301. builder.commit();
  302. inserter.flush();
  303. }
  304. }
  305. /**
  306. * Helper method to map arbitrary objects to user-defined names. This can be
  307. * used create short names for objects to produce small and stable debug
  308. * output. It is guaranteed that when you lookup the same object multiple
  309. * times even with different nameTemplates this method will always return
  310. * the same name which was derived from the first nameTemplate.
  311. * nameTemplates can contain "%n" which will be replaced by a running number
  312. * before used as a name.
  313. *
  314. * @param l
  315. * the object to lookup
  316. * @param nameTemplate
  317. * the name for that object. Can contain "%n" which will be
  318. * replaced by a running number before used as a name. If the
  319. * lookup table already contains the object this parameter will
  320. * be ignored
  321. * @param lookupTable
  322. * a table storing object-name mappings.
  323. * @return a name of that object. Is not guaranteed to be unique. Use
  324. * nameTemplates containing "%n" to always have unique names
  325. */
  326. public static String lookup(Object l, String nameTemplate,
  327. Map<Object, String> lookupTable) {
  328. String name = lookupTable.get(l);
  329. if (name == null) {
  330. name = nameTemplate.replaceAll("%n",
  331. Integer.toString(lookupTable.size()));
  332. lookupTable.put(l, name);
  333. }
  334. return name;
  335. }
  336. /**
  337. * Waits until it is guaranteed that a subsequent file modification has a
  338. * younger modification timestamp than the modification timestamp of the
  339. * given file. This is done by touching a temporary file, reading the
  340. * lastmodified attribute and, if needed, sleeping. After sleeping this loop
  341. * starts again until the filesystem timer has advanced enough.
  342. *
  343. * @param lastFile
  344. * the file on which we want to wait until the filesystem timer
  345. * has advanced more than the lastmodification timestamp of this
  346. * file
  347. * @return return the last measured value of the filesystem timer which is
  348. * greater than then the lastmodification time of lastfile.
  349. * @throws InterruptedException
  350. * @throws IOException
  351. */
  352. public static long fsTick(File lastFile) throws InterruptedException,
  353. IOException {
  354. long sleepTime = 64;
  355. FS fs = FS.DETECTED;
  356. if (lastFile != null && !fs.exists(lastFile))
  357. throw new FileNotFoundException(lastFile.getPath());
  358. File tmp = File.createTempFile("FileTreeIteratorWithTimeControl", null);
  359. try {
  360. long startTime = (lastFile == null) ? fs.lastModified(tmp) : fs
  361. .lastModified(lastFile);
  362. long actTime = fs.lastModified(tmp);
  363. while (actTime <= startTime) {
  364. Thread.sleep(sleepTime);
  365. sleepTime *= 2;
  366. FileOutputStream fos = new FileOutputStream(tmp);
  367. fos.close();
  368. actTime = fs.lastModified(tmp);
  369. }
  370. return actTime;
  371. } finally {
  372. FileUtils.delete(tmp);
  373. }
  374. }
  375. protected void createBranch(ObjectId objectId, String branchName)
  376. throws IOException {
  377. RefUpdate updateRef = db.updateRef(branchName);
  378. updateRef.setNewObjectId(objectId);
  379. updateRef.update();
  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 {
  439. Git git = new Git(db);
  440. Repository repo = git.getRepository();
  441. String originalBranch = repo.getFullBranch();
  442. boolean empty = repo.resolve(Constants.HEAD) == null;
  443. if (!empty) {
  444. if (repo.getRef(branch) == null)
  445. git.branchCreate().setName(branch).call();
  446. git.checkout().setName(branch).call();
  447. }
  448. writeTrashFile(filename, contents);
  449. git.add().addFilepattern(filename).call();
  450. RevCommit commit = git.commit()
  451. .setMessage(branch + ": " + filename).call();
  452. if (originalBranch != null)
  453. git.checkout().setName(originalBranch).call();
  454. else if (empty)
  455. git.branchCreate().setName(branch).setStartPoint(commit).call();
  456. return commit;
  457. } catch (IOException e) {
  458. throw new RuntimeException(e);
  459. } catch (GitAPIException e) {
  460. throw new RuntimeException(e);
  461. }
  462. }
  463. protected DirCacheEntry createEntry(final String path, final FileMode mode) {
  464. return createEntry(path, mode, DirCacheEntry.STAGE_0, path);
  465. }
  466. protected DirCacheEntry createEntry(final String path, final FileMode mode,
  467. final String content) {
  468. return createEntry(path, mode, DirCacheEntry.STAGE_0, content);
  469. }
  470. protected DirCacheEntry createEntry(final String path, final FileMode mode,
  471. final int stage, final String content) {
  472. final DirCacheEntry entry = new DirCacheEntry(path, stage);
  473. entry.setFileMode(mode);
  474. entry.setObjectId(new ObjectInserter.Formatter().idFor(
  475. Constants.OBJ_BLOB, Constants.encode(content)));
  476. return entry;
  477. }
  478. public static void assertEqualsFile(File expected, File actual)
  479. throws IOException {
  480. assertEquals(expected.getCanonicalFile(), actual.getCanonicalFile());
  481. }
  482. }