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.

Tree.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. /*
  2. * Copyright (C) 2007, Robin Rosenberg <me@lathund.dewire.com>
  3. * Copyright (C) 2007-2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  4. * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org>
  5. * and other copyright owners as documented in the project's IP log.
  6. *
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Distribution License v1.0 which
  9. * accompanies this distribution, is reproduced below, and is
  10. * available at http://www.eclipse.org/org/documents/edl-v10.php
  11. *
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or
  15. * without modification, are permitted provided that the following
  16. * conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the
  27. * names of its contributors may be used to endorse or promote
  28. * products derived from this software without specific prior
  29. * written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  32. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  33. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  34. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  41. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  43. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package org.eclipse.jgit.lib;
  46. import java.io.IOException;
  47. import java.text.MessageFormat;
  48. import org.eclipse.jgit.JGitText;
  49. import org.eclipse.jgit.errors.CorruptObjectException;
  50. import org.eclipse.jgit.errors.EntryExistsException;
  51. import org.eclipse.jgit.errors.MissingObjectException;
  52. import org.eclipse.jgit.util.RawParseUtils;
  53. /**
  54. * A representation of a Git tree entry. A Tree is a directory in Git.
  55. */
  56. public class Tree extends TreeEntry implements Treeish {
  57. private static final TreeEntry[] EMPTY_TREE = {};
  58. /**
  59. * Compare two names represented as bytes. Since git treats names of trees and
  60. * blobs differently we have one parameter that represents a '/' for trees. For
  61. * other objects the value should be NUL. The names are compare by their positive
  62. * byte value (0..255).
  63. *
  64. * A blob and a tree with the same name will not compare equal.
  65. *
  66. * @param a name
  67. * @param b name
  68. * @param lasta '/' if a is a tree, else NUL
  69. * @param lastb '/' if b is a tree, else NUL
  70. *
  71. * @return < 0 if a is sorted before b, 0 if they are the same, else b
  72. */
  73. public static final int compareNames(final byte[] a, final byte[] b, final int lasta,final int lastb) {
  74. return compareNames(a, b, 0, b.length, lasta, lastb);
  75. }
  76. private static final int compareNames(final byte[] a, final byte[] nameUTF8,
  77. final int nameStart, final int nameEnd, final int lasta, int lastb) {
  78. int j,k;
  79. for (j = 0, k = nameStart; j < a.length && k < nameEnd; j++, k++) {
  80. final int aj = a[j] & 0xff;
  81. final int bk = nameUTF8[k] & 0xff;
  82. if (aj < bk)
  83. return -1;
  84. else if (aj > bk)
  85. return 1;
  86. }
  87. if (j < a.length) {
  88. int aj = a[j]&0xff;
  89. if (aj < lastb)
  90. return -1;
  91. else if (aj > lastb)
  92. return 1;
  93. else
  94. if (j == a.length - 1)
  95. return 0;
  96. else
  97. return -1;
  98. }
  99. if (k < nameEnd) {
  100. int bk = nameUTF8[k] & 0xff;
  101. if (lasta < bk)
  102. return -1;
  103. else if (lasta > bk)
  104. return 1;
  105. else
  106. if (k == nameEnd - 1)
  107. return 0;
  108. else
  109. return 1;
  110. }
  111. if (lasta < lastb)
  112. return -1;
  113. else if (lasta > lastb)
  114. return 1;
  115. final int namelength = nameEnd - nameStart;
  116. if (a.length == namelength)
  117. return 0;
  118. else if (a.length < namelength)
  119. return -1;
  120. else
  121. return 1;
  122. }
  123. private static final byte[] substring(final byte[] s, final int nameStart,
  124. final int nameEnd) {
  125. if (nameStart == 0 && nameStart == s.length)
  126. return s;
  127. final byte[] n = new byte[nameEnd - nameStart];
  128. System.arraycopy(s, nameStart, n, 0, n.length);
  129. return n;
  130. }
  131. private static final int binarySearch(final TreeEntry[] entries,
  132. final byte[] nameUTF8, final int nameUTF8last, final int nameStart, final int nameEnd) {
  133. if (entries.length == 0)
  134. return -1;
  135. int high = entries.length;
  136. int low = 0;
  137. do {
  138. final int mid = (low + high) >>> 1;
  139. final int cmp = compareNames(entries[mid].getNameUTF8(), nameUTF8,
  140. nameStart, nameEnd, TreeEntry.lastChar(entries[mid]), nameUTF8last);
  141. if (cmp < 0)
  142. low = mid + 1;
  143. else if (cmp == 0)
  144. return mid;
  145. else
  146. high = mid;
  147. } while (low < high);
  148. return -(low + 1);
  149. }
  150. private final Repository db;
  151. private TreeEntry[] contents;
  152. /**
  153. * Constructor for a new Tree
  154. *
  155. * @param repo The repository that owns the Tree.
  156. */
  157. public Tree(final Repository repo) {
  158. super(null, null, null);
  159. db = repo;
  160. contents = EMPTY_TREE;
  161. }
  162. /**
  163. * Construct a Tree object with known content and hash value
  164. *
  165. * @param repo
  166. * @param myId
  167. * @param raw
  168. * @throws IOException
  169. */
  170. public Tree(final Repository repo, final ObjectId myId, final byte[] raw)
  171. throws IOException {
  172. super(null, myId, null);
  173. db = repo;
  174. readTree(raw);
  175. }
  176. /**
  177. * Construct a new Tree under another Tree
  178. *
  179. * @param parent
  180. * @param nameUTF8
  181. */
  182. public Tree(final Tree parent, final byte[] nameUTF8) {
  183. super(parent, null, nameUTF8);
  184. db = parent.getRepository();
  185. contents = EMPTY_TREE;
  186. }
  187. /**
  188. * Construct a Tree with a known SHA-1 under another tree. Data is not yet
  189. * specified and will have to be loaded on demand.
  190. *
  191. * @param parent
  192. * @param id
  193. * @param nameUTF8
  194. */
  195. public Tree(final Tree parent, final ObjectId id, final byte[] nameUTF8) {
  196. super(parent, id, nameUTF8);
  197. db = parent.getRepository();
  198. }
  199. public FileMode getMode() {
  200. return FileMode.TREE;
  201. }
  202. /**
  203. * @return true if this Tree is the top level Tree.
  204. */
  205. public boolean isRoot() {
  206. return getParent() == null;
  207. }
  208. public Repository getRepository() {
  209. return db;
  210. }
  211. public final ObjectId getTreeId() {
  212. return getId();
  213. }
  214. public final Tree getTree() {
  215. return this;
  216. }
  217. /**
  218. * @return true of the data of this Tree is loaded
  219. */
  220. public boolean isLoaded() {
  221. return contents != null;
  222. }
  223. /**
  224. * Forget the in-memory data for this tree.
  225. */
  226. public void unload() {
  227. if (isModified())
  228. throw new IllegalStateException(JGitText.get().cannotUnloadAModifiedTree);
  229. contents = null;
  230. }
  231. /**
  232. * Adds a new or existing file with the specified name to this tree.
  233. * Trees are added if necessary as the name may contain '/':s.
  234. *
  235. * @param name Name
  236. * @return a {@link FileTreeEntry} for the added file.
  237. * @throws IOException
  238. */
  239. public FileTreeEntry addFile(final String name) throws IOException {
  240. return addFile(Repository.gitInternalSlash(Constants.encode(name)), 0);
  241. }
  242. /**
  243. * Adds a new or existing file with the specified name to this tree.
  244. * Trees are added if necessary as the name may contain '/':s.
  245. *
  246. * @param s an array containing the name
  247. * @param offset when the name starts in the tree.
  248. *
  249. * @return a {@link FileTreeEntry} for the added file.
  250. * @throws IOException
  251. */
  252. public FileTreeEntry addFile(final byte[] s, final int offset)
  253. throws IOException {
  254. int slash;
  255. int p;
  256. for (slash = offset; slash < s.length && s[slash] != '/'; slash++) {
  257. // search for path component terminator
  258. }
  259. ensureLoaded();
  260. byte xlast = slash<s.length ? (byte)'/' : 0;
  261. p = binarySearch(contents, s, xlast, offset, slash);
  262. if (p >= 0 && slash < s.length && contents[p] instanceof Tree)
  263. return ((Tree) contents[p]).addFile(s, slash + 1);
  264. final byte[] newName = substring(s, offset, slash);
  265. if (p >= 0)
  266. throw new EntryExistsException(RawParseUtils.decode(newName));
  267. else if (slash < s.length) {
  268. final Tree t = new Tree(this, newName);
  269. insertEntry(p, t);
  270. return t.addFile(s, slash + 1);
  271. } else {
  272. final FileTreeEntry f = new FileTreeEntry(this, null, newName,
  273. false);
  274. insertEntry(p, f);
  275. return f;
  276. }
  277. }
  278. /**
  279. * Adds a new or existing Tree with the specified name to this tree.
  280. * Trees are added if necessary as the name may contain '/':s.
  281. *
  282. * @param name Name
  283. * @return a {@link FileTreeEntry} for the added tree.
  284. * @throws IOException
  285. */
  286. public Tree addTree(final String name) throws IOException {
  287. return addTree(Repository.gitInternalSlash(Constants.encode(name)), 0);
  288. }
  289. /**
  290. * Adds a new or existing Tree with the specified name to this tree.
  291. * Trees are added if necessary as the name may contain '/':s.
  292. *
  293. * @param s an array containing the name
  294. * @param offset when the name starts in the tree.
  295. *
  296. * @return a {@link FileTreeEntry} for the added tree.
  297. * @throws IOException
  298. */
  299. public Tree addTree(final byte[] s, final int offset) throws IOException {
  300. int slash;
  301. int p;
  302. for (slash = offset; slash < s.length && s[slash] != '/'; slash++) {
  303. // search for path component terminator
  304. }
  305. ensureLoaded();
  306. p = binarySearch(contents, s, (byte)'/', offset, slash);
  307. if (p >= 0 && slash < s.length && contents[p] instanceof Tree)
  308. return ((Tree) contents[p]).addTree(s, slash + 1);
  309. final byte[] newName = substring(s, offset, slash);
  310. if (p >= 0)
  311. throw new EntryExistsException(RawParseUtils.decode(newName));
  312. final Tree t = new Tree(this, newName);
  313. insertEntry(p, t);
  314. return slash == s.length ? t : t.addTree(s, slash + 1);
  315. }
  316. /**
  317. * Add the specified tree entry to this tree.
  318. *
  319. * @param e
  320. * @throws IOException
  321. */
  322. public void addEntry(final TreeEntry e) throws IOException {
  323. final int p;
  324. ensureLoaded();
  325. p = binarySearch(contents, e.getNameUTF8(), TreeEntry.lastChar(e), 0, e.getNameUTF8().length);
  326. if (p < 0) {
  327. e.attachParent(this);
  328. insertEntry(p, e);
  329. } else {
  330. throw new EntryExistsException(e.getName());
  331. }
  332. }
  333. private void insertEntry(int p, final TreeEntry e) {
  334. final TreeEntry[] c = contents;
  335. final TreeEntry[] n = new TreeEntry[c.length + 1];
  336. p = -(p + 1);
  337. for (int k = c.length - 1; k >= p; k--)
  338. n[k + 1] = c[k];
  339. n[p] = e;
  340. for (int k = p - 1; k >= 0; k--)
  341. n[k] = c[k];
  342. contents = n;
  343. setModified();
  344. }
  345. void removeEntry(final TreeEntry e) {
  346. final TreeEntry[] c = contents;
  347. final int p = binarySearch(c, e.getNameUTF8(), TreeEntry.lastChar(e), 0,
  348. e.getNameUTF8().length);
  349. if (p >= 0) {
  350. final TreeEntry[] n = new TreeEntry[c.length - 1];
  351. for (int k = c.length - 1; k > p; k--)
  352. n[k - 1] = c[k];
  353. for (int k = p - 1; k >= 0; k--)
  354. n[k] = c[k];
  355. contents = n;
  356. setModified();
  357. }
  358. }
  359. /**
  360. * @return number of members in this tree
  361. * @throws IOException
  362. */
  363. public int memberCount() throws IOException {
  364. ensureLoaded();
  365. return contents.length;
  366. }
  367. /**
  368. * Return all members of the tree sorted in Git order.
  369. *
  370. * Entries are sorted by the numerical unsigned byte
  371. * values with (sub)trees having an implicit '/'. An
  372. * example of a tree with three entries. a:b is an
  373. * actual file name here.
  374. *
  375. * <p>
  376. * 100644 blob e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 a.b
  377. * 040000 tree 4277b6e69d25e5efa77c455340557b384a4c018a a
  378. * 100644 blob e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 a:b
  379. *
  380. * @return all entries in this Tree, sorted.
  381. * @throws IOException
  382. */
  383. public TreeEntry[] members() throws IOException {
  384. ensureLoaded();
  385. final TreeEntry[] c = contents;
  386. if (c.length != 0) {
  387. final TreeEntry[] r = new TreeEntry[c.length];
  388. for (int k = c.length - 1; k >= 0; k--)
  389. r[k] = c[k];
  390. return r;
  391. } else
  392. return c;
  393. }
  394. private boolean exists(final String s, byte slast) throws IOException {
  395. return findMember(s, slast) != null;
  396. }
  397. /**
  398. * @param path to the tree.
  399. * @return true if a tree with the specified path can be found under this
  400. * tree.
  401. * @throws IOException
  402. */
  403. public boolean existsTree(String path) throws IOException {
  404. return exists(path,(byte)'/');
  405. }
  406. /**
  407. * @param path of the non-tree entry.
  408. * @return true if a blob, symlink, or gitlink with the specified name
  409. * can be found under this tree.
  410. * @throws IOException
  411. */
  412. public boolean existsBlob(String path) throws IOException {
  413. return exists(path,(byte)0);
  414. }
  415. private TreeEntry findMember(final String s, byte slast) throws IOException {
  416. return findMember(Repository.gitInternalSlash(Constants.encode(s)), slast, 0);
  417. }
  418. private TreeEntry findMember(final byte[] s, final byte slast, final int offset)
  419. throws IOException {
  420. int slash;
  421. int p;
  422. for (slash = offset; slash < s.length && s[slash] != '/'; slash++) {
  423. // search for path component terminator
  424. }
  425. ensureLoaded();
  426. byte xlast = slash<s.length ? (byte)'/' : slast;
  427. p = binarySearch(contents, s, xlast, offset, slash);
  428. if (p >= 0) {
  429. final TreeEntry r = contents[p];
  430. if (slash < s.length-1)
  431. return r instanceof Tree ? ((Tree) r).findMember(s, slast, slash + 1)
  432. : null;
  433. return r;
  434. }
  435. return null;
  436. }
  437. /**
  438. * @param s
  439. * blob name
  440. * @return a {@link TreeEntry} representing an object with the specified
  441. * relative path.
  442. * @throws IOException
  443. */
  444. public TreeEntry findBlobMember(String s) throws IOException {
  445. return findMember(s,(byte)0);
  446. }
  447. /**
  448. * @param s Tree Name
  449. * @return a Tree with the name s or null
  450. * @throws IOException
  451. */
  452. public TreeEntry findTreeMember(String s) throws IOException {
  453. return findMember(s,(byte)'/');
  454. }
  455. public void accept(final TreeVisitor tv, final int flags)
  456. throws IOException {
  457. final TreeEntry[] c;
  458. if ((MODIFIED_ONLY & flags) == MODIFIED_ONLY && !isModified())
  459. return;
  460. if ((LOADED_ONLY & flags) == LOADED_ONLY && !isLoaded()) {
  461. tv.startVisitTree(this);
  462. tv.endVisitTree(this);
  463. return;
  464. }
  465. ensureLoaded();
  466. tv.startVisitTree(this);
  467. if ((CONCURRENT_MODIFICATION & flags) == CONCURRENT_MODIFICATION)
  468. c = members();
  469. else
  470. c = contents;
  471. for (int k = 0; k < c.length; k++)
  472. c[k].accept(tv, flags);
  473. tv.endVisitTree(this);
  474. }
  475. private void ensureLoaded() throws IOException, MissingObjectException {
  476. if (!isLoaded()) {
  477. ObjectLoader ldr = db.open(getId(), Constants.OBJ_TREE);
  478. readTree(ldr.getCachedBytes());
  479. }
  480. }
  481. private void readTree(final byte[] raw) throws IOException {
  482. final int rawSize = raw.length;
  483. int rawPtr = 0;
  484. TreeEntry[] temp;
  485. int nextIndex = 0;
  486. while (rawPtr < rawSize) {
  487. while (rawPtr < rawSize && raw[rawPtr] != 0)
  488. rawPtr++;
  489. rawPtr++;
  490. rawPtr += Constants.OBJECT_ID_LENGTH;
  491. nextIndex++;
  492. }
  493. temp = new TreeEntry[nextIndex];
  494. rawPtr = 0;
  495. nextIndex = 0;
  496. while (rawPtr < rawSize) {
  497. int c = raw[rawPtr++];
  498. if (c < '0' || c > '7')
  499. throw new CorruptObjectException(getId(), JGitText.get().corruptObjectInvalidEntryMode);
  500. int mode = c - '0';
  501. for (;;) {
  502. c = raw[rawPtr++];
  503. if (' ' == c)
  504. break;
  505. else if (c < '0' || c > '7')
  506. throw new CorruptObjectException(getId(), JGitText.get().corruptObjectInvalidMode);
  507. mode <<= 3;
  508. mode += c - '0';
  509. }
  510. int nameLen = 0;
  511. while (raw[rawPtr + nameLen] != 0)
  512. nameLen++;
  513. final byte[] name = new byte[nameLen];
  514. System.arraycopy(raw, rawPtr, name, 0, nameLen);
  515. rawPtr += nameLen + 1;
  516. final ObjectId id = ObjectId.fromRaw(raw, rawPtr);
  517. rawPtr += Constants.OBJECT_ID_LENGTH;
  518. final TreeEntry ent;
  519. if (FileMode.REGULAR_FILE.equals(mode))
  520. ent = new FileTreeEntry(this, id, name, false);
  521. else if (FileMode.EXECUTABLE_FILE.equals(mode))
  522. ent = new FileTreeEntry(this, id, name, true);
  523. else if (FileMode.TREE.equals(mode))
  524. ent = new Tree(this, id, name);
  525. else if (FileMode.SYMLINK.equals(mode))
  526. ent = new SymlinkTreeEntry(this, id, name);
  527. else if (FileMode.GITLINK.equals(mode))
  528. ent = new GitlinkTreeEntry(this, id, name);
  529. else
  530. throw new CorruptObjectException(getId(), MessageFormat.format(
  531. JGitText.get().corruptObjectInvalidMode2, Integer.toOctalString(mode)));
  532. temp[nextIndex++] = ent;
  533. }
  534. contents = temp;
  535. }
  536. public String toString() {
  537. final StringBuilder r = new StringBuilder();
  538. r.append(ObjectId.toString(getId()));
  539. r.append(" T ");
  540. r.append(getFullName());
  541. return r.toString();
  542. }
  543. }