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