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

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