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

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