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