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