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.TYPE_MASK;
48 import static org.eclipse.jgit.lib.FileMode.TYPE_TREE;
49
50 import java.io.IOException;
51 import java.text.MessageFormat;
52 import java.util.Arrays;
53
54 import org.eclipse.jgit.internal.JGitText;
55 import org.eclipse.jgit.lib.AnyObjectId;
56 import org.eclipse.jgit.lib.ObjectReader;
57 import org.eclipse.jgit.treewalk.CanonicalTreeParser;
58
59 /**
60 * Updates a {@link org.eclipse.jgit.dircache.DirCache} by adding individual
61 * {@link org.eclipse.jgit.dircache.DirCacheEntry}s.
62 * <p>
63 * A builder always starts from a clean slate and appends in every single
64 * <code>DirCacheEntry</code> which the final updated index must have to reflect
65 * its new content.
66 * <p>
67 * For maximum performance applications should add entries in path name order.
68 * Adding entries out of order is permitted, however a final sorting pass will
69 * be implicitly performed during {@link #finish()} to correct any out-of-order
70 * entries. Duplicate detection is also delayed until the sorting is complete.
71 *
72 * @see DirCacheEditor
73 */
74 public class DirCacheBuilder extends BaseDirCacheEditor {
75 private boolean sorted;
76
77 /**
78 * Construct a new builder.
79 *
80 * @param dc
81 * the cache this builder will eventually update.
82 * @param ecnt
83 * estimated number of entries the builder will have upon
84 * completion. This sizes the initial entry table.
85 */
86 protected DirCacheBuilder(final DirCache dc, final int ecnt) {
87 super(dc, ecnt);
88 }
89
90 /**
91 * Append one entry into the resulting entry list.
92 * <p>
93 * The entry is placed at the end of the entry list. If the entry causes the
94 * list to now be incorrectly sorted a final sorting phase will be
95 * automatically enabled within {@link #finish()}.
96 * <p>
97 * The internal entry table is automatically expanded if there is
98 * insufficient space for the new addition.
99 *
100 * @param newEntry
101 * the new entry to add.
102 * @throws java.lang.IllegalArgumentException
103 * If the FileMode of the entry was not set by the caller.
104 */
105 public void add(final DirCacheEntry newEntry) {
106 if (newEntry.getRawMode() == 0)
107 throw new IllegalArgumentException(MessageFormat.format(
108 JGitText.get().fileModeNotSetForPath,
109 newEntry.getPathString()));
110 beforeAdd(newEntry);
111 fastAdd(newEntry);
112 }
113
114 /**
115 * Add a range of existing entries from the destination cache.
116 * <p>
117 * The entries are placed at the end of the entry list. If any of the
118 * entries causes the list to now be incorrectly sorted a final sorting
119 * phase will be automatically enabled within {@link #finish()}.
120 * <p>
121 * This method copies from the destination cache, which has not yet been
122 * updated with this editor's new table. So all offsets into the destination
123 * cache are not affected by any updates that may be currently taking place
124 * in this editor.
125 * <p>
126 * The internal entry table is automatically expanded if there is
127 * insufficient space for the new additions.
128 *
129 * @param pos
130 * first entry to copy from the destination cache.
131 * @param cnt
132 * number of entries to copy.
133 */
134 public void keep(final int pos, int cnt) {
135 beforeAdd(cache.getEntry(pos));
136 fastKeep(pos, cnt);
137 }
138
139 /**
140 * Recursively add an entire tree into this builder.
141 * <p>
142 * If pathPrefix is "a/b" and the tree contains file "c" then the resulting
143 * DirCacheEntry will have the path "a/b/c".
144 * <p>
145 * All entries are inserted at stage 0, therefore assuming that the
146 * application will not insert any other paths with the same pathPrefix.
147 *
148 * @param pathPrefix
149 * UTF-8 encoded prefix to mount the tree's entries at. If the
150 * path does not end with '/' one will be automatically inserted
151 * as necessary.
152 * @param stage
153 * stage of the entries when adding them.
154 * @param reader
155 * reader the tree(s) will be read from during recursive
156 * traversal. This must be the same repository that the resulting
157 * DirCache would be written out to (or used in) otherwise the
158 * caller is simply asking for deferred MissingObjectExceptions.
159 * Caller is responsible for releasing this reader when done.
160 * @param tree
161 * the tree to recursively add. This tree's contents will appear
162 * under <code>pathPrefix</code>. The ObjectId must be that of a
163 * tree; the caller is responsible for dereferencing a tag or
164 * commit (if necessary).
165 * @throws java.io.IOException
166 * a tree cannot be read to iterate through its entries.
167 */
168 public void addTree(byte[] pathPrefix, int stage, ObjectReader reader,
169 AnyObjectId tree) throws IOException {
170 CanonicalTreeParser p = createTreeParser(pathPrefix, reader, tree);
171 while (!p.eof()) {
172 if (isTree(p)) {
173 p = enterTree(p, reader);
174 continue;
175 }
176
177 DirCacheEntry first = toEntry(stage, p);
178 beforeAdd(first);
179 fastAdd(first);
180 p = p.next();
181 break;
182 }
183
184 // Rest of tree entries are correctly sorted; use fastAdd().
185 while (!p.eof()) {
186 if (isTree(p)) {
187 p = enterTree(p, reader);
188 } else {
189 fastAdd(toEntry(stage, p));
190 p = p.next();
191 }
192 }
193 }
194
195 private static CanonicalTreeParser createTreeParser(byte[] pathPrefix,
196 ObjectReader reader, AnyObjectId tree) throws IOException {
197 return new CanonicalTreeParser(pathPrefix, reader, tree);
198 }
199
200 private static boolean isTree(CanonicalTreeParser p) {
201 return (p.getEntryRawMode() & TYPE_MASK) == TYPE_TREE;
202 }
203
204 private static CanonicalTreeParser enterTree(CanonicalTreeParser p,
205 ObjectReader reader) throws IOException {
206 p = p.createSubtreeIterator(reader);
207 return p.eof() ? p.next() : p;
208 }
209
210 private static DirCacheEntry toEntry(int stage, CanonicalTreeParser i) {
211 byte[] buf = i.getEntryPathBuffer();
212 int len = i.getEntryPathLength();
213 byte[] path = new byte[len];
214 System.arraycopy(buf, 0, path, 0, len);
215
216 DirCacheEntry e = new DirCacheEntry(path, stage);
217 e.setFileMode(i.getEntryRawMode());
218 e.setObjectIdFromRaw(i.idBuffer(), i.idOffset());
219 return e;
220 }
221
222 /** {@inheritDoc} */
223 @Override
224 public void finish() {
225 if (!sorted)
226 resort();
227 replace();
228 }
229
230 private void beforeAdd(final DirCacheEntry newEntry) {
231 if (sorted && entryCnt > 0) {
232 final DirCacheEntry lastEntry = entries[entryCnt - 1];
233 final int cr = DirCache.cmp(lastEntry, newEntry);
234 if (cr > 0) {
235 // The new entry sorts before the old entry; we are
236 // no longer sorted correctly. We'll need to redo
237 // the sorting before we can close out the build.
238 //
239 sorted = false;
240 } else if (cr == 0) {
241 // Same file path; we can only insert this if the
242 // stages won't be violated.
243 //
244 final int peStage = lastEntry.getStage();
245 final int dceStage = newEntry.getStage();
246 if (peStage == dceStage)
247 throw bad(newEntry, JGitText.get().duplicateStagesNotAllowed);
248 if (peStage == 0 || dceStage == 0)
249 throw bad(newEntry, JGitText.get().mixedStagesNotAllowed);
250 if (peStage > dceStage)
251 sorted = false;
252 }
253 }
254 }
255
256 private void resort() {
257 Arrays.sort(entries, 0, entryCnt, DirCache.ENT_CMP);
258
259 for (int entryIdx = 1; entryIdx < entryCnt; entryIdx++) {
260 final DirCacheEntry pe = entries[entryIdx - 1];
261 final DirCacheEntry ce = entries[entryIdx];
262 final int cr = DirCache.cmp(pe, ce);
263 if (cr == 0) {
264 // Same file path; we can only allow this if the stages
265 // are 1-3 and no 0 exists.
266 //
267 final int peStage = pe.getStage();
268 final int ceStage = ce.getStage();
269 if (peStage == ceStage)
270 throw bad(ce, JGitText.get().duplicateStagesNotAllowed);
271 if (peStage == 0 || ceStage == 0)
272 throw bad(ce, JGitText.get().mixedStagesNotAllowed);
273 }
274 }
275
276 sorted = true;
277 }
278
279 private static IllegalStateException bad(DirCacheEntry a, String msg) {
280 return new IllegalStateException(String.format(
281 "%s: %d %s", //$NON-NLS-1$
282 msg, Integer.valueOf(a.getStage()), a.getPathString()));
283 }
284 }