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

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