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.dircache.DirCache.cmp;
48 import static org.eclipse.jgit.dircache.DirCacheTree.peq;
49 import static org.eclipse.jgit.lib.FileMode.TYPE_TREE;
50
51 import java.io.IOException;
52 import java.text.MessageFormat;
53 import java.util.ArrayList;
54 import java.util.Collections;
55 import java.util.Comparator;
56 import java.util.List;
57
58 import org.eclipse.jgit.internal.JGitText;
59 import org.eclipse.jgit.lib.Constants;
60 import org.eclipse.jgit.util.Paths;
61
62 /**
63 * Updates a {@link org.eclipse.jgit.dircache.DirCache} by supplying discrete
64 * edit commands.
65 * <p>
66 * An editor updates a DirCache by taking a list of
67 * {@link org.eclipse.jgit.dircache.DirCacheEditor.PathEdit} commands and
68 * executing them against the entries of the destination cache to produce a new
69 * cache. This edit style allows applications to insert a few commands and then
70 * have the editor compute the proper entry indexes necessary to perform an
71 * efficient in-order update of the index records. This can be easier to use
72 * than {@link org.eclipse.jgit.dircache.DirCacheBuilder}.
73 * <p>
74 *
75 * @see DirCacheBuilder
76 */
77 public class DirCacheEditor extends BaseDirCacheEditor {
78 private static final Comparator<PathEdit> EDIT_CMP = (PathEdit o1,
79 PathEdit o2) -> {
80 final byte[] a = o1.path;
81 final byte[] b = o2.path;
82 return cmp(a, a.length, b, b.length);
83 };
84
85 private final List<PathEdit> edits;
86 private int editIdx;
87
88 /**
89 * Construct a new editor.
90 *
91 * @param dc
92 * the cache this editor will eventually update.
93 * @param ecnt
94 * estimated number of entries the editor will have upon
95 * completion. This sizes the initial entry table.
96 */
97 protected DirCacheEditor(DirCache dc, int ecnt) {
98 super(dc, ecnt);
99 edits = new ArrayList<>();
100 }
101
102 /**
103 * Append one edit command to the list of commands to be applied.
104 * <p>
105 * Edit commands may be added in any order chosen by the application. They
106 * are automatically rearranged by the builder to provide the most efficient
107 * update possible.
108 *
109 * @param edit
110 * another edit command.
111 */
112 public void add(PathEdit edit) {
113 edits.add(edit);
114 }
115
116 /** {@inheritDoc} */
117 @Override
118 public boolean commit() throws IOException {
119 if (edits.isEmpty()) {
120 // No changes? Don't rewrite the index.
121 //
122 cache.unlock();
123 return true;
124 }
125 return super.commit();
126 }
127
128 /** {@inheritDoc} */
129 @Override
130 public void finish() {
131 if (!edits.isEmpty()) {
132 applyEdits();
133 replace();
134 }
135 }
136
137 private void applyEdits() {
138 Collections.sort(edits, EDIT_CMP);
139 editIdx = 0;
140
141 final int maxIdx = cache.getEntryCount();
142 int lastIdx = 0;
143 while (editIdx < edits.size()) {
144 PathEdit e = edits.get(editIdx++);
145 int eIdx = cache.findEntry(lastIdx, e.path, e.path.length);
146 final boolean missing = eIdx < 0;
147 if (eIdx < 0)
148 eIdx = -(eIdx + 1);
149 final int cnt = Math.min(eIdx, maxIdx) - lastIdx;
150 if (cnt > 0)
151 fastKeep(lastIdx, cnt);
152
153 if (e instanceof DeletePath) {
154 lastIdx = missing ? eIdx : cache.nextEntry(eIdx);
155 continue;
156 }
157 if (e instanceof DeleteTree) {
158 lastIdx = cache.nextEntry(e.path, e.path.length, eIdx);
159 continue;
160 }
161
162 if (missing) {
163 DirCacheEntry ent = new DirCacheEntry(e.path);
164 e.apply(ent);
165 if (ent.getRawMode() == 0) {
166 throw new IllegalArgumentException(MessageFormat.format(
167 JGitText.get().fileModeNotSetForPath,
168 ent.getPathString()));
169 }
170 lastIdx = e.replace
171 ? deleteOverlappingSubtree(ent, eIdx)
172 : eIdx;
173 fastAdd(ent);
174 } else {
175 // Apply to all entries of the current path (different stages)
176 lastIdx = cache.nextEntry(eIdx);
177 for (int i = eIdx; i < lastIdx; i++) {
178 final DirCacheEntry ent = cache.getEntry(i);
179 e.apply(ent);
180 fastAdd(ent);
181 }
182 }
183 }
184
185 final int cnt = maxIdx - lastIdx;
186 if (cnt > 0)
187 fastKeep(lastIdx, cnt);
188 }
189
190 private int deleteOverlappingSubtree(DirCacheEntry ent, int eIdx) {
191 byte[] entPath = ent.path;
192 int entLen = entPath.length;
193
194 // Delete any file that was previously processed and overlaps
195 // the parent directory for the new entry. Since the editor
196 // always processes entries in path order, binary search back
197 // for the overlap for each parent directory.
198 for (int p = pdir(entPath, entLen); p > 0; p = pdir(entPath, p)) {
199 int i = findEntry(entPath, p);
200 if (i >= 0) {
201 // A file does overlap, delete the file from the array.
202 // No other parents can have overlaps as the file should
203 // have taken care of that itself.
204 int n = --entryCnt - i;
205 System.arraycopy(entries, i + 1, entries, i, n);
206 break;
207 }
208
209 // If at least one other entry already exists in this parent
210 // directory there is no need to continue searching up the tree.
211 i = -(i + 1);
212 if (i < entryCnt && inDir(entries[i], entPath, p)) {
213 break;
214 }
215 }
216
217 int maxEnt = cache.getEntryCount();
218 if (eIdx >= maxEnt) {
219 return maxEnt;
220 }
221
222 DirCacheEntry next = cache.getEntry(eIdx);
223 if (Paths.compare(next.path, 0, next.path.length, 0,
224 entPath, 0, entLen, TYPE_TREE) < 0) {
225 // Next DirCacheEntry sorts before new entry as tree. Defer a
226 // DeleteTree command to delete any entries if they exist. This
227 // case only happens for A, A.c, A/c type of conflicts (rare).
228 insertEdit(new DeleteTree(entPath));
229 return eIdx;
230 }
231
232 // Next entry may be contained by the entry-as-tree, skip if so.
233 while (eIdx < maxEnt && inDir(cache.getEntry(eIdx), entPath, entLen)) {
234 eIdx++;
235 }
236 return eIdx;
237 }
238
239 private int findEntry(byte[] p, int pLen) {
240 int low = 0;
241 int high = entryCnt;
242 while (low < high) {
243 int mid = (low + high) >>> 1;
244 int cmp = cmp(p, pLen, entries[mid]);
245 if (cmp < 0) {
246 high = mid;
247 } else if (cmp == 0) {
248 while (mid > 0 && cmp(p, pLen, entries[mid - 1]) == 0) {
249 mid--;
250 }
251 return mid;
252 } else {
253 low = mid + 1;
254 }
255 }
256 return -(low + 1);
257 }
258
259 private void insertEdit(DeleteTree d) {
260 for (int i = editIdx; i < edits.size(); i++) {
261 int cmp = EDIT_CMP.compare(d, edits.get(i));
262 if (cmp < 0) {
263 edits.add(i, d);
264 return;
265 } else if (cmp == 0) {
266 return;
267 }
268 }
269 edits.add(d);
270 }
271
272 private static boolean inDir(DirCacheEntry e, byte[] path, int pLen) {
273 return e.path.length > pLen && e.path[pLen] == '/'
274 && peq(path, e.path, pLen);
275 }
276
277 private static int pdir(byte[] path, int e) {
278 for (e--; e > 0; e--) {
279 if (path[e] == '/') {
280 return e;
281 }
282 }
283 return 0;
284 }
285
286 /**
287 * Any index record update.
288 * <p>
289 * Applications should subclass and provide their own implementation for the
290 * {@link #apply(DirCacheEntry)} method. The editor will invoke apply once
291 * for each record in the index which matches the path name. If there are
292 * multiple records (for example in stages 1, 2 and 3), the edit instance
293 * will be called multiple times, once for each stage.
294 */
295 public abstract static class PathEdit {
296 final byte[] path;
297 boolean replace = true;
298
299 /**
300 * Create a new update command by path name.
301 *
302 * @param entryPath
303 * path of the file within the repository.
304 */
305 public PathEdit(String entryPath) {
306 path = Constants.encode(entryPath);
307 }
308
309 PathEdit(byte[] path) {
310 this.path = path;
311 }
312
313 /**
314 * Create a new update command for an existing entry instance.
315 *
316 * @param ent
317 * entry instance to match path of. Only the path of this
318 * entry is actually considered during command evaluation.
319 */
320 public PathEdit(DirCacheEntry ent) {
321 path = ent.path;
322 }
323
324 /**
325 * Configure if a file can replace a directory (or vice versa).
326 * <p>
327 * Default is {@code true} as this is usually the desired behavior.
328 *
329 * @param ok
330 * if true a file can replace a directory, or a directory can
331 * replace a file.
332 * @return {@code this}
333 * @since 4.2
334 */
335 public PathEdit setReplace(boolean ok) {
336 replace = ok;
337 return this;
338 }
339
340 /**
341 * Apply the update to a single cache entry matching the path.
342 * <p>
343 * After apply is invoked the entry is added to the output table, and
344 * will be included in the new index.
345 *
346 * @param ent
347 * the entry being processed. All fields are zeroed out if
348 * the path is a new path in the index.
349 */
350 public abstract void apply(DirCacheEntry ent);
351
352 @Override
353 public String toString() {
354 String p = DirCacheEntry.toString(path);
355 return getClass().getSimpleName() + '[' + p + ']';
356 }
357 }
358
359 /**
360 * Deletes a single file entry from the index.
361 * <p>
362 * This deletion command removes only a single file at the given location,
363 * but removes multiple stages (if present) for that path. To remove a
364 * complete subtree use {@link DeleteTree} instead.
365 *
366 * @see DeleteTree
367 */
368 public static final class DeletePath extends PathEdit {
369 /**
370 * Create a new deletion command by path name.
371 *
372 * @param entryPath
373 * path of the file within the repository.
374 */
375 public DeletePath(String entryPath) {
376 super(entryPath);
377 }
378
379 /**
380 * Create a new deletion command for an existing entry instance.
381 *
382 * @param ent
383 * entry instance to remove. Only the path of this entry is
384 * actually considered during command evaluation.
385 */
386 public DeletePath(DirCacheEntry ent) {
387 super(ent);
388 }
389
390 @Override
391 public void apply(DirCacheEntry ent) {
392 throw new UnsupportedOperationException(JGitText.get().noApplyInDelete);
393 }
394 }
395
396 /**
397 * Recursively deletes all paths under a subtree.
398 * <p>
399 * This deletion command is more generic than {@link DeletePath} as it can
400 * remove all records which appear recursively under the same subtree.
401 * Multiple stages are removed (if present) for any deleted entry.
402 * <p>
403 * This command will not remove a single file entry. To remove a single file
404 * use {@link DeletePath}.
405 *
406 * @see DeletePath
407 */
408 public static final class DeleteTree extends PathEdit {
409 /**
410 * Create a new tree deletion command by path name.
411 *
412 * @param entryPath
413 * path of the subtree within the repository. If the path
414 * does not end with "/" a "/" is implicitly added to ensure
415 * only the subtree's contents are matched by the command.
416 * The special case "" (not "/"!) deletes all entries.
417 */
418 public DeleteTree(String entryPath) {
419 super(entryPath.isEmpty()
420 || entryPath.charAt(entryPath.length() - 1) == '/'
421 ? entryPath
422 : entryPath + '/');
423 }
424
425 DeleteTree(byte[] path) {
426 super(appendSlash(path));
427 }
428
429 private static byte[] appendSlash(byte[] path) {
430 int n = path.length;
431 if (n > 0 && path[n - 1] != '/') {
432 byte[] r = new byte[n + 1];
433 System.arraycopy(path, 0, r, 0, n);
434 r[n] = '/';
435 return r;
436 }
437 return path;
438 }
439
440 @Override
441 public void apply(DirCacheEntry ent) {
442 throw new UnsupportedOperationException(JGitText.get().noApplyInDelete);
443 }
444 }
445 }