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.

DiffUtils.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /*
  2. * Copyright 2011 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.utils;
  17. import java.io.ByteArrayOutputStream;
  18. import java.io.Serializable;
  19. import java.text.MessageFormat;
  20. import java.util.ArrayList;
  21. import java.util.List;
  22. import org.eclipse.jgit.api.BlameCommand;
  23. import org.eclipse.jgit.blame.BlameResult;
  24. import org.eclipse.jgit.diff.DiffEntry;
  25. import org.eclipse.jgit.diff.DiffFormatter;
  26. import org.eclipse.jgit.diff.RawText;
  27. import org.eclipse.jgit.diff.RawTextComparator;
  28. import org.eclipse.jgit.lib.ObjectId;
  29. import org.eclipse.jgit.lib.Repository;
  30. import org.eclipse.jgit.revwalk.RevCommit;
  31. import org.eclipse.jgit.revwalk.RevTree;
  32. import org.eclipse.jgit.revwalk.RevWalk;
  33. import org.slf4j.Logger;
  34. import org.slf4j.LoggerFactory;
  35. import com.gitblit.models.AnnotatedLine;
  36. import com.gitblit.models.PathModel.PathChangeModel;
  37. /**
  38. * DiffUtils is a class of utility methods related to diff, patch, and blame.
  39. *
  40. * The diff methods support pluggable diff output types like Gitblit, Gitweb,
  41. * and Plain.
  42. *
  43. * @author James Moger
  44. *
  45. */
  46. public class DiffUtils {
  47. private static final Logger LOGGER = LoggerFactory.getLogger(DiffUtils.class);
  48. /**
  49. * Enumeration for the diff output types.
  50. */
  51. public static enum DiffOutputType {
  52. PLAIN, HTML;
  53. public static DiffOutputType forName(String name) {
  54. for (DiffOutputType type : values()) {
  55. if (type.name().equalsIgnoreCase(name)) {
  56. return type;
  57. }
  58. }
  59. return null;
  60. }
  61. }
  62. /**
  63. * Encapsulates the output of a diff.
  64. */
  65. public static class DiffOutput implements Serializable {
  66. private static final long serialVersionUID = 1L;
  67. public final DiffOutputType type;
  68. public final String content;
  69. public final DiffStat stat;
  70. DiffOutput(DiffOutputType type, String content, DiffStat stat) {
  71. this.type = type;
  72. this.content = content;
  73. this.stat = stat;
  74. }
  75. public PathChangeModel getPath(String path) {
  76. if (stat == null) {
  77. return null;
  78. }
  79. return stat.getPath(path);
  80. }
  81. }
  82. /**
  83. * Class that represents the number of insertions and deletions from a
  84. * chunk.
  85. */
  86. public static class DiffStat implements Serializable {
  87. private static final long serialVersionUID = 1L;
  88. public final List<PathChangeModel> paths = new ArrayList<PathChangeModel>();
  89. private final String commitId;
  90. public DiffStat(String commitId) {
  91. this.commitId = commitId;
  92. }
  93. public PathChangeModel addPath(DiffEntry entry) {
  94. PathChangeModel pcm = PathChangeModel.from(entry, commitId);
  95. paths.add(pcm);
  96. return pcm;
  97. }
  98. public int getInsertions() {
  99. int val = 0;
  100. for (PathChangeModel entry : paths) {
  101. val += entry.insertions;
  102. }
  103. return val;
  104. }
  105. public int getDeletions() {
  106. int val = 0;
  107. for (PathChangeModel entry : paths) {
  108. val += entry.deletions;
  109. }
  110. return val;
  111. }
  112. public PathChangeModel getPath(String path) {
  113. PathChangeModel stat = null;
  114. for (PathChangeModel p : paths) {
  115. if (p.path.equals(path)) {
  116. stat = p;
  117. break;
  118. }
  119. }
  120. return stat;
  121. }
  122. @Override
  123. public String toString() {
  124. StringBuilder sb = new StringBuilder();
  125. for (PathChangeModel entry : paths) {
  126. sb.append(entry.toString()).append('\n');
  127. }
  128. sb.setLength(sb.length() - 1);
  129. return sb.toString();
  130. }
  131. }
  132. public static class NormalizedDiffStat implements Serializable {
  133. private static final long serialVersionUID = 1L;
  134. public final int insertions;
  135. public final int deletions;
  136. public final int blanks;
  137. NormalizedDiffStat(int insertions, int deletions, int blanks) {
  138. this.insertions = insertions;
  139. this.deletions = deletions;
  140. this.blanks = blanks;
  141. }
  142. }
  143. /**
  144. * Returns the complete diff of the specified commit compared to its primary
  145. * parent.
  146. *
  147. * @param repository
  148. * @param commit
  149. * @param outputType
  150. * @return the diff
  151. */
  152. public static DiffOutput getCommitDiff(Repository repository, RevCommit commit,
  153. DiffOutputType outputType) {
  154. return getDiff(repository, null, commit, null, outputType);
  155. }
  156. /**
  157. * Returns the diff for the specified file or folder from the specified
  158. * commit compared to its primary parent.
  159. *
  160. * @param repository
  161. * @param commit
  162. * @param path
  163. * @param outputType
  164. * @return the diff
  165. */
  166. public static DiffOutput getDiff(Repository repository, RevCommit commit, String path,
  167. DiffOutputType outputType) {
  168. return getDiff(repository, null, commit, path, outputType);
  169. }
  170. /**
  171. * Returns the complete diff between the two specified commits.
  172. *
  173. * @param repository
  174. * @param baseCommit
  175. * @param commit
  176. * @param outputType
  177. * @return the diff
  178. */
  179. public static DiffOutput getDiff(Repository repository, RevCommit baseCommit, RevCommit commit,
  180. DiffOutputType outputType) {
  181. return getDiff(repository, baseCommit, commit, null, outputType);
  182. }
  183. /**
  184. * Returns the diff between two commits for the specified file.
  185. *
  186. * @param repository
  187. * @param baseCommit
  188. * if base commit is null the diff is to the primary parent of
  189. * the commit.
  190. * @param commit
  191. * @param path
  192. * if the path is specified, the diff is restricted to that file
  193. * or folder. if unspecified, the diff is for the entire commit.
  194. * @param outputType
  195. * @return the diff
  196. */
  197. public static DiffOutput getDiff(Repository repository, RevCommit baseCommit, RevCommit commit,
  198. String path, DiffOutputType outputType) {
  199. DiffStat stat = null;
  200. String diff = null;
  201. try {
  202. final ByteArrayOutputStream os = new ByteArrayOutputStream();
  203. RawTextComparator cmp = RawTextComparator.DEFAULT;
  204. DiffFormatter df;
  205. switch (outputType) {
  206. case HTML:
  207. df = new GitBlitDiffFormatter(os, commit.getName());
  208. break;
  209. case PLAIN:
  210. default:
  211. df = new DiffFormatter(os);
  212. break;
  213. }
  214. df.setRepository(repository);
  215. df.setDiffComparator(cmp);
  216. df.setDetectRenames(true);
  217. RevTree commitTree = commit.getTree();
  218. RevTree baseTree;
  219. if (baseCommit == null) {
  220. if (commit.getParentCount() > 0) {
  221. final RevWalk rw = new RevWalk(repository);
  222. RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
  223. rw.dispose();
  224. baseTree = parent.getTree();
  225. } else {
  226. // FIXME initial commit. no parent?!
  227. baseTree = commitTree;
  228. }
  229. } else {
  230. baseTree = baseCommit.getTree();
  231. }
  232. List<DiffEntry> diffEntries = df.scan(baseTree, commitTree);
  233. if (path != null && path.length() > 0) {
  234. for (DiffEntry diffEntry : diffEntries) {
  235. if (diffEntry.getNewPath().equalsIgnoreCase(path)) {
  236. df.format(diffEntry);
  237. break;
  238. }
  239. }
  240. } else {
  241. df.format(diffEntries);
  242. }
  243. if (df instanceof GitBlitDiffFormatter) {
  244. // workaround for complex private methods in DiffFormatter
  245. diff = ((GitBlitDiffFormatter) df).getHtml();
  246. stat = ((GitBlitDiffFormatter) df).getDiffStat();
  247. } else {
  248. diff = os.toString();
  249. }
  250. df.flush();
  251. } catch (Throwable t) {
  252. LOGGER.error("failed to generate commit diff!", t);
  253. }
  254. return new DiffOutput(outputType, diff, stat);
  255. }
  256. /**
  257. * Returns the diff between the two commits for the specified file or folder
  258. * formatted as a patch.
  259. *
  260. * @param repository
  261. * @param baseCommit
  262. * if base commit is unspecified, the patch is generated against
  263. * the primary parent of the specified commit.
  264. * @param commit
  265. * @param path
  266. * if path is specified, the patch is generated only for the
  267. * specified file or folder. if unspecified, the patch is
  268. * generated for the entire diff between the two commits.
  269. * @return patch as a string
  270. */
  271. public static String getCommitPatch(Repository repository, RevCommit baseCommit,
  272. RevCommit commit, String path) {
  273. String diff = null;
  274. try {
  275. final ByteArrayOutputStream os = new ByteArrayOutputStream();
  276. RawTextComparator cmp = RawTextComparator.DEFAULT;
  277. PatchFormatter df = new PatchFormatter(os);
  278. df.setRepository(repository);
  279. df.setDiffComparator(cmp);
  280. df.setDetectRenames(true);
  281. RevTree commitTree = commit.getTree();
  282. RevTree baseTree;
  283. if (baseCommit == null) {
  284. if (commit.getParentCount() > 0) {
  285. final RevWalk rw = new RevWalk(repository);
  286. RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
  287. baseTree = parent.getTree();
  288. } else {
  289. // FIXME initial commit. no parent?!
  290. baseTree = commitTree;
  291. }
  292. } else {
  293. baseTree = baseCommit.getTree();
  294. }
  295. List<DiffEntry> diffEntries = df.scan(baseTree, commitTree);
  296. if (path != null && path.length() > 0) {
  297. for (DiffEntry diffEntry : diffEntries) {
  298. if (diffEntry.getNewPath().equalsIgnoreCase(path)) {
  299. df.format(diffEntry);
  300. break;
  301. }
  302. }
  303. } else {
  304. df.format(diffEntries);
  305. }
  306. diff = df.getPatch(commit);
  307. df.flush();
  308. } catch (Throwable t) {
  309. LOGGER.error("failed to generate commit diff!", t);
  310. }
  311. return diff;
  312. }
  313. public static DiffStat getDiffStat(Repository repository, RevCommit commit) {
  314. return getDiffStat(repository, null, commit, null);
  315. }
  316. /**
  317. * Returns the diffstat between the two commits for the specified file or folder.
  318. *
  319. * @param repository
  320. * @param baseCommit
  321. * if base commit is unspecified, the diffstat is generated against
  322. * the primary parent of the specified commit.
  323. * @param commit
  324. * @param path
  325. * if path is specified, the diffstat is generated only for the
  326. * specified file or folder. if unspecified, the diffstat is
  327. * generated for the entire diff between the two commits.
  328. * @return patch as a string
  329. */
  330. public static DiffStat getDiffStat(Repository repository, RevCommit baseCommit,
  331. RevCommit commit, String path) {
  332. DiffStat stat = null;
  333. try {
  334. RawTextComparator cmp = RawTextComparator.DEFAULT;
  335. DiffStatFormatter df = new DiffStatFormatter(commit.getName());
  336. df.setRepository(repository);
  337. df.setDiffComparator(cmp);
  338. df.setDetectRenames(true);
  339. RevTree commitTree = commit.getTree();
  340. RevTree baseTree;
  341. if (baseCommit == null) {
  342. if (commit.getParentCount() > 0) {
  343. final RevWalk rw = new RevWalk(repository);
  344. RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
  345. baseTree = parent.getTree();
  346. } else {
  347. // FIXME initial commit. no parent?!
  348. baseTree = commitTree;
  349. }
  350. } else {
  351. baseTree = baseCommit.getTree();
  352. }
  353. List<DiffEntry> diffEntries = df.scan(baseTree, commitTree);
  354. if (path != null && path.length() > 0) {
  355. for (DiffEntry diffEntry : diffEntries) {
  356. if (diffEntry.getNewPath().equalsIgnoreCase(path)) {
  357. df.format(diffEntry);
  358. break;
  359. }
  360. }
  361. } else {
  362. df.format(diffEntries);
  363. }
  364. stat = df.getDiffStat();
  365. df.flush();
  366. } catch (Throwable t) {
  367. LOGGER.error("failed to generate commit diff!", t);
  368. }
  369. return stat;
  370. }
  371. /**
  372. * Returns the list of lines in the specified source file annotated with the
  373. * source commit metadata.
  374. *
  375. * @param repository
  376. * @param blobPath
  377. * @param objectId
  378. * @return list of annotated lines
  379. */
  380. public static List<AnnotatedLine> blame(Repository repository, String blobPath, String objectId) {
  381. List<AnnotatedLine> lines = new ArrayList<AnnotatedLine>();
  382. try {
  383. ObjectId object;
  384. if (StringUtils.isEmpty(objectId)) {
  385. object = JGitUtils.getDefaultBranch(repository);
  386. } else {
  387. object = repository.resolve(objectId);
  388. }
  389. BlameCommand blameCommand = new BlameCommand(repository);
  390. blameCommand.setFilePath(blobPath);
  391. blameCommand.setStartCommit(object);
  392. BlameResult blameResult = blameCommand.call();
  393. RawText rawText = blameResult.getResultContents();
  394. int length = rawText.size();
  395. for (int i = 0; i < length; i++) {
  396. RevCommit commit = blameResult.getSourceCommit(i);
  397. AnnotatedLine line = new AnnotatedLine(commit, i + 1, rawText.getString(i));
  398. lines.add(line);
  399. }
  400. } catch (Throwable t) {
  401. LOGGER.error(MessageFormat.format("failed to generate blame for {0} {1}!", blobPath, objectId), t);
  402. }
  403. return lines;
  404. }
  405. /**
  406. * Normalizes a diffstat to an N-segment display.
  407. *
  408. * @params segments
  409. * @param insertions
  410. * @param deletions
  411. * @return a normalized diffstat
  412. */
  413. public static NormalizedDiffStat normalizeDiffStat(final int segments, final int insertions, final int deletions) {
  414. final int total = insertions + deletions;
  415. final float fi = ((float) insertions) / total;
  416. int si;
  417. int sd;
  418. int sb;
  419. if (deletions == 0) {
  420. // only addition
  421. si = Math.min(insertions, segments);
  422. sd = 0;
  423. sb = si < segments ? (segments - si) : 0;
  424. } else if (insertions == 0) {
  425. // only deletion
  426. si = 0;
  427. sd = Math.min(deletions, segments);
  428. sb = sd < segments ? (segments - sd) : 0;
  429. } else if (total <= segments) {
  430. // total churn fits in segment display
  431. si = insertions;
  432. sd = deletions;
  433. sb = segments - total;
  434. } else if ((segments % 2) > 0 && fi > 0.45f && fi < 0.55f) {
  435. // odd segment display, fairly even +/-, use even number of segments
  436. si = Math.round(((float) insertions)/total * (segments - 1));
  437. sd = segments - 1 - si;
  438. sb = 1;
  439. } else {
  440. si = Math.round(((float) insertions)/total * segments);
  441. sd = segments - si;
  442. sb = 0;
  443. }
  444. return new NormalizedDiffStat(si, sd, sb);
  445. }
  446. }