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

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