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

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