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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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.errors.CorruptObjectException;
  49. import org.eclipse.jgit.errors.EntryExistsException;
  50. import org.eclipse.jgit.errors.MissingObjectException;
  51. import org.eclipse.jgit.errors.ObjectWritingException;
  52. import org.eclipse.jgit.internal.JGitText;
  53. import org.eclipse.jgit.util.RawParseUtils;
  54. /**
  55. * A representation of a Git tree entry. A Tree is a directory in Git.
  56. *
  57. * @deprecated To look up information about a single path, use
  58. * {@link org.eclipse.jgit.treewalk.TreeWalk#forPath(Repository, String, org.eclipse.jgit.revwalk.RevTree)}.
  59. * To lookup information about multiple paths at once, use a
  60. * {@link org.eclipse.jgit.treewalk.TreeWalk} and obtain the current entry's
  61. * information from its getter methods.
  62. * @noreference This class is not intended to be referenced by clients.
  63. * @noextend This class is not intended to be subclassed by clients.
  64. */
  65. @Deprecated
  66. public class Tree extends TreeEntry {
  67. private static final TreeEntry[] EMPTY_TREE = {};
  68. /**
  69. * Compare two names represented as bytes. Since git treats names of trees and
  70. * blobs differently we have one parameter that represents a '/' for trees. For
  71. * other objects the value should be NUL. The names are compare by their positive
  72. * byte value (0..255).
  73. *
  74. * A blob and a tree with the same name will not compare equal.
  75. *
  76. * @param a name
  77. * @param b name
  78. * @param lasta '/' if a is a tree, else NUL
  79. * @param lastb '/' if b is a tree, else NUL
  80. *
  81. * @return &lt; 0 if a is sorted before b, 0 if they are the same, else b
  82. */
  83. public static final int compareNames(final byte[] a, final byte[] b, final int lasta,final int lastb) {
  84. return compareNames(a, b, 0, b.length, lasta, lastb);
  85. }
  86. private static final int compareNames(final byte[] a, final byte[] nameUTF8,
  87. final int nameStart, final int nameEnd, final int lasta, int lastb) {
  88. int j,k;
  89. for (j = 0, k = nameStart; j < a.length && k < nameEnd; j++, k++) {
  90. final int aj = a[j] & 0xff;
  91. final int bk = nameUTF8[k] & 0xff;
  92. if (aj < bk)
  93. return -1;
  94. else if (aj > bk)
  95. return 1;
  96. }
  97. if (j < a.length) {
  98. int aj = a[j]&0xff;
  99. if (aj < lastb)
  100. return -1;
  101. else if (aj > lastb)
  102. return 1;
  103. else
  104. if (j == a.length - 1)
  105. return 0;
  106. else
  107. return -1;
  108. }
  109. if (k < nameEnd) {
  110. int bk = nameUTF8[k] & 0xff;
  111. if (lasta < bk)
  112. return -1;
  113. else if (lasta > bk)
  114. return 1;
  115. else
  116. if (k == nameEnd - 1)
  117. return 0;
  118. else
  119. return 1;
  120. }
  121. if (lasta < lastb)
  122. return -1;
  123. else if (lasta > lastb)
  124. return 1;
  125. final int namelength = nameEnd - nameStart;
  126. if (a.length == namelength)
  127. return 0;
  128. else if (a.length < namelength)
  129. return -1;
  130. else
  131. return 1;
  132. }
  133. private static final byte[] substring(final byte[] s, final int nameStart,
  134. final int nameEnd) {
  135. if (nameStart == 0 && nameStart == s.length)
  136. return s;
  137. final byte[] n = new byte[nameEnd - nameStart];
  138. System.arraycopy(s, nameStart, n, 0, n.length);
  139. return n;
  140. }
  141. private static final int binarySearch(final TreeEntry[] entries,
  142. final byte[] nameUTF8, final int nameUTF8last, final int nameStart, final int nameEnd) {
  143. if (entries.length == 0)
  144. return -1;
  145. int high = entries.length;
  146. int low = 0;
  147. do {
  148. final int mid = (low + high) >>> 1;
  149. final int cmp = compareNames(entries[mid].getNameUTF8(), nameUTF8,
  150. nameStart, nameEnd, TreeEntry.lastChar(entries[mid]), nameUTF8last);
  151. if (cmp < 0)
  152. low = mid + 1;
  153. else if (cmp == 0)
  154. return mid;
  155. else
  156. high = mid;
  157. } while (low < high);
  158. return -(low + 1);
  159. }
  160. private final Repository db;
  161. private TreeEntry[] contents;
  162. /**
  163. * Constructor for a new Tree
  164. *
  165. * @param repo The repository that owns the Tree.
  166. */
  167. public Tree(final Repository repo) {
  168. super(null, null, null);
  169. db = repo;
  170. contents = EMPTY_TREE;
  171. }
  172. /**
  173. * Construct a Tree object with known content and hash value
  174. *
  175. * @param repo
  176. * @param myId
  177. * @param raw
  178. * @throws IOException
  179. */
  180. public Tree(final Repository repo, final ObjectId myId, final byte[] raw)
  181. throws IOException {
  182. super(null, myId, null);
  183. db = repo;
  184. readTree(raw);
  185. }
  186. /**
  187. * Construct a new Tree under another Tree
  188. *
  189. * @param parent
  190. * @param nameUTF8
  191. */
  192. public Tree(final Tree parent, final byte[] nameUTF8) {
  193. super(parent, null, nameUTF8);
  194. db = parent.getRepository();
  195. contents = EMPTY_TREE;
  196. }
  197. /**
  198. * Construct a Tree with a known SHA-1 under another tree. Data is not yet
  199. * specified and will have to be loaded on demand.
  200. *
  201. * @param parent
  202. * @param id
  203. * @param nameUTF8
  204. */
  205. public Tree(final Tree parent, final ObjectId id, final byte[] nameUTF8) {
  206. super(parent, id, nameUTF8);
  207. db = parent.getRepository();
  208. }
  209. public FileMode getMode() {
  210. return FileMode.TREE;
  211. }
  212. /**
  213. * @return true if this Tree is the top level Tree.
  214. */
  215. public boolean isRoot() {
  216. return getParent() == null;
  217. }
  218. public Repository getRepository() {
  219. return db;
  220. }
  221. /**
  222. * @return true of the data of this Tree is loaded
  223. */
  224. public boolean isLoaded() {
  225. return contents != null;
  226. }
  227. /**
  228. * Forget the in-memory data for this tree.
  229. */
  230. public void unload() {
  231. if (isModified())
  232. throw new IllegalStateException(JGitText.get().cannotUnloadAModifiedTree);
  233. contents = null;
  234. }
  235. /**
  236. * Adds a new or existing file with the specified name to this tree.
  237. * Trees are added if necessary as the name may contain '/':s.
  238. *
  239. * @param name Name
  240. * @return a {@link FileTreeEntry} for the added file.
  241. * @throws IOException
  242. */
  243. public FileTreeEntry addFile(final String name) throws IOException {
  244. return addFile(Repository.gitInternalSlash(Constants.encode(name)), 0);
  245. }
  246. /**
  247. * Adds a new or existing file with the specified name to this tree.
  248. * Trees are added if necessary as the name may contain '/':s.
  249. *
  250. * @param s an array containing the name
  251. * @param offset when the name starts in the tree.
  252. *
  253. * @return a {@link FileTreeEntry} for the added file.
  254. * @throws IOException
  255. */
  256. public FileTreeEntry addFile(final byte[] s, final int offset)
  257. throws IOException {
  258. int slash;
  259. int p;
  260. for (slash = offset; slash < s.length && s[slash] != '/'; slash++) {
  261. // search for path component terminator
  262. }
  263. ensureLoaded();
  264. byte xlast = slash<s.length ? (byte)'/' : 0;
  265. p = binarySearch(contents, s, xlast, offset, slash);
  266. if (p >= 0 && slash < s.length && contents[p] instanceof Tree)
  267. return ((Tree) contents[p]).addFile(s, slash + 1);
  268. final byte[] newName = substring(s, offset, slash);
  269. if (p >= 0)
  270. throw new EntryExistsException(RawParseUtils.decode(newName));
  271. else if (slash < s.length) {
  272. final Tree t = new Tree(this, newName);
  273. insertEntry(p, t);
  274. return t.addFile(s, slash + 1);
  275. } else {
  276. final FileTreeEntry f = new FileTreeEntry(this, null, newName,
  277. false);
  278. insertEntry(p, f);
  279. return f;
  280. }
  281. }
  282. /**
  283. * Adds a new or existing Tree with the specified name to this tree.
  284. * Trees are added if necessary as the name may contain '/':s.
  285. *
  286. * @param name Name
  287. * @return a {@link FileTreeEntry} for the added tree.
  288. * @throws IOException
  289. */
  290. public Tree addTree(final String name) throws IOException {
  291. return addTree(Repository.gitInternalSlash(Constants.encode(name)), 0);
  292. }
  293. /**
  294. * Adds a new or existing Tree with the specified name to this tree.
  295. * Trees are added if necessary as the name may contain '/':s.
  296. *
  297. * @param s an array containing the name
  298. * @param offset when the name starts in the tree.
  299. *
  300. * @return a {@link FileTreeEntry} for the added tree.
  301. * @throws IOException
  302. */
  303. public Tree addTree(final byte[] s, final int offset) throws IOException {
  304. int slash;
  305. int p;
  306. for (slash = offset; slash < s.length && s[slash] != '/'; slash++) {
  307. // search for path component terminator
  308. }
  309. ensureLoaded();
  310. p = binarySearch(contents, s, (byte)'/', offset, slash);
  311. if (p >= 0 && slash < s.length && contents[p] instanceof Tree)
  312. return ((Tree) contents[p]).addTree(s, slash + 1);
  313. final byte[] newName = substring(s, offset, slash);
  314. if (p >= 0)
  315. throw new EntryExistsException(RawParseUtils.decode(newName));
  316. final Tree t = new Tree(this, newName);
  317. insertEntry(p, t);
  318. return slash == s.length ? t : t.addTree(s, slash + 1);
  319. }
  320. /**
  321. * Add the specified tree entry to this tree.
  322. *
  323. * @param e
  324. * @throws IOException
  325. */
  326. public void addEntry(final TreeEntry e) throws IOException {
  327. final int p;
  328. ensureLoaded();
  329. p = binarySearch(contents, e.getNameUTF8(), TreeEntry.lastChar(e), 0, e.getNameUTF8().length);
  330. if (p < 0) {
  331. e.attachParent(this);
  332. insertEntry(p, e);
  333. } else {
  334. throw new EntryExistsException(e.getName());
  335. }
  336. }
  337. private void insertEntry(int p, final TreeEntry e) {
  338. final TreeEntry[] c = contents;
  339. final TreeEntry[] n = new TreeEntry[c.length + 1];
  340. p = -(p + 1);
  341. for (int k = c.length - 1; k >= p; k--)
  342. n[k + 1] = c[k];
  343. n[p] = e;
  344. for (int k = p - 1; k >= 0; k--)
  345. n[k] = c[k];
  346. contents = n;
  347. setModified();
  348. }
  349. void removeEntry(final TreeEntry e) {
  350. final TreeEntry[] c = contents;
  351. final int p = binarySearch(c, e.getNameUTF8(), TreeEntry.lastChar(e), 0,
  352. e.getNameUTF8().length);
  353. if (p >= 0) {
  354. final TreeEntry[] n = new TreeEntry[c.length - 1];
  355. for (int k = c.length - 1; k > p; k--)
  356. n[k - 1] = c[k];
  357. for (int k = p - 1; k >= 0; k--)
  358. n[k] = c[k];
  359. contents = n;
  360. setModified();
  361. }
  362. }
  363. /**
  364. * @return number of members in this tree
  365. * @throws IOException
  366. */
  367. public int memberCount() throws IOException {
  368. ensureLoaded();
  369. return contents.length;
  370. }
  371. /**
  372. * Return all members of the tree sorted in Git order.
  373. *
  374. * Entries are sorted by the numerical unsigned byte
  375. * values with (sub)trees having an implicit '/'. An
  376. * example of a tree with three entries. a:b is an
  377. * actual file name here.
  378. *
  379. * <p>
  380. * 100644 blob e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 a.b
  381. * 040000 tree 4277b6e69d25e5efa77c455340557b384a4c018a a
  382. * 100644 blob e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 a:b
  383. *
  384. * @return all entries in this Tree, sorted.
  385. * @throws IOException
  386. */
  387. public TreeEntry[] members() throws IOException {
  388. ensureLoaded();
  389. final TreeEntry[] c = contents;
  390. if (c.length != 0) {
  391. final TreeEntry[] r = new TreeEntry[c.length];
  392. for (int k = c.length - 1; k >= 0; k--)
  393. r[k] = c[k];
  394. return r;
  395. } else
  396. return c;
  397. }
  398. private boolean exists(final String s, byte slast) throws IOException {
  399. return findMember(s, slast) != null;
  400. }
  401. /**
  402. * @param path to the tree.
  403. * @return true if a tree with the specified path can be found under this
  404. * tree.
  405. * @throws IOException
  406. */
  407. public boolean existsTree(String path) throws IOException {
  408. return exists(path,(byte)'/');
  409. }
  410. /**
  411. * @param path of the non-tree entry.
  412. * @return true if a blob, symlink, or gitlink with the specified name
  413. * can be found under this tree.
  414. * @throws IOException
  415. */
  416. public boolean existsBlob(String path) throws IOException {
  417. return exists(path,(byte)0);
  418. }
  419. private TreeEntry findMember(final String s, byte slast) throws IOException {
  420. return findMember(Repository.gitInternalSlash(Constants.encode(s)), slast, 0);
  421. }
  422. private TreeEntry findMember(final byte[] s, final byte slast, final int offset)
  423. throws IOException {
  424. int slash;
  425. int p;
  426. for (slash = offset; slash < s.length && s[slash] != '/'; slash++) {
  427. // search for path component terminator
  428. }
  429. ensureLoaded();
  430. byte xlast = slash<s.length ? (byte)'/' : slast;
  431. p = binarySearch(contents, s, xlast, offset, slash);
  432. if (p >= 0) {
  433. final TreeEntry r = contents[p];
  434. if (slash < s.length-1)
  435. return r instanceof Tree ? ((Tree) r).findMember(s, slast, slash + 1)
  436. : null;
  437. return r;
  438. }
  439. return null;
  440. }
  441. /**
  442. * @param s
  443. * blob name
  444. * @return a {@link TreeEntry} representing an object with the specified
  445. * relative path.
  446. * @throws IOException
  447. */
  448. public TreeEntry findBlobMember(String s) throws IOException {
  449. return findMember(s,(byte)0);
  450. }
  451. /**
  452. * @param s Tree Name
  453. * @return a Tree with the name s or null
  454. * @throws IOException
  455. */
  456. public TreeEntry findTreeMember(String s) throws IOException {
  457. return findMember(s,(byte)'/');
  458. }
  459. private void ensureLoaded() throws IOException, MissingObjectException {
  460. if (!isLoaded()) {
  461. ObjectLoader ldr = db.open(getId(), Constants.OBJ_TREE);
  462. readTree(ldr.getCachedBytes());
  463. }
  464. }
  465. private void readTree(final byte[] raw) throws IOException {
  466. final int rawSize = raw.length;
  467. int rawPtr = 0;
  468. TreeEntry[] temp;
  469. int nextIndex = 0;
  470. while (rawPtr < rawSize) {
  471. while (rawPtr < rawSize && raw[rawPtr] != 0)
  472. rawPtr++;
  473. rawPtr++;
  474. rawPtr += Constants.OBJECT_ID_LENGTH;
  475. nextIndex++;
  476. }
  477. temp = new TreeEntry[nextIndex];
  478. rawPtr = 0;
  479. nextIndex = 0;
  480. while (rawPtr < rawSize) {
  481. int c = raw[rawPtr++];
  482. if (c < '0' || c > '7')
  483. throw new CorruptObjectException(getId(), JGitText.get().corruptObjectInvalidEntryMode);
  484. int mode = c - '0';
  485. for (;;) {
  486. c = raw[rawPtr++];
  487. if (' ' == c)
  488. break;
  489. else if (c < '0' || c > '7')
  490. throw new CorruptObjectException(getId(), JGitText.get().corruptObjectInvalidMode);
  491. mode <<= 3;
  492. mode += c - '0';
  493. }
  494. int nameLen = 0;
  495. while (raw[rawPtr + nameLen] != 0)
  496. nameLen++;
  497. final byte[] name = new byte[nameLen];
  498. System.arraycopy(raw, rawPtr, name, 0, nameLen);
  499. rawPtr += nameLen + 1;
  500. final ObjectId id = ObjectId.fromRaw(raw, rawPtr);
  501. rawPtr += Constants.OBJECT_ID_LENGTH;
  502. final TreeEntry ent;
  503. if (FileMode.REGULAR_FILE.equals(mode))
  504. ent = new FileTreeEntry(this, id, name, false);
  505. else if (FileMode.EXECUTABLE_FILE.equals(mode))
  506. ent = new FileTreeEntry(this, id, name, true);
  507. else if (FileMode.TREE.equals(mode))
  508. ent = new Tree(this, id, name);
  509. else if (FileMode.SYMLINK.equals(mode))
  510. ent = new SymlinkTreeEntry(this, id, name);
  511. else if (FileMode.GITLINK.equals(mode))
  512. ent = new GitlinkTreeEntry(this, id, name);
  513. else
  514. throw new CorruptObjectException(getId(), MessageFormat.format(
  515. JGitText.get().corruptObjectInvalidMode2, Integer.toOctalString(mode)));
  516. temp[nextIndex++] = ent;
  517. }
  518. contents = temp;
  519. }
  520. /**
  521. * Format this Tree in canonical format.
  522. *
  523. * @return canonical encoding of the tree object.
  524. * @throws IOException
  525. * the tree cannot be loaded, or its not in a writable state.
  526. */
  527. public byte[] format() throws IOException {
  528. TreeFormatter fmt = new TreeFormatter();
  529. for (TreeEntry e : members()) {
  530. ObjectId id = e.getId();
  531. if (id == null)
  532. throw new ObjectWritingException(MessageFormat.format(JGitText
  533. .get().objectAtPathDoesNotHaveId, e.getFullName()));
  534. fmt.append(e.getNameUTF8(), e.getMode(), id);
  535. }
  536. return fmt.toByteArray();
  537. }
  538. public String toString() {
  539. final StringBuilder r = new StringBuilder();
  540. r.append(ObjectId.toString(getId()));
  541. r.append(" T "); //$NON-NLS-1$
  542. r.append(getFullName());
  543. return r.toString();
  544. }
  545. }