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

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