add fsTick() to RepositoryTestCase
[jgit.git] / org.eclipse.jgit.test / tst / org / eclipse / jgit / lib / RepositoryTestCase.java
blob36b28ae0779ceb6f305d51076b899a0ea0de8fce
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.
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
13 * All rights reserved.
15 * Redistribution and use in source and binary forms, with or
16 * without modification, are permitted provided that the following
17 * conditions are met:
19 * - Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
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.
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.
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.
47 package org.eclipse.jgit.lib;
49 import java.io.File;
50 import java.io.FileInputStream;
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 java.util.TreeSet;
58 import org.eclipse.jgit.dircache.DirCache;
59 import org.eclipse.jgit.dircache.DirCacheIterator;
60 import org.eclipse.jgit.junit.LocalDiskRepositoryTestCase;
61 import org.eclipse.jgit.storage.file.FileRepository;
62 import org.eclipse.jgit.treewalk.NameConflictTreeWalk;
64 /**
65 * Base class for most JGit unit tests.
67 * Sets up a predefined test repository and has support for creating additional
68 * repositories and destroying them when the tests are finished.
70 public abstract class RepositoryTestCase extends LocalDiskRepositoryTestCase {
71 protected static void copyFile(final File src, final File dst)
72 throws IOException {
73 final FileInputStream fis = new FileInputStream(src);
74 try {
75 final FileOutputStream fos = new FileOutputStream(dst);
76 try {
77 final byte[] buf = new byte[4096];
78 int r;
79 while ((r = fis.read(buf)) > 0) {
80 fos.write(buf, 0, r);
82 } finally {
83 fos.close();
85 } finally {
86 fis.close();
90 protected File writeTrashFile(final String name, final String data)
91 throws IOException {
92 File path = new File(db.getWorkTree(), name);
93 write(path, data);
94 return path;
97 protected static void checkFile(File f, final String checkData)
98 throws IOException {
99 Reader r = new InputStreamReader(new FileInputStream(f), "ISO-8859-1");
100 try {
101 char[] data = new char[(int) f.length()];
102 if (f.length() != r.read(data))
103 throw new IOException("Internal error reading file data from "+f);
104 assertEquals(checkData, new String(data));
105 } finally {
106 r.close();
110 /** Test repository, initialized for this test case. */
111 protected FileRepository db;
113 /** Working directory of {@link #db}. */
114 protected File trash;
116 @Override
117 protected void setUp() throws Exception {
118 super.setUp();
119 db = createWorkRepository();
120 trash = db.getWorkTree();
123 public static final int MOD_TIME = 1;
125 public static final int SMUDGE = 2;
127 public static final int LENGTH = 4;
129 public static final int CONTENT_ID = 8;
132 * Represent the state of the index in one String. This representation is
133 * useful when writing tests which do assertions on the state of the index.
134 * By default information about path, mode, stage (if different from 0) is
135 * included. A bitmask controls which additional info about
136 * modificationTimes, smudge state and length is included.
137 * <p>
138 * The format of the returned string is described with this BNF:
140 * <pre>
141 * result = ( "[" path mode stage? time? smudge? length? sha1? "]" )* .
142 * mode = ", mode:" number .
143 * stage = ", stage:" number .
144 * time = ", time:t" timestamp-index .
145 * smudge = "" | ", smudged" .
146 * length = ", length:" number .
147 * sha1 = ", sha1:" hex-sha1 .
149 * 'stage' is only presented when the stage is different from 0. All
150 * reported time stamps are mapped to strings like "t0", "t1", ... "tn". The
151 * smallest reported time-stamp will be called "t0". This allows to write
152 * assertions against the string although the concrete value of the
153 * time stamps is unknown.
155 * @param includedOptions
156 * a bitmask constructed out of the constants {@link #MOD_TIME},
157 * {@link #SMUDGE}, {@link #LENGTH} and {@link #CONTENT_ID}
158 * controlling which info is present in the resulting string.
159 * @return a string encoding the index state
160 * @throws IllegalStateException
161 * @throws IOException
163 public String indexState(int includedOptions)
164 throws IllegalStateException, IOException {
165 DirCache dc = db.readDirCache();
166 StringBuilder sb = new StringBuilder();
167 TreeSet<Long> timeStamps = null;
169 // iterate once over the dircache just to collect all time stamps
170 if (0 != (includedOptions & MOD_TIME)) {
171 timeStamps = new TreeSet<Long>();
172 for (int i=0; i<dc.getEntryCount(); ++i)
173 timeStamps.add(Long.valueOf(dc.getEntry(i).getLastModified()));
176 // iterate again, now produce the result string
177 NameConflictTreeWalk tw = new NameConflictTreeWalk(db);
178 tw.reset();
179 tw.addTree(new DirCacheIterator(dc));
180 while (tw.next()) {
181 DirCacheIterator dcIt = tw.getTree(0, DirCacheIterator.class);
182 sb.append("["+tw.getPathString()+", mode:" + dcIt.getEntryFileMode());
183 int stage = dcIt.getDirCacheEntry().getStage();
184 if (stage != 0)
185 sb.append(", stage:" + stage);
186 if (0 != (includedOptions & MOD_TIME)) {
187 sb.append(", time:t"+
188 timeStamps.headSet(Long.valueOf(dcIt.getDirCacheEntry().getLastModified())).size());
190 if (0 != (includedOptions & SMUDGE))
191 if (dcIt.getDirCacheEntry().isSmudged())
192 sb.append(", smudged");
193 if (0 != (includedOptions & LENGTH))
194 sb.append(", length:"
195 + Integer.toString(dcIt.getDirCacheEntry().getLength()));
196 if (0 != (includedOptions & CONTENT_ID))
197 sb.append(", sha1:" + ObjectId.toString(dcIt
198 .getEntryObjectId()));
199 sb.append("]");
201 return sb.toString();
205 * Helper method to map arbitrary objects to user-defined names. This can be
206 * used create short names for objects to produce small and stable debug
207 * output. It is guaranteed that when you lookup the same object multiple
208 * times even with different nameTemplates this method will always return
209 * the same name which was derived from the first nameTemplate.
210 * nameTemplates can contain "%n" which will be replaced by a running number
211 * before used as a name.
213 * @param l
214 * the object to lookup
215 * @param nameTemplate
216 * the name for that object. Can contain "%n" which will be
217 * replaced by a running number before used as a name. If the
218 * lookup table already contains the object this parameter will
219 * be ignored
220 * @param lookupTable
221 * a table storing object-name mappings.
222 * @return a name of that object. Is not guaranteed to be unique. Use
223 * nameTemplates containing "%n" to always have unique names
225 public static String lookup(Object l, String nameTemplate,
226 Map<Object, String> lookupTable) {
227 String name = lookupTable.get(l);
228 if (name == null) {
229 name = nameTemplate.replaceAll("%n",
230 Integer.toString(lookupTable.size()));
231 lookupTable.put(l, name);
233 return name;
237 * Waits until it is guaranteed that a subsequent file modification has a
238 * younger modification timestamp than the modification timestamp of the
239 * given file. This is done by touching a temporary file, reading the
240 * lastmodified attribute and, if needed, sleeping. After sleeping this loop
241 * starts again until the filesystem timer has advanced enough.
243 * @param lastFile
244 * the file on which we want to wait until the filesystem timer
245 * has advanced more than the lastmodification timestamp of this
246 * file
247 * @return return the last measured value of the filesystem timer which is
248 * greater than then the lastmodification time of lastfile.
249 * @throws InterruptedException
250 * @throws IOException
252 public static long fsTick(File lastFile) throws InterruptedException,
253 IOException {
254 long sleepTime = 1;
255 File tmp = File.createTempFile("FileTreeIteratorWithTimeControl", null);
256 try {
257 long startTime = (lastFile == null) ? tmp.lastModified() : lastFile
258 .lastModified();
259 long actTime = tmp.lastModified();
260 while (actTime <= startTime) {
261 Thread.sleep(sleepTime);
262 sleepTime *= 5;
263 tmp.setLastModified(System.currentTimeMillis());
264 actTime = tmp.lastModified();
266 return actTime;
267 } finally {
268 tmp.delete();