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.

WorkingTreeIterator.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /*
  2. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.treewalk;
  44. import java.io.IOException;
  45. import java.io.InputStream;
  46. import java.nio.ByteBuffer;
  47. import java.nio.CharBuffer;
  48. import java.nio.charset.CharacterCodingException;
  49. import java.nio.charset.CharsetEncoder;
  50. import java.security.MessageDigest;
  51. import java.util.Arrays;
  52. import java.util.Comparator;
  53. import org.eclipse.jgit.errors.CorruptObjectException;
  54. import org.eclipse.jgit.lib.Constants;
  55. import org.eclipse.jgit.lib.FileMode;
  56. /**
  57. * Walks a working directory tree as part of a {@link TreeWalk}.
  58. * <p>
  59. * Most applications will want to use the standard implementation of this
  60. * iterator, {@link FileTreeIterator}, as that does all IO through the standard
  61. * <code>java.io</code> package. Plugins for a Java based IDE may however wish
  62. * to create their own implementations of this class to allow traversal of the
  63. * IDE's project space, as well as benefit from any caching the IDE may have.
  64. *
  65. * @see FileTreeIterator
  66. */
  67. public abstract class WorkingTreeIterator extends AbstractTreeIterator {
  68. /** An empty entry array, suitable for {@link #init(Entry[])}. */
  69. protected static final Entry[] EOF = {};
  70. /** Size we perform file IO in if we have to read and hash a file. */
  71. private static final int BUFFER_SIZE = 2048;
  72. /** The {@link #idBuffer()} for the current entry. */
  73. private byte[] contentId;
  74. /** Index within {@link #entries} that {@link #contentId} came from. */
  75. private int contentIdFromPtr;
  76. /** Buffer used to perform {@link #contentId} computations. */
  77. private byte[] contentReadBuffer;
  78. /** Digest computer for {@link #contentId} computations. */
  79. private MessageDigest contentDigest;
  80. /** File name character encoder. */
  81. private final CharsetEncoder nameEncoder;
  82. /** List of entries obtained from the subclass. */
  83. private Entry[] entries;
  84. /** Total number of entries in {@link #entries} that are valid. */
  85. private int entryCnt;
  86. /** Current position within {@link #entries}. */
  87. private int ptr;
  88. /** Create a new iterator with no parent. */
  89. protected WorkingTreeIterator() {
  90. super();
  91. nameEncoder = Constants.CHARSET.newEncoder();
  92. }
  93. /**
  94. * Create a new iterator with no parent and a prefix.
  95. * <p>
  96. * The prefix path supplied is inserted in front of all paths generated by
  97. * this iterator. It is intended to be used when an iterator is being
  98. * created for a subsection of an overall repository and needs to be
  99. * combined with other iterators that are created to run over the entire
  100. * repository namespace.
  101. *
  102. * @param prefix
  103. * position of this iterator in the repository tree. The value
  104. * may be null or the empty string to indicate the prefix is the
  105. * root of the repository. A trailing slash ('/') is
  106. * automatically appended if the prefix does not end in '/'.
  107. */
  108. protected WorkingTreeIterator(final String prefix) {
  109. super(prefix);
  110. nameEncoder = Constants.CHARSET.newEncoder();
  111. }
  112. /**
  113. * Create an iterator for a subtree of an existing iterator.
  114. *
  115. * @param p
  116. * parent tree iterator.
  117. */
  118. protected WorkingTreeIterator(final WorkingTreeIterator p) {
  119. super(p);
  120. nameEncoder = p.nameEncoder;
  121. }
  122. @Override
  123. public byte[] idBuffer() {
  124. if (contentIdFromPtr == ptr)
  125. return contentId;
  126. switch (mode & FileMode.TYPE_MASK) {
  127. case FileMode.TYPE_FILE:
  128. contentIdFromPtr = ptr;
  129. return contentId = idBufferBlob(entries[ptr]);
  130. case FileMode.TYPE_SYMLINK:
  131. // Java does not support symbolic links, so we should not
  132. // have reached this particular part of the walk code.
  133. //
  134. return zeroid;
  135. case FileMode.TYPE_GITLINK:
  136. // TODO: Support obtaining current HEAD SHA-1 from nested repository
  137. //
  138. return zeroid;
  139. }
  140. return zeroid;
  141. }
  142. private void initializeDigest() {
  143. if (contentDigest != null)
  144. return;
  145. if (parent == null) {
  146. contentReadBuffer = new byte[BUFFER_SIZE];
  147. contentDigest = Constants.newMessageDigest();
  148. } else {
  149. final WorkingTreeIterator p = (WorkingTreeIterator) parent;
  150. p.initializeDigest();
  151. contentReadBuffer = p.contentReadBuffer;
  152. contentDigest = p.contentDigest;
  153. }
  154. }
  155. private static final byte[] digits = { '0', '1', '2', '3', '4', '5', '6',
  156. '7', '8', '9' };
  157. private static final byte[] hblob = Constants
  158. .encodedTypeString(Constants.OBJ_BLOB);
  159. private byte[] idBufferBlob(final Entry e) {
  160. try {
  161. final InputStream is = e.openInputStream();
  162. if (is == null)
  163. return zeroid;
  164. try {
  165. initializeDigest();
  166. contentDigest.reset();
  167. contentDigest.update(hblob);
  168. contentDigest.update((byte) ' ');
  169. final long blobLength = e.getLength();
  170. long sz = blobLength;
  171. if (sz == 0) {
  172. contentDigest.update((byte) '0');
  173. } else {
  174. final int bufn = contentReadBuffer.length;
  175. int p = bufn;
  176. do {
  177. contentReadBuffer[--p] = digits[(int) (sz % 10)];
  178. sz /= 10;
  179. } while (sz > 0);
  180. contentDigest.update(contentReadBuffer, p, bufn - p);
  181. }
  182. contentDigest.update((byte) 0);
  183. for (;;) {
  184. final int r = is.read(contentReadBuffer);
  185. if (r <= 0)
  186. break;
  187. contentDigest.update(contentReadBuffer, 0, r);
  188. sz += r;
  189. }
  190. if (sz != blobLength)
  191. return zeroid;
  192. return contentDigest.digest();
  193. } finally {
  194. try {
  195. is.close();
  196. } catch (IOException err2) {
  197. // Suppress any error related to closing an input
  198. // stream. We don't care, we should not have any
  199. // outstanding data to flush or anything like that.
  200. }
  201. }
  202. } catch (IOException err) {
  203. // Can't read the file? Don't report the failure either.
  204. //
  205. return zeroid;
  206. }
  207. }
  208. @Override
  209. public int idOffset() {
  210. return 0;
  211. }
  212. @Override
  213. public boolean first() {
  214. return ptr == 0;
  215. }
  216. @Override
  217. public boolean eof() {
  218. return ptr == entryCnt;
  219. }
  220. @Override
  221. public void next(final int delta) throws CorruptObjectException {
  222. ptr += delta;
  223. if (!eof())
  224. parseEntry();
  225. }
  226. @Override
  227. public void back(final int delta) throws CorruptObjectException {
  228. ptr -= delta;
  229. parseEntry();
  230. }
  231. private void parseEntry() {
  232. final Entry e = entries[ptr];
  233. mode = e.getMode().getBits();
  234. final int nameLen = e.encodedNameLen;
  235. ensurePathCapacity(pathOffset + nameLen, pathOffset);
  236. System.arraycopy(e.encodedName, 0, path, pathOffset, nameLen);
  237. pathLen = pathOffset + nameLen;
  238. }
  239. /**
  240. * Get the byte length of this entry.
  241. *
  242. * @return size of this file, in bytes.
  243. */
  244. public long getEntryLength() {
  245. return current().getLength();
  246. }
  247. /**
  248. * Get the last modified time of this entry.
  249. *
  250. * @return last modified time of this file, in milliseconds since the epoch
  251. * (Jan 1, 1970 UTC).
  252. */
  253. public long getEntryLastModified() {
  254. return current().getLastModified();
  255. }
  256. private static final Comparator<Entry> ENTRY_CMP = new Comparator<Entry>() {
  257. public int compare(final Entry o1, final Entry o2) {
  258. final byte[] a = o1.encodedName;
  259. final byte[] b = o2.encodedName;
  260. final int aLen = o1.encodedNameLen;
  261. final int bLen = o2.encodedNameLen;
  262. int cPos;
  263. for (cPos = 0; cPos < aLen && cPos < bLen; cPos++) {
  264. final int cmp = (a[cPos] & 0xff) - (b[cPos] & 0xff);
  265. if (cmp != 0)
  266. return cmp;
  267. }
  268. if (cPos < aLen)
  269. return (a[cPos] & 0xff) - lastPathChar(o2);
  270. if (cPos < bLen)
  271. return lastPathChar(o1) - (b[cPos] & 0xff);
  272. return lastPathChar(o1) - lastPathChar(o2);
  273. }
  274. };
  275. static int lastPathChar(final Entry e) {
  276. return e.getMode() == FileMode.TREE ? '/' : '\0';
  277. }
  278. /**
  279. * Constructor helper.
  280. *
  281. * @param list
  282. * files in the subtree of the work tree this iterator operates
  283. * on
  284. */
  285. protected void init(final Entry[] list) {
  286. // Filter out nulls, . and .. as these are not valid tree entries,
  287. // also cache the encoded forms of the path names for efficient use
  288. // later on during sorting and iteration.
  289. //
  290. entries = list;
  291. int i, o;
  292. for (i = 0, o = 0; i < entries.length; i++) {
  293. final Entry e = entries[i];
  294. if (e == null)
  295. continue;
  296. final String name = e.getName();
  297. if (".".equals(name) || "..".equals(name))
  298. continue;
  299. if (Constants.DOT_GIT.equals(name))
  300. continue;
  301. if (i != o)
  302. entries[o] = e;
  303. e.encodeName(nameEncoder);
  304. o++;
  305. }
  306. entryCnt = o;
  307. Arrays.sort(entries, 0, entryCnt, ENTRY_CMP);
  308. contentIdFromPtr = -1;
  309. ptr = 0;
  310. if (!eof())
  311. parseEntry();
  312. }
  313. /**
  314. * Obtain the current entry from this iterator.
  315. *
  316. * @return the currently selected entry.
  317. */
  318. protected Entry current() {
  319. return entries[ptr];
  320. }
  321. /** A single entry within a working directory tree. */
  322. protected static abstract class Entry {
  323. byte[] encodedName;
  324. int encodedNameLen;
  325. void encodeName(final CharsetEncoder enc) {
  326. final ByteBuffer b;
  327. try {
  328. b = enc.encode(CharBuffer.wrap(getName()));
  329. } catch (CharacterCodingException e) {
  330. // This should so never happen.
  331. throw new RuntimeException("Unencodeable file: " + getName());
  332. }
  333. encodedNameLen = b.limit();
  334. if (b.hasArray() && b.arrayOffset() == 0)
  335. encodedName = b.array();
  336. else
  337. b.get(encodedName = new byte[encodedNameLen]);
  338. }
  339. public String toString() {
  340. return getMode().toString() + " " + getName();
  341. }
  342. /**
  343. * Get the type of this entry.
  344. * <p>
  345. * <b>Note: Efficient implementation required.</b>
  346. * <p>
  347. * The implementation of this method must be efficient. If a subclass
  348. * needs to compute the value they should cache the reference within an
  349. * instance member instead.
  350. *
  351. * @return a file mode constant from {@link FileMode}.
  352. */
  353. public abstract FileMode getMode();
  354. /**
  355. * Get the byte length of this entry.
  356. * <p>
  357. * <b>Note: Efficient implementation required.</b>
  358. * <p>
  359. * The implementation of this method must be efficient. If a subclass
  360. * needs to compute the value they should cache the reference within an
  361. * instance member instead.
  362. *
  363. * @return size of this file, in bytes.
  364. */
  365. public abstract long getLength();
  366. /**
  367. * Get the last modified time of this entry.
  368. * <p>
  369. * <b>Note: Efficient implementation required.</b>
  370. * <p>
  371. * The implementation of this method must be efficient. If a subclass
  372. * needs to compute the value they should cache the reference within an
  373. * instance member instead.
  374. *
  375. * @return time since the epoch (in ms) of the last change.
  376. */
  377. public abstract long getLastModified();
  378. /**
  379. * Get the name of this entry within its directory.
  380. * <p>
  381. * Efficient implementations are not required. The caller will obtain
  382. * the name only once and cache it once obtained.
  383. *
  384. * @return name of the entry.
  385. */
  386. public abstract String getName();
  387. /**
  388. * Obtain an input stream to read the file content.
  389. * <p>
  390. * Efficient implementations are not required. The caller will usually
  391. * obtain the stream only once per entry, if at all.
  392. * <p>
  393. * The input stream should not use buffering if the implementation can
  394. * avoid it. The caller will buffer as necessary to perform efficient
  395. * block IO operations.
  396. * <p>
  397. * The caller will close the stream once complete.
  398. *
  399. * @return a stream to read from the file.
  400. * @throws IOException
  401. * the file could not be opened for reading.
  402. */
  403. public abstract InputStream openInputStream() throws IOException;
  404. }
  405. }