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.

DiffFormatter.java 34KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  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.diff.DiffAlgorithm.SupportedAlgorithm;
  62. import org.eclipse.jgit.diff.DiffEntry.ChangeType;
  63. import org.eclipse.jgit.dircache.DirCacheIterator;
  64. import org.eclipse.jgit.errors.AmbiguousObjectException;
  65. import org.eclipse.jgit.errors.CorruptObjectException;
  66. import org.eclipse.jgit.errors.LargeObjectException;
  67. import org.eclipse.jgit.errors.MissingObjectException;
  68. import org.eclipse.jgit.internal.JGitText;
  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. * Get the prefix applied in front of old file paths.
  242. *
  243. * @return the prefix
  244. */
  245. public String getOldPrefix() {
  246. return this.oldPrefix;
  247. }
  248. /**
  249. * Set the prefix applied in front of new file paths.
  250. *
  251. * @param prefix
  252. * the prefix in front of new paths. Typically this is the
  253. * standard string {@code "b/"}, but may be any prefix desired by
  254. * the caller. Must not be null. Use the empty string to have no
  255. * prefix at all.
  256. */
  257. public void setNewPrefix(String prefix) {
  258. newPrefix = prefix;
  259. }
  260. /**
  261. * Get the prefix applied in front of new file paths.
  262. *
  263. * @return the prefix
  264. */
  265. public String getNewPrefix() {
  266. return this.newPrefix;
  267. }
  268. /** @return true if rename detection is enabled. */
  269. public boolean isDetectRenames() {
  270. return renameDetector != null;
  271. }
  272. /**
  273. * Enable or disable rename detection.
  274. *
  275. * Before enabling rename detection the repository must be set with
  276. * {@link #setRepository(Repository)}. Once enabled the detector can be
  277. * configured away from its defaults by obtaining the instance directly from
  278. * {@link #getRenameDetector()} and invoking configuration.
  279. *
  280. * @param on
  281. * if rename detection should be enabled.
  282. */
  283. public void setDetectRenames(boolean on) {
  284. if (on && renameDetector == null) {
  285. assertHaveRepository();
  286. renameDetector = new RenameDetector(db);
  287. } else if (!on)
  288. renameDetector = null;
  289. }
  290. /** @return the rename detector if rename detection is enabled. */
  291. public RenameDetector getRenameDetector() {
  292. return renameDetector;
  293. }
  294. /**
  295. * Set the progress monitor for long running rename detection.
  296. *
  297. * @param pm
  298. * progress monitor to receive rename detection status through.
  299. */
  300. public void setProgressMonitor(ProgressMonitor pm) {
  301. progressMonitor = pm;
  302. }
  303. /**
  304. * Set the filter to produce only specific paths.
  305. *
  306. * If the filter is an instance of {@link FollowFilter}, the filter path
  307. * will be updated during successive scan or format invocations. The updated
  308. * path can be obtained from {@link #getPathFilter()}.
  309. *
  310. * @param filter
  311. * the tree filter to apply.
  312. */
  313. public void setPathFilter(TreeFilter filter) {
  314. pathFilter = filter != null ? filter : TreeFilter.ALL;
  315. }
  316. /** @return the current path filter. */
  317. public TreeFilter getPathFilter() {
  318. return pathFilter;
  319. }
  320. /**
  321. * Flush the underlying output stream of this formatter.
  322. *
  323. * @throws IOException
  324. * the stream's own flush method threw an exception.
  325. */
  326. public void flush() throws IOException {
  327. out.flush();
  328. }
  329. /** Release the internal ObjectReader state. */
  330. public void release() {
  331. if (reader != null)
  332. reader.release();
  333. }
  334. /**
  335. * Determine the differences between two trees.
  336. *
  337. * No output is created, instead only the file paths that are different are
  338. * returned. Callers may choose to format these paths themselves, or convert
  339. * them into {@link FileHeader} instances with a complete edit list by
  340. * calling {@link #toFileHeader(DiffEntry)}.
  341. *
  342. * @param a
  343. * the old (or previous) side.
  344. * @param b
  345. * the new (or updated) side.
  346. * @return the paths that are different.
  347. * @throws IOException
  348. * trees cannot be read or file contents cannot be read.
  349. */
  350. public List<DiffEntry> scan(AnyObjectId a, AnyObjectId b)
  351. throws IOException {
  352. assertHaveRepository();
  353. RevWalk rw = new RevWalk(reader);
  354. return scan(rw.parseTree(a), rw.parseTree(b));
  355. }
  356. /**
  357. * Determine the differences between two trees.
  358. *
  359. * No output is created, instead only the file paths that are different are
  360. * returned. Callers may choose to format these paths themselves, or convert
  361. * them into {@link FileHeader} instances with a complete edit list by
  362. * calling {@link #toFileHeader(DiffEntry)}.
  363. *
  364. * @param a
  365. * the old (or previous) side.
  366. * @param b
  367. * the new (or updated) side.
  368. * @return the paths that are different.
  369. * @throws IOException
  370. * trees cannot be read or file contents cannot be read.
  371. */
  372. public List<DiffEntry> scan(RevTree a, RevTree b) throws IOException {
  373. assertHaveRepository();
  374. CanonicalTreeParser aParser = new CanonicalTreeParser();
  375. CanonicalTreeParser bParser = new CanonicalTreeParser();
  376. aParser.reset(reader, a);
  377. bParser.reset(reader, b);
  378. return scan(aParser, bParser);
  379. }
  380. /**
  381. * Determine the differences between two trees.
  382. *
  383. * No output is created, instead only the file paths that are different are
  384. * returned. Callers may choose to format these paths themselves, or convert
  385. * them into {@link FileHeader} instances with a complete edit list by
  386. * calling {@link #toFileHeader(DiffEntry)}.
  387. *
  388. * @param a
  389. * the old (or previous) side.
  390. * @param b
  391. * the new (or updated) side.
  392. * @return the paths that are different.
  393. * @throws IOException
  394. * trees cannot be read or file contents cannot be read.
  395. */
  396. public List<DiffEntry> scan(AbstractTreeIterator a, AbstractTreeIterator b)
  397. throws IOException {
  398. assertHaveRepository();
  399. TreeWalk walk = new TreeWalk(reader);
  400. walk.addTree(a);
  401. walk.addTree(b);
  402. walk.setRecursive(true);
  403. TreeFilter filter = getDiffTreeFilterFor(a, b);
  404. if (pathFilter instanceof FollowFilter) {
  405. walk.setFilter(AndTreeFilter.create(
  406. PathFilter.create(((FollowFilter) pathFilter).getPath()),
  407. filter));
  408. } else {
  409. walk.setFilter(AndTreeFilter.create(pathFilter, filter));
  410. }
  411. source = new ContentSource.Pair(source(a), source(b));
  412. List<DiffEntry> files = DiffEntry.scan(walk);
  413. if (pathFilter instanceof FollowFilter && isAdd(files)) {
  414. // The file we are following was added here, find where it
  415. // came from so we can properly show the rename or copy,
  416. // then continue digging backwards.
  417. //
  418. a.reset();
  419. b.reset();
  420. walk.reset();
  421. walk.addTree(a);
  422. walk.addTree(b);
  423. walk.setFilter(filter);
  424. if (renameDetector == null)
  425. setDetectRenames(true);
  426. files = updateFollowFilter(detectRenames(DiffEntry.scan(walk)));
  427. } else if (renameDetector != null)
  428. files = detectRenames(files);
  429. return files;
  430. }
  431. private static TreeFilter getDiffTreeFilterFor(AbstractTreeIterator a,
  432. AbstractTreeIterator b) {
  433. if (a instanceof DirCacheIterator && b instanceof WorkingTreeIterator)
  434. return new IndexDiffFilter(0, 1);
  435. if (a instanceof WorkingTreeIterator && b instanceof DirCacheIterator)
  436. return new IndexDiffFilter(1, 0);
  437. TreeFilter filter = TreeFilter.ANY_DIFF;
  438. if (a instanceof WorkingTreeIterator)
  439. filter = AndTreeFilter.create(new NotIgnoredFilter(0), filter);
  440. if (b instanceof WorkingTreeIterator)
  441. filter = AndTreeFilter.create(new NotIgnoredFilter(1), filter);
  442. return filter;
  443. }
  444. private ContentSource source(AbstractTreeIterator iterator) {
  445. if (iterator instanceof WorkingTreeIterator)
  446. return ContentSource.create((WorkingTreeIterator) iterator);
  447. return ContentSource.create(reader);
  448. }
  449. private List<DiffEntry> detectRenames(List<DiffEntry> files)
  450. throws IOException {
  451. renameDetector.reset();
  452. renameDetector.addAll(files);
  453. return renameDetector.compute(reader, progressMonitor);
  454. }
  455. private boolean isAdd(List<DiffEntry> files) {
  456. String oldPath = ((FollowFilter) pathFilter).getPath();
  457. for (DiffEntry ent : files) {
  458. if (ent.getChangeType() == ADD && ent.getNewPath().equals(oldPath))
  459. return true;
  460. }
  461. return false;
  462. }
  463. private List<DiffEntry> updateFollowFilter(List<DiffEntry> files) {
  464. String oldPath = ((FollowFilter) pathFilter).getPath();
  465. for (DiffEntry ent : files) {
  466. if (isRename(ent) && ent.getNewPath().equals(oldPath)) {
  467. pathFilter = FollowFilter.create(ent.getOldPath());
  468. return Collections.singletonList(ent);
  469. }
  470. }
  471. return Collections.emptyList();
  472. }
  473. private static boolean isRename(DiffEntry ent) {
  474. return ent.getChangeType() == RENAME || ent.getChangeType() == COPY;
  475. }
  476. /**
  477. * Format the differences between two trees.
  478. *
  479. * The patch is expressed as instructions to modify {@code a} to make it
  480. * {@code b}.
  481. *
  482. * @param a
  483. * the old (or previous) side.
  484. * @param b
  485. * the new (or updated) side.
  486. * @throws IOException
  487. * trees cannot be read, file contents cannot be read, or the
  488. * patch cannot be output.
  489. */
  490. public void format(AnyObjectId a, AnyObjectId b) throws IOException {
  491. format(scan(a, b));
  492. }
  493. /**
  494. * Format the differences between two trees.
  495. *
  496. * The patch is expressed as instructions to modify {@code a} to make it
  497. * {@code b}.
  498. *
  499. * @param a
  500. * the old (or previous) side.
  501. * @param b
  502. * the new (or updated) side.
  503. * @throws IOException
  504. * trees cannot be read, file contents cannot be read, or the
  505. * patch cannot be output.
  506. */
  507. public void format(RevTree a, RevTree b) throws IOException {
  508. format(scan(a, b));
  509. }
  510. /**
  511. * Format the differences between two trees.
  512. *
  513. * The patch is expressed as instructions to modify {@code a} to make it
  514. * {@code b}.
  515. *
  516. * @param a
  517. * the old (or previous) side.
  518. * @param b
  519. * the new (or updated) side.
  520. * @throws IOException
  521. * trees cannot be read, file contents cannot be read, or the
  522. * patch cannot be output.
  523. */
  524. public void format(AbstractTreeIterator a, AbstractTreeIterator b)
  525. throws IOException {
  526. format(scan(a, b));
  527. }
  528. /**
  529. * Format a patch script from a list of difference entries. Requires
  530. * {@link #scan(AbstractTreeIterator, AbstractTreeIterator)} to have been
  531. * called first.
  532. *
  533. * @param entries
  534. * entries describing the affected files.
  535. * @throws IOException
  536. * a file's content cannot be read, or the output stream cannot
  537. * be written to.
  538. */
  539. public void format(List<? extends DiffEntry> entries) throws IOException {
  540. for (DiffEntry ent : entries)
  541. format(ent);
  542. }
  543. /**
  544. * Format a patch script for one file entry.
  545. *
  546. * @param ent
  547. * the entry to be formatted.
  548. * @throws IOException
  549. * a file's content cannot be read, or the output stream cannot
  550. * be written to.
  551. */
  552. public void format(DiffEntry ent) throws IOException {
  553. FormatResult res = createFormatResult(ent);
  554. format(res.header, res.a, res.b);
  555. }
  556. private void writeGitLinkDiffText(OutputStream o, DiffEntry ent)
  557. throws IOException {
  558. if (ent.getOldMode() == GITLINK) {
  559. o.write(encodeASCII("-Subproject commit " + ent.getOldId().name()
  560. + "\n"));
  561. }
  562. if (ent.getNewMode() == GITLINK) {
  563. o.write(encodeASCII("+Subproject commit " + ent.getNewId().name()
  564. + "\n"));
  565. }
  566. }
  567. private String format(AbbreviatedObjectId id) {
  568. if (id.isComplete() && db != null) {
  569. try {
  570. id = reader.abbreviate(id.toObjectId(), abbreviationLength);
  571. } catch (IOException cannotAbbreviate) {
  572. // Ignore this. We'll report the full identity.
  573. }
  574. }
  575. return id.name();
  576. }
  577. private static String quotePath(String name) {
  578. return QuotedString.GIT_PATH.quote(name);
  579. }
  580. /**
  581. * Format a patch script, reusing a previously parsed FileHeader.
  582. * <p>
  583. * This formatter is primarily useful for editing an existing patch script
  584. * to increase or reduce the number of lines of context within the script.
  585. * All header lines are reused as-is from the supplied FileHeader.
  586. *
  587. * @param head
  588. * existing file header containing the header lines to copy.
  589. * @param a
  590. * text source for the pre-image version of the content. This
  591. * must match the content of {@link FileHeader#getOldId()}.
  592. * @param b
  593. * text source for the post-image version of the content. This
  594. * must match the content of {@link FileHeader#getNewId()}.
  595. * @throws IOException
  596. * writing to the supplied stream failed.
  597. */
  598. public void format(final FileHeader head, final RawText a, final RawText b)
  599. throws IOException {
  600. // Reuse the existing FileHeader as-is by blindly copying its
  601. // header lines, but avoiding its hunks. Instead we recreate
  602. // the hunks from the text instances we have been supplied.
  603. //
  604. final int start = head.getStartOffset();
  605. int end = head.getEndOffset();
  606. if (!head.getHunks().isEmpty())
  607. end = head.getHunks().get(0).getStartOffset();
  608. out.write(head.getBuffer(), start, end - start);
  609. if (head.getPatchType() == PatchType.UNIFIED)
  610. format(head.toEditList(), a, b);
  611. }
  612. /**
  613. * Formats a list of edits in unified diff format
  614. *
  615. * @param edits
  616. * some differences which have been calculated between A and B
  617. * @param a
  618. * the text A which was compared
  619. * @param b
  620. * the text B which was compared
  621. * @throws IOException
  622. */
  623. public void format(final EditList edits, final RawText a, final RawText b)
  624. throws IOException {
  625. for (int curIdx = 0; curIdx < edits.size();) {
  626. Edit curEdit = edits.get(curIdx);
  627. final int endIdx = findCombinedEnd(edits, curIdx);
  628. final Edit endEdit = edits.get(endIdx);
  629. int aCur = Math.max(0, curEdit.getBeginA() - context);
  630. int bCur = Math.max(0, curEdit.getBeginB() - context);
  631. final int aEnd = Math.min(a.size(), endEdit.getEndA() + context);
  632. final int bEnd = Math.min(b.size(), endEdit.getEndB() + context);
  633. writeHunkHeader(aCur, aEnd, bCur, bEnd);
  634. while (aCur < aEnd || bCur < bEnd) {
  635. if (aCur < curEdit.getBeginA() || endIdx + 1 < curIdx) {
  636. writeContextLine(a, aCur);
  637. if (isEndOfLineMissing(a, aCur))
  638. out.write(noNewLine);
  639. aCur++;
  640. bCur++;
  641. } else if (aCur < curEdit.getEndA()) {
  642. writeRemovedLine(a, aCur);
  643. if (isEndOfLineMissing(a, aCur))
  644. out.write(noNewLine);
  645. aCur++;
  646. } else if (bCur < curEdit.getEndB()) {
  647. writeAddedLine(b, bCur);
  648. if (isEndOfLineMissing(b, bCur))
  649. out.write(noNewLine);
  650. bCur++;
  651. }
  652. if (end(curEdit, aCur, bCur) && ++curIdx < edits.size())
  653. curEdit = edits.get(curIdx);
  654. }
  655. }
  656. }
  657. /**
  658. * Output a line of context (unmodified 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 writeContextLine(final RawText text, final int line)
  667. throws IOException {
  668. writeLine(' ', text, line);
  669. }
  670. private boolean isEndOfLineMissing(final RawText text, final int line) {
  671. return line + 1 == text.size() && text.isMissingNewlineAtEnd();
  672. }
  673. /**
  674. * Output an added line.
  675. *
  676. * @param text
  677. * RawText for accessing raw data
  678. * @param line
  679. * the line number within text
  680. * @throws IOException
  681. */
  682. protected void writeAddedLine(final RawText text, final int line)
  683. throws IOException {
  684. writeLine('+', text, line);
  685. }
  686. /**
  687. * Output a removed line
  688. *
  689. * @param text
  690. * RawText for accessing raw data
  691. * @param line
  692. * the line number within text
  693. * @throws IOException
  694. */
  695. protected void writeRemovedLine(final RawText text, final int line)
  696. throws IOException {
  697. writeLine('-', text, line);
  698. }
  699. /**
  700. * Output a hunk header
  701. *
  702. * @param aStartLine
  703. * within first source
  704. * @param aEndLine
  705. * within first source
  706. * @param bStartLine
  707. * within second source
  708. * @param bEndLine
  709. * within second source
  710. * @throws IOException
  711. */
  712. protected void writeHunkHeader(int aStartLine, int aEndLine,
  713. int bStartLine, int bEndLine) throws IOException {
  714. out.write('@');
  715. out.write('@');
  716. writeRange('-', aStartLine + 1, aEndLine - aStartLine);
  717. writeRange('+', bStartLine + 1, bEndLine - bStartLine);
  718. out.write(' ');
  719. out.write('@');
  720. out.write('@');
  721. out.write('\n');
  722. }
  723. private void writeRange(final char prefix, final int begin, final int cnt)
  724. throws IOException {
  725. out.write(' ');
  726. out.write(prefix);
  727. switch (cnt) {
  728. case 0:
  729. // If the range is empty, its beginning number must be the
  730. // line just before the range, or 0 if the range is at the
  731. // start of the file stream. Here, begin is always 1 based,
  732. // so an empty file would produce "0,0".
  733. //
  734. out.write(encodeASCII(begin - 1));
  735. out.write(',');
  736. out.write('0');
  737. break;
  738. case 1:
  739. // If the range is exactly one line, produce only the number.
  740. //
  741. out.write(encodeASCII(begin));
  742. break;
  743. default:
  744. out.write(encodeASCII(begin));
  745. out.write(',');
  746. out.write(encodeASCII(cnt));
  747. break;
  748. }
  749. }
  750. /**
  751. * Write a standard patch script line.
  752. *
  753. * @param prefix
  754. * prefix before the line, typically '-', '+', ' '.
  755. * @param text
  756. * the text object to obtain the line from.
  757. * @param cur
  758. * line number to output.
  759. * @throws IOException
  760. * the stream threw an exception while writing to it.
  761. */
  762. protected void writeLine(final char prefix, final RawText text,
  763. final int cur) throws IOException {
  764. out.write(prefix);
  765. text.writeLine(out, cur);
  766. out.write('\n');
  767. }
  768. /**
  769. * Creates a {@link FileHeader} representing the given {@link DiffEntry}
  770. * <p>
  771. * This method does not use the OutputStream associated with this
  772. * DiffFormatter instance. It is therefore safe to instantiate this
  773. * DiffFormatter instance with a {@link DisabledOutputStream} if this method
  774. * is the only one that will be used.
  775. *
  776. * @param ent
  777. * the DiffEntry to create the FileHeader for
  778. * @return a FileHeader representing the DiffEntry. The FileHeader's buffer
  779. * will contain only the header of the diff output. It will also
  780. * contain one {@link HunkHeader}.
  781. * @throws IOException
  782. * the stream threw an exception while writing to it, or one of
  783. * the blobs referenced by the DiffEntry could not be read.
  784. * @throws CorruptObjectException
  785. * one of the blobs referenced by the DiffEntry is corrupt.
  786. * @throws MissingObjectException
  787. * one of the blobs referenced by the DiffEntry is missing.
  788. */
  789. public FileHeader toFileHeader(DiffEntry ent) throws IOException,
  790. CorruptObjectException, MissingObjectException {
  791. return createFormatResult(ent).header;
  792. }
  793. private static class FormatResult {
  794. FileHeader header;
  795. RawText a;
  796. RawText b;
  797. }
  798. private FormatResult createFormatResult(DiffEntry ent) throws IOException,
  799. CorruptObjectException, MissingObjectException {
  800. final FormatResult res = new FormatResult();
  801. ByteArrayOutputStream buf = new ByteArrayOutputStream();
  802. final EditList editList;
  803. final FileHeader.PatchType type;
  804. formatHeader(buf, ent);
  805. if (ent.getOldMode() == GITLINK || ent.getNewMode() == GITLINK) {
  806. formatOldNewPaths(buf, ent);
  807. writeGitLinkDiffText(buf, ent);
  808. editList = new EditList();
  809. type = PatchType.UNIFIED;
  810. } else {
  811. assertHaveRepository();
  812. byte[] aRaw = open(OLD, ent);
  813. byte[] bRaw = open(NEW, ent);
  814. if (aRaw == BINARY || bRaw == BINARY //
  815. || RawText.isBinary(aRaw) || RawText.isBinary(bRaw)) {
  816. formatOldNewPaths(buf, ent);
  817. buf.write(encodeASCII("Binary files differ\n"));
  818. editList = new EditList();
  819. type = PatchType.BINARY;
  820. } else {
  821. res.a = new RawText(aRaw);
  822. res.b = new RawText(bRaw);
  823. editList = diff(res.a, res.b);
  824. type = PatchType.UNIFIED;
  825. switch (ent.getChangeType()) {
  826. case RENAME:
  827. case COPY:
  828. if (!editList.isEmpty())
  829. formatOldNewPaths(buf, ent);
  830. break;
  831. default:
  832. formatOldNewPaths(buf, ent);
  833. break;
  834. }
  835. }
  836. }
  837. res.header = new FileHeader(buf.toByteArray(), editList, type);
  838. return res;
  839. }
  840. private EditList diff(RawText a, RawText b) {
  841. return diffAlgorithm.diff(comparator, a, b);
  842. }
  843. private void assertHaveRepository() {
  844. if (db == null)
  845. throw new IllegalStateException(JGitText.get().repositoryIsRequired);
  846. }
  847. private byte[] open(DiffEntry.Side side, DiffEntry entry)
  848. throws IOException {
  849. if (entry.getMode(side) == FileMode.MISSING)
  850. return EMPTY;
  851. if (entry.getMode(side).getObjectType() != Constants.OBJ_BLOB)
  852. return EMPTY;
  853. if (isBinary(entry.getPath(side)))
  854. return BINARY;
  855. AbbreviatedObjectId id = entry.getId(side);
  856. if (!id.isComplete()) {
  857. Collection<ObjectId> ids = reader.resolve(id);
  858. if (ids.size() == 1) {
  859. id = AbbreviatedObjectId.fromObjectId(ids.iterator().next());
  860. switch (side) {
  861. case OLD:
  862. entry.oldId = id;
  863. break;
  864. case NEW:
  865. entry.newId = id;
  866. break;
  867. }
  868. } else if (ids.size() == 0)
  869. throw new MissingObjectException(id, Constants.OBJ_BLOB);
  870. else
  871. throw new AmbiguousObjectException(id, ids);
  872. }
  873. try {
  874. ObjectLoader ldr = source.open(side, entry);
  875. return ldr.getBytes(binaryFileThreshold);
  876. } catch (LargeObjectException.ExceedsLimit overLimit) {
  877. return BINARY;
  878. } catch (LargeObjectException.ExceedsByteArrayLimit overLimit) {
  879. return BINARY;
  880. } catch (LargeObjectException.OutOfMemory tooBig) {
  881. return BINARY;
  882. } catch (LargeObjectException tooBig) {
  883. tooBig.setObjectId(id.toObjectId());
  884. throw tooBig;
  885. }
  886. }
  887. private boolean isBinary(String path) {
  888. return false;
  889. }
  890. private void formatHeader(ByteArrayOutputStream o, DiffEntry ent)
  891. throws IOException {
  892. final ChangeType type = ent.getChangeType();
  893. final String oldp = ent.getOldPath();
  894. final String newp = ent.getNewPath();
  895. final FileMode oldMode = ent.getOldMode();
  896. final FileMode newMode = ent.getNewMode();
  897. o.write(encodeASCII("diff --git "));
  898. o.write(encode(quotePath(oldPrefix + (type == ADD ? newp : oldp))));
  899. o.write(' ');
  900. o.write(encode(quotePath(newPrefix + (type == DELETE ? oldp : newp))));
  901. o.write('\n');
  902. switch (type) {
  903. case ADD:
  904. o.write(encodeASCII("new file mode "));
  905. newMode.copyTo(o);
  906. o.write('\n');
  907. break;
  908. case DELETE:
  909. o.write(encodeASCII("deleted file mode "));
  910. oldMode.copyTo(o);
  911. o.write('\n');
  912. break;
  913. case RENAME:
  914. o.write(encodeASCII("similarity index " + ent.getScore() + "%"));
  915. o.write('\n');
  916. o.write(encode("rename from " + quotePath(oldp)));
  917. o.write('\n');
  918. o.write(encode("rename to " + quotePath(newp)));
  919. o.write('\n');
  920. break;
  921. case COPY:
  922. o.write(encodeASCII("similarity index " + ent.getScore() + "%"));
  923. o.write('\n');
  924. o.write(encode("copy from " + quotePath(oldp)));
  925. o.write('\n');
  926. o.write(encode("copy to " + quotePath(newp)));
  927. o.write('\n');
  928. if (!oldMode.equals(newMode)) {
  929. o.write(encodeASCII("new file mode "));
  930. newMode.copyTo(o);
  931. o.write('\n');
  932. }
  933. break;
  934. case MODIFY:
  935. if (0 < ent.getScore()) {
  936. o.write(encodeASCII("dissimilarity index "
  937. + (100 - ent.getScore()) + "%"));
  938. o.write('\n');
  939. }
  940. break;
  941. }
  942. if ((type == MODIFY || type == RENAME) && !oldMode.equals(newMode)) {
  943. o.write(encodeASCII("old mode "));
  944. oldMode.copyTo(o);
  945. o.write('\n');
  946. o.write(encodeASCII("new mode "));
  947. newMode.copyTo(o);
  948. o.write('\n');
  949. }
  950. if (!ent.getOldId().equals(ent.getNewId())) {
  951. formatIndexLine(o, ent);
  952. }
  953. }
  954. /**
  955. * @param o
  956. * the stream the formatter will write line data to
  957. * @param ent
  958. * the DiffEntry to create the FileHeader for
  959. * @throws IOException
  960. * writing to the supplied stream failed.
  961. */
  962. protected void formatIndexLine(OutputStream o, DiffEntry ent)
  963. throws IOException {
  964. o.write(encodeASCII("index " //
  965. + format(ent.getOldId()) //
  966. + ".." //
  967. + format(ent.getNewId())));
  968. if (ent.getOldMode().equals(ent.getNewMode())) {
  969. o.write(' ');
  970. ent.getNewMode().copyTo(o);
  971. }
  972. o.write('\n');
  973. }
  974. private void formatOldNewPaths(ByteArrayOutputStream o, DiffEntry ent)
  975. throws IOException {
  976. if (ent.oldId.equals(ent.newId))
  977. return;
  978. final String oldp;
  979. final String newp;
  980. switch (ent.getChangeType()) {
  981. case ADD:
  982. oldp = DiffEntry.DEV_NULL;
  983. newp = quotePath(newPrefix + ent.getNewPath());
  984. break;
  985. case DELETE:
  986. oldp = quotePath(oldPrefix + ent.getOldPath());
  987. newp = DiffEntry.DEV_NULL;
  988. break;
  989. default:
  990. oldp = quotePath(oldPrefix + ent.getOldPath());
  991. newp = quotePath(newPrefix + ent.getNewPath());
  992. break;
  993. }
  994. o.write(encode("--- " + oldp + "\n"));
  995. o.write(encode("+++ " + newp + "\n"));
  996. }
  997. private int findCombinedEnd(final List<Edit> edits, final int i) {
  998. int end = i + 1;
  999. while (end < edits.size()
  1000. && (combineA(edits, end) || combineB(edits, end)))
  1001. end++;
  1002. return end - 1;
  1003. }
  1004. private boolean combineA(final List<Edit> e, final int i) {
  1005. return e.get(i).getBeginA() - e.get(i - 1).getEndA() <= 2 * context;
  1006. }
  1007. private boolean combineB(final List<Edit> e, final int i) {
  1008. return e.get(i).getBeginB() - e.get(i - 1).getEndB() <= 2 * context;
  1009. }
  1010. private static boolean end(final Edit edit, final int a, final int b) {
  1011. return edit.getEndA() <= a && edit.getEndB() <= b;
  1012. }
  1013. }