Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

DiffFormatter.java 33KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  1. /*
  2. * Copyright (C) 2009, Google Inc.
  3. * Copyright (C) 2008-2009, Johannes E. Schindelin <johannes.schindelin@gmx.de>
  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.diff;
  45. import static org.eclipse.jgit.diff.DiffEntry.ChangeType.ADD;
  46. import static org.eclipse.jgit.diff.DiffEntry.ChangeType.COPY;
  47. import static org.eclipse.jgit.diff.DiffEntry.ChangeType.DELETE;
  48. import static org.eclipse.jgit.diff.DiffEntry.ChangeType.MODIFY;
  49. import static org.eclipse.jgit.diff.DiffEntry.ChangeType.RENAME;
  50. import static org.eclipse.jgit.diff.DiffEntry.Side.NEW;
  51. import static org.eclipse.jgit.diff.DiffEntry.Side.OLD;
  52. import static org.eclipse.jgit.lib.Constants.encode;
  53. import static org.eclipse.jgit.lib.Constants.encodeASCII;
  54. import static org.eclipse.jgit.lib.FileMode.GITLINK;
  55. import java.io.ByteArrayOutputStream;
  56. import java.io.IOException;
  57. import java.io.OutputStream;
  58. import java.util.Collection;
  59. import java.util.Collections;
  60. import java.util.List;
  61. import org.eclipse.jgit.JGitText;
  62. import org.eclipse.jgit.diff.DiffAlgorithm.SupportedAlgorithm;
  63. import org.eclipse.jgit.diff.DiffEntry.ChangeType;
  64. import org.eclipse.jgit.dircache.DirCacheIterator;
  65. import org.eclipse.jgit.errors.AmbiguousObjectException;
  66. import org.eclipse.jgit.errors.CorruptObjectException;
  67. import org.eclipse.jgit.errors.LargeObjectException;
  68. import org.eclipse.jgit.errors.MissingObjectException;
  69. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  70. import org.eclipse.jgit.lib.AnyObjectId;
  71. import org.eclipse.jgit.lib.ConfigConstants;
  72. import org.eclipse.jgit.lib.Constants;
  73. import org.eclipse.jgit.lib.FileMode;
  74. import org.eclipse.jgit.lib.ObjectId;
  75. import org.eclipse.jgit.lib.ObjectLoader;
  76. import org.eclipse.jgit.lib.ObjectReader;
  77. import org.eclipse.jgit.lib.ProgressMonitor;
  78. import org.eclipse.jgit.lib.Repository;
  79. import org.eclipse.jgit.patch.FileHeader;
  80. import org.eclipse.jgit.patch.FileHeader.PatchType;
  81. import org.eclipse.jgit.patch.HunkHeader;
  82. import org.eclipse.jgit.revwalk.FollowFilter;
  83. import org.eclipse.jgit.revwalk.RevTree;
  84. import org.eclipse.jgit.revwalk.RevWalk;
  85. import org.eclipse.jgit.storage.pack.PackConfig;
  86. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  87. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  88. import org.eclipse.jgit.treewalk.TreeWalk;
  89. import org.eclipse.jgit.treewalk.WorkingTreeIterator;
  90. import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
  91. import org.eclipse.jgit.treewalk.filter.IndexDiffFilter;
  92. import org.eclipse.jgit.treewalk.filter.NotIgnoredFilter;
  93. import org.eclipse.jgit.treewalk.filter.PathFilter;
  94. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  95. import org.eclipse.jgit.util.QuotedString;
  96. import org.eclipse.jgit.util.io.DisabledOutputStream;
  97. /**
  98. * Format a Git style patch script.
  99. */
  100. public class DiffFormatter {
  101. private static final int DEFAULT_BINARY_FILE_THRESHOLD = PackConfig.DEFAULT_BIG_FILE_THRESHOLD;
  102. private static final byte[] noNewLine = encodeASCII("\\ No newline at end of file\n");
  103. /** Magic return content indicating it is empty or no content present. */
  104. private static final byte[] EMPTY = new byte[] {};
  105. /** Magic return indicating the content is binary. */
  106. private static final byte[] BINARY = new byte[] {};
  107. private final OutputStream out;
  108. private Repository db;
  109. private ObjectReader reader;
  110. private int context = 3;
  111. private int abbreviationLength = 7;
  112. private DiffAlgorithm diffAlgorithm;
  113. private RawTextComparator comparator = RawTextComparator.DEFAULT;
  114. private int binaryFileThreshold = DEFAULT_BINARY_FILE_THRESHOLD;
  115. private String oldPrefix = "a/";
  116. private String newPrefix = "b/";
  117. private TreeFilter pathFilter = TreeFilter.ALL;
  118. private RenameDetector renameDetector;
  119. private ProgressMonitor progressMonitor;
  120. private ContentSource.Pair source;
  121. /**
  122. * Create a new formatter with a default level of context.
  123. *
  124. * @param out
  125. * the stream the formatter will write line data to. This stream
  126. * should have buffering arranged by the caller, as many small
  127. * writes are performed to it.
  128. */
  129. public DiffFormatter(OutputStream out) {
  130. this.out = out;
  131. }
  132. /** @return the stream we are outputting data to. */
  133. protected OutputStream getOutputStream() {
  134. return out;
  135. }
  136. /**
  137. * Set the repository the formatter can load object contents from.
  138. *
  139. * Once a repository has been set, the formatter must be released to ensure
  140. * the internal ObjectReader is able to release its resources.
  141. *
  142. * @param repository
  143. * source repository holding referenced objects.
  144. */
  145. public void setRepository(Repository repository) {
  146. if (reader != null)
  147. reader.release();
  148. db = repository;
  149. reader = db.newObjectReader();
  150. ContentSource cs = ContentSource.create(reader);
  151. source = new ContentSource.Pair(cs, cs);
  152. DiffConfig dc = db.getConfig().get(DiffConfig.KEY);
  153. if (dc.isNoPrefix()) {
  154. setOldPrefix("");
  155. setNewPrefix("");
  156. }
  157. setDetectRenames(dc.isRenameDetectionEnabled());
  158. diffAlgorithm = DiffAlgorithm.getAlgorithm(db.getConfig().getEnum(
  159. ConfigConstants.CONFIG_DIFF_SECTION, null,
  160. ConfigConstants.CONFIG_KEY_ALGORITHM,
  161. SupportedAlgorithm.HISTOGRAM));
  162. }
  163. /**
  164. * Change the number of lines of context to display.
  165. *
  166. * @param lineCount
  167. * number of lines of context to see before the first
  168. * modification and after the last modification within a hunk of
  169. * the modified file.
  170. */
  171. public void setContext(final int lineCount) {
  172. if (lineCount < 0)
  173. throw new IllegalArgumentException(
  174. JGitText.get().contextMustBeNonNegative);
  175. context = lineCount;
  176. }
  177. /**
  178. * Change the number of digits to show in an ObjectId.
  179. *
  180. * @param count
  181. * number of digits to show in an ObjectId.
  182. */
  183. public void setAbbreviationLength(final int count) {
  184. if (count < 0)
  185. throw new IllegalArgumentException(
  186. JGitText.get().abbreviationLengthMustBeNonNegative);
  187. abbreviationLength = count;
  188. }
  189. /**
  190. * Set the algorithm that constructs difference output.
  191. *
  192. * @param alg
  193. * the algorithm to produce text file differences.
  194. * @see HistogramDiff
  195. */
  196. public void setDiffAlgorithm(DiffAlgorithm alg) {
  197. diffAlgorithm = alg;
  198. }
  199. /**
  200. * Set the line equivalence function for text file differences.
  201. *
  202. * @param cmp
  203. * The equivalence function used to determine if two lines of
  204. * text are identical. The function can be changed to ignore
  205. * various types of whitespace.
  206. * @see RawTextComparator#DEFAULT
  207. * @see RawTextComparator#WS_IGNORE_ALL
  208. * @see RawTextComparator#WS_IGNORE_CHANGE
  209. * @see RawTextComparator#WS_IGNORE_LEADING
  210. * @see RawTextComparator#WS_IGNORE_TRAILING
  211. */
  212. public void setDiffComparator(RawTextComparator cmp) {
  213. comparator = cmp;
  214. }
  215. /**
  216. * Set maximum file size for text files.
  217. *
  218. * Files larger than this size will be treated as though they are binary and
  219. * not text. Default is {@value #DEFAULT_BINARY_FILE_THRESHOLD} .
  220. *
  221. * @param threshold
  222. * the limit, in bytes. Files larger than this size will be
  223. * assumed to be binary, even if they aren't.
  224. */
  225. public void setBinaryFileThreshold(int threshold) {
  226. this.binaryFileThreshold = threshold;
  227. }
  228. /**
  229. * Set the prefix applied in front of old file paths.
  230. *
  231. * @param prefix
  232. * the prefix in front of old paths. Typically this is the
  233. * standard string {@code "a/"}, but may be any prefix desired by
  234. * the caller. Must not be null. Use the empty string to have no
  235. * prefix at all.
  236. */
  237. public void setOldPrefix(String prefix) {
  238. oldPrefix = prefix;
  239. }
  240. /**
  241. * Set the prefix applied in front of new file paths.
  242. *
  243. * @param prefix
  244. * the prefix in front of new paths. Typically this is the
  245. * standard string {@code "b/"}, but may be any prefix desired by
  246. * the caller. Must not be null. Use the empty string to have no
  247. * prefix at all.
  248. */
  249. public void setNewPrefix(String prefix) {
  250. newPrefix = prefix;
  251. }
  252. /** @return true if rename detection is enabled. */
  253. public boolean isDetectRenames() {
  254. return renameDetector != null;
  255. }
  256. /**
  257. * Enable or disable rename detection.
  258. *
  259. * Before enabling rename detection the repository must be set with
  260. * {@link #setRepository(Repository)}. Once enabled the detector can be
  261. * configured away from its defaults by obtaining the instance directly from
  262. * {@link #getRenameDetector()} and invoking configuration.
  263. *
  264. * @param on
  265. * if rename detection should be enabled.
  266. */
  267. public void setDetectRenames(boolean on) {
  268. if (on && renameDetector == null) {
  269. assertHaveRepository();
  270. renameDetector = new RenameDetector(db);
  271. } else if (!on)
  272. renameDetector = null;
  273. }
  274. /** @return the rename detector if rename detection is enabled. */
  275. public RenameDetector getRenameDetector() {
  276. return renameDetector;
  277. }
  278. /**
  279. * Set the progress monitor for long running rename detection.
  280. *
  281. * @param pm
  282. * progress monitor to receive rename detection status through.
  283. */
  284. public void setProgressMonitor(ProgressMonitor pm) {
  285. progressMonitor = pm;
  286. }
  287. /**
  288. * Set the filter to produce only specific paths.
  289. *
  290. * If the filter is an instance of {@link FollowFilter}, the filter path
  291. * will be updated during successive scan or format invocations. The updated
  292. * path can be obtained from {@link #getPathFilter()}.
  293. *
  294. * @param filter
  295. * the tree filter to apply.
  296. */
  297. public void setPathFilter(TreeFilter filter) {
  298. pathFilter = filter != null ? filter : TreeFilter.ALL;
  299. }
  300. /** @return the current path filter. */
  301. public TreeFilter getPathFilter() {
  302. return pathFilter;
  303. }
  304. /**
  305. * Flush the underlying output stream of this formatter.
  306. *
  307. * @throws IOException
  308. * the stream's own flush method threw an exception.
  309. */
  310. public void flush() throws IOException {
  311. out.flush();
  312. }
  313. /** Release the internal ObjectReader state. */
  314. public void release() {
  315. if (reader != null)
  316. reader.release();
  317. }
  318. /**
  319. * Determine the differences between two trees.
  320. *
  321. * No output is created, instead only the file paths that are different are
  322. * returned. Callers may choose to format these paths themselves, or convert
  323. * them into {@link FileHeader} instances with a complete edit list by
  324. * calling {@link #toFileHeader(DiffEntry)}.
  325. *
  326. * @param a
  327. * the old (or previous) side.
  328. * @param b
  329. * the new (or updated) side.
  330. * @return the paths that are different.
  331. * @throws IOException
  332. * trees cannot be read or file contents cannot be read.
  333. */
  334. public List<DiffEntry> scan(AnyObjectId a, AnyObjectId b)
  335. throws IOException {
  336. assertHaveRepository();
  337. RevWalk rw = new RevWalk(reader);
  338. return scan(rw.parseTree(a), rw.parseTree(b));
  339. }
  340. /**
  341. * Determine the differences between two trees.
  342. *
  343. * No output is created, instead only the file paths that are different are
  344. * returned. Callers may choose to format these paths themselves, or convert
  345. * them into {@link FileHeader} instances with a complete edit list by
  346. * calling {@link #toFileHeader(DiffEntry)}.
  347. *
  348. * @param a
  349. * the old (or previous) side.
  350. * @param b
  351. * the new (or updated) side.
  352. * @return the paths that are different.
  353. * @throws IOException
  354. * trees cannot be read or file contents cannot be read.
  355. */
  356. public List<DiffEntry> scan(RevTree a, RevTree b) throws IOException {
  357. assertHaveRepository();
  358. CanonicalTreeParser aParser = new CanonicalTreeParser();
  359. CanonicalTreeParser bParser = new CanonicalTreeParser();
  360. aParser.reset(reader, a);
  361. bParser.reset(reader, b);
  362. return scan(aParser, bParser);
  363. }
  364. /**
  365. * Determine the differences between two trees.
  366. *
  367. * No output is created, instead only the file paths that are different are
  368. * returned. Callers may choose to format these paths themselves, or convert
  369. * them into {@link FileHeader} instances with a complete edit list by
  370. * calling {@link #toFileHeader(DiffEntry)}.
  371. *
  372. * @param a
  373. * the old (or previous) side.
  374. * @param b
  375. * the new (or updated) side.
  376. * @return the paths that are different.
  377. * @throws IOException
  378. * trees cannot be read or file contents cannot be read.
  379. */
  380. public List<DiffEntry> scan(AbstractTreeIterator a, AbstractTreeIterator b)
  381. throws IOException {
  382. assertHaveRepository();
  383. TreeWalk walk = new TreeWalk(reader);
  384. walk.addTree(a);
  385. walk.addTree(b);
  386. walk.setRecursive(true);
  387. TreeFilter filter = getDiffTreeFilterFor(a, b);
  388. if (pathFilter instanceof FollowFilter) {
  389. walk.setFilter(AndTreeFilter.create(
  390. PathFilter.create(((FollowFilter) pathFilter).getPath()),
  391. filter));
  392. } else {
  393. walk.setFilter(AndTreeFilter.create(pathFilter, filter));
  394. }
  395. source = new ContentSource.Pair(source(a), source(b));
  396. List<DiffEntry> files = DiffEntry.scan(walk);
  397. if (pathFilter instanceof FollowFilter && isAdd(files)) {
  398. // The file we are following was added here, find where it
  399. // came from so we can properly show the rename or copy,
  400. // then continue digging backwards.
  401. //
  402. a.reset();
  403. b.reset();
  404. walk.reset();
  405. walk.addTree(a);
  406. walk.addTree(b);
  407. walk.setFilter(filter);
  408. if (renameDetector == null)
  409. setDetectRenames(true);
  410. files = updateFollowFilter(detectRenames(DiffEntry.scan(walk)));
  411. } else if (renameDetector != null)
  412. files = detectRenames(files);
  413. return files;
  414. }
  415. private static TreeFilter getDiffTreeFilterFor(AbstractTreeIterator a,
  416. AbstractTreeIterator b) {
  417. if (a instanceof DirCacheIterator && b instanceof WorkingTreeIterator)
  418. return new IndexDiffFilter(0, 1);
  419. if (a instanceof WorkingTreeIterator && b instanceof DirCacheIterator)
  420. return new IndexDiffFilter(1, 0);
  421. TreeFilter filter = TreeFilter.ANY_DIFF;
  422. if (a instanceof WorkingTreeIterator)
  423. filter = AndTreeFilter.create(new NotIgnoredFilter(0), filter);
  424. if (b instanceof WorkingTreeIterator)
  425. filter = AndTreeFilter.create(new NotIgnoredFilter(1), filter);
  426. return filter;
  427. }
  428. private ContentSource source(AbstractTreeIterator iterator) {
  429. if (iterator instanceof WorkingTreeIterator)
  430. return ContentSource.create((WorkingTreeIterator) iterator);
  431. return ContentSource.create(reader);
  432. }
  433. private List<DiffEntry> detectRenames(List<DiffEntry> files)
  434. throws IOException {
  435. renameDetector.reset();
  436. renameDetector.addAll(files);
  437. return renameDetector.compute(reader, progressMonitor);
  438. }
  439. private boolean isAdd(List<DiffEntry> files) {
  440. String oldPath = ((FollowFilter) pathFilter).getPath();
  441. for (DiffEntry ent : files) {
  442. if (ent.getChangeType() == ADD && ent.getNewPath().equals(oldPath))
  443. return true;
  444. }
  445. return false;
  446. }
  447. private List<DiffEntry> updateFollowFilter(List<DiffEntry> files) {
  448. String oldPath = ((FollowFilter) pathFilter).getPath();
  449. for (DiffEntry ent : files) {
  450. if (isRename(ent) && ent.getNewPath().equals(oldPath)) {
  451. pathFilter = FollowFilter.create(ent.getOldPath());
  452. return Collections.singletonList(ent);
  453. }
  454. }
  455. return Collections.emptyList();
  456. }
  457. private static boolean isRename(DiffEntry ent) {
  458. return ent.getChangeType() == RENAME || ent.getChangeType() == COPY;
  459. }
  460. /**
  461. * Format the differences between two trees.
  462. *
  463. * The patch is expressed as instructions to modify {@code a} to make it
  464. * {@code b}.
  465. *
  466. * @param a
  467. * the old (or previous) side.
  468. * @param b
  469. * the new (or updated) side.
  470. * @throws IOException
  471. * trees cannot be read, file contents cannot be read, or the
  472. * patch cannot be output.
  473. */
  474. public void format(AnyObjectId a, AnyObjectId b) throws IOException {
  475. format(scan(a, b));
  476. }
  477. /**
  478. * Format the differences between two trees.
  479. *
  480. * The patch is expressed as instructions to modify {@code a} to make it
  481. * {@code b}.
  482. *
  483. * @param a
  484. * the old (or previous) side.
  485. * @param b
  486. * the new (or updated) side.
  487. * @throws IOException
  488. * trees cannot be read, file contents cannot be read, or the
  489. * patch cannot be output.
  490. */
  491. public void format(RevTree a, RevTree b) throws IOException {
  492. format(scan(a, b));
  493. }
  494. /**
  495. * Format the differences between two trees.
  496. *
  497. * The patch is expressed as instructions to modify {@code a} to make it
  498. * {@code b}.
  499. *
  500. * @param a
  501. * the old (or previous) side.
  502. * @param b
  503. * the new (or updated) side.
  504. * @throws IOException
  505. * trees cannot be read, file contents cannot be read, or the
  506. * patch cannot be output.
  507. */
  508. public void format(AbstractTreeIterator a, AbstractTreeIterator b)
  509. throws IOException {
  510. format(scan(a, b));
  511. }
  512. /**
  513. * Format a patch script from a list of difference entries. Requires
  514. * {@link #scan(AbstractTreeIterator, AbstractTreeIterator)} to have been
  515. * called first.
  516. *
  517. * @param entries
  518. * entries describing the affected files.
  519. * @throws IOException
  520. * a file's content cannot be read, or the output stream cannot
  521. * be written to.
  522. */
  523. public void format(List<? extends DiffEntry> entries) throws IOException {
  524. for (DiffEntry ent : entries)
  525. format(ent);
  526. }
  527. /**
  528. * Format a patch script for one file entry.
  529. *
  530. * @param ent
  531. * the entry to be formatted.
  532. * @throws IOException
  533. * a file's content cannot be read, or the output stream cannot
  534. * be written to.
  535. */
  536. public void format(DiffEntry ent) throws IOException {
  537. FormatResult res = createFormatResult(ent);
  538. format(res.header, res.a, res.b);
  539. }
  540. private void writeGitLinkDiffText(OutputStream o, DiffEntry ent)
  541. throws IOException {
  542. if (ent.getOldMode() == GITLINK) {
  543. o.write(encodeASCII("-Subproject commit " + ent.getOldId().name()
  544. + "\n"));
  545. }
  546. if (ent.getNewMode() == GITLINK) {
  547. o.write(encodeASCII("+Subproject commit " + ent.getNewId().name()
  548. + "\n"));
  549. }
  550. }
  551. private String format(AbbreviatedObjectId id) {
  552. if (id.isComplete() && db != null) {
  553. try {
  554. id = reader.abbreviate(id.toObjectId(), abbreviationLength);
  555. } catch (IOException cannotAbbreviate) {
  556. // Ignore this. We'll report the full identity.
  557. }
  558. }
  559. return id.name();
  560. }
  561. private static String quotePath(String name) {
  562. return QuotedString.GIT_PATH.quote(name);
  563. }
  564. /**
  565. * Format a patch script, reusing a previously parsed FileHeader.
  566. * <p>
  567. * This formatter is primarily useful for editing an existing patch script
  568. * to increase or reduce the number of lines of context within the script.
  569. * All header lines are reused as-is from the supplied FileHeader.
  570. *
  571. * @param head
  572. * existing file header containing the header lines to copy.
  573. * @param a
  574. * text source for the pre-image version of the content. This
  575. * must match the content of {@link FileHeader#getOldId()}.
  576. * @param b
  577. * text source for the post-image version of the content. This
  578. * must match the content of {@link FileHeader#getNewId()}.
  579. * @throws IOException
  580. * writing to the supplied stream failed.
  581. */
  582. public void format(final FileHeader head, final RawText a, final RawText b)
  583. throws IOException {
  584. // Reuse the existing FileHeader as-is by blindly copying its
  585. // header lines, but avoiding its hunks. Instead we recreate
  586. // the hunks from the text instances we have been supplied.
  587. //
  588. final int start = head.getStartOffset();
  589. int end = head.getEndOffset();
  590. if (!head.getHunks().isEmpty())
  591. end = head.getHunks().get(0).getStartOffset();
  592. out.write(head.getBuffer(), start, end - start);
  593. if (head.getPatchType() == PatchType.UNIFIED)
  594. format(head.toEditList(), a, b);
  595. }
  596. /**
  597. * Formats a list of edits in unified diff format
  598. *
  599. * @param edits
  600. * some differences which have been calculated between A and B
  601. * @param a
  602. * the text A which was compared
  603. * @param b
  604. * the text B which was compared
  605. * @throws IOException
  606. */
  607. public void format(final EditList edits, final RawText a, final RawText b)
  608. throws IOException {
  609. for (int curIdx = 0; curIdx < edits.size();) {
  610. Edit curEdit = edits.get(curIdx);
  611. final int endIdx = findCombinedEnd(edits, curIdx);
  612. final Edit endEdit = edits.get(endIdx);
  613. int aCur = Math.max(0, curEdit.getBeginA() - context);
  614. int bCur = Math.max(0, curEdit.getBeginB() - context);
  615. final int aEnd = Math.min(a.size(), endEdit.getEndA() + context);
  616. final int bEnd = Math.min(b.size(), endEdit.getEndB() + context);
  617. writeHunkHeader(aCur, aEnd, bCur, bEnd);
  618. while (aCur < aEnd || bCur < bEnd) {
  619. if (aCur < curEdit.getBeginA() || endIdx + 1 < curIdx) {
  620. writeContextLine(a, aCur);
  621. if (isEndOfLineMissing(a, aCur))
  622. out.write(noNewLine);
  623. aCur++;
  624. bCur++;
  625. } else if (aCur < curEdit.getEndA()) {
  626. writeRemovedLine(a, aCur);
  627. if (isEndOfLineMissing(a, aCur))
  628. out.write(noNewLine);
  629. aCur++;
  630. } else if (bCur < curEdit.getEndB()) {
  631. writeAddedLine(b, bCur);
  632. if (isEndOfLineMissing(b, bCur))
  633. out.write(noNewLine);
  634. bCur++;
  635. }
  636. if (end(curEdit, aCur, bCur) && ++curIdx < edits.size())
  637. curEdit = edits.get(curIdx);
  638. }
  639. }
  640. }
  641. /**
  642. * Output a line of context (unmodified line).
  643. *
  644. * @param text
  645. * RawText for accessing raw data
  646. * @param line
  647. * the line number within text
  648. * @throws IOException
  649. */
  650. protected void writeContextLine(final RawText text, final int line)
  651. throws IOException {
  652. writeLine(' ', text, line);
  653. }
  654. private boolean isEndOfLineMissing(final RawText text, final int line) {
  655. return line + 1 == text.size() && text.isMissingNewlineAtEnd();
  656. }
  657. /**
  658. * Output an added line.
  659. *
  660. * @param text
  661. * RawText for accessing raw data
  662. * @param line
  663. * the line number within text
  664. * @throws IOException
  665. */
  666. protected void writeAddedLine(final RawText text, final int line)
  667. throws IOException {
  668. writeLine('+', text, line);
  669. }
  670. /**
  671. * Output a removed line
  672. *
  673. * @param text
  674. * RawText for accessing raw data
  675. * @param line
  676. * the line number within text
  677. * @throws IOException
  678. */
  679. protected void writeRemovedLine(final RawText text, final int line)
  680. throws IOException {
  681. writeLine('-', text, line);
  682. }
  683. /**
  684. * Output a hunk header
  685. *
  686. * @param aStartLine
  687. * within first source
  688. * @param aEndLine
  689. * within first source
  690. * @param bStartLine
  691. * within second source
  692. * @param bEndLine
  693. * within second source
  694. * @throws IOException
  695. */
  696. protected void writeHunkHeader(int aStartLine, int aEndLine,
  697. int bStartLine, int bEndLine) throws IOException {
  698. out.write('@');
  699. out.write('@');
  700. writeRange('-', aStartLine + 1, aEndLine - aStartLine);
  701. writeRange('+', bStartLine + 1, bEndLine - bStartLine);
  702. out.write(' ');
  703. out.write('@');
  704. out.write('@');
  705. out.write('\n');
  706. }
  707. private void writeRange(final char prefix, final int begin, final int cnt)
  708. throws IOException {
  709. out.write(' ');
  710. out.write(prefix);
  711. switch (cnt) {
  712. case 0:
  713. // If the range is empty, its beginning number must be the
  714. // line just before the range, or 0 if the range is at the
  715. // start of the file stream. Here, begin is always 1 based,
  716. // so an empty file would produce "0,0".
  717. //
  718. out.write(encodeASCII(begin - 1));
  719. out.write(',');
  720. out.write('0');
  721. break;
  722. case 1:
  723. // If the range is exactly one line, produce only the number.
  724. //
  725. out.write(encodeASCII(begin));
  726. break;
  727. default:
  728. out.write(encodeASCII(begin));
  729. out.write(',');
  730. out.write(encodeASCII(cnt));
  731. break;
  732. }
  733. }
  734. /**
  735. * Write a standard patch script line.
  736. *
  737. * @param prefix
  738. * prefix before the line, typically '-', '+', ' '.
  739. * @param text
  740. * the text object to obtain the line from.
  741. * @param cur
  742. * line number to output.
  743. * @throws IOException
  744. * the stream threw an exception while writing to it.
  745. */
  746. protected void writeLine(final char prefix, final RawText text,
  747. final int cur) throws IOException {
  748. out.write(prefix);
  749. text.writeLine(out, cur);
  750. out.write('\n');
  751. }
  752. /**
  753. * Creates a {@link FileHeader} representing the given {@link DiffEntry}
  754. * <p>
  755. * This method does not use the OutputStream associated with this
  756. * DiffFormatter instance. It is therefore safe to instantiate this
  757. * DiffFormatter instance with a {@link DisabledOutputStream} if this method
  758. * is the only one that will be used.
  759. *
  760. * @param ent
  761. * the DiffEntry to create the FileHeader for
  762. * @return a FileHeader representing the DiffEntry. The FileHeader's buffer
  763. * will contain only the header of the diff output. It will also
  764. * contain one {@link HunkHeader}.
  765. * @throws IOException
  766. * the stream threw an exception while writing to it, or one of
  767. * the blobs referenced by the DiffEntry could not be read.
  768. * @throws CorruptObjectException
  769. * one of the blobs referenced by the DiffEntry is corrupt.
  770. * @throws MissingObjectException
  771. * one of the blobs referenced by the DiffEntry is missing.
  772. */
  773. public FileHeader toFileHeader(DiffEntry ent) throws IOException,
  774. CorruptObjectException, MissingObjectException {
  775. return createFormatResult(ent).header;
  776. }
  777. private static class FormatResult {
  778. FileHeader header;
  779. RawText a;
  780. RawText b;
  781. }
  782. private FormatResult createFormatResult(DiffEntry ent) throws IOException,
  783. CorruptObjectException, MissingObjectException {
  784. final FormatResult res = new FormatResult();
  785. ByteArrayOutputStream buf = new ByteArrayOutputStream();
  786. final EditList editList;
  787. final FileHeader.PatchType type;
  788. formatHeader(buf, ent);
  789. if (ent.getOldMode() == GITLINK || ent.getNewMode() == GITLINK) {
  790. formatOldNewPaths(buf, ent);
  791. writeGitLinkDiffText(buf, ent);
  792. editList = new EditList();
  793. type = PatchType.UNIFIED;
  794. } else {
  795. assertHaveRepository();
  796. byte[] aRaw = open(OLD, ent);
  797. byte[] bRaw = open(NEW, ent);
  798. if (aRaw == BINARY || bRaw == BINARY //
  799. || RawText.isBinary(aRaw) || RawText.isBinary(bRaw)) {
  800. formatOldNewPaths(buf, ent);
  801. buf.write(encodeASCII("Binary files differ\n"));
  802. editList = new EditList();
  803. type = PatchType.BINARY;
  804. } else {
  805. res.a = new RawText(aRaw);
  806. res.b = new RawText(bRaw);
  807. editList = diff(res.a, res.b);
  808. type = PatchType.UNIFIED;
  809. switch (ent.getChangeType()) {
  810. case RENAME:
  811. case COPY:
  812. if (!editList.isEmpty())
  813. formatOldNewPaths(buf, ent);
  814. break;
  815. default:
  816. formatOldNewPaths(buf, ent);
  817. break;
  818. }
  819. }
  820. }
  821. res.header = new FileHeader(buf.toByteArray(), editList, type);
  822. return res;
  823. }
  824. private EditList diff(RawText a, RawText b) {
  825. return diffAlgorithm.diff(comparator, a, b);
  826. }
  827. private void assertHaveRepository() {
  828. if (db == null)
  829. throw new IllegalStateException(JGitText.get().repositoryIsRequired);
  830. }
  831. private byte[] open(DiffEntry.Side side, DiffEntry entry)
  832. throws IOException {
  833. if (entry.getMode(side) == FileMode.MISSING)
  834. return EMPTY;
  835. if (entry.getMode(side).getObjectType() != Constants.OBJ_BLOB)
  836. return EMPTY;
  837. if (isBinary(entry.getPath(side)))
  838. return BINARY;
  839. AbbreviatedObjectId id = entry.getId(side);
  840. if (!id.isComplete()) {
  841. Collection<ObjectId> ids = reader.resolve(id);
  842. if (ids.size() == 1) {
  843. id = AbbreviatedObjectId.fromObjectId(ids.iterator().next());
  844. switch (side) {
  845. case OLD:
  846. entry.oldId = id;
  847. break;
  848. case NEW:
  849. entry.newId = id;
  850. break;
  851. }
  852. } else if (ids.size() == 0)
  853. throw new MissingObjectException(id, Constants.OBJ_BLOB);
  854. else
  855. throw new AmbiguousObjectException(id, ids);
  856. }
  857. try {
  858. ObjectLoader ldr = source.open(side, entry);
  859. return ldr.getBytes(binaryFileThreshold);
  860. } catch (LargeObjectException.ExceedsLimit overLimit) {
  861. return BINARY;
  862. } catch (LargeObjectException.ExceedsByteArrayLimit overLimit) {
  863. return BINARY;
  864. } catch (LargeObjectException.OutOfMemory tooBig) {
  865. return BINARY;
  866. } catch (LargeObjectException tooBig) {
  867. tooBig.setObjectId(id.toObjectId());
  868. throw tooBig;
  869. }
  870. }
  871. private boolean isBinary(String path) {
  872. return false;
  873. }
  874. private void formatHeader(ByteArrayOutputStream o, DiffEntry ent)
  875. throws IOException {
  876. final ChangeType type = ent.getChangeType();
  877. final String oldp = ent.getOldPath();
  878. final String newp = ent.getNewPath();
  879. final FileMode oldMode = ent.getOldMode();
  880. final FileMode newMode = ent.getNewMode();
  881. o.write(encodeASCII("diff --git "));
  882. o.write(encode(quotePath(oldPrefix + (type == ADD ? newp : oldp))));
  883. o.write(' ');
  884. o.write(encode(quotePath(newPrefix + (type == DELETE ? oldp : newp))));
  885. o.write('\n');
  886. switch (type) {
  887. case ADD:
  888. o.write(encodeASCII("new file mode "));
  889. newMode.copyTo(o);
  890. o.write('\n');
  891. break;
  892. case DELETE:
  893. o.write(encodeASCII("deleted file mode "));
  894. oldMode.copyTo(o);
  895. o.write('\n');
  896. break;
  897. case RENAME:
  898. o.write(encodeASCII("similarity index " + ent.getScore() + "%"));
  899. o.write('\n');
  900. o.write(encode("rename from " + quotePath(oldp)));
  901. o.write('\n');
  902. o.write(encode("rename to " + quotePath(newp)));
  903. o.write('\n');
  904. break;
  905. case COPY:
  906. o.write(encodeASCII("similarity index " + ent.getScore() + "%"));
  907. o.write('\n');
  908. o.write(encode("copy from " + quotePath(oldp)));
  909. o.write('\n');
  910. o.write(encode("copy to " + quotePath(newp)));
  911. o.write('\n');
  912. if (!oldMode.equals(newMode)) {
  913. o.write(encodeASCII("new file mode "));
  914. newMode.copyTo(o);
  915. o.write('\n');
  916. }
  917. break;
  918. case MODIFY:
  919. if (0 < ent.getScore()) {
  920. o.write(encodeASCII("dissimilarity index "
  921. + (100 - ent.getScore()) + "%"));
  922. o.write('\n');
  923. }
  924. break;
  925. }
  926. if ((type == MODIFY || type == RENAME) && !oldMode.equals(newMode)) {
  927. o.write(encodeASCII("old mode "));
  928. oldMode.copyTo(o);
  929. o.write('\n');
  930. o.write(encodeASCII("new mode "));
  931. newMode.copyTo(o);
  932. o.write('\n');
  933. }
  934. if (!ent.getOldId().equals(ent.getNewId())) {
  935. formatIndexLine(o, ent);
  936. }
  937. }
  938. /**
  939. * @param o
  940. * the stream the formatter will write line data to
  941. * @param ent
  942. * the DiffEntry to create the FileHeader for
  943. * @throws IOException
  944. * writing to the supplied stream failed.
  945. */
  946. protected void formatIndexLine(OutputStream o, DiffEntry ent)
  947. throws IOException {
  948. o.write(encodeASCII("index " //
  949. + format(ent.getOldId()) //
  950. + ".." //
  951. + format(ent.getNewId())));
  952. if (ent.getOldMode().equals(ent.getNewMode())) {
  953. o.write(' ');
  954. ent.getNewMode().copyTo(o);
  955. }
  956. o.write('\n');
  957. }
  958. private void formatOldNewPaths(ByteArrayOutputStream o, DiffEntry ent)
  959. throws IOException {
  960. if (ent.oldId.equals(ent.newId))
  961. return;
  962. final String oldp;
  963. final String newp;
  964. switch (ent.getChangeType()) {
  965. case ADD:
  966. oldp = DiffEntry.DEV_NULL;
  967. newp = quotePath(newPrefix + ent.getNewPath());
  968. break;
  969. case DELETE:
  970. oldp = quotePath(oldPrefix + ent.getOldPath());
  971. newp = DiffEntry.DEV_NULL;
  972. break;
  973. default:
  974. oldp = quotePath(oldPrefix + ent.getOldPath());
  975. newp = quotePath(newPrefix + ent.getNewPath());
  976. break;
  977. }
  978. o.write(encode("--- " + oldp + "\n"));
  979. o.write(encode("+++ " + newp + "\n"));
  980. }
  981. private int findCombinedEnd(final List<Edit> edits, final int i) {
  982. int end = i + 1;
  983. while (end < edits.size()
  984. && (combineA(edits, end) || combineB(edits, end)))
  985. end++;
  986. return end - 1;
  987. }
  988. private boolean combineA(final List<Edit> e, final int i) {
  989. return e.get(i).getBeginA() - e.get(i - 1).getEndA() <= 2 * context;
  990. }
  991. private boolean combineB(final List<Edit> e, final int i) {
  992. return e.get(i).getBeginB() - e.get(i - 1).getEndB() <= 2 * context;
  993. }
  994. private static boolean end(final Edit edit, final int a, final int b) {
  995. return edit.getEndA() <= a && edit.getEndB() <= b;
  996. }
  997. }