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.

DirCacheTree.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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.lib.FileMode.TREE;
  46. import static org.eclipse.jgit.lib.TreeFormatter.entrySize;
  47. import java.io.IOException;
  48. import java.io.OutputStream;
  49. import java.nio.ByteBuffer;
  50. import java.util.Arrays;
  51. import java.util.Comparator;
  52. import org.eclipse.jgit.errors.UnmergedPathException;
  53. import org.eclipse.jgit.lib.Constants;
  54. import org.eclipse.jgit.lib.ObjectId;
  55. import org.eclipse.jgit.lib.ObjectInserter;
  56. import org.eclipse.jgit.lib.TreeFormatter;
  57. import org.eclipse.jgit.util.MutableInteger;
  58. import org.eclipse.jgit.util.RawParseUtils;
  59. /**
  60. * Single tree record from the 'TREE' {@link DirCache} extension.
  61. * <p>
  62. * A valid cache tree record contains the object id of a tree object and the
  63. * total number of {@link DirCacheEntry} instances (counted recursively) from
  64. * the DirCache contained within the tree. This information facilitates faster
  65. * traversal of the index and quicker generation of tree objects prior to
  66. * creating a new commit.
  67. * <p>
  68. * An invalid cache tree record indicates a known subtree whose file entries
  69. * have changed in ways that cause the tree to no longer have a known object id.
  70. * Invalid cache tree records must be revalidated prior to use.
  71. */
  72. public class DirCacheTree {
  73. private static final byte[] NO_NAME = {};
  74. private static final DirCacheTree[] NO_CHILDREN = {};
  75. private static final Comparator<DirCacheTree> TREE_CMP = new Comparator<DirCacheTree>() {
  76. public int compare(final DirCacheTree o1, final DirCacheTree o2) {
  77. final byte[] a = o1.encodedName;
  78. final byte[] b = o2.encodedName;
  79. final int aLen = a.length;
  80. final int bLen = b.length;
  81. int cPos;
  82. for (cPos = 0; cPos < aLen && cPos < bLen; cPos++) {
  83. final int cmp = (a[cPos] & 0xff) - (b[cPos] & 0xff);
  84. if (cmp != 0)
  85. return cmp;
  86. }
  87. if (aLen == bLen)
  88. return 0;
  89. if (aLen < bLen)
  90. return '/' - (b[cPos] & 0xff);
  91. return (a[cPos] & 0xff) - '/';
  92. }
  93. };
  94. /** Tree this tree resides in; null if we are the root. */
  95. private DirCacheTree parent;
  96. /** Name of this tree within its parent. */
  97. private byte[] encodedName;
  98. /** Number of {@link DirCacheEntry} records that belong to this tree. */
  99. private int entrySpan;
  100. /** Unique SHA-1 of this tree; null if invalid. */
  101. private ObjectId id;
  102. /** Child trees, if any, sorted by {@link #encodedName}. */
  103. private DirCacheTree[] children;
  104. /** Number of valid children in {@link #children}. */
  105. private int childCnt;
  106. DirCacheTree() {
  107. encodedName = NO_NAME;
  108. children = NO_CHILDREN;
  109. childCnt = 0;
  110. entrySpan = -1;
  111. }
  112. private DirCacheTree(final DirCacheTree myParent, final byte[] path,
  113. final int pathOff, final int pathLen) {
  114. parent = myParent;
  115. encodedName = new byte[pathLen];
  116. System.arraycopy(path, pathOff, encodedName, 0, pathLen);
  117. children = NO_CHILDREN;
  118. childCnt = 0;
  119. entrySpan = -1;
  120. }
  121. DirCacheTree(final byte[] in, final MutableInteger off,
  122. final DirCacheTree myParent) {
  123. parent = myParent;
  124. int ptr = RawParseUtils.next(in, off.value, '\0');
  125. final int nameLen = ptr - off.value - 1;
  126. if (nameLen > 0) {
  127. encodedName = new byte[nameLen];
  128. System.arraycopy(in, off.value, encodedName, 0, nameLen);
  129. } else
  130. encodedName = NO_NAME;
  131. entrySpan = RawParseUtils.parseBase10(in, ptr, off);
  132. final int subcnt = RawParseUtils.parseBase10(in, off.value, off);
  133. off.value = RawParseUtils.next(in, off.value, '\n');
  134. if (entrySpan >= 0) {
  135. // Valid trees have a positive entry count and an id of a
  136. // tree object that should exist in the object database.
  137. //
  138. id = ObjectId.fromRaw(in, off.value);
  139. off.value += Constants.OBJECT_ID_LENGTH;
  140. }
  141. if (subcnt > 0) {
  142. boolean alreadySorted = true;
  143. children = new DirCacheTree[subcnt];
  144. for (int i = 0; i < subcnt; i++) {
  145. children[i] = new DirCacheTree(in, off, this);
  146. // C Git's ordering differs from our own; it prefers to
  147. // sort by length first. This sometimes produces a sort
  148. // we do not desire. On the other hand it may have been
  149. // created by us, and be sorted the way we want.
  150. //
  151. if (alreadySorted && i > 0
  152. && TREE_CMP.compare(children[i - 1], children[i]) > 0)
  153. alreadySorted = false;
  154. }
  155. if (!alreadySorted)
  156. Arrays.sort(children, 0, subcnt, TREE_CMP);
  157. } else {
  158. // Leaf level trees have no children, only (file) entries.
  159. //
  160. children = NO_CHILDREN;
  161. }
  162. childCnt = subcnt;
  163. }
  164. void write(final byte[] tmp, final OutputStream os) throws IOException {
  165. int ptr = tmp.length;
  166. tmp[--ptr] = '\n';
  167. ptr = RawParseUtils.formatBase10(tmp, ptr, childCnt);
  168. tmp[--ptr] = ' ';
  169. ptr = RawParseUtils.formatBase10(tmp, ptr, isValid() ? entrySpan : -1);
  170. tmp[--ptr] = 0;
  171. os.write(encodedName);
  172. os.write(tmp, ptr, tmp.length - ptr);
  173. if (isValid()) {
  174. id.copyRawTo(tmp, 0);
  175. os.write(tmp, 0, Constants.OBJECT_ID_LENGTH);
  176. }
  177. for (int i = 0; i < childCnt; i++)
  178. children[i].write(tmp, os);
  179. }
  180. /**
  181. * Determine if this cache is currently valid.
  182. * <p>
  183. * A valid cache tree knows how many {@link DirCacheEntry} instances from
  184. * the parent {@link DirCache} reside within this tree (recursively
  185. * enumerated). It also knows the object id of the tree, as the tree should
  186. * be readily available from the repository's object database.
  187. *
  188. * @return true if this tree is knows key details about itself; false if the
  189. * tree needs to be regenerated.
  190. */
  191. public boolean isValid() {
  192. return id != null;
  193. }
  194. /**
  195. * Get the number of entries this tree spans within the DirCache.
  196. * <p>
  197. * If this tree is not valid (see {@link #isValid()}) this method's return
  198. * value is always strictly negative (less than 0) but is otherwise an
  199. * undefined result.
  200. *
  201. * @return total number of entries (recursively) contained within this tree.
  202. */
  203. public int getEntrySpan() {
  204. return entrySpan;
  205. }
  206. /**
  207. * Get the number of cached subtrees contained within this tree.
  208. *
  209. * @return number of child trees available through this tree.
  210. */
  211. public int getChildCount() {
  212. return childCnt;
  213. }
  214. /**
  215. * Get the i-th child cache tree.
  216. *
  217. * @param i
  218. * index of the child to obtain.
  219. * @return the child tree.
  220. */
  221. public DirCacheTree getChild(final int i) {
  222. return children[i];
  223. }
  224. ObjectId getObjectId() {
  225. return id;
  226. }
  227. /**
  228. * Get the tree's name within its parent.
  229. * <p>
  230. * This method is not very efficient and is primarily meant for debugging
  231. * and final output generation. Applications should try to avoid calling it,
  232. * and if invoked do so only once per interesting entry, where the name is
  233. * absolutely required for correct function.
  234. *
  235. * @return name of the tree. This does not contain any '/' characters.
  236. */
  237. public String getNameString() {
  238. final ByteBuffer bb = ByteBuffer.wrap(encodedName);
  239. return Constants.CHARSET.decode(bb).toString();
  240. }
  241. /**
  242. * Get the tree's path within the repository.
  243. * <p>
  244. * This method is not very efficient and is primarily meant for debugging
  245. * and final output generation. Applications should try to avoid calling it,
  246. * and if invoked do so only once per interesting entry, where the name is
  247. * absolutely required for correct function.
  248. *
  249. * @return path of the tree, relative to the repository root. If this is not
  250. * the root tree the path ends with '/'. The root tree's path string
  251. * is the empty string ("").
  252. */
  253. public String getPathString() {
  254. final StringBuilder r = new StringBuilder();
  255. appendName(r);
  256. return r.toString();
  257. }
  258. /**
  259. * Write (if necessary) this tree to the object store.
  260. *
  261. * @param cache
  262. * the complete cache from DirCache.
  263. * @param cIdx
  264. * first position of <code>cache</code> that is a member of this
  265. * tree. The path of <code>cache[cacheIdx].path</code> for the
  266. * range <code>[0,pathOff-1)</code> matches the complete path of
  267. * this tree, from the root of the repository.
  268. * @param pathOffset
  269. * number of bytes of <code>cache[cacheIdx].path</code> that
  270. * matches this tree's path. The value at array position
  271. * <code>cache[cacheIdx].path[pathOff-1]</code> is always '/' if
  272. * <code>pathOff</code> is > 0.
  273. * @param ow
  274. * the writer to use when serializing to the store.
  275. * @return identity of this tree.
  276. * @throws UnmergedPathException
  277. * one or more paths contain higher-order stages (stage > 0),
  278. * which cannot be stored in a tree object.
  279. * @throws IOException
  280. * an unexpected error occurred writing to the object store.
  281. */
  282. ObjectId writeTree(final DirCacheEntry[] cache, int cIdx,
  283. final int pathOffset, final ObjectInserter ow)
  284. throws UnmergedPathException, IOException {
  285. if (id == null) {
  286. final int endIdx = cIdx + entrySpan;
  287. final TreeFormatter fmt = new TreeFormatter(computeSize(cache,
  288. cIdx, pathOffset, ow));
  289. int childIdx = 0;
  290. int entryIdx = cIdx;
  291. while (entryIdx < endIdx) {
  292. final DirCacheEntry e = cache[entryIdx];
  293. final byte[] ep = e.path;
  294. if (childIdx < childCnt) {
  295. final DirCacheTree st = children[childIdx];
  296. if (st.contains(ep, pathOffset, ep.length)) {
  297. fmt.append(st.encodedName, TREE, st.id);
  298. entryIdx += st.entrySpan;
  299. childIdx++;
  300. continue;
  301. }
  302. }
  303. fmt.append(ep, pathOffset, ep.length - pathOffset, e
  304. .getFileMode(), e.idBuffer(), e.idOffset());
  305. entryIdx++;
  306. }
  307. id = ow.insert(fmt);
  308. }
  309. return id;
  310. }
  311. private int computeSize(final DirCacheEntry[] cache, int cIdx,
  312. final int pathOffset, final ObjectInserter ow)
  313. throws UnmergedPathException, IOException {
  314. final int endIdx = cIdx + entrySpan;
  315. int childIdx = 0;
  316. int entryIdx = cIdx;
  317. int size = 0;
  318. while (entryIdx < endIdx) {
  319. final DirCacheEntry e = cache[entryIdx];
  320. if (e.getStage() != 0)
  321. throw new UnmergedPathException(e);
  322. final byte[] ep = e.path;
  323. if (childIdx < childCnt) {
  324. final DirCacheTree st = children[childIdx];
  325. if (st.contains(ep, pathOffset, ep.length)) {
  326. final int stOffset = pathOffset + st.nameLength() + 1;
  327. st.writeTree(cache, entryIdx, stOffset, ow);
  328. size += entrySize(TREE, st.nameLength());
  329. entryIdx += st.entrySpan;
  330. childIdx++;
  331. continue;
  332. }
  333. }
  334. size += entrySize(e.getFileMode(), ep.length - pathOffset);
  335. entryIdx++;
  336. }
  337. return size;
  338. }
  339. private void appendName(final StringBuilder r) {
  340. if (parent != null) {
  341. parent.appendName(r);
  342. r.append(getNameString());
  343. r.append('/');
  344. } else if (nameLength() > 0) {
  345. r.append(getNameString());
  346. r.append('/');
  347. }
  348. }
  349. final int nameLength() {
  350. return encodedName.length;
  351. }
  352. final boolean contains(final byte[] a, int aOff, final int aLen) {
  353. final byte[] e = encodedName;
  354. final int eLen = e.length;
  355. for (int eOff = 0; eOff < eLen && aOff < aLen; eOff++, aOff++)
  356. if (e[eOff] != a[aOff])
  357. return false;
  358. if (aOff >= aLen)
  359. return false;
  360. return a[aOff] == '/';
  361. }
  362. /**
  363. * Update (if necessary) this tree's entrySpan.
  364. *
  365. * @param cache
  366. * the complete cache from DirCache.
  367. * @param cCnt
  368. * number of entries in <code>cache</code> that are valid for
  369. * iteration.
  370. * @param cIdx
  371. * first position of <code>cache</code> that is a member of this
  372. * tree. The path of <code>cache[cacheIdx].path</code> for the
  373. * range <code>[0,pathOff-1)</code> matches the complete path of
  374. * this tree, from the root of the repository.
  375. * @param pathOff
  376. * number of bytes of <code>cache[cacheIdx].path</code> that
  377. * matches this tree's path. The value at array position
  378. * <code>cache[cacheIdx].path[pathOff-1]</code> is always '/' if
  379. * <code>pathOff</code> is > 0.
  380. */
  381. void validate(final DirCacheEntry[] cache, final int cCnt, int cIdx,
  382. final int pathOff) {
  383. if (entrySpan >= 0 && cIdx + entrySpan <= cCnt) {
  384. // If we are valid, our children are also valid.
  385. // We have no need to validate them.
  386. //
  387. return;
  388. }
  389. entrySpan = 0;
  390. if (cCnt == 0) {
  391. // Special case of an empty index, and we are the root tree.
  392. //
  393. return;
  394. }
  395. final byte[] firstPath = cache[cIdx].path;
  396. int stIdx = 0;
  397. while (cIdx < cCnt) {
  398. final byte[] currPath = cache[cIdx].path;
  399. if (pathOff > 0 && !peq(firstPath, currPath, pathOff)) {
  400. // The current entry is no longer in this tree. Our
  401. // span is updated and the remainder goes elsewhere.
  402. //
  403. break;
  404. }
  405. DirCacheTree st = stIdx < childCnt ? children[stIdx] : null;
  406. final int cc = namecmp(currPath, pathOff, st);
  407. if (cc > 0) {
  408. // This subtree is now empty.
  409. //
  410. removeChild(stIdx);
  411. continue;
  412. }
  413. if (cc < 0) {
  414. final int p = slash(currPath, pathOff);
  415. if (p < 0) {
  416. // The entry has no '/' and thus is directly in this
  417. // tree. Count it as one of our own.
  418. //
  419. cIdx++;
  420. entrySpan++;
  421. continue;
  422. }
  423. // Build a new subtree for this entry.
  424. //
  425. st = new DirCacheTree(this, currPath, pathOff, p - pathOff);
  426. insertChild(stIdx, st);
  427. }
  428. // The entry is contained in this subtree.
  429. //
  430. assert(st != null);
  431. st.validate(cache, cCnt, cIdx, pathOff + st.nameLength() + 1);
  432. cIdx += st.entrySpan;
  433. entrySpan += st.entrySpan;
  434. stIdx++;
  435. }
  436. // None of our remaining children can be in this tree
  437. // as the current cache entry is after our own name.
  438. //
  439. while (stIdx < childCnt)
  440. removeChild(childCnt - 1);
  441. }
  442. private void insertChild(final int stIdx, final DirCacheTree st) {
  443. final DirCacheTree[] c = children;
  444. if (childCnt + 1 <= c.length) {
  445. if (stIdx < childCnt)
  446. System.arraycopy(c, stIdx, c, stIdx + 1, childCnt - stIdx);
  447. c[stIdx] = st;
  448. childCnt++;
  449. return;
  450. }
  451. final int n = c.length;
  452. final DirCacheTree[] a = new DirCacheTree[n + 1];
  453. if (stIdx > 0)
  454. System.arraycopy(c, 0, a, 0, stIdx);
  455. a[stIdx] = st;
  456. if (stIdx < n)
  457. System.arraycopy(c, stIdx, a, stIdx + 1, n - stIdx);
  458. children = a;
  459. childCnt++;
  460. }
  461. private void removeChild(final int stIdx) {
  462. final int n = --childCnt;
  463. if (stIdx < n)
  464. System.arraycopy(children, stIdx + 1, children, stIdx, n - stIdx);
  465. children[n] = null;
  466. }
  467. static boolean peq(final byte[] a, final byte[] b, int aLen) {
  468. if (b.length < aLen)
  469. return false;
  470. for (aLen--; aLen >= 0; aLen--)
  471. if (a[aLen] != b[aLen])
  472. return false;
  473. return true;
  474. }
  475. private static int namecmp(final byte[] a, int aPos, final DirCacheTree ct) {
  476. if (ct == null)
  477. return -1;
  478. final byte[] b = ct.encodedName;
  479. final int aLen = a.length;
  480. final int bLen = b.length;
  481. int bPos = 0;
  482. for (; aPos < aLen && bPos < bLen; aPos++, bPos++) {
  483. final int cmp = (a[aPos] & 0xff) - (b[bPos] & 0xff);
  484. if (cmp != 0)
  485. return cmp;
  486. }
  487. if (bPos == bLen)
  488. return a[aPos] == '/' ? 0 : -1;
  489. return aLen - bLen;
  490. }
  491. private static int slash(final byte[] a, int aPos) {
  492. final int aLen = a.length;
  493. for (; aPos < aLen; aPos++)
  494. if (a[aPos] == '/')
  495. return aPos;
  496. return -1;
  497. }
  498. @Override
  499. public String toString() {
  500. return getNameString();
  501. }
  502. }