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.

Blame.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. /*
  2. * Copyright (C) 2011, Google Inc.
  3. * Copyright (C) 2009, Christian Halstrick <christian.halstrick@sap.com>
  4. * Copyright (C) 2009, Johannes E. Schindelin
  5. * Copyright (C) 2009, Johannes Schindelin <johannes.schindelin@gmx.de>
  6. * and other copyright owners as documented in the project's IP log.
  7. *
  8. * This program and the accompanying materials are made available
  9. * under the terms of the Eclipse Distribution License v1.0 which
  10. * accompanies this distribution, is reproduced below, and is
  11. * available at http://www.eclipse.org/org/documents/edl-v10.php
  12. *
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or
  16. * without modification, are permitted provided that the following
  17. * conditions are met:
  18. *
  19. * - Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. *
  22. * - Redistributions in binary form must reproduce the above
  23. * copyright notice, this list of conditions and the following
  24. * disclaimer in the documentation and/or other materials provided
  25. * with the distribution.
  26. *
  27. * - Neither the name of the Eclipse Foundation, Inc. nor the
  28. * names of its contributors may be used to endorse or promote
  29. * products derived from this software without specific prior
  30. * written permission.
  31. *
  32. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  33. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  34. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  37. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  38. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  39. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  40. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  41. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  42. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  43. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  44. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. */
  46. package org.eclipse.jgit.pgm;
  47. import static java.lang.Integer.valueOf;
  48. import static java.lang.Long.valueOf;
  49. import static org.eclipse.jgit.lib.Constants.OBJECT_ID_STRING_LENGTH;
  50. import java.io.File;
  51. import java.io.IOException;
  52. import java.text.MessageFormat;
  53. import java.text.SimpleDateFormat;
  54. import java.util.ArrayList;
  55. import java.util.HashMap;
  56. import java.util.List;
  57. import java.util.Map;
  58. import java.util.regex.Pattern;
  59. import org.eclipse.jgit.blame.BlameGenerator;
  60. import org.eclipse.jgit.blame.BlameResult;
  61. import org.eclipse.jgit.diff.RawText;
  62. import org.eclipse.jgit.diff.RawTextComparator;
  63. import org.eclipse.jgit.dircache.DirCache;
  64. import org.eclipse.jgit.lib.Constants;
  65. import org.eclipse.jgit.lib.ObjectReader;
  66. import org.eclipse.jgit.lib.PersonIdent;
  67. import org.eclipse.jgit.pgm.internal.CLIText;
  68. import org.eclipse.jgit.revwalk.RevCommit;
  69. import org.eclipse.jgit.revwalk.RevFlag;
  70. import org.kohsuke.args4j.Argument;
  71. import org.kohsuke.args4j.Option;
  72. @Command(common = false, usage = "usage_Blame")
  73. class Blame extends TextBuiltin {
  74. private RawTextComparator comparator = RawTextComparator.DEFAULT;
  75. @Option(name = "-w", usage = "usage_ignoreWhitespace")
  76. void ignoreAllSpace(@SuppressWarnings("unused") boolean on) {
  77. comparator = RawTextComparator.WS_IGNORE_ALL;
  78. }
  79. @Option(name = "--abbrev", metaVar = "metaVar_n", usage = "usage_abbrevCommits")
  80. private int abbrev;
  81. @Option(name = "-l", usage = "usage_blameLongRevision")
  82. private boolean showLongRevision;
  83. @Option(name = "-t", usage = "usage_blameRawTimestamp")
  84. private boolean showRawTimestamp;
  85. @Option(name = "-b", usage = "usage_blameShowBlankBoundary")
  86. private boolean showBlankBoundary;
  87. @Option(name = "-s", usage = "usage_blameSuppressAuthor")
  88. private boolean noAuthor;
  89. @Option(name = "--show-email", aliases = { "-e" }, usage = "usage_blameShowEmail")
  90. private boolean showAuthorEmail;
  91. @Option(name = "--show-name", aliases = { "-f" }, usage = "usage_blameShowSourcePath")
  92. private boolean showSourcePath;
  93. @Option(name = "--show-number", aliases = { "-n" }, usage = "usage_blameShowSourceLine")
  94. private boolean showSourceLine;
  95. @Option(name = "--root", usage = "usage_blameShowRoot")
  96. private boolean root;
  97. @Option(name = "-L", metaVar = "metaVar_blameL", usage = "usage_blameRange")
  98. private String rangeString;
  99. @Option(name = "--reverse", metaVar = "metaVar_blameReverse", usage = "usage_blameReverse")
  100. private List<RevCommit> reverseRange = new ArrayList<>(2);
  101. @Argument(index = 0, required = false, metaVar = "metaVar_revision")
  102. private String revision;
  103. @Argument(index = 1, required = false, metaVar = "metaVar_file")
  104. private String file;
  105. private ObjectReader reader;
  106. private final Map<RevCommit, String> abbreviatedCommits = new HashMap<>();
  107. private SimpleDateFormat dateFmt;
  108. private int begin;
  109. private int end;
  110. private BlameResult blame;
  111. @Override
  112. protected void run() throws Exception {
  113. if (file == null) {
  114. if (revision == null)
  115. throw die(CLIText.get().fileIsRequired);
  116. file = revision;
  117. revision = null;
  118. }
  119. boolean autoAbbrev = abbrev == 0;
  120. if (abbrev == 0)
  121. abbrev = db.getConfig().getInt("core", "abbrev", 7); //$NON-NLS-1$ //$NON-NLS-2$
  122. if (!showBlankBoundary)
  123. root = db.getConfig().getBoolean("blame", "blankboundary", false); //$NON-NLS-1$ //$NON-NLS-2$
  124. if (!root)
  125. root = db.getConfig().getBoolean("blame", "showroot", false); //$NON-NLS-1$ //$NON-NLS-2$
  126. if (showRawTimestamp)
  127. dateFmt = new SimpleDateFormat("ZZZZ"); //$NON-NLS-1$
  128. else
  129. dateFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ZZZZ"); //$NON-NLS-1$
  130. reader = db.newObjectReader();
  131. try (BlameGenerator generator = new BlameGenerator(db, file)) {
  132. RevFlag scanned = generator.newFlag("SCANNED"); //$NON-NLS-1$
  133. generator.setTextComparator(comparator);
  134. if (!reverseRange.isEmpty()) {
  135. RevCommit rangeStart = null;
  136. List<RevCommit> rangeEnd = new ArrayList<>(2);
  137. for (RevCommit c : reverseRange) {
  138. if (c.has(RevFlag.UNINTERESTING))
  139. rangeStart = c;
  140. else
  141. rangeEnd.add(c);
  142. }
  143. generator.reverse(rangeStart, rangeEnd);
  144. } else if (revision != null) {
  145. generator.push(null, db.resolve(revision + "^{commit}")); //$NON-NLS-1$
  146. } else {
  147. generator.push(null, db.resolve(Constants.HEAD));
  148. if (!db.isBare()) {
  149. DirCache dc = db.readDirCache();
  150. int entry = dc.findEntry(file);
  151. if (0 <= entry)
  152. generator.push(null, dc.getEntry(entry).getObjectId());
  153. File inTree = new File(db.getWorkTree(), file);
  154. if (db.getFS().isFile(inTree))
  155. generator.push(null, new RawText(inTree));
  156. }
  157. }
  158. blame = BlameResult.create(generator);
  159. begin = 0;
  160. end = blame.getResultContents().size();
  161. if (rangeString != null)
  162. parseLineRangeOption();
  163. blame.computeRange(begin, end);
  164. int authorWidth = 8;
  165. int dateWidth = 8;
  166. int pathWidth = 1;
  167. int maxSourceLine = 1;
  168. for (int line = begin; line < end; line++) {
  169. RevCommit c = blame.getSourceCommit(line);
  170. if (c != null && !c.has(scanned)) {
  171. c.add(scanned);
  172. if (autoAbbrev)
  173. abbrev = Math.max(abbrev, uniqueAbbrevLen(c));
  174. authorWidth = Math.max(authorWidth, author(line).length());
  175. dateWidth = Math.max(dateWidth, date(line).length());
  176. pathWidth = Math.max(pathWidth, path(line).length());
  177. }
  178. while (line + 1 < end && blame.getSourceCommit(line + 1) == c)
  179. line++;
  180. maxSourceLine = Math.max(maxSourceLine, blame.getSourceLine(line));
  181. }
  182. String pathFmt = MessageFormat.format(" %{0}s", valueOf(pathWidth)); //$NON-NLS-1$
  183. String numFmt = MessageFormat.format(" %{0}d", //$NON-NLS-1$
  184. valueOf(1 + (int) Math.log10(maxSourceLine + 1)));
  185. String lineFmt = MessageFormat.format(" %{0}d) ", //$NON-NLS-1$
  186. valueOf(1 + (int) Math.log10(end + 1)));
  187. String authorFmt = MessageFormat.format(" (%-{0}s %{1}s", //$NON-NLS-1$
  188. valueOf(authorWidth), valueOf(dateWidth));
  189. for (int line = begin; line < end;) {
  190. RevCommit c = blame.getSourceCommit(line);
  191. String commit = abbreviate(c);
  192. String author = null;
  193. String date = null;
  194. if (!noAuthor) {
  195. author = author(line);
  196. date = date(line);
  197. }
  198. do {
  199. outw.print(commit);
  200. if (showSourcePath)
  201. outw.format(pathFmt, path(line));
  202. if (showSourceLine)
  203. outw.format(numFmt, valueOf(blame.getSourceLine(line) + 1));
  204. if (!noAuthor)
  205. outw.format(authorFmt, author, date);
  206. outw.format(lineFmt, valueOf(line + 1));
  207. outw.flush();
  208. blame.getResultContents().writeLine(outs, line);
  209. outs.flush();
  210. outw.print('\n');
  211. } while (++line < end && blame.getSourceCommit(line) == c);
  212. }
  213. } finally {
  214. reader.close();
  215. }
  216. }
  217. private int uniqueAbbrevLen(RevCommit commit) throws IOException {
  218. return reader.abbreviate(commit, abbrev).length();
  219. }
  220. private void parseLineRangeOption() {
  221. String beginStr, endStr;
  222. if (rangeString.startsWith("/")) { //$NON-NLS-1$
  223. int c = rangeString.indexOf("/,", 1); //$NON-NLS-1$
  224. if (c < 0) {
  225. beginStr = rangeString;
  226. endStr = String.valueOf(end);
  227. } else {
  228. beginStr = rangeString.substring(0, c);
  229. endStr = rangeString.substring(c + 2);
  230. }
  231. } else {
  232. int c = rangeString.indexOf(',');
  233. if (c < 0) {
  234. beginStr = rangeString;
  235. endStr = String.valueOf(end);
  236. } else if (c == 0) {
  237. beginStr = "0"; //$NON-NLS-1$
  238. endStr = rangeString.substring(1);
  239. } else {
  240. beginStr = rangeString.substring(0, c);
  241. endStr = rangeString.substring(c + 1);
  242. }
  243. }
  244. if (beginStr.equals("")) //$NON-NLS-1$
  245. begin = 0;
  246. else if (beginStr.startsWith("/")) //$NON-NLS-1$
  247. begin = findLine(0, beginStr);
  248. else
  249. begin = Math.max(0, Integer.parseInt(beginStr) - 1);
  250. if (endStr.equals("")) //$NON-NLS-1$
  251. end = blame.getResultContents().size();
  252. else if (endStr.startsWith("/")) //$NON-NLS-1$
  253. end = findLine(begin, endStr);
  254. else if (endStr.startsWith("-")) //$NON-NLS-1$
  255. end = begin + Integer.parseInt(endStr);
  256. else if (endStr.startsWith("+")) //$NON-NLS-1$
  257. end = begin + Integer.parseInt(endStr.substring(1));
  258. else
  259. end = Math.max(0, Integer.parseInt(endStr) - 1);
  260. }
  261. private int findLine(int b, String regex) {
  262. String re = regex.substring(1, regex.length() - 1);
  263. if (!re.startsWith("^")) //$NON-NLS-1$
  264. re = ".*" + re; //$NON-NLS-1$
  265. if (!re.endsWith("$")) //$NON-NLS-1$
  266. re = re + ".*"; //$NON-NLS-1$
  267. Pattern p = Pattern.compile(re);
  268. RawText text = blame.getResultContents();
  269. for (int line = b; line < text.size(); line++) {
  270. if (p.matcher(text.getString(line)).matches())
  271. return line;
  272. }
  273. return b;
  274. }
  275. private String path(int line) {
  276. String p = blame.getSourcePath(line);
  277. return p != null ? p : ""; //$NON-NLS-1$
  278. }
  279. private String author(int line) {
  280. PersonIdent author = blame.getSourceAuthor(line);
  281. if (author == null)
  282. return ""; //$NON-NLS-1$
  283. String name = showAuthorEmail ? author.getEmailAddress() : author
  284. .getName();
  285. return name != null ? name : ""; //$NON-NLS-1$
  286. }
  287. private String date(int line) {
  288. if (blame.getSourceCommit(line) == null)
  289. return ""; //$NON-NLS-1$
  290. PersonIdent author = blame.getSourceAuthor(line);
  291. if (author == null)
  292. return ""; //$NON-NLS-1$
  293. dateFmt.setTimeZone(author.getTimeZone());
  294. if (!showRawTimestamp)
  295. return dateFmt.format(author.getWhen());
  296. return String.format("%d %s", //$NON-NLS-1$
  297. valueOf(author.getWhen().getTime() / 1000L),
  298. dateFmt.format(author.getWhen()));
  299. }
  300. private String abbreviate(RevCommit commit) throws IOException {
  301. String r = abbreviatedCommits.get(commit);
  302. if (r != null)
  303. return r;
  304. if (showBlankBoundary && commit.getParentCount() == 0)
  305. commit = null;
  306. if (commit == null) {
  307. int len = showLongRevision ? OBJECT_ID_STRING_LENGTH : (abbrev + 1);
  308. StringBuilder b = new StringBuilder(len);
  309. for (int i = 0; i < len; i++)
  310. b.append(' ');
  311. r = b.toString();
  312. } else if (!root && commit.getParentCount() == 0) {
  313. if (showLongRevision)
  314. r = "^" + commit.name().substring(0, OBJECT_ID_STRING_LENGTH - 1); //$NON-NLS-1$
  315. else
  316. r = "^" + reader.abbreviate(commit, abbrev).name(); //$NON-NLS-1$
  317. } else {
  318. if (showLongRevision)
  319. r = commit.name();
  320. else
  321. r = reader.abbreviate(commit, abbrev + 1).name();
  322. }
  323. abbreviatedCommits.put(commit, r);
  324. return r;
  325. }
  326. }