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