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.

RefLogUtils.java 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. /*
  2. * Copyright 2013 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.utils;
  17. import java.io.IOException;
  18. import java.text.DateFormat;
  19. import java.text.MessageFormat;
  20. import java.text.SimpleDateFormat;
  21. import java.util.ArrayList;
  22. import java.util.Arrays;
  23. import java.util.Collection;
  24. import java.util.Collections;
  25. import java.util.Date;
  26. import java.util.HashMap;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Set;
  30. import java.util.TimeZone;
  31. import java.util.TreeSet;
  32. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  33. import org.eclipse.jgit.api.errors.JGitInternalException;
  34. import org.eclipse.jgit.dircache.DirCache;
  35. import org.eclipse.jgit.dircache.DirCacheBuilder;
  36. import org.eclipse.jgit.dircache.DirCacheEntry;
  37. import org.eclipse.jgit.internal.JGitText;
  38. import org.eclipse.jgit.lib.CommitBuilder;
  39. import org.eclipse.jgit.lib.FileMode;
  40. import org.eclipse.jgit.lib.ObjectId;
  41. import org.eclipse.jgit.lib.ObjectInserter;
  42. import org.eclipse.jgit.lib.PersonIdent;
  43. import org.eclipse.jgit.lib.Ref;
  44. import org.eclipse.jgit.lib.RefRename;
  45. import org.eclipse.jgit.lib.RefUpdate;
  46. import org.eclipse.jgit.lib.RefUpdate.Result;
  47. import org.eclipse.jgit.lib.Repository;
  48. import org.eclipse.jgit.revwalk.RevCommit;
  49. import org.eclipse.jgit.revwalk.RevWalk;
  50. import org.eclipse.jgit.transport.ReceiveCommand;
  51. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  52. import org.eclipse.jgit.treewalk.TreeWalk;
  53. import org.slf4j.Logger;
  54. import org.slf4j.LoggerFactory;
  55. import com.gitblit.Constants;
  56. import com.gitblit.models.DailyLogEntry;
  57. import com.gitblit.models.PathModel.PathChangeModel;
  58. import com.gitblit.models.RefLogEntry;
  59. import com.gitblit.models.RefModel;
  60. import com.gitblit.models.RepositoryCommit;
  61. import com.gitblit.models.UserModel;
  62. /**
  63. * Utility class for maintaining a reflog within a git repository on an
  64. * orphan branch.
  65. *
  66. * @author James Moger
  67. *
  68. */
  69. public class RefLogUtils {
  70. private static final String GB_REFLOG = "refs/gitblit/reflog";
  71. private static final Logger LOGGER = LoggerFactory.getLogger(RefLogUtils.class);
  72. /**
  73. * Log an error message and exception.
  74. *
  75. * @param t
  76. * @param repository
  77. * if repository is not null it MUST be the {0} parameter in the
  78. * pattern.
  79. * @param pattern
  80. * @param objects
  81. */
  82. private static void error(Throwable t, Repository repository, String pattern, Object... objects) {
  83. List<Object> parameters = new ArrayList<Object>();
  84. if (objects != null && objects.length > 0) {
  85. for (Object o : objects) {
  86. parameters.add(o);
  87. }
  88. }
  89. if (repository != null) {
  90. parameters.add(0, repository.getDirectory().getAbsolutePath());
  91. }
  92. LOGGER.error(MessageFormat.format(pattern, parameters.toArray()), t);
  93. }
  94. /**
  95. * Returns true if the repository has a reflog branch.
  96. *
  97. * @param repository
  98. * @return true if the repository has a reflog branch
  99. */
  100. public static boolean hasRefLogBranch(Repository repository) {
  101. try {
  102. return repository.getRef(GB_REFLOG) != null;
  103. } catch(Exception e) {
  104. LOGGER.error("failed to determine hasRefLogBranch", e);
  105. }
  106. return false;
  107. }
  108. /**
  109. * Returns a RefModel for the reflog branch in the repository. If the
  110. * branch can not be found, null is returned.
  111. *
  112. * @param repository
  113. * @return a refmodel for the reflog branch or null
  114. */
  115. public static RefModel getRefLogBranch(Repository repository) {
  116. List<RefModel> refs = JGitUtils.getRefs(repository, com.gitblit.Constants.R_GITBLIT);
  117. RefModel pushLog = null;
  118. final String GB_PUSHES = "refs/gitblit/pushes";
  119. for (RefModel ref : refs) {
  120. if (ref.reference.getName().equals(GB_REFLOG)) {
  121. return ref;
  122. } else if (ref.reference.getName().equals(GB_PUSHES)) {
  123. pushLog = ref;
  124. }
  125. }
  126. if (pushLog != null) {
  127. // rename refs/gitblit/pushes to refs/gitblit/reflog
  128. RefRename cmd;
  129. try {
  130. cmd = repository.renameRef(GB_PUSHES, GB_REFLOG);
  131. cmd.setRefLogIdent(new PersonIdent("Gitblit", "gitblit@localhost"));
  132. cmd.setRefLogMessage("renamed " + GB_PUSHES + " => " + GB_REFLOG);
  133. Result res = cmd.rename();
  134. switch (res) {
  135. case RENAMED:
  136. return getRefLogBranch(repository);
  137. default:
  138. LOGGER.error("failed to rename " + GB_PUSHES + " => " + GB_REFLOG + " (" + res.name() + ")");
  139. }
  140. } catch (IOException e) {
  141. LOGGER.error("failed to rename pushlog", e);
  142. }
  143. }
  144. return null;
  145. }
  146. private static UserModel newUserModelFrom(PersonIdent ident) {
  147. String name = ident.getName();
  148. String username;
  149. String displayname;
  150. if (name.indexOf('/') > -1) {
  151. int slash = name.indexOf('/');
  152. displayname = name.substring(0, slash);
  153. username = name.substring(slash + 1);
  154. } else {
  155. displayname = name;
  156. username = ident.getEmailAddress();
  157. }
  158. UserModel user = new UserModel(username);
  159. user.displayName = displayname;
  160. user.emailAddress = ident.getEmailAddress();
  161. return user;
  162. }
  163. /**
  164. * Logs a ref deletion.
  165. *
  166. * @param user
  167. * @param repository
  168. * @param ref
  169. * @return true, if the update was successful
  170. */
  171. public static boolean deleteRef(UserModel user, Repository repository, Ref ref) {
  172. try {
  173. if (ref == null) {
  174. return false;
  175. }
  176. RefModel reflogBranch = getRefLogBranch(repository);
  177. if (reflogBranch == null) {
  178. return false;
  179. }
  180. List<RevCommit> log = JGitUtils.getRevLog(repository, reflogBranch.getName(), ref.getName(), 0, 1);
  181. if (log.isEmpty()) {
  182. // this ref is not in the reflog branch
  183. return false;
  184. }
  185. ReceiveCommand cmd = new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), ref.getName());
  186. return updateRefLog(user, repository, Arrays.asList(cmd));
  187. } catch (Throwable t) {
  188. error(t, repository, "Failed to commit reflog entry to {0}");
  189. }
  190. return false;
  191. }
  192. /**
  193. * Updates the reflog with the received commands.
  194. *
  195. * @param user
  196. * @param repository
  197. * @param commands
  198. * @return true, if the update was successful
  199. */
  200. public static boolean updateRefLog(UserModel user, Repository repository,
  201. Collection<ReceiveCommand> commands) {
  202. RefModel reflogBranch = getRefLogBranch(repository);
  203. if (reflogBranch == null) {
  204. JGitUtils.createOrphanBranch(repository, GB_REFLOG, null);
  205. }
  206. boolean success = false;
  207. String message = "push";
  208. try {
  209. ObjectId headId = repository.resolve(GB_REFLOG + "^{commit}");
  210. ObjectInserter odi = repository.newObjectInserter();
  211. try {
  212. // Create the in-memory index of the push log entry
  213. DirCache index = createIndex(repository, headId, commands);
  214. ObjectId indexTreeId = index.writeTree(odi);
  215. PersonIdent ident;
  216. if (UserModel.ANONYMOUS.equals(user)) {
  217. // anonymous push
  218. ident = new PersonIdent(user.username + "/" + user.username, user.username);
  219. } else {
  220. // construct real pushing account
  221. ident = new PersonIdent(MessageFormat.format("{0}/{1}", user.getDisplayName(), user.username),
  222. user.emailAddress == null ? user.username : user.emailAddress);
  223. }
  224. // Create a commit object
  225. CommitBuilder commit = new CommitBuilder();
  226. commit.setAuthor(ident);
  227. commit.setCommitter(ident);
  228. commit.setEncoding(Constants.ENCODING);
  229. commit.setMessage(message);
  230. commit.setParentId(headId);
  231. commit.setTreeId(indexTreeId);
  232. // Insert the commit into the repository
  233. ObjectId commitId = odi.insert(commit);
  234. odi.flush();
  235. RevWalk revWalk = new RevWalk(repository);
  236. try {
  237. RevCommit revCommit = revWalk.parseCommit(commitId);
  238. RefUpdate ru = repository.updateRef(GB_REFLOG);
  239. ru.setNewObjectId(commitId);
  240. ru.setExpectedOldObjectId(headId);
  241. ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
  242. Result rc = ru.forceUpdate();
  243. switch (rc) {
  244. case NEW:
  245. case FORCED:
  246. case FAST_FORWARD:
  247. success = true;
  248. break;
  249. case REJECTED:
  250. case LOCK_FAILURE:
  251. throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD,
  252. ru.getRef(), rc);
  253. default:
  254. throw new JGitInternalException(MessageFormat.format(
  255. JGitText.get().updatingRefFailed, GB_REFLOG, commitId.toString(),
  256. rc));
  257. }
  258. } finally {
  259. revWalk.release();
  260. }
  261. } finally {
  262. odi.release();
  263. }
  264. } catch (Throwable t) {
  265. error(t, repository, "Failed to commit reflog entry to {0}");
  266. }
  267. return success;
  268. }
  269. /**
  270. * Creates an in-memory index of the push log entry.
  271. *
  272. * @param repo
  273. * @param headId
  274. * @param commands
  275. * @return an in-memory index
  276. * @throws IOException
  277. */
  278. private static DirCache createIndex(Repository repo, ObjectId headId,
  279. Collection<ReceiveCommand> commands) throws IOException {
  280. DirCache inCoreIndex = DirCache.newInCore();
  281. DirCacheBuilder dcBuilder = inCoreIndex.builder();
  282. ObjectInserter inserter = repo.newObjectInserter();
  283. long now = System.currentTimeMillis();
  284. Set<String> ignorePaths = new TreeSet<String>();
  285. try {
  286. // add receive commands to the temporary index
  287. for (ReceiveCommand command : commands) {
  288. // use the ref names as the path names
  289. String path = command.getRefName();
  290. ignorePaths.add(path);
  291. StringBuilder change = new StringBuilder();
  292. change.append(command.getType().name()).append(' ');
  293. switch (command.getType()) {
  294. case CREATE:
  295. change.append(ObjectId.zeroId().getName());
  296. change.append(' ');
  297. change.append(command.getNewId().getName());
  298. break;
  299. case UPDATE:
  300. case UPDATE_NONFASTFORWARD:
  301. change.append(command.getOldId().getName());
  302. change.append(' ');
  303. change.append(command.getNewId().getName());
  304. break;
  305. case DELETE:
  306. change = null;
  307. break;
  308. }
  309. if (change == null) {
  310. // ref deleted
  311. continue;
  312. }
  313. String content = change.toString();
  314. // create an index entry for this attachment
  315. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  316. dcEntry.setLength(content.length());
  317. dcEntry.setLastModified(now);
  318. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  319. // insert object
  320. dcEntry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, content.getBytes("UTF-8")));
  321. // add to temporary in-core index
  322. dcBuilder.add(dcEntry);
  323. }
  324. // Traverse HEAD to add all other paths
  325. TreeWalk treeWalk = new TreeWalk(repo);
  326. int hIdx = -1;
  327. if (headId != null)
  328. hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
  329. treeWalk.setRecursive(true);
  330. while (treeWalk.next()) {
  331. String path = treeWalk.getPathString();
  332. CanonicalTreeParser hTree = null;
  333. if (hIdx != -1)
  334. hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
  335. if (!ignorePaths.contains(path)) {
  336. // add entries from HEAD for all other paths
  337. if (hTree != null) {
  338. // create a new DirCacheEntry with data retrieved from
  339. // HEAD
  340. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  341. dcEntry.setObjectId(hTree.getEntryObjectId());
  342. dcEntry.setFileMode(hTree.getEntryFileMode());
  343. // add to temporary in-core index
  344. dcBuilder.add(dcEntry);
  345. }
  346. }
  347. }
  348. // release the treewalk
  349. treeWalk.release();
  350. // finish temporary in-core index used for this commit
  351. dcBuilder.finish();
  352. } finally {
  353. inserter.release();
  354. }
  355. return inCoreIndex;
  356. }
  357. public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository) {
  358. return getRefLog(repositoryName, repository, null, 0, -1);
  359. }
  360. public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository, int maxCount) {
  361. return getRefLog(repositoryName, repository, null, 0, maxCount);
  362. }
  363. public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository, int offset, int maxCount) {
  364. return getRefLog(repositoryName, repository, null, offset, maxCount);
  365. }
  366. public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository, Date minimumDate) {
  367. return getRefLog(repositoryName, repository, minimumDate, 0, -1);
  368. }
  369. /**
  370. * Returns the list of reflog entries as they were recorded by Gitblit.
  371. * Each RefLogEntry may represent multiple ref updates.
  372. *
  373. * @param repositoryName
  374. * @param repository
  375. * @param minimumDate
  376. * @param offset
  377. * @param maxCount
  378. * if < 0, all pushes are returned.
  379. * @return a list of push log entries
  380. */
  381. public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository,
  382. Date minimumDate, int offset, int maxCount) {
  383. List<RefLogEntry> list = new ArrayList<RefLogEntry>();
  384. RefModel ref = getRefLogBranch(repository);
  385. if (ref == null) {
  386. return list;
  387. }
  388. if (maxCount == 0) {
  389. return list;
  390. }
  391. Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository);
  392. List<RevCommit> pushes;
  393. if (minimumDate == null) {
  394. pushes = JGitUtils.getRevLog(repository, GB_REFLOG, offset, maxCount);
  395. } else {
  396. pushes = JGitUtils.getRevLog(repository, GB_REFLOG, minimumDate);
  397. }
  398. for (RevCommit push : pushes) {
  399. if (push.getAuthorIdent().getName().equalsIgnoreCase("gitblit")) {
  400. // skip gitblit/internal commits
  401. continue;
  402. }
  403. UserModel user = newUserModelFrom(push.getAuthorIdent());
  404. Date date = push.getAuthorIdent().getWhen();
  405. RefLogEntry log = new RefLogEntry(repositoryName, date, user);
  406. List<PathChangeModel> changedRefs = JGitUtils.getFilesInCommit(repository, push);
  407. if (changedRefs.isEmpty()) {
  408. // skip empty commits
  409. continue;
  410. }
  411. list.add(log);
  412. for (PathChangeModel change : changedRefs) {
  413. switch (change.changeType) {
  414. case DELETE:
  415. log.updateRef(change.path, ReceiveCommand.Type.DELETE);
  416. break;
  417. case ADD:
  418. log.updateRef(change.path, ReceiveCommand.Type.CREATE);
  419. default:
  420. String content = JGitUtils.getStringContent(repository, push.getTree(), change.path);
  421. String [] fields = content.split(" ");
  422. String oldId = fields[1];
  423. String newId = fields[2];
  424. log.updateRef(change.path, ReceiveCommand.Type.valueOf(fields[0]), oldId, newId);
  425. if (ObjectId.zeroId().getName().equals(newId)) {
  426. // ref deletion
  427. continue;
  428. }
  429. List<RevCommit> pushedCommits = JGitUtils.getRevLog(repository, oldId, newId);
  430. for (RevCommit pushedCommit : pushedCommits) {
  431. RepositoryCommit repoCommit = log.addCommit(change.path, pushedCommit);
  432. if (repoCommit != null) {
  433. repoCommit.setRefs(allRefs.get(pushedCommit.getId()));
  434. }
  435. }
  436. }
  437. }
  438. }
  439. Collections.sort(list);
  440. return list;
  441. }
  442. /**
  443. * Returns the list of pushes separated by ref (e.g. each ref has it's own
  444. * PushLogEntry object).
  445. *
  446. * @param repositoryName
  447. * @param repository
  448. * @param maxCount
  449. * @return a list of push log entries separated by ref
  450. */
  451. public static List<RefLogEntry> getLogByRef(String repositoryName, Repository repository, int maxCount) {
  452. return getLogByRef(repositoryName, repository, 0, maxCount);
  453. }
  454. /**
  455. * Returns the list of pushes separated by ref (e.g. each ref has it's own
  456. * PushLogEntry object).
  457. *
  458. * @param repositoryName
  459. * @param repository
  460. * @param offset
  461. * @param maxCount
  462. * @return a list of push log entries separated by ref
  463. */
  464. public static List<RefLogEntry> getLogByRef(String repositoryName, Repository repository, int offset,
  465. int maxCount) {
  466. // break the push log into ref push logs and then merge them back into a list
  467. Map<String, List<RefLogEntry>> refMap = new HashMap<String, List<RefLogEntry>>();
  468. List<RefLogEntry> refLog = getRefLog(repositoryName, repository, offset, maxCount);
  469. for (RefLogEntry entry : refLog) {
  470. for (String ref : entry.getChangedRefs()) {
  471. if (!refMap.containsKey(ref)) {
  472. refMap.put(ref, new ArrayList<RefLogEntry>());
  473. }
  474. // construct new ref-specific ref change entry
  475. RefLogEntry refChange;
  476. if (entry instanceof DailyLogEntry) {
  477. // simulated push log from commits grouped by date
  478. refChange = new DailyLogEntry(entry.repository, entry.date);
  479. } else {
  480. // real push log entry
  481. refChange = new RefLogEntry(entry.repository, entry.date, entry.user);
  482. }
  483. refChange.updateRef(ref, entry.getChangeType(ref), entry.getOldId(ref), entry.getNewId(ref));
  484. refChange.addCommits(entry.getCommits(ref));
  485. refMap.get(ref).add(refChange);
  486. }
  487. }
  488. // merge individual ref changes into master list
  489. List<RefLogEntry> mergedRefLog = new ArrayList<RefLogEntry>();
  490. for (List<RefLogEntry> refPush : refMap.values()) {
  491. mergedRefLog.addAll(refPush);
  492. }
  493. // sort ref log
  494. Collections.sort(mergedRefLog);
  495. return mergedRefLog;
  496. }
  497. /**
  498. * Returns the list of ref changes separated by ref (e.g. each ref has it's own
  499. * RefLogEntry object).
  500. *
  501. * @param repositoryName
  502. * @param repository
  503. * @param minimumDate
  504. * @return a list of ref log entries separated by ref
  505. */
  506. public static List<RefLogEntry> getLogByRef(String repositoryName, Repository repository, Date minimumDate) {
  507. // break the push log into ref push logs and then merge them back into a list
  508. Map<String, List<RefLogEntry>> refMap = new HashMap<String, List<RefLogEntry>>();
  509. List<RefLogEntry> pushes = getRefLog(repositoryName, repository, minimumDate);
  510. for (RefLogEntry push : pushes) {
  511. for (String ref : push.getChangedRefs()) {
  512. if (!refMap.containsKey(ref)) {
  513. refMap.put(ref, new ArrayList<RefLogEntry>());
  514. }
  515. // construct new ref-specific push log entry
  516. RefLogEntry refPush = new RefLogEntry(push.repository, push.date, push.user);
  517. refPush.updateRef(ref, push.getChangeType(ref), push.getOldId(ref), push.getNewId(ref));
  518. refPush.addCommits(push.getCommits(ref));
  519. refMap.get(ref).add(refPush);
  520. }
  521. }
  522. // merge individual ref pushes into master list
  523. List<RefLogEntry> refPushLog = new ArrayList<RefLogEntry>();
  524. for (List<RefLogEntry> refPush : refMap.values()) {
  525. refPushLog.addAll(refPush);
  526. }
  527. // sort ref push log
  528. Collections.sort(refPushLog);
  529. return refPushLog;
  530. }
  531. /**
  532. * Returns a commit log grouped by day.
  533. *
  534. * @param repositoryName
  535. * @param repository
  536. * @param minimumDate
  537. * @param offset
  538. * @param maxCount
  539. * if < 0, all pushes are returned.
  540. * @param the timezone to use when aggregating commits by date
  541. * @return a list of grouped commit log entries
  542. */
  543. public static List<DailyLogEntry> getDailyLog(String repositoryName, Repository repository,
  544. Date minimumDate, int offset, int maxCount,
  545. TimeZone timezone) {
  546. DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
  547. df.setTimeZone(timezone);
  548. Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository);
  549. Map<String, DailyLogEntry> tags = new HashMap<String, DailyLogEntry>();
  550. Map<String, DailyLogEntry> pulls = new HashMap<String, DailyLogEntry>();
  551. Map<String, DailyLogEntry> dailydigests = new HashMap<String, DailyLogEntry>();
  552. String linearParent = null;
  553. for (RefModel local : JGitUtils.getLocalBranches(repository, true, -1)) {
  554. if (!local.getDate().after(minimumDate)) {
  555. // branch not recently updated
  556. continue;
  557. }
  558. String branch = local.getName();
  559. List<RepositoryCommit> commits = CommitCache.instance().getCommits(repositoryName, repository, branch, minimumDate);
  560. linearParent = null;
  561. for (RepositoryCommit commit : commits) {
  562. if (linearParent != null) {
  563. if (!commit.getName().equals(linearParent)) {
  564. // only follow linear branch commits
  565. continue;
  566. }
  567. }
  568. Date date = commit.getCommitDate();
  569. String dateStr = df.format(date);
  570. if (!dailydigests.containsKey(dateStr)) {
  571. dailydigests.put(dateStr, new DailyLogEntry(repositoryName, date));
  572. }
  573. DailyLogEntry digest = dailydigests.get(dateStr);
  574. if (commit.getParentCount() == 0) {
  575. linearParent = null;
  576. digest.updateRef(branch, ReceiveCommand.Type.CREATE);
  577. } else {
  578. linearParent = commit.getParents()[0].getId().getName();
  579. digest.updateRef(branch, ReceiveCommand.Type.UPDATE, linearParent, commit.getName());
  580. }
  581. RepositoryCommit repoCommit = digest.addCommit(commit);
  582. if (repoCommit != null) {
  583. List<RefModel> matchedRefs = allRefs.get(commit.getId());
  584. repoCommit.setRefs(matchedRefs);
  585. if (!ArrayUtils.isEmpty(matchedRefs)) {
  586. for (RefModel ref : matchedRefs) {
  587. if (ref.getName().startsWith(Constants.R_TAGS)) {
  588. // treat tags as special events in the log
  589. if (!tags.containsKey(dateStr)) {
  590. UserModel tagUser = newUserModelFrom(ref.getAuthorIdent());
  591. Date tagDate = commit.getAuthorIdent().getWhen();
  592. tags.put(dateStr, new DailyLogEntry(repositoryName, tagDate, tagUser));
  593. }
  594. RefLogEntry tagEntry = tags.get(dateStr);
  595. tagEntry.updateRef(ref.getName(), ReceiveCommand.Type.CREATE);
  596. RepositoryCommit rc = repoCommit.clone(ref.getName());
  597. tagEntry.addCommit(rc);
  598. } else if (ref.getName().startsWith(Constants.R_PULL)) {
  599. // treat pull requests as special events in the log
  600. if (!pulls.containsKey(dateStr)) {
  601. UserModel commitUser = newUserModelFrom(ref.getAuthorIdent());
  602. Date commitDate = commit.getAuthorIdent().getWhen();
  603. pulls.put(dateStr, new DailyLogEntry(repositoryName, commitDate, commitUser));
  604. }
  605. RefLogEntry pullEntry = pulls.get(dateStr);
  606. pullEntry.updateRef(ref.getName(), ReceiveCommand.Type.CREATE);
  607. RepositoryCommit rc = repoCommit.clone(ref.getName());
  608. pullEntry.addCommit(rc);
  609. }
  610. }
  611. }
  612. }
  613. }
  614. }
  615. List<DailyLogEntry> list = new ArrayList<DailyLogEntry>(dailydigests.values());
  616. list.addAll(tags.values());
  617. //list.addAll(pulls.values());
  618. Collections.sort(list);
  619. return list;
  620. }
  621. /**
  622. * Returns the list of commits separated by ref (e.g. each ref has it's own
  623. * PushLogEntry object for each day).
  624. *
  625. * @param repositoryName
  626. * @param repository
  627. * @param minimumDate
  628. * @param the timezone to use when aggregating commits by date
  629. * @return a list of push log entries separated by ref and date
  630. */
  631. public static List<DailyLogEntry> getDailyLogByRef(String repositoryName, Repository repository,
  632. Date minimumDate, TimeZone timezone) {
  633. // break the push log into ref push logs and then merge them back into a list
  634. Map<String, List<DailyLogEntry>> refMap = new HashMap<String, List<DailyLogEntry>>();
  635. List<DailyLogEntry> pushes = getDailyLog(repositoryName, repository, minimumDate, 0, -1, timezone);
  636. for (DailyLogEntry push : pushes) {
  637. for (String ref : push.getChangedRefs()) {
  638. if (!refMap.containsKey(ref)) {
  639. refMap.put(ref, new ArrayList<DailyLogEntry>());
  640. }
  641. // construct new ref-specific push log entry
  642. DailyLogEntry refPush = new DailyLogEntry(push.repository, push.date, push.user);
  643. refPush.updateRef(ref, push.getChangeType(ref), push.getOldId(ref), push.getNewId(ref));
  644. refPush.addCommits(push.getCommits(ref));
  645. refMap.get(ref).add(refPush);
  646. }
  647. }
  648. // merge individual ref pushes into master list
  649. List<DailyLogEntry> refPushLog = new ArrayList<DailyLogEntry>();
  650. for (List<DailyLogEntry> refPush : refMap.values()) {
  651. for (DailyLogEntry entry : refPush) {
  652. if (entry.getCommitCount() > 0) {
  653. refPushLog.add(entry);
  654. }
  655. }
  656. }
  657. // sort ref push log
  658. Collections.sort(refPushLog);
  659. return refPushLog;
  660. }
  661. }