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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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.
  514. *
  515. * @param entries
  516. * entries describing the affected files.
  517. * @throws IOException
  518. * a file's content cannot be read, or the output stream cannot
  519. * be written to.
  520. */
  521. public void format(List<? extends DiffEntry> entries) throws IOException {
  522. for (DiffEntry ent : entries)
  523. format(ent);
  524. }
  525. /**
  526. * Format a patch script for one file entry.
  527. *
  528. * @param ent
  529. * the entry to be formatted.
  530. * @throws IOException
  531. * a file's content cannot be read, or the output stream cannot
  532. * be written to.
  533. */
  534. public void format(DiffEntry ent) throws IOException {
  535. FormatResult res = createFormatResult(ent);
  536. format(res.header, res.a, res.b);
  537. }
  538. private void writeGitLinkDiffText(OutputStream o, DiffEntry ent)
  539. throws IOException {
  540. if (ent.getOldMode() == GITLINK) {
  541. o.write(encodeASCII("-Subproject commit " + ent.getOldId().name()
  542. + "\n"));
  543. }
  544. if (ent.getNewMode() == GITLINK) {
  545. o.write(encodeASCII("+Subproject commit " + ent.getNewId().name()
  546. + "\n"));
  547. }
  548. }
  549. private String format(AbbreviatedObjectId id) {
  550. if (id.isComplete() && db != null) {
  551. try {
  552. id = reader.abbreviate(id.toObjectId(), abbreviationLength);
  553. } catch (IOException cannotAbbreviate) {
  554. // Ignore this. We'll report the full identity.
  555. }
  556. }
  557. return id.name();
  558. }
  559. private static String quotePath(String name) {
  560. return QuotedString.GIT_PATH.quote(name);
  561. }
  562. /**
  563. * Format a patch script, reusing a previously parsed FileHeader.
  564. * <p>
  565. * This formatter is primarily useful for editing an existing patch script
  566. * to increase or reduce the number of lines of context within the script.
  567. * All header lines are reused as-is from the supplied FileHeader.
  568. *
  569. * @param head
  570. * existing file header containing the header lines to copy.
  571. * @param a
  572. * text source for the pre-image version of the content. This
  573. * must match the content of {@link FileHeader#getOldId()}.
  574. * @param b
  575. * text source for the post-image version of the content. This
  576. * must match the content of {@link FileHeader#getNewId()}.
  577. * @throws IOException
  578. * writing to the supplied stream failed.
  579. */
  580. public void format(final FileHeader head, final RawText a, final RawText b)
  581. throws IOException {
  582. // Reuse the existing FileHeader as-is by blindly copying its
  583. // header lines, but avoiding its hunks. Instead we recreate
  584. // the hunks from the text instances we have been supplied.
  585. //
  586. final int start = head.getStartOffset();
  587. int end = head.getEndOffset();
  588. if (!head.getHunks().isEmpty())
  589. end = head.getHunks().get(0).getStartOffset();
  590. out.write(head.getBuffer(), start, end - start);
  591. if (head.getPatchType() == PatchType.UNIFIED)
  592. format(head.toEditList(), a, b);
  593. }
  594. /**
  595. * Formats a list of edits in unified diff format
  596. *
  597. * @param edits
  598. * some differences which have been calculated between A and B
  599. * @param a
  600. * the text A which was compared
  601. * @param b
  602. * the text B which was compared
  603. * @throws IOException
  604. */
  605. public void format(final EditList edits, final RawText a, final RawText b)
  606. throws IOException {
  607. for (int curIdx = 0; curIdx < edits.size();) {
  608. Edit curEdit = edits.get(curIdx);
  609. final int endIdx = findCombinedEnd(edits, curIdx);
  610. final Edit endEdit = edits.get(endIdx);
  611. int aCur = Math.max(0, curEdit.getBeginA() - context);
  612. int bCur = Math.max(0, curEdit.getBeginB() - context);
  613. final int aEnd = Math.min(a.size(), endEdit.getEndA() + context);
  614. final int bEnd = Math.min(b.size(), endEdit.getEndB() + context);
  615. writeHunkHeader(aCur, aEnd, bCur, bEnd);
  616. while (aCur < aEnd || bCur < bEnd) {
  617. if (aCur < curEdit.getBeginA() || endIdx + 1 < curIdx) {
  618. writeContextLine(a, aCur);
  619. if (isEndOfLineMissing(a, aCur))
  620. out.write(noNewLine);
  621. aCur++;
  622. bCur++;
  623. } else if (aCur < curEdit.getEndA()) {
  624. writeRemovedLine(a, aCur);
  625. if (isEndOfLineMissing(a, aCur))
  626. out.write(noNewLine);
  627. aCur++;
  628. } else if (bCur < curEdit.getEndB()) {
  629. writeAddedLine(b, bCur);
  630. if (isEndOfLineMissing(b, bCur))
  631. out.write(noNewLine);
  632. bCur++;
  633. }
  634. if (end(curEdit, aCur, bCur) && ++curIdx < edits.size())
  635. curEdit = edits.get(curIdx);
  636. }
  637. }
  638. }
  639. /**
  640. * Output a line of context (unmodified line).
  641. *
  642. * @param text
  643. * RawText for accessing raw data
  644. * @param line
  645. * the line number within text
  646. * @throws IOException
  647. */
  648. protected void writeContextLine(final RawText text, final int line)
  649. throws IOException {
  650. writeLine(' ', text, line);
  651. }
  652. private boolean isEndOfLineMissing(final RawText text, final int line) {
  653. return line + 1 == text.size() && text.isMissingNewlineAtEnd();
  654. }
  655. /**
  656. * Output an added line.
  657. *
  658. * @param text
  659. * RawText for accessing raw data
  660. * @param line
  661. * the line number within text
  662. * @throws IOException
  663. */
  664. protected void writeAddedLine(final RawText text, final int line)
  665. throws IOException {
  666. writeLine('+', text, line);
  667. }
  668. /**
  669. * Output a removed line
  670. *
  671. * @param text
  672. * RawText for accessing raw data
  673. * @param line
  674. * the line number within text
  675. * @throws IOException
  676. */
  677. protected void writeRemovedLine(final RawText text, final int line)
  678. throws IOException {
  679. writeLine('-', text, line);
  680. }
  681. /**
  682. * Output a hunk header
  683. *
  684. * @param aStartLine
  685. * within first source
  686. * @param aEndLine
  687. * within first source
  688. * @param bStartLine
  689. * within second source
  690. * @param bEndLine
  691. * within second source
  692. * @throws IOException
  693. */
  694. protected void writeHunkHeader(int aStartLine, int aEndLine,
  695. int bStartLine, int bEndLine) throws IOException {
  696. out.write('@');
  697. out.write('@');
  698. writeRange('-', aStartLine + 1, aEndLine - aStartLine);
  699. writeRange('+', bStartLine + 1, bEndLine - bStartLine);
  700. out.write(' ');
  701. out.write('@');
  702. out.write('@');
  703. out.write('\n');
  704. }
  705. private void writeRange(final char prefix, final int begin, final int cnt)
  706. throws IOException {
  707. out.write(' ');
  708. out.write(prefix);
  709. switch (cnt) {
  710. case 0:
  711. // If the range is empty, its beginning number must be the
  712. // line just before the range, or 0 if the range is at the
  713. // start of the file stream. Here, begin is always 1 based,
  714. // so an empty file would produce "0,0".
  715. //
  716. out.write(encodeASCII(begin - 1));
  717. out.write(',');
  718. out.write('0');
  719. break;
  720. case 1:
  721. // If the range is exactly one line, produce only the number.
  722. //
  723. out.write(encodeASCII(begin));
  724. break;
  725. default:
  726. out.write(encodeASCII(begin));
  727. out.write(',');
  728. out.write(encodeASCII(cnt));
  729. break;
  730. }
  731. }
  732. /**
  733. * Write a standard patch script line.
  734. *
  735. * @param prefix
  736. * prefix before the line, typically '-', '+', ' '.
  737. * @param text
  738. * the text object to obtain the line from.
  739. * @param cur
  740. * line number to output.
  741. * @throws IOException
  742. * the stream threw an exception while writing to it.
  743. */
  744. protected void writeLine(final char prefix, final RawText text,
  745. final int cur) throws IOException {
  746. out.write(prefix);
  747. text.writeLine(out, cur);
  748. out.write('\n');
  749. }
  750. /**
  751. * Creates a {@link FileHeader} representing the given {@link DiffEntry}
  752. * <p>
  753. * This method does not use the OutputStream associated with this
  754. * DiffFormatter instance. It is therefore safe to instantiate this
  755. * DiffFormatter instance with a {@link DisabledOutputStream} if this method
  756. * is the only one that will be used.
  757. *
  758. * @param ent
  759. * the DiffEntry to create the FileHeader for
  760. * @return a FileHeader representing the DiffEntry. The FileHeader's buffer
  761. * will contain only the header of the diff output. It will also
  762. * contain one {@link HunkHeader}.
  763. * @throws IOException
  764. * the stream threw an exception while writing to it, or one of
  765. * the blobs referenced by the DiffEntry could not be read.
  766. * @throws CorruptObjectException
  767. * one of the blobs referenced by the DiffEntry is corrupt.
  768. * @throws MissingObjectException
  769. * one of the blobs referenced by the DiffEntry is missing.
  770. */
  771. public FileHeader toFileHeader(DiffEntry ent) throws IOException,
  772. CorruptObjectException, MissingObjectException {
  773. return createFormatResult(ent).header;
  774. }
  775. private static class FormatResult {
  776. FileHeader header;
  777. RawText a;
  778. RawText b;
  779. }
  780. private FormatResult createFormatResult(DiffEntry ent) throws IOException,
  781. CorruptObjectException, MissingObjectException {
  782. final FormatResult res = new FormatResult();
  783. ByteArrayOutputStream buf = new ByteArrayOutputStream();
  784. final EditList editList;
  785. final FileHeader.PatchType type;
  786. formatHeader(buf, ent);
  787. if (ent.getOldMode() == GITLINK || ent.getNewMode() == GITLINK) {
  788. formatOldNewPaths(buf, ent);
  789. writeGitLinkDiffText(buf, ent);
  790. editList = new EditList();
  791. type = PatchType.UNIFIED;
  792. } else {
  793. assertHaveRepository();
  794. byte[] aRaw = open(OLD, ent);
  795. byte[] bRaw = open(NEW, ent);
  796. if (aRaw == BINARY || bRaw == BINARY //
  797. || RawText.isBinary(aRaw) || RawText.isBinary(bRaw)) {
  798. formatOldNewPaths(buf, ent);
  799. buf.write(encodeASCII("Binary files differ\n"));
  800. editList = new EditList();
  801. type = PatchType.BINARY;
  802. } else {
  803. res.a = new RawText(aRaw);
  804. res.b = new RawText(bRaw);
  805. editList = diff(res.a, res.b);
  806. type = PatchType.UNIFIED;
  807. switch (ent.getChangeType()) {
  808. case RENAME:
  809. case COPY:
  810. if (!editList.isEmpty())
  811. formatOldNewPaths(buf, ent);
  812. break;
  813. default:
  814. formatOldNewPaths(buf, ent);
  815. break;
  816. }
  817. }
  818. }
  819. res.header = new FileHeader(buf.toByteArray(), editList, type);
  820. return res;
  821. }
  822. private EditList diff(RawText a, RawText b) {
  823. return diffAlgorithm.diff(comparator, a, b);
  824. }
  825. private void assertHaveRepository() {
  826. if (db == null)
  827. throw new IllegalStateException(JGitText.get().repositoryIsRequired);
  828. }
  829. private byte[] open(DiffEntry.Side side, DiffEntry entry)
  830. throws IOException {
  831. if (entry.getMode(side) == FileMode.MISSING)
  832. return EMPTY;
  833. if (entry.getMode(side).getObjectType() != Constants.OBJ_BLOB)
  834. return EMPTY;
  835. if (isBinary(entry.getPath(side)))
  836. return BINARY;
  837. AbbreviatedObjectId id = entry.getId(side);
  838. if (!id.isComplete()) {
  839. Collection<ObjectId> ids = reader.resolve(id);
  840. if (ids.size() == 1) {
  841. id = AbbreviatedObjectId.fromObjectId(ids.iterator().next());
  842. switch (side) {
  843. case OLD:
  844. entry.oldId = id;
  845. break;
  846. case NEW:
  847. entry.newId = id;
  848. break;
  849. }
  850. } else if (ids.size() == 0)
  851. throw new MissingObjectException(id, Constants.OBJ_BLOB);
  852. else
  853. throw new AmbiguousObjectException(id, ids);
  854. }
  855. try {
  856. ObjectLoader ldr = source.open(side, entry);
  857. return ldr.getBytes(binaryFileThreshold);
  858. } catch (LargeObjectException.ExceedsLimit overLimit) {
  859. return BINARY;
  860. } catch (LargeObjectException.ExceedsByteArrayLimit overLimit) {
  861. return BINARY;
  862. } catch (LargeObjectException.OutOfMemory tooBig) {
  863. return BINARY;
  864. } catch (LargeObjectException tooBig) {
  865. tooBig.setObjectId(id.toObjectId());
  866. throw tooBig;
  867. }
  868. }
  869. private boolean isBinary(String path) {
  870. return false;
  871. }
  872. private void formatHeader(ByteArrayOutputStream o, DiffEntry ent)
  873. throws IOException {
  874. final ChangeType type = ent.getChangeType();
  875. final String oldp = ent.getOldPath();
  876. final String newp = ent.getNewPath();
  877. final FileMode oldMode = ent.getOldMode();
  878. final FileMode newMode = ent.getNewMode();
  879. o.write(encodeASCII("diff --git "));
  880. o.write(encode(quotePath(oldPrefix + (type == ADD ? newp : oldp))));
  881. o.write(' ');
  882. o.write(encode(quotePath(newPrefix + (type == DELETE ? oldp : newp))));
  883. o.write('\n');
  884. switch (type) {
  885. case ADD:
  886. o.write(encodeASCII("new file mode "));
  887. newMode.copyTo(o);
  888. o.write('\n');
  889. break;
  890. case DELETE:
  891. o.write(encodeASCII("deleted file mode "));
  892. oldMode.copyTo(o);
  893. o.write('\n');
  894. break;
  895. case RENAME:
  896. o.write(encodeASCII("similarity index " + ent.getScore() + "%"));
  897. o.write('\n');
  898. o.write(encode("rename from " + quotePath(oldp)));
  899. o.write('\n');
  900. o.write(encode("rename to " + quotePath(newp)));
  901. o.write('\n');
  902. break;
  903. case COPY:
  904. o.write(encodeASCII("similarity index " + ent.getScore() + "%"));
  905. o.write('\n');
  906. o.write(encode("copy from " + quotePath(oldp)));
  907. o.write('\n');
  908. o.write(encode("copy to " + quotePath(newp)));
  909. o.write('\n');
  910. if (!oldMode.equals(newMode)) {
  911. o.write(encodeASCII("new file mode "));
  912. newMode.copyTo(o);
  913. o.write('\n');
  914. }
  915. break;
  916. case MODIFY:
  917. if (0 < ent.getScore()) {
  918. o.write(encodeASCII("dissimilarity index "
  919. + (100 - ent.getScore()) + "%"));
  920. o.write('\n');
  921. }
  922. break;
  923. }
  924. if ((type == MODIFY || type == RENAME) && !oldMode.equals(newMode)) {
  925. o.write(encodeASCII("old mode "));
  926. oldMode.copyTo(o);
  927. o.write('\n');
  928. o.write(encodeASCII("new mode "));
  929. newMode.copyTo(o);
  930. o.write('\n');
  931. }
  932. if (!ent.getOldId().equals(ent.getNewId())) {
  933. o.write(encodeASCII("index " //
  934. + format(ent.getOldId()) //
  935. + ".." //
  936. + format(ent.getNewId())));
  937. if (oldMode.equals(newMode)) {
  938. o.write(' ');
  939. newMode.copyTo(o);
  940. }
  941. o.write('\n');
  942. }
  943. }
  944. private void formatOldNewPaths(ByteArrayOutputStream o, DiffEntry ent)
  945. throws IOException {
  946. final String oldp;
  947. final String newp;
  948. switch (ent.getChangeType()) {
  949. case ADD:
  950. oldp = DiffEntry.DEV_NULL;
  951. newp = quotePath(newPrefix + ent.getNewPath());
  952. break;
  953. case DELETE:
  954. oldp = quotePath(oldPrefix + ent.getOldPath());
  955. newp = DiffEntry.DEV_NULL;
  956. break;
  957. default:
  958. oldp = quotePath(oldPrefix + ent.getOldPath());
  959. newp = quotePath(newPrefix + ent.getNewPath());
  960. break;
  961. }
  962. o.write(encode("--- " + oldp + "\n"));
  963. o.write(encode("+++ " + newp + "\n"));
  964. }
  965. private int findCombinedEnd(final List<Edit> edits, final int i) {
  966. int end = i + 1;
  967. while (end < edits.size()
  968. && (combineA(edits, end) || combineB(edits, end)))
  969. end++;
  970. return end - 1;
  971. }
  972. private boolean combineA(final List<Edit> e, final int i) {
  973. return e.get(i).getBeginA() - e.get(i - 1).getEndA() <= 2 * context;
  974. }
  975. private boolean combineB(final List<Edit> e, final int i) {
  976. return e.get(i).getBeginB() - e.get(i - 1).getEndB() <= 2 * context;
  977. }
  978. private static boolean end(final Edit edit, final int a, final int b) {
  979. return edit.getEndA() <= a && edit.getEndB() <= b;
  980. }
  981. }