Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

DiffFormatter.java 35KB

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