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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 org.eclipse.jgit.lib.Constants.OBJECT_ID_STRING_LENGTH;
  48. import java.io.File;
  49. import java.io.IOException;
  50. import java.text.MessageFormat;
  51. import java.text.SimpleDateFormat;
  52. import java.util.ArrayList;
  53. import java.util.HashMap;
  54. import java.util.List;
  55. import java.util.Map;
  56. import java.util.regex.Pattern;
  57. import org.eclipse.jgit.blame.BlameGenerator;
  58. import org.eclipse.jgit.blame.BlameResult;
  59. import org.eclipse.jgit.diff.RawText;
  60. import org.eclipse.jgit.diff.RawTextComparator;
  61. import org.eclipse.jgit.dircache.DirCache;
  62. import org.eclipse.jgit.lib.Constants;
  63. import org.eclipse.jgit.lib.ObjectReader;
  64. import org.eclipse.jgit.lib.PersonIdent;
  65. import org.eclipse.jgit.revwalk.RevCommit;
  66. import org.eclipse.jgit.revwalk.RevFlag;
  67. import org.kohsuke.args4j.Argument;
  68. import org.kohsuke.args4j.Option;
  69. @Command(common = false, usage = "usage_Blame")
  70. class Blame extends TextBuiltin {
  71. private RawTextComparator comparator = RawTextComparator.DEFAULT;
  72. @Option(name = "-w", usage = "usage_ignoreWhitespace")
  73. void ignoreAllSpace(@SuppressWarnings("unused") boolean on) {
  74. comparator = RawTextComparator.WS_IGNORE_ALL;
  75. }
  76. @Option(name = "--abbrev", metaVar = "metaVar_n", usage = "usage_abbrevCommits")
  77. private int abbrev;
  78. @Option(name = "-l", usage = "usage_blameLongRevision")
  79. private boolean showLongRevision;
  80. @Option(name = "-t", usage = "usage_blameRawTimestamp")
  81. private boolean showRawTimestamp;
  82. @Option(name = "-b", usage = "usage_blameShowBlankBoundary")
  83. private boolean showBlankBoundary;
  84. @Option(name = "-s", usage = "usage_blameSuppressAuthor")
  85. private boolean noAuthor;
  86. @Option(name = "--show-email", aliases = { "-e" }, usage = "usage_blameShowEmail")
  87. private boolean showAuthorEmail;
  88. @Option(name = "--show-name", aliases = { "-f" }, usage = "usage_blameShowSourcePath")
  89. private boolean showSourcePath;
  90. @Option(name = "--show-number", aliases = { "-n" }, usage = "usage_blameShowSourceLine")
  91. private boolean showSourceLine;
  92. @Option(name = "--root", usage = "usage_blameShowRoot")
  93. private boolean root;
  94. @Option(name = "-L", metaVar = "metaVar_blameL", usage = "usage_blameRange")
  95. private String rangeString;
  96. @Option(name = "--reverse", metaVar = "metaVar_blameReverse", usage = "usage_blameReverse")
  97. private List<RevCommit> reverseRange = new ArrayList<RevCommit>(2);
  98. @Argument(index = 0, required = false, metaVar = "metaVar_revision")
  99. private String revision;
  100. @Argument(index = 1, required = false, metaVar = "metaVar_file")
  101. private String file;
  102. private ObjectReader reader;
  103. private final Map<RevCommit, String> abbreviatedCommits = new HashMap<RevCommit, String>();
  104. private SimpleDateFormat dateFmt;
  105. private int begin;
  106. private int end;
  107. private BlameResult blame;
  108. @Override
  109. protected void run() throws Exception {
  110. if (file == null) {
  111. if (revision == null)
  112. throw die(CLIText.get().fileIsRequired);
  113. file = revision;
  114. revision = null;
  115. }
  116. if (abbrev == 0)
  117. abbrev = db.getConfig().getInt("core", "abbrev", 7);
  118. if (!showBlankBoundary)
  119. root = db.getConfig().getBoolean("blame", "blankboundary", false);
  120. if (!root)
  121. root = db.getConfig().getBoolean("blame", "showroot", false);
  122. if (showRawTimestamp)
  123. dateFmt = new SimpleDateFormat("ZZZZ");
  124. else
  125. dateFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ZZZZ");
  126. BlameGenerator generator = new BlameGenerator(db, file);
  127. reader = db.newObjectReader();
  128. try {
  129. generator.setTextComparator(comparator);
  130. if (!reverseRange.isEmpty()) {
  131. RevCommit rangeStart = null;
  132. List<RevCommit> rangeEnd = new ArrayList<RevCommit>(2);
  133. for (RevCommit c : reverseRange) {
  134. if (c.has(RevFlag.UNINTERESTING))
  135. rangeStart = c;
  136. else
  137. rangeEnd.add(c);
  138. }
  139. generator.reverse(rangeStart, rangeEnd);
  140. } else if (revision != null) {
  141. generator.push(null, db.resolve(revision + "^{commit}"));
  142. } else {
  143. generator.push(null, db.resolve(Constants.HEAD));
  144. if (!db.isBare()) {
  145. DirCache dc = db.readDirCache();
  146. int entry = dc.findEntry(file);
  147. if (0 <= entry)
  148. generator.push(null, dc.getEntry(entry).getObjectId());
  149. File inTree = new File(db.getWorkTree(), file);
  150. if (inTree.isFile())
  151. generator.push(null, new RawText(inTree));
  152. }
  153. }
  154. blame = BlameResult.create(generator);
  155. begin = 0;
  156. end = blame.getResultContents().size();
  157. if (rangeString != null)
  158. parseLineRangeOption();
  159. blame.computeRange(begin, end);
  160. int authorWidth = 8;
  161. int dateWidth = 8;
  162. int pathWidth = 1;
  163. int maxSourceLine = 1;
  164. for (int line = begin; line < end; line++) {
  165. authorWidth = Math.max(authorWidth, author(line).length());
  166. dateWidth = Math.max(dateWidth, date(line).length());
  167. pathWidth = Math.max(pathWidth, path(line).length());
  168. maxSourceLine = Math.max(maxSourceLine, blame.getSourceLine(line));
  169. }
  170. String pathFmt = MessageFormat.format(" %{0}s", pathWidth);
  171. String numFmt = MessageFormat.format(" %{0}d",
  172. 1 + (int) Math.log10(maxSourceLine + 1));
  173. String lineFmt = MessageFormat.format(" %{0}d) ",
  174. 1 + (int) Math.log10(end + 1));
  175. String authorFmt = MessageFormat.format(" (%-{0}s %{1}s",
  176. authorWidth, dateWidth);
  177. for (int line = begin; line < end; line++) {
  178. out.print(abbreviate(blame.getSourceCommit(line)));
  179. if (showSourcePath)
  180. out.format(pathFmt, path(line));
  181. if (showSourceLine)
  182. out.format(numFmt, blame.getSourceLine(line) + 1);
  183. if (!noAuthor)
  184. out.format(authorFmt, author(line), date(line));
  185. out.format(lineFmt, line + 1);
  186. out.flush();
  187. blame.getResultContents().writeLine(System.out, line);
  188. out.print('\n');
  189. }
  190. } finally {
  191. generator.release();
  192. reader.release();
  193. }
  194. }
  195. private void parseLineRangeOption() {
  196. String beginStr, endStr;
  197. if (rangeString.startsWith("/")) {
  198. int c = rangeString.indexOf("/,", 1);
  199. if (c < 0) {
  200. beginStr = rangeString;
  201. endStr = String.valueOf(end);
  202. } else {
  203. beginStr = rangeString.substring(0, c);
  204. endStr = rangeString.substring(c + 2);
  205. }
  206. } else {
  207. int c = rangeString.indexOf(',');
  208. if (c < 0) {
  209. beginStr = rangeString;
  210. endStr = String.valueOf(end);
  211. } else if (c == 0) {
  212. beginStr = "0";
  213. endStr = rangeString.substring(1);
  214. } else {
  215. beginStr = rangeString.substring(0, c);
  216. endStr = rangeString.substring(c + 1);
  217. }
  218. }
  219. if (beginStr.equals(""))
  220. begin = 0;
  221. else if (beginStr.startsWith("/"))
  222. begin = findLine(0, beginStr);
  223. else
  224. begin = Math.max(0, Integer.parseInt(beginStr) - 1);
  225. if (endStr.equals(""))
  226. end = blame.getResultContents().size();
  227. else if (endStr.startsWith("/"))
  228. end = findLine(begin, endStr);
  229. else if (endStr.startsWith("-"))
  230. end = begin + Integer.parseInt(endStr);
  231. else if (endStr.startsWith("+"))
  232. end = begin + Integer.parseInt(endStr.substring(1));
  233. else
  234. end = Math.max(0, Integer.parseInt(endStr) - 1);
  235. }
  236. private int findLine(int b, String regex) {
  237. String re = regex.substring(1, regex.length() - 1);
  238. if (!re.startsWith("^"))
  239. re = ".*" + re;
  240. if (!re.endsWith("$"))
  241. re = re + ".*";
  242. Pattern p = Pattern.compile(re);
  243. RawText text = blame.getResultContents();
  244. for (int line = b; line < text.size(); line++) {
  245. if (p.matcher(text.getString(line)).matches())
  246. return line;
  247. }
  248. return b;
  249. }
  250. private String path(int line) {
  251. String p = blame.getSourcePath(line);
  252. return p != null ? p : "";
  253. }
  254. private String author(int line) {
  255. PersonIdent author = blame.getSourceAuthor(line);
  256. if (author == null)
  257. return "";
  258. String name = showAuthorEmail ? author.getEmailAddress() : author
  259. .getName();
  260. return name != null ? name : "";
  261. }
  262. private String date(int line) {
  263. if (blame.getSourceCommit(line) == null)
  264. return "";
  265. PersonIdent author = blame.getSourceAuthor(line);
  266. if (author == null)
  267. return "";
  268. dateFmt.setTimeZone(author.getTimeZone());
  269. if (!showRawTimestamp)
  270. return dateFmt.format(author.getWhen());
  271. return String.format("%d %s", author.getWhen().getTime() / 1000L,
  272. dateFmt.format(author.getWhen()));
  273. }
  274. private String abbreviate(RevCommit commit) throws IOException {
  275. String r = abbreviatedCommits.get(commit);
  276. if (r != null)
  277. return r;
  278. if (showBlankBoundary && commit.getParentCount() == 0)
  279. commit = null;
  280. if (commit == null) {
  281. int len = showLongRevision ? OBJECT_ID_STRING_LENGTH : (abbrev + 1);
  282. StringBuilder b = new StringBuilder(len);
  283. for (int i = 0; i < len; i++)
  284. b.append(' ');
  285. r = b.toString();
  286. } else if (!root && commit.getParentCount() == 0) {
  287. if (showLongRevision)
  288. r = "^" + commit.name().substring(0, OBJECT_ID_STRING_LENGTH - 1);
  289. else
  290. r = "^" + reader.abbreviate(commit, abbrev).name();
  291. } else {
  292. if (showLongRevision)
  293. r = commit.name();
  294. else
  295. r = reader.abbreviate(commit, abbrev + 1).name();
  296. }
  297. abbreviatedCommits.put(commit, r);
  298. return r;
  299. }
  300. }