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