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

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