Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

IpLogGenerator.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. /*
  2. * Copyright (C) 2010, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.iplog;
  44. import java.io.BufferedReader;
  45. import java.io.File;
  46. import java.io.FileReader;
  47. import java.io.IOException;
  48. import java.io.OutputStream;
  49. import java.text.MessageFormat;
  50. import java.text.ParseException;
  51. import java.text.SimpleDateFormat;
  52. import java.util.ArrayList;
  53. import java.util.Collection;
  54. import java.util.Collections;
  55. import java.util.Comparator;
  56. import java.util.Date;
  57. import java.util.HashMap;
  58. import java.util.HashSet;
  59. import java.util.Map;
  60. import java.util.Set;
  61. import java.util.TreeMap;
  62. import java.util.TreeSet;
  63. import javax.xml.parsers.DocumentBuilderFactory;
  64. import javax.xml.parsers.ParserConfigurationException;
  65. import javax.xml.transform.OutputKeys;
  66. import javax.xml.transform.Transformer;
  67. import javax.xml.transform.TransformerConfigurationException;
  68. import javax.xml.transform.TransformerException;
  69. import javax.xml.transform.TransformerFactory;
  70. import javax.xml.transform.dom.DOMSource;
  71. import javax.xml.transform.stream.StreamResult;
  72. import org.eclipse.jgit.diff.Edit;
  73. import org.eclipse.jgit.diff.EditList;
  74. import org.eclipse.jgit.diff.MyersDiff;
  75. import org.eclipse.jgit.diff.RawText;
  76. import org.eclipse.jgit.diff.RawTextComparator;
  77. import org.eclipse.jgit.errors.ConfigInvalidException;
  78. import org.eclipse.jgit.iplog.Committer.ActiveRange;
  79. import org.eclipse.jgit.lib.BlobBasedConfig;
  80. import org.eclipse.jgit.lib.Constants;
  81. import org.eclipse.jgit.lib.MutableObjectId;
  82. import org.eclipse.jgit.lib.ObjectReader;
  83. import org.eclipse.jgit.lib.PersonIdent;
  84. import org.eclipse.jgit.lib.Repository;
  85. import org.eclipse.jgit.revwalk.RevCommit;
  86. import org.eclipse.jgit.revwalk.RevTree;
  87. import org.eclipse.jgit.revwalk.RevWalk;
  88. import org.eclipse.jgit.treewalk.NameConflictTreeWalk;
  89. import org.eclipse.jgit.treewalk.TreeWalk;
  90. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  91. import org.eclipse.jgit.util.RawParseUtils;
  92. import org.w3c.dom.Document;
  93. import org.w3c.dom.Element;
  94. /**
  95. * Creates an Eclipse IP log in XML format.
  96. *
  97. * @see <a href="http://www.eclipse.org/projects/xml/iplog.xsd">IP log XSD</a>
  98. */
  99. public class IpLogGenerator {
  100. private static final String IPLOG_NS = "http://www.eclipse.org/projects/xml/iplog";
  101. private static final String IPLOG_PFX = "iplog:";
  102. private static final String INDENT = "{http://xml.apache.org/xslt}indent-amount";
  103. /** Projects indexed by their ID string, e.g. {@code technology.jgit}. */
  104. private final Map<String, Project> projects = new TreeMap<String, Project>();
  105. /** Projects indexed by their ID string, e.g. {@code technology.jgit}. */
  106. private final Map<String, Project> consumedProjects = new TreeMap<String, Project>();
  107. /** Known committers, indexed by their foundation ID. */
  108. private final Map<String, Committer> committersById = new HashMap<String, Committer>();
  109. /** Known committers, indexed by their email address. */
  110. private final Map<String, Committer> committersByEmail = new HashMap<String, Committer>();
  111. /** Discovered contributors. */
  112. private final Map<String, Contributor> contributorsByName = new HashMap<String, Contributor>();
  113. /** All known CQs matching the projects we care about. */
  114. private final Set<CQ> cqs = new HashSet<CQ>();
  115. /** Root commits which were scanned to gather project data. */
  116. private final Set<RevCommit> commits = new HashSet<RevCommit>();
  117. /** The meta file we loaded to bootstrap our definitions. */
  118. private IpLogMeta meta;
  119. /** URL to obtain review information about a specific contribution. */
  120. private String reviewUrl;
  121. private String characterEncoding = "UTF-8";
  122. private Repository db;
  123. private RevWalk rw;
  124. private NameConflictTreeWalk tw;
  125. private ObjectReader curs;
  126. private final MutableObjectId idbuf = new MutableObjectId();
  127. private Document doc;
  128. /** Create an empty generator. */
  129. public IpLogGenerator() {
  130. // Do nothing.
  131. }
  132. /**
  133. * Set the character encoding used to write the output file.
  134. *
  135. * @param encodingName
  136. * the character set encoding name.
  137. */
  138. public void setCharacterEncoding(String encodingName) {
  139. characterEncoding = encodingName;
  140. }
  141. /**
  142. * Scan a Git repository's history to compute the changes within it.
  143. *
  144. * @param repo
  145. * the repository to scan.
  146. * @param startCommit
  147. * commit the IP log is needed for.
  148. * @param version
  149. * symbolic label for the version.
  150. * @throws IOException
  151. * the repository cannot be read.
  152. * @throws ConfigInvalidException
  153. * the {@code .eclipse_iplog} file present at the top level of
  154. * {@code startId} is not a valid configuration file.
  155. */
  156. public void scan(Repository repo, RevCommit startCommit, String version)
  157. throws IOException, ConfigInvalidException {
  158. try {
  159. db = repo;
  160. curs = db.newObjectReader();
  161. rw = new RevWalk(curs);
  162. tw = new NameConflictTreeWalk(curs);
  163. RevCommit c = rw.parseCommit(startCommit);
  164. loadEclipseIpLog(version, c);
  165. loadCommitters(repo);
  166. scanProjectCommits(meta.getProjects().get(0), c);
  167. commits.add(c);
  168. } finally {
  169. curs.release();
  170. db = null;
  171. rw = null;
  172. tw = null;
  173. }
  174. }
  175. private void loadEclipseIpLog(String version, RevCommit commit)
  176. throws IOException, ConfigInvalidException {
  177. TreeWalk log = TreeWalk.forPath(db, IpLogMeta.IPLOG_CONFIG_FILE, commit
  178. .getTree());
  179. if (log == null)
  180. return;
  181. meta = new IpLogMeta();
  182. try {
  183. meta.loadFrom(new BlobBasedConfig(null, db, log.getObjectId(0)));
  184. } catch (ConfigInvalidException e) {
  185. throw new ConfigInvalidException(MessageFormat.format(IpLogText.get().configurationFileInCommitIsInvalid
  186. , log.getPathString(), commit.name()), e);
  187. }
  188. if (meta.getProjects().isEmpty()) {
  189. throw new ConfigInvalidException(MessageFormat.format(IpLogText.get().configurationFileInCommitHasNoProjectsDeclared
  190. , log.getPathString(), commit.name()));
  191. }
  192. for (Project p : meta.getProjects()) {
  193. p.setVersion(version);
  194. projects.put(p.getName(), p);
  195. }
  196. for (Project p : meta.getConsumedProjects()) {
  197. consumedProjects.put(p.getName(), p);
  198. }
  199. cqs.addAll(meta.getCQs());
  200. reviewUrl = meta.getReviewUrl();
  201. }
  202. private void loadCommitters(Repository repo) throws IOException {
  203. SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  204. File list = new File(repo.getDirectory(), "gerrit_committers");
  205. BufferedReader br = new BufferedReader(new FileReader(list));
  206. try {
  207. String line;
  208. while ((line = br.readLine()) != null) {
  209. String[] field = line.trim().split(" *\\| *");
  210. String user = field[1];
  211. String name = field[2];
  212. String email = field[3];
  213. Date begin = parseDate(dt, field[4]);
  214. Date end = parseDate(dt, field[5]);
  215. if (user.startsWith("username:"))
  216. user = user.substring("username:".length());
  217. Committer who = committersById.get(user);
  218. if (who == null) {
  219. who = new Committer(user);
  220. int sp = name.indexOf(' ');
  221. if (0 < sp) {
  222. who.setFirstName(name.substring(0, sp).trim());
  223. who.setLastName(name.substring(sp + 1).trim());
  224. } else {
  225. who.setFirstName(name);
  226. who.setLastName(null);
  227. }
  228. committersById.put(who.getID(), who);
  229. }
  230. who.addEmailAddress(email);
  231. who.addActiveRange(new ActiveRange(begin, end));
  232. committersByEmail.put(email, who);
  233. }
  234. } finally {
  235. br.close();
  236. }
  237. }
  238. private Date parseDate(SimpleDateFormat dt, String value)
  239. throws IOException {
  240. if ("NULL".equals(value) || "".equals(value) || value == null)
  241. return null;
  242. int dot = value.indexOf('.');
  243. if (0 < dot)
  244. value = value.substring(0, dot);
  245. try {
  246. return dt.parse(value);
  247. } catch (ParseException e) {
  248. IOException err = new IOException(MessageFormat.format(IpLogText.get().invalidDate, value));
  249. err.initCause(e);
  250. throw err;
  251. }
  252. }
  253. private void scanProjectCommits(Project proj, RevCommit start)
  254. throws IOException {
  255. rw.reset();
  256. rw.markStart(start);
  257. RevCommit commit;
  258. while ((commit = rw.next()) != null) {
  259. if (proj.isSkippedCommit(commit)) {
  260. continue;
  261. }
  262. final PersonIdent author = commit.getAuthorIdent();
  263. final Date when = author.getWhen();
  264. Committer who = committersByEmail.get(author.getEmailAddress());
  265. if (who != null && who.inRange(when)) {
  266. // Commit was written by the committer while they were
  267. // an active committer on the project.
  268. //
  269. who.setHasCommits(true);
  270. continue;
  271. }
  272. // Commit from a non-committer contributor.
  273. //
  274. final int cnt = commit.getParentCount();
  275. if (2 <= cnt) {
  276. // Avoid a pointless merge attributed to a non-committer.
  277. // Skip this commit if every file matches at least one
  278. // of the parent commits exactly, if so then the blame
  279. // for code in that file can be fully passed onto that
  280. // parent and this non-committer isn't responsible.
  281. //
  282. tw.setFilter(TreeFilter.ANY_DIFF);
  283. tw.setRecursive(true);
  284. RevTree[] trees = new RevTree[1 + cnt];
  285. trees[0] = commit.getTree();
  286. for (int i = 0; i < cnt; i++)
  287. trees[i + 1] = commit.getParent(i).getTree();
  288. tw.reset(trees);
  289. boolean matchAll = true;
  290. while (tw.next()) {
  291. boolean matchOne = false;
  292. for (int i = 1; i <= cnt; i++) {
  293. if (tw.getRawMode(0) == tw.getRawMode(i)
  294. && tw.idEqual(0, i)) {
  295. matchOne = true;
  296. break;
  297. }
  298. }
  299. if (!matchOne) {
  300. matchAll = false;
  301. break;
  302. }
  303. }
  304. if (matchAll)
  305. continue;
  306. }
  307. Contributor contributor = contributorsByName.get(author.getName());
  308. if (contributor == null) {
  309. String id = author.getEmailAddress();
  310. String name = author.getName();
  311. contributor = new Contributor(id, name);
  312. contributorsByName.put(name, contributor);
  313. }
  314. String id = commit.name();
  315. String subj = commit.getShortMessage();
  316. SingleContribution item = new SingleContribution(id, when, subj);
  317. if (2 <= cnt) {
  318. item.setSize("(merge)");
  319. contributor.add(item);
  320. continue;
  321. }
  322. int addedLines = 0;
  323. if (1 == cnt) {
  324. final RevCommit parent = commit.getParent(0);
  325. tw.setFilter(TreeFilter.ANY_DIFF);
  326. tw.setRecursive(true);
  327. tw.reset(new RevTree[] { parent.getTree(), commit.getTree() });
  328. while (tw.next()) {
  329. if (tw.getFileMode(1).getObjectType() != Constants.OBJ_BLOB)
  330. continue;
  331. byte[] oldImage;
  332. if (tw.getFileMode(0).getObjectType() == Constants.OBJ_BLOB)
  333. oldImage = openBlob(0);
  334. else
  335. oldImage = new byte[0];
  336. EditList edits = new MyersDiff<RawText>(
  337. RawTextComparator.DEFAULT, new RawText(oldImage),
  338. new RawText(openBlob(1))).getEdits();
  339. for (Edit e : edits)
  340. addedLines += e.getEndB() - e.getBeginB();
  341. }
  342. } else { // no parents, everything is an addition
  343. tw.setFilter(TreeFilter.ALL);
  344. tw.setRecursive(true);
  345. tw.reset(commit.getTree());
  346. while (tw.next()) {
  347. if (tw.getFileMode(0).getObjectType() == Constants.OBJ_BLOB) {
  348. byte[] buf = openBlob(0);
  349. for (int ptr = 0; ptr < buf.length;) {
  350. ptr = RawParseUtils.nextLF(buf, ptr);
  351. addedLines++;
  352. }
  353. }
  354. }
  355. }
  356. if (addedLines < 0)
  357. throw new IOException(MessageFormat.format(IpLogText.get().incorrectlyScanned, commit.name()));
  358. if (1 == addedLines)
  359. item.setSize("+1 line");
  360. else
  361. item.setSize("+" + addedLines + " lines");
  362. contributor.add(item);
  363. }
  364. }
  365. private byte[] openBlob(int side) throws IOException {
  366. tw.getObjectId(idbuf, side);
  367. return curs.open(idbuf, Constants.OBJ_BLOB).getCachedBytes();
  368. }
  369. /**
  370. * Dump the scanned information into an XML file.
  371. *
  372. * @param out
  373. * the file stream to write to. The caller is responsible for
  374. * closing the stream upon completion.
  375. * @throws IOException
  376. * the stream cannot be written.
  377. */
  378. public void writeTo(OutputStream out) throws IOException {
  379. try {
  380. TransformerFactory factory = TransformerFactory.newInstance();
  381. Transformer s = factory.newTransformer();
  382. s.setOutputProperty(OutputKeys.ENCODING, characterEncoding);
  383. s.setOutputProperty(OutputKeys.METHOD, "xml");
  384. s.setOutputProperty(OutputKeys.INDENT, "yes");
  385. s.setOutputProperty(INDENT, "2");
  386. s.transform(new DOMSource(toXML()), new StreamResult(out));
  387. } catch (ParserConfigurationException e) {
  388. IOException err = new IOException(IpLogText.get().cannotSerializeXML);
  389. err.initCause(e);
  390. throw err;
  391. } catch (TransformerConfigurationException e) {
  392. IOException err = new IOException(IpLogText.get().cannotSerializeXML);
  393. err.initCause(e);
  394. throw err;
  395. } catch (TransformerException e) {
  396. IOException err = new IOException(IpLogText.get().cannotSerializeXML);
  397. err.initCause(e);
  398. throw err;
  399. }
  400. }
  401. private Document toXML() throws ParserConfigurationException {
  402. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  403. factory.setNamespaceAware(true);
  404. doc = factory.newDocumentBuilder().newDocument();
  405. Element root = createElement("iplog");
  406. doc.appendChild(root);
  407. if (projects.size() == 1) {
  408. Project soleProject = projects.values().iterator().next();
  409. root.setAttribute("name", soleProject.getID());
  410. }
  411. Set<String> licenses = new TreeSet<String>();
  412. for (Project project : sort(projects, Project.COMPARATOR)) {
  413. root.appendChild(createProject(project));
  414. licenses.addAll(project.getLicenses());
  415. }
  416. if (!consumedProjects.isEmpty())
  417. appendBlankLine(root);
  418. for (Project project : sort(consumedProjects, Project.COMPARATOR)) {
  419. root.appendChild(createConsumes(project));
  420. licenses.addAll(project.getLicenses());
  421. }
  422. for (RevCommit c : sort(commits))
  423. root.appendChild(createCommitMeta(c));
  424. if (licenses.size() > 1)
  425. appendBlankLine(root);
  426. for (String name : sort(licenses))
  427. root.appendChild(createLicense(name));
  428. if (!cqs.isEmpty())
  429. appendBlankLine(root);
  430. for (CQ cq : sort(cqs, CQ.COMPARATOR))
  431. root.appendChild(createCQ(cq));
  432. if (!committersByEmail.isEmpty())
  433. appendBlankLine(root);
  434. for (Committer committer : sort(committersById, Committer.COMPARATOR))
  435. root.appendChild(createCommitter(committer));
  436. for (Contributor c : sort(contributorsByName, Contributor.COMPARATOR)) {
  437. appendBlankLine(root);
  438. root.appendChild(createContributor(c));
  439. }
  440. return doc;
  441. }
  442. private void appendBlankLine(Element root) {
  443. root.appendChild(doc.createTextNode("\n\n "));
  444. }
  445. private Element createProject(Project p) {
  446. Element project = createElement("project");
  447. populateProjectType(p, project);
  448. return project;
  449. }
  450. private Element createConsumes(Project p) {
  451. Element project = createElement("consumes");
  452. populateProjectType(p, project);
  453. return project;
  454. }
  455. private void populateProjectType(Project p, Element project) {
  456. required(project, "id", p.getID());
  457. required(project, "name", p.getName());
  458. optional(project, "comments", p.getComments());
  459. optional(project, "version", p.getVersion());
  460. }
  461. private Element createCommitMeta(RevCommit c) {
  462. Element meta = createElement("meta");
  463. required(meta, "key", "git-commit");
  464. required(meta, "value", c.name());
  465. return meta;
  466. }
  467. private Element createLicense(String name) {
  468. Element license = createElement("license");
  469. required(license, "id", name);
  470. optional(license, "description", null);
  471. optional(license, "comments", null);
  472. return license;
  473. }
  474. private Element createCQ(CQ cq) {
  475. Element r = createElement("cq");
  476. required(r, "id", Long.toString(cq.getID()));
  477. required(r, "description", cq.getDescription());
  478. optional(r, "license", cq.getLicense());
  479. optional(r, "use", cq.getUse());
  480. optional(r, "state", cq.getState());
  481. optional(r, "comments", cq.getComments());
  482. return r;
  483. }
  484. private Element createCommitter(Committer who) {
  485. Element r = createElement("committer");
  486. required(r, "id", who.getID());
  487. required(r, "firstName", who.getFirstName());
  488. required(r, "lastName", who.getLastName());
  489. optional(r, "affiliation", who.getAffiliation());
  490. required(r, "active", Boolean.toString(who.isActive()));
  491. required(r, "hasCommits", Boolean.toString(who.hasCommits()));
  492. optional(r, "comments", who.getComments());
  493. return r;
  494. }
  495. private Element createContributor(Contributor c) {
  496. Element r = createElement("contributor");
  497. required(r, "id", c.getID());
  498. required(r, "name", c.getName());
  499. for (SingleContribution s : sort(c.getContributions(),
  500. SingleContribution.COMPARATOR))
  501. r.appendChild(createContribution(s));
  502. return r;
  503. }
  504. private Element createContribution(SingleContribution s) {
  505. Element r = createElement("contribution");
  506. required(r, "id", s.getID());
  507. required(r, "description", s.getSummary());
  508. required(r, "size", s.getSize());
  509. if (reviewUrl != null)
  510. optional(r, "url", reviewUrl + s.getID());
  511. return r;
  512. }
  513. private Element createElement(String name) {
  514. return doc.createElementNS(IPLOG_NS, IPLOG_PFX + name);
  515. }
  516. private void required(Element r, String name, String value) {
  517. if (value == null)
  518. value = "";
  519. r.setAttribute(name, value);
  520. }
  521. private void optional(Element r, String name, String value) {
  522. if (value != null && value.length() > 0)
  523. r.setAttribute(name, value);
  524. }
  525. private static <T, Q extends Comparator<T>> Iterable<T> sort(
  526. Collection<T> objs, Q cmp) {
  527. ArrayList<T> sorted = new ArrayList<T>(objs);
  528. Collections.sort(sorted, cmp);
  529. return sorted;
  530. }
  531. private static <T, Q extends Comparator<T>> Iterable<T> sort(
  532. Map<?, T> objs, Q cmp) {
  533. return sort(objs.values(), cmp);
  534. }
  535. @SuppressWarnings("unchecked")
  536. private static <T extends Comparable> Iterable<T> sort(Collection<T> objs) {
  537. ArrayList<T> sorted = new ArrayList<T>(objs);
  538. Collections.sort(sorted);
  539. return sorted;
  540. }
  541. }