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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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
  190. && sameCommit(blame.getSourceCommit(line + 1), c)) {
  191. line++;
  192. }
  193. maxSourceLine = Math.max(maxSourceLine, blame.getSourceLine(line));
  194. }
  195. String pathFmt = MessageFormat.format(" %{0}s", valueOf(pathWidth)); //$NON-NLS-1$
  196. String numFmt = MessageFormat.format(" %{0}d", //$NON-NLS-1$
  197. valueOf(1 + (int) Math.log10(maxSourceLine + 1)));
  198. String lineFmt = MessageFormat.format(" %{0}d) ", //$NON-NLS-1$
  199. valueOf(1 + (int) Math.log10(end + 1)));
  200. String authorFmt = MessageFormat.format(" (%-{0}s %{1}s", //$NON-NLS-1$
  201. valueOf(authorWidth), valueOf(dateWidth));
  202. for (int line = begin; line < end;) {
  203. RevCommit c = blame.getSourceCommit(line);
  204. String commit = abbreviate(reader, c);
  205. String author = null;
  206. String date = null;
  207. if (!noAuthor) {
  208. author = author(line);
  209. date = date(line);
  210. }
  211. do {
  212. outw.print(commit);
  213. if (showSourcePath) {
  214. outw.format(pathFmt, path(line));
  215. }
  216. if (showSourceLine) {
  217. outw.format(numFmt, valueOf(blame.getSourceLine(line) + 1));
  218. }
  219. if (!noAuthor) {
  220. outw.format(authorFmt, author, date);
  221. }
  222. outw.format(lineFmt, valueOf(line + 1));
  223. outw.flush();
  224. blame.getResultContents().writeLine(outs, line);
  225. outs.flush();
  226. outw.print('\n');
  227. } while (++line < end
  228. && sameCommit(blame.getSourceCommit(line), c));
  229. }
  230. } catch (NoWorkTreeException | IOException e) {
  231. throw die(e.getMessage(), e);
  232. }
  233. }
  234. @SuppressWarnings("ReferenceEquality")
  235. private static boolean sameCommit(RevCommit a, RevCommit b) {
  236. // Reference comparison is intentional; BlameGenerator uses a single
  237. // RevWalk which caches the RevCommit objects, and if a given commit
  238. // is cached the RevWalk returns the same instance.
  239. return a == b;
  240. }
  241. private int uniqueAbbrevLen(ObjectReader reader, RevCommit commit)
  242. throws IOException {
  243. return reader.abbreviate(commit, abbrev).length();
  244. }
  245. private void parseLineRangeOption() {
  246. String beginStr, endStr;
  247. if (rangeString.startsWith("/")) { //$NON-NLS-1$
  248. int c = rangeString.indexOf("/,", 1); //$NON-NLS-1$
  249. if (c < 0) {
  250. beginStr = rangeString;
  251. endStr = String.valueOf(end);
  252. } else {
  253. beginStr = rangeString.substring(0, c);
  254. endStr = rangeString.substring(c + 2);
  255. }
  256. } else {
  257. int c = rangeString.indexOf(',');
  258. if (c < 0) {
  259. beginStr = rangeString;
  260. endStr = String.valueOf(end);
  261. } else if (c == 0) {
  262. beginStr = "0"; //$NON-NLS-1$
  263. endStr = rangeString.substring(1);
  264. } else {
  265. beginStr = rangeString.substring(0, c);
  266. endStr = rangeString.substring(c + 1);
  267. }
  268. }
  269. if (beginStr.isEmpty())
  270. begin = 0;
  271. else if (beginStr.startsWith("/")) //$NON-NLS-1$
  272. begin = findLine(0, beginStr);
  273. else
  274. begin = Math.max(0, Integer.parseInt(beginStr) - 1);
  275. if (endStr.isEmpty())
  276. end = blame.getResultContents().size();
  277. else if (endStr.startsWith("/")) //$NON-NLS-1$
  278. end = findLine(begin, endStr);
  279. else if (endStr.startsWith("-")) //$NON-NLS-1$
  280. end = begin + Integer.parseInt(endStr);
  281. else if (endStr.startsWith("+")) //$NON-NLS-1$
  282. end = begin + Integer.parseInt(endStr.substring(1));
  283. else
  284. end = Math.max(0, Integer.parseInt(endStr) - 1);
  285. }
  286. private int findLine(int b, String regex) {
  287. String re = regex.substring(1, regex.length() - 1);
  288. if (!re.startsWith("^")) //$NON-NLS-1$
  289. re = ".*" + re; //$NON-NLS-1$
  290. if (!re.endsWith("$")) //$NON-NLS-1$
  291. re = re + ".*"; //$NON-NLS-1$
  292. Pattern p = Pattern.compile(re);
  293. RawText text = blame.getResultContents();
  294. for (int line = b; line < text.size(); line++) {
  295. if (p.matcher(text.getString(line)).matches())
  296. return line;
  297. }
  298. return b;
  299. }
  300. private String path(int line) {
  301. String p = blame.getSourcePath(line);
  302. return p != null ? p : ""; //$NON-NLS-1$
  303. }
  304. private String author(int line) {
  305. PersonIdent author = blame.getSourceAuthor(line);
  306. if (author == null)
  307. return ""; //$NON-NLS-1$
  308. String name = showAuthorEmail ? author.getEmailAddress() : author
  309. .getName();
  310. return name != null ? name : ""; //$NON-NLS-1$
  311. }
  312. private String date(int line) {
  313. if (blame.getSourceCommit(line) == null)
  314. return ""; //$NON-NLS-1$
  315. PersonIdent author = blame.getSourceAuthor(line);
  316. if (author == null)
  317. return ""; //$NON-NLS-1$
  318. dateFmt.setTimeZone(author.getTimeZone());
  319. if (!showRawTimestamp)
  320. return dateFmt.format(author.getWhen());
  321. return String.format("%d %s", //$NON-NLS-1$
  322. valueOf(author.getWhen().getTime() / 1000L),
  323. dateFmt.format(author.getWhen()));
  324. }
  325. private String abbreviate(ObjectReader reader, RevCommit commit)
  326. throws IOException {
  327. String r = abbreviatedCommits.get(commit);
  328. if (r != null)
  329. return r;
  330. if (showBlankBoundary && commit.getParentCount() == 0)
  331. commit = null;
  332. if (commit == null) {
  333. int len = showLongRevision ? OBJECT_ID_STRING_LENGTH : (abbrev + 1);
  334. StringBuilder b = new StringBuilder(len);
  335. for (int i = 0; i < len; i++)
  336. b.append(' ');
  337. r = b.toString();
  338. } else if (!root && commit.getParentCount() == 0) {
  339. if (showLongRevision)
  340. r = "^" + commit.name().substring(0, OBJECT_ID_STRING_LENGTH - 1); //$NON-NLS-1$
  341. else
  342. r = "^" + reader.abbreviate(commit, abbrev).name(); //$NON-NLS-1$
  343. } else {
  344. if (showLongRevision)
  345. r = commit.name();
  346. else
  347. r = reader.abbreviate(commit, abbrev + 1).name();
  348. }
  349. abbreviatedCommits.put(commit, r);
  350. return r;
  351. }
  352. }