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

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