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

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