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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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<RevCommit>(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<RevCommit, String>();
  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. BlameGenerator generator = new BlameGenerator(db, file);
  131. RevFlag scanned = generator.newFlag("SCANNED"); //$NON-NLS-1$
  132. reader = db.newObjectReader();
  133. try {
  134. generator.setTextComparator(comparator);
  135. if (!reverseRange.isEmpty()) {
  136. RevCommit rangeStart = null;
  137. List<RevCommit> rangeEnd = new ArrayList<RevCommit>(2);
  138. for (RevCommit c : reverseRange) {
  139. if (c.has(RevFlag.UNINTERESTING))
  140. rangeStart = c;
  141. else
  142. rangeEnd.add(c);
  143. }
  144. generator.reverse(rangeStart, rangeEnd);
  145. } else if (revision != null) {
  146. generator.push(null, db.resolve(revision + "^{commit}")); //$NON-NLS-1$
  147. } else {
  148. generator.push(null, db.resolve(Constants.HEAD));
  149. if (!db.isBare()) {
  150. DirCache dc = db.readDirCache();
  151. int entry = dc.findEntry(file);
  152. if (0 <= entry)
  153. generator.push(null, dc.getEntry(entry).getObjectId());
  154. File inTree = new File(db.getWorkTree(), file);
  155. if (db.getFS().isFile(inTree))
  156. generator.push(null, new RawText(inTree));
  157. }
  158. }
  159. blame = BlameResult.create(generator);
  160. begin = 0;
  161. end = blame.getResultContents().size();
  162. if (rangeString != null)
  163. parseLineRangeOption();
  164. blame.computeRange(begin, end);
  165. int authorWidth = 8;
  166. int dateWidth = 8;
  167. int pathWidth = 1;
  168. int maxSourceLine = 1;
  169. for (int line = begin; line < end; line++) {
  170. RevCommit c = blame.getSourceCommit(line);
  171. if (c != null && !c.has(scanned)) {
  172. c.add(scanned);
  173. if (autoAbbrev)
  174. abbrev = Math.max(abbrev, uniqueAbbrevLen(c));
  175. authorWidth = Math.max(authorWidth, author(line).length());
  176. dateWidth = Math.max(dateWidth, date(line).length());
  177. pathWidth = Math.max(pathWidth, path(line).length());
  178. }
  179. while (line + 1 < end && blame.getSourceCommit(line + 1) == c)
  180. line++;
  181. maxSourceLine = Math.max(maxSourceLine, blame.getSourceLine(line));
  182. }
  183. String pathFmt = MessageFormat.format(" %{0}s", valueOf(pathWidth)); //$NON-NLS-1$
  184. String numFmt = MessageFormat.format(" %{0}d", //$NON-NLS-1$
  185. valueOf(1 + (int) Math.log10(maxSourceLine + 1)));
  186. String lineFmt = MessageFormat.format(" %{0}d) ", //$NON-NLS-1$
  187. valueOf(1 + (int) Math.log10(end + 1)));
  188. String authorFmt = MessageFormat.format(" (%-{0}s %{1}s", //$NON-NLS-1$
  189. valueOf(authorWidth), valueOf(dateWidth));
  190. for (int line = begin; line < end;) {
  191. RevCommit c = blame.getSourceCommit(line);
  192. String commit = abbreviate(c);
  193. String author = null;
  194. String date = null;
  195. if (!noAuthor) {
  196. author = author(line);
  197. date = date(line);
  198. }
  199. do {
  200. outw.print(commit);
  201. if (showSourcePath)
  202. outw.format(pathFmt, path(line));
  203. if (showSourceLine)
  204. outw.format(numFmt, valueOf(blame.getSourceLine(line) + 1));
  205. if (!noAuthor)
  206. outw.format(authorFmt, author, date);
  207. outw.format(lineFmt, valueOf(line + 1));
  208. outw.flush();
  209. blame.getResultContents().writeLine(outs, line);
  210. outs.flush();
  211. outw.print('\n');
  212. } while (++line < end && blame.getSourceCommit(line) == c);
  213. }
  214. } finally {
  215. generator.release();
  216. reader.release();
  217. }
  218. }
  219. private int uniqueAbbrevLen(RevCommit commit) throws IOException {
  220. return reader.abbreviate(commit, abbrev).length();
  221. }
  222. private void parseLineRangeOption() {
  223. String beginStr, endStr;
  224. if (rangeString.startsWith("/")) { //$NON-NLS-1$
  225. int c = rangeString.indexOf("/,", 1); //$NON-NLS-1$
  226. if (c < 0) {
  227. beginStr = rangeString;
  228. endStr = String.valueOf(end);
  229. } else {
  230. beginStr = rangeString.substring(0, c);
  231. endStr = rangeString.substring(c + 2);
  232. }
  233. } else {
  234. int c = rangeString.indexOf(',');
  235. if (c < 0) {
  236. beginStr = rangeString;
  237. endStr = String.valueOf(end);
  238. } else if (c == 0) {
  239. beginStr = "0"; //$NON-NLS-1$
  240. endStr = rangeString.substring(1);
  241. } else {
  242. beginStr = rangeString.substring(0, c);
  243. endStr = rangeString.substring(c + 1);
  244. }
  245. }
  246. if (beginStr.equals("")) //$NON-NLS-1$
  247. begin = 0;
  248. else if (beginStr.startsWith("/")) //$NON-NLS-1$
  249. begin = findLine(0, beginStr);
  250. else
  251. begin = Math.max(0, Integer.parseInt(beginStr) - 1);
  252. if (endStr.equals("")) //$NON-NLS-1$
  253. end = blame.getResultContents().size();
  254. else if (endStr.startsWith("/")) //$NON-NLS-1$
  255. end = findLine(begin, endStr);
  256. else if (endStr.startsWith("-")) //$NON-NLS-1$
  257. end = begin + Integer.parseInt(endStr);
  258. else if (endStr.startsWith("+")) //$NON-NLS-1$
  259. end = begin + Integer.parseInt(endStr.substring(1));
  260. else
  261. end = Math.max(0, Integer.parseInt(endStr) - 1);
  262. }
  263. private int findLine(int b, String regex) {
  264. String re = regex.substring(1, regex.length() - 1);
  265. if (!re.startsWith("^")) //$NON-NLS-1$
  266. re = ".*" + re; //$NON-NLS-1$
  267. if (!re.endsWith("$")) //$NON-NLS-1$
  268. re = re + ".*"; //$NON-NLS-1$
  269. Pattern p = Pattern.compile(re);
  270. RawText text = blame.getResultContents();
  271. for (int line = b; line < text.size(); line++) {
  272. if (p.matcher(text.getString(line)).matches())
  273. return line;
  274. }
  275. return b;
  276. }
  277. private String path(int line) {
  278. String p = blame.getSourcePath(line);
  279. return p != null ? p : ""; //$NON-NLS-1$
  280. }
  281. private String author(int line) {
  282. PersonIdent author = blame.getSourceAuthor(line);
  283. if (author == null)
  284. return ""; //$NON-NLS-1$
  285. String name = showAuthorEmail ? author.getEmailAddress() : author
  286. .getName();
  287. return name != null ? name : ""; //$NON-NLS-1$
  288. }
  289. private String date(int line) {
  290. if (blame.getSourceCommit(line) == null)
  291. return ""; //$NON-NLS-1$
  292. PersonIdent author = blame.getSourceAuthor(line);
  293. if (author == null)
  294. return ""; //$NON-NLS-1$
  295. dateFmt.setTimeZone(author.getTimeZone());
  296. if (!showRawTimestamp)
  297. return dateFmt.format(author.getWhen());
  298. return String.format("%d %s", //$NON-NLS-1$
  299. valueOf(author.getWhen().getTime() / 1000L),
  300. dateFmt.format(author.getWhen()));
  301. }
  302. private String abbreviate(RevCommit commit) throws IOException {
  303. String r = abbreviatedCommits.get(commit);
  304. if (r != null)
  305. return r;
  306. if (showBlankBoundary && commit.getParentCount() == 0)
  307. commit = null;
  308. if (commit == null) {
  309. int len = showLongRevision ? OBJECT_ID_STRING_LENGTH : (abbrev + 1);
  310. StringBuilder b = new StringBuilder(len);
  311. for (int i = 0; i < len; i++)
  312. b.append(' ');
  313. r = b.toString();
  314. } else if (!root && commit.getParentCount() == 0) {
  315. if (showLongRevision)
  316. r = "^" + commit.name().substring(0, OBJECT_ID_STRING_LENGTH - 1); //$NON-NLS-1$
  317. else
  318. r = "^" + reader.abbreviate(commit, abbrev).name(); //$NON-NLS-1$
  319. } else {
  320. if (showLongRevision)
  321. r = commit.name();
  322. else
  323. r = reader.abbreviate(commit, abbrev + 1).name();
  324. }
  325. abbreviatedCommits.put(commit, r);
  326. return r;
  327. }
  328. }