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