Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

DirCacheEditor.java 13KB

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