Recursively load an entire tree into a DirCacheBuilder
[egit/charleso.git] / org.spearce.jgit / src / org / spearce / jgit / dircache / DirCacheBuilder.java
blob9a9d1743dad3c1fe4eb26e7f3215f8f0173f38c1
1 /*
2 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or
7 * without modification, are permitted provided that the following
8 * conditions are met:
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * - Neither the name of the Git Development Community nor the
19 * names of its contributors may be used to endorse or promote
20 * products derived from this software without specific prior
21 * written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
24 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
25 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
33 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 package org.spearce.jgit.dircache;
40 import java.io.IOException;
41 import java.util.Arrays;
43 import org.spearce.jgit.lib.AnyObjectId;
44 import org.spearce.jgit.lib.Repository;
45 import org.spearce.jgit.lib.WindowCursor;
46 import org.spearce.jgit.treewalk.AbstractTreeIterator;
47 import org.spearce.jgit.treewalk.CanonicalTreeParser;
48 import org.spearce.jgit.treewalk.TreeWalk;
50 /**
51 * Updates a {@link DirCache} by adding individual {@link DirCacheEntry}s.
52 * <p>
53 * A builder always starts from a clean slate and appends in every single
54 * <code>DirCacheEntry</code> which the final updated index must have to reflect
55 * its new content.
56 * <p>
57 * For maximum performance applications should add entries in path name order.
58 * Adding entries out of order is permitted, however a final sorting pass will
59 * be implicitly performed during {@link #finish()} to correct any out-of-order
60 * entries. Duplicate detection is also delayed until the sorting is complete.
62 * @see DirCacheEditor
64 public class DirCacheBuilder extends BaseDirCacheEditor {
65 private boolean sorted;
67 /**
68 * Construct a new builder.
70 * @param dc
71 * the cache this builder will eventually update.
72 * @param ecnt
73 * estimated number of entries the builder will have upon
74 * completion. This sizes the initial entry table.
76 protected DirCacheBuilder(final DirCache dc, final int ecnt) {
77 super(dc, ecnt);
80 /**
81 * Append one entry into the resulting entry list.
82 * <p>
83 * The entry is placed at the end of the entry list. If the entry causes the
84 * list to now be incorrectly sorted a final sorting phase will be
85 * automatically enabled within {@link #finish()}.
86 * <p>
87 * The internal entry table is automatically expanded if there is
88 * insufficient space for the new addition.
90 * @param newEntry
91 * the new entry to add.
93 public void add(final DirCacheEntry newEntry) {
94 beforeAdd(newEntry);
95 fastAdd(newEntry);
98 /**
99 * Add a range of existing entries from the destination cache.
100 * <p>
101 * The entries are placed at the end of the entry list. If any of the
102 * entries causes the list to now be incorrectly sorted a final sorting
103 * phase will be automatically enabled within {@link #finish()}.
104 * <p>
105 * This method copies from the destination cache, which has not yet been
106 * updated with this editor's new table. So all offsets into the destination
107 * cache are not affected by any updates that may be currently taking place
108 * in this editor.
109 * <p>
110 * The internal entry table is automatically expanded if there is
111 * insufficient space for the new additions.
113 * @param pos
114 * first entry to copy from the destination cache.
115 * @param cnt
116 * number of entries to copy.
118 public void keep(final int pos, int cnt) {
119 beforeAdd(cache.getEntry(pos));
120 fastKeep(pos, cnt);
124 * Recursively add an entire tree into this builder.
125 * <p>
126 * If pathPrefix is "a/b" and the tree contains file "c" then the resulting
127 * DirCacheEntry will have the path "a/b/c".
128 * <p>
129 * All entries are inserted at stage 0, therefore assuming that the
130 * application will not insert any other paths with the same pathPrefix.
132 * @param pathPrefix
133 * UTF-8 encoded prefix to mount the tree's entries at. If the
134 * path does not end with '/' one will be automatically inserted
135 * as necessary.
136 * @param db
137 * repository the tree(s) will be read from during recursive
138 * traversal. This must be the same repository that the resulting
139 * DirCache would be written out to (or used in) otherwise the
140 * caller is simply asking for deferred MissingObjectExceptions.
141 * @param tree
142 * the tree to recursively add. This tree's contents will appear
143 * under <code>pathPrefix</code>. The ObjectId must be that of a
144 * tree; the caller is responsible for dereferencing a tag or
145 * commit (if necessary).
146 * @throws IOException
147 * a tree cannot be read to iterate through its entries.
149 public void addTree(final byte[] pathPrefix, final Repository db,
150 final AnyObjectId tree) throws IOException {
151 final TreeWalk tw = new TreeWalk(db);
152 tw.reset();
153 final WindowCursor curs = new WindowCursor();
154 try {
155 tw.addTree(new CanonicalTreeParser(pathPrefix, db, tree
156 .toObjectId(), curs));
157 } finally {
158 curs.release();
160 tw.setRecursive(true);
161 if (tw.next()) {
162 final DirCacheEntry newEntry = toEntry(tw);
163 beforeAdd(newEntry);
164 fastAdd(newEntry);
165 while (tw.next())
166 fastAdd(toEntry(tw));
170 private DirCacheEntry toEntry(final TreeWalk tw) {
171 final DirCacheEntry e = new DirCacheEntry(tw.getRawPath());
172 final AbstractTreeIterator i;
174 i = tw.getTree(0, AbstractTreeIterator.class);
175 e.setFileMode(tw.getFileMode(0));
176 e.setObjectIdFromRaw(i.idBuffer(), i.idOffset());
177 return e;
180 public void finish() {
181 if (!sorted)
182 resort();
183 replace();
186 private void beforeAdd(final DirCacheEntry newEntry) {
187 if (sorted && entryCnt > 0) {
188 final DirCacheEntry lastEntry = entries[entryCnt - 1];
189 final int cr = DirCache.cmp(lastEntry, newEntry);
190 if (cr > 0) {
191 // The new entry sorts before the old entry; we are
192 // no longer sorted correctly. We'll need to redo
193 // the sorting before we can close out the build.
195 sorted = false;
196 } else if (cr == 0) {
197 // Same file path; we can only insert this if the
198 // stages won't be violated.
200 final int peStage = lastEntry.getStage();
201 final int dceStage = newEntry.getStage();
202 if (peStage == dceStage)
203 throw bad(newEntry, "Duplicate stages not allowed");
204 if (peStage == 0 || dceStage == 0)
205 throw bad(newEntry, "Mixed stages not allowed");
206 if (peStage > dceStage)
207 sorted = false;
212 private void resort() {
213 Arrays.sort(entries, 0, entryCnt, DirCache.ENT_CMP);
215 for (int entryIdx = 1; entryIdx < entryCnt; entryIdx++) {
216 final DirCacheEntry pe = entries[entryIdx - 1];
217 final DirCacheEntry ce = entries[entryIdx];
218 final int cr = DirCache.cmp(pe, ce);
219 if (cr == 0) {
220 // Same file path; we can only allow this if the stages
221 // are 1-3 and no 0 exists.
223 final int peStage = pe.getStage();
224 final int ceStage = ce.getStage();
225 if (peStage == ceStage)
226 throw bad(ce, "Duplicate stages not allowed");
227 if (peStage == 0 || ceStage == 0)
228 throw bad(ce, "Mixed stages not allowed");
232 sorted = true;
235 private static IllegalStateException bad(final DirCacheEntry a,
236 final String msg) {
237 return new IllegalStateException(msg + ": " + a.getStage() + " "
238 + a.getPathString());