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