View Javadoc
1   /*
2    * Copyright (C) 2008-2009, Google Inc.
3    * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
4    * and other copyright owners as documented in the project's IP log.
5    *
6    * This program and the accompanying materials are made available
7    * under the terms of the Eclipse Distribution License v1.0 which
8    * accompanies this distribution, is reproduced below, and is
9    * available at http://www.eclipse.org/org/documents/edl-v10.php
10   *
11   * All rights reserved.
12   *
13   * Redistribution and use in source and binary forms, with or
14   * without modification, are permitted provided that the following
15   * conditions are met:
16   *
17   * - Redistributions of source code must retain the above copyright
18   *   notice, this list of conditions and the following disclaimer.
19   *
20   * - Redistributions in binary form must reproduce the above
21   *   copyright notice, this list of conditions and the following
22   *   disclaimer in the documentation and/or other materials provided
23   *   with the distribution.
24   *
25   * - Neither the name of the Eclipse Foundation, Inc. nor the
26   *   names of its contributors may be used to endorse or promote
27   *   products derived from this software without specific prior
28   *   written permission.
29   *
30   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
31   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
32   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
35   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
38   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
39   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
40   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
41   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
42   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43   */
44  
45  package org.eclipse.jgit.dircache;
46  
47  import static org.eclipse.jgit.lib.FileMode.TREE;
48  import static org.eclipse.jgit.lib.TreeFormatter.entrySize;
49  
50  import java.io.IOException;
51  import java.io.OutputStream;
52  import java.nio.ByteBuffer;
53  import java.util.Arrays;
54  import java.util.Comparator;
55  
56  import org.eclipse.jgit.errors.UnmergedPathException;
57  import org.eclipse.jgit.lib.Constants;
58  import org.eclipse.jgit.lib.ObjectId;
59  import org.eclipse.jgit.lib.ObjectInserter;
60  import org.eclipse.jgit.lib.TreeFormatter;
61  import org.eclipse.jgit.util.MutableInteger;
62  import org.eclipse.jgit.util.RawParseUtils;
63  
64  /**
65   * Single tree record from the 'TREE' {@link DirCache} extension.
66   * <p>
67   * A valid cache tree record contains the object id of a tree object and the
68   * total number of {@link DirCacheEntry} instances (counted recursively) from
69   * the DirCache contained within the tree. This information facilitates faster
70   * traversal of the index and quicker generation of tree objects prior to
71   * creating a new commit.
72   * <p>
73   * An invalid cache tree record indicates a known subtree whose file entries
74   * have changed in ways that cause the tree to no longer have a known object id.
75   * Invalid cache tree records must be revalidated prior to use.
76   */
77  public class DirCacheTree {
78  	private static final byte[] NO_NAME = {};
79  
80  	private static final DirCacheTree[] NO_CHILDREN = {};
81  
82  	private static final Comparator<DirCacheTree> TREE_CMP = new Comparator<DirCacheTree>() {
83  		public int compare(final DirCacheTree o1, final DirCacheTree o2) {
84  			final byte[] a = o1.encodedName;
85  			final byte[] b = o2.encodedName;
86  			final int aLen = a.length;
87  			final int bLen = b.length;
88  			int cPos;
89  			for (cPos = 0; cPos < aLen && cPos < bLen; cPos++) {
90  				final int cmp = (a[cPos] & 0xff) - (b[cPos] & 0xff);
91  				if (cmp != 0)
92  					return cmp;
93  			}
94  			if (aLen == bLen)
95  				return 0;
96  			if (aLen < bLen)
97  				return '/' - (b[cPos] & 0xff);
98  			return (a[cPos] & 0xff) - '/';
99  		}
100 	};
101 
102 	/** Tree this tree resides in; null if we are the root. */
103 	private DirCacheTree parent;
104 
105 	/** Name of this tree within its parent. */
106 	private byte[] encodedName;
107 
108 	/** Number of {@link DirCacheEntry} records that belong to this tree. */
109 	private int entrySpan;
110 
111 	/** Unique SHA-1 of this tree; null if invalid. */
112 	private ObjectId id;
113 
114 	/** Child trees, if any, sorted by {@link #encodedName}. */
115 	private DirCacheTree[] children;
116 
117 	/** Number of valid children in {@link #children}. */
118 	private int childCnt;
119 
120 	DirCacheTree() {
121 		encodedName = NO_NAME;
122 		children = NO_CHILDREN;
123 		childCnt = 0;
124 		entrySpan = -1;
125 	}
126 
127 	private DirCacheTree(final DirCacheTree myParent, final byte[] path,
128 			final int pathOff, final int pathLen) {
129 		parent = myParent;
130 		encodedName = new byte[pathLen];
131 		System.arraycopy(path, pathOff, encodedName, 0, pathLen);
132 		children = NO_CHILDREN;
133 		childCnt = 0;
134 		entrySpan = -1;
135 	}
136 
137 	DirCacheTree(final byte[] in, final MutableInteger off,
138 			final DirCacheTree myParent) {
139 		parent = myParent;
140 
141 		int ptr = RawParseUtils.next(in, off.value, '\0');
142 		final int nameLen = ptr - off.value - 1;
143 		if (nameLen > 0) {
144 			encodedName = new byte[nameLen];
145 			System.arraycopy(in, off.value, encodedName, 0, nameLen);
146 		} else
147 			encodedName = NO_NAME;
148 
149 		entrySpan = RawParseUtils.parseBase10(in, ptr, off);
150 		final int subcnt = RawParseUtils.parseBase10(in, off.value, off);
151 		off.value = RawParseUtils.next(in, off.value, '\n');
152 
153 		if (entrySpan >= 0) {
154 			// Valid trees have a positive entry count and an id of a
155 			// tree object that should exist in the object database.
156 			//
157 			id = ObjectId.fromRaw(in, off.value);
158 			off.value += Constants.OBJECT_ID_LENGTH;
159 		}
160 
161 		if (subcnt > 0) {
162 			boolean alreadySorted = true;
163 			children = new DirCacheTree[subcnt];
164 			for (int i = 0; i < subcnt; i++) {
165 				children[i] = new DirCacheTree(in, off, this);
166 
167 				// C Git's ordering differs from our own; it prefers to
168 				// sort by length first. This sometimes produces a sort
169 				// we do not desire. On the other hand it may have been
170 				// created by us, and be sorted the way we want.
171 				//
172 				if (alreadySorted && i > 0
173 						&& TREE_CMP.compare(children[i - 1], children[i]) > 0)
174 					alreadySorted = false;
175 			}
176 			if (!alreadySorted)
177 				Arrays.sort(children, 0, subcnt, TREE_CMP);
178 		} else {
179 			// Leaf level trees have no children, only (file) entries.
180 			//
181 			children = NO_CHILDREN;
182 		}
183 		childCnt = subcnt;
184 	}
185 
186 	void write(final byte[] tmp, final OutputStream os) throws IOException {
187 		int ptr = tmp.length;
188 		tmp[--ptr] = '\n';
189 		ptr = RawParseUtils.formatBase10(tmp, ptr, childCnt);
190 		tmp[--ptr] = ' ';
191 		ptr = RawParseUtils.formatBase10(tmp, ptr, isValid() ? entrySpan : -1);
192 		tmp[--ptr] = 0;
193 
194 		os.write(encodedName);
195 		os.write(tmp, ptr, tmp.length - ptr);
196 		if (isValid()) {
197 			id.copyRawTo(tmp, 0);
198 			os.write(tmp, 0, Constants.OBJECT_ID_LENGTH);
199 		}
200 		for (int i = 0; i < childCnt; i++)
201 			children[i].write(tmp, os);
202 	}
203 
204 	/**
205 	 * Determine if this cache is currently valid.
206 	 * <p>
207 	 * A valid cache tree knows how many {@link DirCacheEntry} instances from
208 	 * the parent {@link DirCache} reside within this tree (recursively
209 	 * enumerated). It also knows the object id of the tree, as the tree should
210 	 * be readily available from the repository's object database.
211 	 *
212 	 * @return true if this tree is knows key details about itself; false if the
213 	 *         tree needs to be regenerated.
214 	 */
215 	public boolean isValid() {
216 		return id != null;
217 	}
218 
219 	/**
220 	 * Get the number of entries this tree spans within the DirCache.
221 	 * <p>
222 	 * If this tree is not valid (see {@link #isValid()}) this method's return
223 	 * value is always strictly negative (less than 0) but is otherwise an
224 	 * undefined result.
225 	 *
226 	 * @return total number of entries (recursively) contained within this tree.
227 	 */
228 	public int getEntrySpan() {
229 		return entrySpan;
230 	}
231 
232 	/**
233 	 * Get the number of cached subtrees contained within this tree.
234 	 *
235 	 * @return number of child trees available through this tree.
236 	 */
237 	public int getChildCount() {
238 		return childCnt;
239 	}
240 
241 	/**
242 	 * Get the i-th child cache tree.
243 	 *
244 	 * @param i
245 	 *            index of the child to obtain.
246 	 * @return the child tree.
247 	 */
248 	public DirCacheTree getChild(final int i) {
249 		return children[i];
250 	}
251 
252 	ObjectId getObjectId() {
253 		return id;
254 	}
255 
256 	/**
257 	 * Get the tree's name within its parent.
258 	 * <p>
259 	 * This method is not very efficient and is primarily meant for debugging
260 	 * and final output generation. Applications should try to avoid calling it,
261 	 * and if invoked do so only once per interesting entry, where the name is
262 	 * absolutely required for correct function.
263 	 *
264 	 * @return name of the tree. This does not contain any '/' characters.
265 	 */
266 	public String getNameString() {
267 		final ByteBuffer bb = ByteBuffer.wrap(encodedName);
268 		return Constants.CHARSET.decode(bb).toString();
269 	}
270 
271 	/**
272 	 * Get the tree's path within the repository.
273 	 * <p>
274 	 * This method is not very efficient and is primarily meant for debugging
275 	 * and final output generation. Applications should try to avoid calling it,
276 	 * and if invoked do so only once per interesting entry, where the name is
277 	 * absolutely required for correct function.
278 	 *
279 	 * @return path of the tree, relative to the repository root. If this is not
280 	 *         the root tree the path ends with '/'. The root tree's path string
281 	 *         is the empty string ("").
282 	 */
283 	public String getPathString() {
284 		final StringBuilder r = new StringBuilder();
285 		appendName(r);
286 		return r.toString();
287 	}
288 
289 	/**
290 	 * Write (if necessary) this tree to the object store.
291 	 *
292 	 * @param cache
293 	 *            the complete cache from DirCache.
294 	 * @param cIdx
295 	 *            first position of <code>cache</code> that is a member of this
296 	 *            tree. The path of <code>cache[cacheIdx].path</code> for the
297 	 *            range <code>[0,pathOff-1)</code> matches the complete path of
298 	 *            this tree, from the root of the repository.
299 	 * @param pathOffset
300 	 *            number of bytes of <code>cache[cacheIdx].path</code> that
301 	 *            matches this tree's path. The value at array position
302 	 *            <code>cache[cacheIdx].path[pathOff-1]</code> is always '/' if
303 	 *            <code>pathOff</code> is > 0.
304 	 * @param ow
305 	 *            the writer to use when serializing to the store.
306 	 * @return identity of this tree.
307 	 * @throws UnmergedPathException
308 	 *             one or more paths contain higher-order stages (stage > 0),
309 	 *             which cannot be stored in a tree object.
310 	 * @throws IOException
311 	 *             an unexpected error occurred writing to the object store.
312 	 */
313 	ObjectId writeTree(final DirCacheEntry[] cache, int cIdx,
314 			final int pathOffset, final ObjectInserter ow)
315 			throws UnmergedPathException, IOException {
316 		if (id == null) {
317 			final int endIdx = cIdx + entrySpan;
318 			final TreeFormatter fmt = new TreeFormatter(computeSize(cache,
319 					cIdx, pathOffset, ow));
320 			int childIdx = 0;
321 			int entryIdx = cIdx;
322 
323 			while (entryIdx < endIdx) {
324 				final DirCacheEntry e = cache[entryIdx];
325 				final byte[] ep = e.path;
326 				if (childIdx < childCnt) {
327 					final DirCacheTree st = children[childIdx];
328 					if (st.contains(ep, pathOffset, ep.length)) {
329 						fmt.append(st.encodedName, TREE, st.id);
330 						entryIdx += st.entrySpan;
331 						childIdx++;
332 						continue;
333 					}
334 				}
335 
336 				fmt.append(ep, pathOffset, ep.length - pathOffset, e
337 						.getFileMode(), e.idBuffer(), e.idOffset());
338 				entryIdx++;
339 			}
340 
341 			id = ow.insert(fmt);
342 		}
343 		return id;
344 	}
345 
346 	private int computeSize(final DirCacheEntry[] cache, int cIdx,
347 			final int pathOffset, final ObjectInserter ow)
348 			throws UnmergedPathException, IOException {
349 		final int endIdx = cIdx + entrySpan;
350 		int childIdx = 0;
351 		int entryIdx = cIdx;
352 		int size = 0;
353 
354 		while (entryIdx < endIdx) {
355 			final DirCacheEntry e = cache[entryIdx];
356 			if (e.getStage() != 0)
357 				throw new UnmergedPathException(e);
358 
359 			final byte[] ep = e.path;
360 			if (childIdx < childCnt) {
361 				final DirCacheTree st = children[childIdx];
362 				if (st.contains(ep, pathOffset, ep.length)) {
363 					final int stOffset = pathOffset + st.nameLength() + 1;
364 					st.writeTree(cache, entryIdx, stOffset, ow);
365 
366 					size += entrySize(TREE, st.nameLength());
367 
368 					entryIdx += st.entrySpan;
369 					childIdx++;
370 					continue;
371 				}
372 			}
373 
374 			size += entrySize(e.getFileMode(), ep.length - pathOffset);
375 			entryIdx++;
376 		}
377 
378 		return size;
379 	}
380 
381 	private void appendName(final StringBuilder r) {
382 		if (parent != null) {
383 			parent.appendName(r);
384 			r.append(getNameString());
385 			r.append('/');
386 		} else if (nameLength() > 0) {
387 			r.append(getNameString());
388 			r.append('/');
389 		}
390 	}
391 
392 	final int nameLength() {
393 		return encodedName.length;
394 	}
395 
396 	final boolean contains(final byte[] a, int aOff, final int aLen) {
397 		final byte[] e = encodedName;
398 		final int eLen = e.length;
399 		for (int eOff = 0; eOff < eLen && aOff < aLen; eOff++, aOff++)
400 			if (e[eOff] != a[aOff])
401 				return false;
402 		if (aOff >= aLen)
403 			return false;
404 		return a[aOff] == '/';
405 	}
406 
407 	/**
408 	 * Update (if necessary) this tree's entrySpan.
409 	 *
410 	 * @param cache
411 	 *            the complete cache from DirCache.
412 	 * @param cCnt
413 	 *            number of entries in <code>cache</code> that are valid for
414 	 *            iteration.
415 	 * @param cIdx
416 	 *            first position of <code>cache</code> that is a member of this
417 	 *            tree. The path of <code>cache[cacheIdx].path</code> for the
418 	 *            range <code>[0,pathOff-1)</code> matches the complete path of
419 	 *            this tree, from the root of the repository.
420 	 * @param pathOff
421 	 *            number of bytes of <code>cache[cacheIdx].path</code> that
422 	 *            matches this tree's path. The value at array position
423 	 *            <code>cache[cacheIdx].path[pathOff-1]</code> is always '/' if
424 	 *            <code>pathOff</code> is > 0.
425 	 */
426 	void validate(final DirCacheEntry[] cache, final int cCnt, int cIdx,
427 			final int pathOff) {
428 		if (entrySpan >= 0 && cIdx + entrySpan <= cCnt) {
429 			// If we are valid, our children are also valid.
430 			// We have no need to validate them.
431 			//
432 			return;
433 		}
434 
435 		entrySpan = 0;
436 		if (cCnt == 0) {
437 			// Special case of an empty index, and we are the root tree.
438 			//
439 			return;
440 		}
441 
442 		final byte[] firstPath = cache[cIdx].path;
443 		int stIdx = 0;
444 		while (cIdx < cCnt) {
445 			final byte[] currPath = cache[cIdx].path;
446 			if (pathOff > 0 && !peq(firstPath, currPath, pathOff)) {
447 				// The current entry is no longer in this tree. Our
448 				// span is updated and the remainder goes elsewhere.
449 				//
450 				break;
451 			}
452 
453 			DirCacheTree st = stIdx < childCnt ? children[stIdx] : null;
454 			final int cc = namecmp(currPath, pathOff, st);
455 			if (cc > 0) {
456 				// This subtree is now empty.
457 				//
458 				removeChild(stIdx);
459 				continue;
460 			}
461 
462 			if (cc < 0) {
463 				final int p = slash(currPath, pathOff);
464 				if (p < 0) {
465 					// The entry has no '/' and thus is directly in this
466 					// tree. Count it as one of our own.
467 					//
468 					cIdx++;
469 					entrySpan++;
470 					continue;
471 				}
472 
473 				// Build a new subtree for this entry.
474 				//
475 				st = new DirCacheTree(this, currPath, pathOff, p - pathOff);
476 				insertChild(stIdx, st);
477 			}
478 
479 			// The entry is contained in this subtree.
480 			//
481 			assert(st != null);
482 			st.validate(cache, cCnt, cIdx, pathOff + st.nameLength() + 1);
483 			cIdx += st.entrySpan;
484 			entrySpan += st.entrySpan;
485 			stIdx++;
486 		}
487 
488 		// None of our remaining children can be in this tree
489 		// as the current cache entry is after our own name.
490 		//
491 		while (stIdx < childCnt)
492 			removeChild(childCnt - 1);
493 	}
494 
495 	private void insertChild(final int stIdx, final DirCacheTree st) {
496 		final DirCacheTree[] c = children;
497 		if (childCnt + 1 <= c.length) {
498 			if (stIdx < childCnt)
499 				System.arraycopy(c, stIdx, c, stIdx + 1, childCnt - stIdx);
500 			c[stIdx] = st;
501 			childCnt++;
502 			return;
503 		}
504 
505 		final int n = c.length;
506 		final DirCacheTree[] a = new DirCacheTree[n + 1];
507 		if (stIdx > 0)
508 			System.arraycopy(c, 0, a, 0, stIdx);
509 		a[stIdx] = st;
510 		if (stIdx < n)
511 			System.arraycopy(c, stIdx, a, stIdx + 1, n - stIdx);
512 		children = a;
513 		childCnt++;
514 	}
515 
516 	private void removeChild(final int stIdx) {
517 		final int n = --childCnt;
518 		if (stIdx < n)
519 			System.arraycopy(children, stIdx + 1, children, stIdx, n - stIdx);
520 		children[n] = null;
521 	}
522 
523 	static boolean peq(final byte[] a, final byte[] b, int aLen) {
524 		if (b.length < aLen)
525 			return false;
526 		for (aLen--; aLen >= 0; aLen--)
527 			if (a[aLen] != b[aLen])
528 				return false;
529 		return true;
530 	}
531 
532 	private static int namecmp(final byte[] a, int aPos, final DirCacheTree ct) {
533 		if (ct == null)
534 			return -1;
535 		final byte[] b = ct.encodedName;
536 		final int aLen = a.length;
537 		final int bLen = b.length;
538 		int bPos = 0;
539 		for (; aPos < aLen && bPos < bLen; aPos++, bPos++) {
540 			final int cmp = (a[aPos] & 0xff) - (b[bPos] & 0xff);
541 			if (cmp != 0)
542 				return cmp;
543 		}
544 		if (bPos == bLen)
545 			return a[aPos] == '/' ? 0 : -1;
546 		return aLen - bLen;
547 	}
548 
549 	private static int slash(final byte[] a, int aPos) {
550 		final int aLen = a.length;
551 		for (; aPos < aLen; aPos++)
552 			if (a[aPos] == '/')
553 				return aPos;
554 		return -1;
555 	}
556 
557 	@Override
558 	public String toString() {
559 		return getNameString();
560 	}
561 }