You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DirCacheEditor.java 13KB

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