Refactor AbstractTreeIterator semantics to start on first entry
[egit.git] / org.spearce.jgit / src / org / spearce / jgit / treewalk / AbstractTreeIterator.java
blob208adc72488cdbdcefb08bc1a998fe07570059a6
1 /*
2 * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
3 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
5 * All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
9 * conditions are met:
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * - Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following
16 * disclaimer in the documentation and/or other materials provided
17 * with the distribution.
19 * - Neither the name of the Git Development Community nor the
20 * names of its contributors may be used to endorse or promote
21 * products derived from this software without specific prior
22 * written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
25 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
26 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
34 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 package org.spearce.jgit.treewalk;
41 import java.io.IOException;
42 import java.nio.ByteBuffer;
43 import java.nio.CharBuffer;
45 import org.spearce.jgit.errors.CorruptObjectException;
46 import org.spearce.jgit.errors.IncorrectObjectTypeException;
47 import org.spearce.jgit.lib.Constants;
48 import org.spearce.jgit.lib.FileMode;
49 import org.spearce.jgit.lib.ObjectId;
50 import org.spearce.jgit.lib.Repository;
51 import org.spearce.jgit.treewalk.filter.TreeFilter;
53 /**
54 * Walks a Git tree (directory) in Git sort order.
55 * <p>
56 * A new iterator instance should be positioned on the first entry, or at eof.
57 * Data for the first entry (if not at eof) should be available immediately.
58 * <p>
59 * Implementors must walk a tree in the Git sort order, which has the following
60 * odd sorting:
61 * <ol>
62 * <li>A.c</li>
63 * <li>A/c</li>
64 * <li>A0c</li>
65 * </ol>
66 * <p>
67 * In the second item, <code>A</code> is the name of a subtree and
68 * <code>c</code> is a file within that subtree. The other two items are files
69 * in the root level tree.
71 * @see CanonicalTreeParser
73 public abstract class AbstractTreeIterator {
74 private static final int DEFAULT_PATH_SIZE = 128;
76 /** A dummy object id buffer that matches the zero ObjectId. */
77 protected static final byte[] zeroid = new byte[Constants.OBJECT_ID_LENGTH];
79 /** Iterator for the parent tree; null if we are the root iterator. */
80 final AbstractTreeIterator parent;
82 /** The iterator this current entry is path equal to. */
83 AbstractTreeIterator matches;
85 /**
86 * Mode bits for the current entry.
87 * <p>
88 * A numerical value from FileMode is usually faster for an iterator to
89 * obtain from its data source so this is the preferred representation.
91 * @see org.spearce.jgit.lib.FileMode
93 protected int mode;
95 /**
96 * Path buffer for the current entry.
97 * <p>
98 * This buffer is pre-allocated at the start of walking and is shared from
99 * parent iterators down into their subtree iterators. The sharing allows
100 * the current entry to always be a full path from the root, while each
101 * subtree only needs to populate the part that is under their control.
103 protected byte[] path;
106 * Position within {@link #path} this iterator starts writing at.
107 * <p>
108 * This is the first offset in {@link #path} that this iterator must
109 * populate during {@link #next}. At the root level (when {@link #parent}
110 * is null) this is 0. For a subtree iterator the index before this position
111 * should have the value '/'.
113 protected final int pathOffset;
116 * Total length of the current entry's complete path from the root.
117 * <p>
118 * This is the number of bytes within {@link #path} that pertain to the
119 * current entry. Values at this index through the end of the array are
120 * garbage and may be randomly populated from prior entries.
122 protected int pathLen;
124 /** Create a new iterator with no parent. */
125 protected AbstractTreeIterator() {
126 parent = null;
127 path = new byte[DEFAULT_PATH_SIZE];
128 pathOffset = 0;
132 * Create a new iterator with no parent and a prefix.
133 * <p>
134 * The prefix path supplied is inserted in front of all paths generated by
135 * this iterator. It is intended to be used when an iterator is being
136 * created for a subsection of an overall repository and needs to be
137 * combined with other iterators that are created to run over the entire
138 * repository namespace.
140 * @param prefix
141 * position of this iterator in the repository tree. The value
142 * may be null or the empty string to indicate the prefix is the
143 * root of the repository. A trailing slash ('/') is
144 * automatically appended if the prefix does not end in '/'.
146 protected AbstractTreeIterator(final String prefix) {
147 parent = null;
149 if (prefix != null && prefix.length() > 0) {
150 final ByteBuffer b;
152 b = Constants.CHARSET.encode(CharBuffer.wrap(prefix));
153 pathLen = b.limit();
154 path = new byte[Math.max(DEFAULT_PATH_SIZE, pathLen + 1)];
155 b.get(path, 0, pathLen);
156 if (path[pathLen - 1] != '/')
157 path[pathLen++] = '/';
158 pathOffset = pathLen;
159 } else {
160 path = new byte[DEFAULT_PATH_SIZE];
161 pathOffset = 0;
166 * Create an iterator for a subtree of an existing iterator.
168 * @param p
169 * parent tree iterator.
171 protected AbstractTreeIterator(final AbstractTreeIterator p) {
172 parent = p;
173 path = p.path;
174 pathOffset = p.pathLen + 1;
175 try {
176 path[pathOffset - 1] = '/';
177 } catch (ArrayIndexOutOfBoundsException e) {
178 growPath(p.pathLen);
179 path[pathOffset - 1] = '/';
184 * Create an iterator for a subtree of an existing iterator.
185 * <p>
186 * The caller is responsible for setting up the path of the child iterator.
188 * @param p
189 * parent tree iterator.
190 * @param childPath
191 * path array to be used by the child iterator. This path must
192 * contain the path from the top of the walk to the first child
193 * and must end with a '/'.
194 * @param childPathOffset
195 * position within <code>childPath</code> where the child can
196 * insert its data. The value at
197 * <code>childPath[childPathOffset-1]</code> must be '/'.
199 protected AbstractTreeIterator(final AbstractTreeIterator p,
200 final byte[] childPath, final int childPathOffset) {
201 parent = p;
202 path = childPath;
203 pathOffset = childPathOffset;
207 * Grow the path buffer larger.
209 * @param len
210 * number of live bytes in the path buffer. This many bytes will
211 * be moved into the larger buffer.
213 protected void growPath(final int len) {
214 final byte[] n = new byte[path.length << 1];
215 System.arraycopy(path, 0, n, 0, len);
216 for (AbstractTreeIterator p = this; p != null; p = p.parent)
217 p.path = n;
221 * Compare the path of this current entry to another iterator's entry.
223 * @param p
224 * the other iterator to compare the path against.
225 * @return -1 if this entry sorts first; 0 if the entries are equal; 1 if
226 * p's entry sorts first.
228 public int pathCompare(final AbstractTreeIterator p) {
229 return pathCompare(p, p.mode);
232 int pathCompare(final AbstractTreeIterator p, final int pMode) {
233 final byte[] a = path;
234 final byte[] b = p.path;
235 final int aLen = pathLen;
236 final int bLen = p.pathLen;
237 int cPos;
239 // Its common when we are a subtree for both parents to match;
240 // when this happens everything in path[0..cPos] is known to
241 // be equal and does not require evaluation again.
243 cPos = alreadyMatch(this, p);
245 for (; cPos < aLen && cPos < bLen; cPos++) {
246 final int cmp = (a[cPos] & 0xff) - (b[cPos] & 0xff);
247 if (cmp != 0)
248 return cmp;
251 if (cPos < aLen)
252 return (a[cPos] & 0xff) - lastPathChar(pMode);
253 if (cPos < bLen)
254 return lastPathChar(mode) - (b[cPos] & 0xff);
255 return lastPathChar(mode) - lastPathChar(pMode);
258 private static int alreadyMatch(AbstractTreeIterator a,
259 AbstractTreeIterator b) {
260 for (;;) {
261 final AbstractTreeIterator ap = a.parent;
262 final AbstractTreeIterator bp = b.parent;
263 if (ap == null || bp == null)
264 return 0;
265 if (ap.matches == bp.matches)
266 return a.pathOffset;
267 a = ap;
268 b = bp;
272 private static int lastPathChar(final int mode) {
273 return FileMode.TREE.equals(mode) ? '/' : '\0';
277 * Check if the current entry of both iterators has the same id.
278 * <p>
279 * This method is faster than {@link #getEntryObjectId()} as it does not
280 * require copying the bytes out of the buffers. A direct {@link #idBuffer}
281 * compare operation is performed.
283 * @param otherIterator
284 * the other iterator to test against.
285 * @return true if both iterators have the same object id; false otherwise.
287 public boolean idEqual(final AbstractTreeIterator otherIterator) {
288 return ObjectId.equals(idBuffer(), idOffset(),
289 otherIterator.idBuffer(), otherIterator.idOffset());
293 * Get the object id of the current entry.
295 * @return an object id for the current entry.
297 public ObjectId getEntryObjectId() {
298 return ObjectId.fromRaw(idBuffer(), idOffset());
302 * Get the byte array buffer object IDs must be copied out of.
303 * <p>
304 * The id buffer contains the bytes necessary to construct an ObjectId for
305 * the current entry of this iterator. The buffer can be the same buffer for
306 * all entries, or it can be a unique buffer per-entry. Implementations are
307 * encouraged to expose their private buffer whenever possible to reduce
308 * garbage generation and copying costs.
310 * @return byte array the implementation stores object IDs within.
311 * @see #getEntryObjectId()
313 public abstract byte[] idBuffer();
316 * Get the position within {@link #idBuffer()} of this entry's ObjectId.
318 * @return offset into the array returned by {@link #idBuffer()} where the
319 * ObjectId must be copied out of.
321 public abstract int idOffset();
324 * Create a new iterator for the current entry's subtree.
325 * <p>
326 * The parent reference of the iterator must be <code>this</code>,
327 * otherwise the caller would not be able to exit out of the subtree
328 * iterator correctly and return to continue walking <code>this</code>.
330 * @param repo
331 * repository to load the tree data from.
332 * @return a new parser that walks over the current subtree.
333 * @throws IncorrectObjectTypeException
334 * the current entry is not actually a tree and cannot be parsed
335 * as though it were a tree.
336 * @throws IOException
337 * a loose object or pack file could not be read.
339 public abstract AbstractTreeIterator createSubtreeIterator(Repository repo)
340 throws IncorrectObjectTypeException, IOException;
343 * Is this tree iterator at its EOF point (no more entries)?
344 * <p>
345 * An iterator is at EOF if there is no current entry.
347 * @return true if we have walked all entries and have none left.
349 public abstract boolean eof();
352 * Advance to the next tree entry, populating this iterator with its data.
353 * <p>
354 * Implementations must populate the following members:
355 * <ul>
356 * <li>{@link #mode}</li>
357 * <li>{@link #path} (from {@link #pathOffset} to {@link #pathLen})</li>
358 * <li>{@link #pathLen}</li>
359 * </ul>
360 * as well as any implementation dependent information necessary to
361 * accurately return data from {@link #idBuffer()} and {@link #idOffset()}
362 * when demanded.
364 * @throws CorruptObjectException
365 * the tree is invalid.
367 public abstract void next() throws CorruptObjectException;
370 * Advance to the next tree entry, populating this iterator with its data.
371 * <p>
372 * This method behaves like {@link #next()} but is called by
373 * {@link TreeWalk} only if a {@link TreeFilter} was used and ruled out the
374 * current entry from the results. In such cases this tree iterator may
375 * perform special behavior.
377 * @throws CorruptObjectException
378 * the tree is invalid.
380 public void skip() throws CorruptObjectException {
381 next();
385 * Indicates to the iterator that no more entries will be read.
386 * <p>
387 * This is only invoked by TreeWalk when the iteration is aborted early due
388 * to a {@link org.spearce.jgit.errors.StopWalkException} being thrown from
389 * within a TreeFilter.
391 public void stopWalk() {
392 // Do nothing by default. Most iterators do not care.