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

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