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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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, String ref) {
  172. try {
  173. Ref refObj = repository.getRef(ref);
  174. if (refObj == null && !ref.startsWith(Constants.R_HEADS) && ref.startsWith(Constants.R_TAGS)) {
  175. // find fully qualified ref
  176. refObj = repository.getRef(Constants.R_HEADS + ref);
  177. if (refObj == null) {
  178. refObj = repository.getRef(Constants.R_TAGS + ref);
  179. }
  180. }
  181. if (refObj == null) {
  182. return false;
  183. }
  184. ReceiveCommand cmd = new ReceiveCommand(refObj.getObjectId(), ObjectId.zeroId(), refObj.getName());
  185. return updateRefLog(user, repository, Arrays.asList(cmd));
  186. } catch (Throwable t) {
  187. error(t, repository, "Failed to commit reflog entry to {0}");
  188. }
  189. return false;
  190. }
  191. /**
  192. * Updates the reflog with the received commands.
  193. *
  194. * @param user
  195. * @param repository
  196. * @param commands
  197. * @return true, if the update was successful
  198. */
  199. public static boolean updateRefLog(UserModel user, Repository repository,
  200. Collection<ReceiveCommand> commands) {
  201. RefModel reflogBranch = getRefLogBranch(repository);
  202. if (reflogBranch == null) {
  203. JGitUtils.createOrphanBranch(repository, GB_REFLOG, null);
  204. }
  205. boolean success = false;
  206. String message = "push";
  207. try {
  208. ObjectId headId = repository.resolve(GB_REFLOG + "^{commit}");
  209. ObjectInserter odi = repository.newObjectInserter();
  210. try {
  211. // Create the in-memory index of the push log entry
  212. DirCache index = createIndex(repository, headId, commands);
  213. ObjectId indexTreeId = index.writeTree(odi);
  214. PersonIdent ident;
  215. if (UserModel.ANONYMOUS.equals(user)) {
  216. // anonymous push
  217. ident = new PersonIdent(user.username + "/" + user.username, user.username);
  218. } else {
  219. // construct real pushing account
  220. ident = new PersonIdent(MessageFormat.format("{0}/{1}", user.getDisplayName(), user.username),
  221. user.emailAddress == null ? user.username : user.emailAddress);
  222. }
  223. // Create a commit object
  224. CommitBuilder commit = new CommitBuilder();
  225. commit.setAuthor(ident);
  226. commit.setCommitter(ident);
  227. commit.setEncoding(Constants.ENCODING);
  228. commit.setMessage(message);
  229. commit.setParentId(headId);
  230. commit.setTreeId(indexTreeId);
  231. // Insert the commit into the repository
  232. ObjectId commitId = odi.insert(commit);
  233. odi.flush();
  234. RevWalk revWalk = new RevWalk(repository);
  235. try {
  236. RevCommit revCommit = revWalk.parseCommit(commitId);
  237. RefUpdate ru = repository.updateRef(GB_REFLOG);
  238. ru.setNewObjectId(commitId);
  239. ru.setExpectedOldObjectId(headId);
  240. ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
  241. Result rc = ru.forceUpdate();
  242. switch (rc) {
  243. case NEW:
  244. case FORCED:
  245. case FAST_FORWARD:
  246. success = true;
  247. break;
  248. case REJECTED:
  249. case LOCK_FAILURE:
  250. throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD,
  251. ru.getRef(), rc);
  252. default:
  253. throw new JGitInternalException(MessageFormat.format(
  254. JGitText.get().updatingRefFailed, GB_REFLOG, commitId.toString(),
  255. rc));
  256. }
  257. } finally {
  258. revWalk.release();
  259. }
  260. } finally {
  261. odi.release();
  262. }
  263. } catch (Throwable t) {
  264. error(t, repository, "Failed to commit reflog entry to {0}");
  265. }
  266. return success;
  267. }
  268. /**
  269. * Creates an in-memory index of the push log entry.
  270. *
  271. * @param repo
  272. * @param headId
  273. * @param commands
  274. * @return an in-memory index
  275. * @throws IOException
  276. */
  277. private static DirCache createIndex(Repository repo, ObjectId headId,
  278. Collection<ReceiveCommand> commands) throws IOException {
  279. DirCache inCoreIndex = DirCache.newInCore();
  280. DirCacheBuilder dcBuilder = inCoreIndex.builder();
  281. ObjectInserter inserter = repo.newObjectInserter();
  282. long now = System.currentTimeMillis();
  283. Set<String> ignorePaths = new TreeSet<String>();
  284. try {
  285. // add receive commands to the temporary index
  286. for (ReceiveCommand command : commands) {
  287. // use the ref names as the path names
  288. String path = command.getRefName();
  289. ignorePaths.add(path);
  290. StringBuilder change = new StringBuilder();
  291. change.append(command.getType().name()).append(' ');
  292. switch (command.getType()) {
  293. case CREATE:
  294. change.append(ObjectId.zeroId().getName());
  295. change.append(' ');
  296. change.append(command.getNewId().getName());
  297. break;
  298. case UPDATE:
  299. case UPDATE_NONFASTFORWARD:
  300. change.append(command.getOldId().getName());
  301. change.append(' ');
  302. change.append(command.getNewId().getName());
  303. break;
  304. case DELETE:
  305. change = null;
  306. break;
  307. }
  308. if (change == null) {
  309. // ref deleted
  310. continue;
  311. }
  312. String content = change.toString();
  313. // create an index entry for this attachment
  314. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  315. dcEntry.setLength(content.length());
  316. dcEntry.setLastModified(now);
  317. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  318. // insert object
  319. dcEntry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, content.getBytes("UTF-8")));
  320. // add to temporary in-core index
  321. dcBuilder.add(dcEntry);
  322. }
  323. // Traverse HEAD to add all other paths
  324. TreeWalk treeWalk = new TreeWalk(repo);
  325. int hIdx = -1;
  326. if (headId != null)
  327. hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
  328. treeWalk.setRecursive(true);
  329. while (treeWalk.next()) {
  330. String path = treeWalk.getPathString();
  331. CanonicalTreeParser hTree = null;
  332. if (hIdx != -1)
  333. hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
  334. if (!ignorePaths.contains(path)) {
  335. // add entries from HEAD for all other paths
  336. if (hTree != null) {
  337. // create a new DirCacheEntry with data retrieved from
  338. // HEAD
  339. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  340. dcEntry.setObjectId(hTree.getEntryObjectId());
  341. dcEntry.setFileMode(hTree.getEntryFileMode());
  342. // add to temporary in-core index
  343. dcBuilder.add(dcEntry);
  344. }
  345. }
  346. }
  347. // release the treewalk
  348. treeWalk.release();
  349. // finish temporary in-core index used for this commit
  350. dcBuilder.finish();
  351. } finally {
  352. inserter.release();
  353. }
  354. return inCoreIndex;
  355. }
  356. public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository) {
  357. return getRefLog(repositoryName, repository, null, 0, -1);
  358. }
  359. public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository, int maxCount) {
  360. return getRefLog(repositoryName, repository, null, 0, maxCount);
  361. }
  362. public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository, int offset, int maxCount) {
  363. return getRefLog(repositoryName, repository, null, offset, maxCount);
  364. }
  365. public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository, Date minimumDate) {
  366. return getRefLog(repositoryName, repository, minimumDate, 0, -1);
  367. }
  368. /**
  369. * Returns the list of reflog entries as they were recorded by Gitblit.
  370. * Each RefLogEntry may represent multiple ref updates.
  371. *
  372. * @param repositoryName
  373. * @param repository
  374. * @param minimumDate
  375. * @param offset
  376. * @param maxCount
  377. * if < 0, all pushes are returned.
  378. * @return a list of push log entries
  379. */
  380. public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository,
  381. Date minimumDate, int offset, int maxCount) {
  382. List<RefLogEntry> list = new ArrayList<RefLogEntry>();
  383. RefModel ref = getRefLogBranch(repository);
  384. if (ref == null) {
  385. return list;
  386. }
  387. if (maxCount == 0) {
  388. return list;
  389. }
  390. Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository);
  391. List<RevCommit> pushes;
  392. if (minimumDate == null) {
  393. pushes = JGitUtils.getRevLog(repository, GB_REFLOG, offset, maxCount);
  394. } else {
  395. pushes = JGitUtils.getRevLog(repository, GB_REFLOG, minimumDate);
  396. }
  397. for (RevCommit push : pushes) {
  398. if (push.getAuthorIdent().getName().equalsIgnoreCase("gitblit")) {
  399. // skip gitblit/internal commits
  400. continue;
  401. }
  402. UserModel user = newUserModelFrom(push.getAuthorIdent());
  403. Date date = push.getAuthorIdent().getWhen();
  404. RefLogEntry log = new RefLogEntry(repositoryName, date, user);
  405. list.add(log);
  406. List<PathChangeModel> changedRefs = JGitUtils.getFilesInCommit(repository, push);
  407. for (PathChangeModel change : changedRefs) {
  408. switch (change.changeType) {
  409. case DELETE:
  410. log.updateRef(change.path, ReceiveCommand.Type.DELETE);
  411. break;
  412. case ADD:
  413. log.updateRef(change.path, ReceiveCommand.Type.CREATE);
  414. default:
  415. String content = JGitUtils.getStringContent(repository, push.getTree(), change.path);
  416. String [] fields = content.split(" ");
  417. String oldId = fields[1];
  418. String newId = fields[2];
  419. log.updateRef(change.path, ReceiveCommand.Type.valueOf(fields[0]), oldId, newId);
  420. List<RevCommit> pushedCommits = JGitUtils.getRevLog(repository, oldId, newId);
  421. for (RevCommit pushedCommit : pushedCommits) {
  422. RepositoryCommit repoCommit = log.addCommit(change.path, pushedCommit);
  423. if (repoCommit != null) {
  424. repoCommit.setRefs(allRefs.get(pushedCommit.getId()));
  425. }
  426. }
  427. }
  428. }
  429. }
  430. Collections.sort(list);
  431. return list;
  432. }
  433. /**
  434. * Returns the list of pushes separated by ref (e.g. each ref has it's own
  435. * PushLogEntry object).
  436. *
  437. * @param repositoryName
  438. * @param repository
  439. * @param maxCount
  440. * @return a list of push log entries separated by ref
  441. */
  442. public static List<RefLogEntry> getLogByRef(String repositoryName, Repository repository, int maxCount) {
  443. return getLogByRef(repositoryName, repository, 0, maxCount);
  444. }
  445. /**
  446. * Returns the list of pushes separated by ref (e.g. each ref has it's own
  447. * PushLogEntry object).
  448. *
  449. * @param repositoryName
  450. * @param repository
  451. * @param offset
  452. * @param maxCount
  453. * @return a list of push log entries separated by ref
  454. */
  455. public static List<RefLogEntry> getLogByRef(String repositoryName, Repository repository, int offset,
  456. int maxCount) {
  457. // break the push log into ref push logs and then merge them back into a list
  458. Map<String, List<RefLogEntry>> refMap = new HashMap<String, List<RefLogEntry>>();
  459. List<RefLogEntry> refLog = getRefLog(repositoryName, repository, offset, maxCount);
  460. for (RefLogEntry entry : refLog) {
  461. for (String ref : entry.getChangedRefs()) {
  462. if (!refMap.containsKey(ref)) {
  463. refMap.put(ref, new ArrayList<RefLogEntry>());
  464. }
  465. // construct new ref-specific ref change entry
  466. RefLogEntry refChange;
  467. if (entry instanceof DailyLogEntry) {
  468. // simulated push log from commits grouped by date
  469. refChange = new DailyLogEntry(entry.repository, entry.date);
  470. } else {
  471. // real push log entry
  472. refChange = new RefLogEntry(entry.repository, entry.date, entry.user);
  473. }
  474. refChange.updateRef(ref, entry.getChangeType(ref), entry.getOldId(ref), entry.getNewId(ref));
  475. refChange.addCommits(entry.getCommits(ref));
  476. refMap.get(ref).add(refChange);
  477. }
  478. }
  479. // merge individual ref changes into master list
  480. List<RefLogEntry> mergedRefLog = new ArrayList<RefLogEntry>();
  481. for (List<RefLogEntry> refPush : refMap.values()) {
  482. mergedRefLog.addAll(refPush);
  483. }
  484. // sort ref log
  485. Collections.sort(mergedRefLog);
  486. return mergedRefLog;
  487. }
  488. /**
  489. * Returns the list of ref changes separated by ref (e.g. each ref has it's own
  490. * RefLogEntry object).
  491. *
  492. * @param repositoryName
  493. * @param repository
  494. * @param minimumDate
  495. * @return a list of ref log entries separated by ref
  496. */
  497. public static List<RefLogEntry> getLogByRef(String repositoryName, Repository repository, Date minimumDate) {
  498. // break the push log into ref push logs and then merge them back into a list
  499. Map<String, List<RefLogEntry>> refMap = new HashMap<String, List<RefLogEntry>>();
  500. List<RefLogEntry> pushes = getRefLog(repositoryName, repository, minimumDate);
  501. for (RefLogEntry push : pushes) {
  502. for (String ref : push.getChangedRefs()) {
  503. if (!refMap.containsKey(ref)) {
  504. refMap.put(ref, new ArrayList<RefLogEntry>());
  505. }
  506. // construct new ref-specific push log entry
  507. RefLogEntry refPush = new RefLogEntry(push.repository, push.date, push.user);
  508. refPush.updateRef(ref, push.getChangeType(ref), push.getOldId(ref), push.getNewId(ref));
  509. refPush.addCommits(push.getCommits(ref));
  510. refMap.get(ref).add(refPush);
  511. }
  512. }
  513. // merge individual ref pushes into master list
  514. List<RefLogEntry> refPushLog = new ArrayList<RefLogEntry>();
  515. for (List<RefLogEntry> refPush : refMap.values()) {
  516. refPushLog.addAll(refPush);
  517. }
  518. // sort ref push log
  519. Collections.sort(refPushLog);
  520. return refPushLog;
  521. }
  522. /**
  523. * Returns a commit log grouped by day.
  524. *
  525. * @param repositoryName
  526. * @param repository
  527. * @param minimumDate
  528. * @param offset
  529. * @param maxCount
  530. * if < 0, all pushes are returned.
  531. * @param the timezone to use when aggregating commits by date
  532. * @return a list of grouped commit log entries
  533. */
  534. public static List<DailyLogEntry> getDailyLog(String repositoryName, Repository repository,
  535. Date minimumDate, int offset, int maxCount,
  536. TimeZone timezone) {
  537. DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
  538. df.setTimeZone(timezone);
  539. Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository);
  540. Map<String, DailyLogEntry> tags = new HashMap<String, DailyLogEntry>();
  541. Map<String, DailyLogEntry> pulls = new HashMap<String, DailyLogEntry>();
  542. Map<String, DailyLogEntry> dailydigests = new HashMap<String, DailyLogEntry>();
  543. String linearParent = null;
  544. for (RefModel local : JGitUtils.getLocalBranches(repository, true, -1)) {
  545. if (!local.getDate().after(minimumDate)) {
  546. // branch not recently updated
  547. continue;
  548. }
  549. String branch = local.getName();
  550. List<RepositoryCommit> commits = CommitCache.instance().getCommits(repositoryName, repository, branch, minimumDate);
  551. linearParent = null;
  552. for (RepositoryCommit commit : commits) {
  553. if (linearParent != null) {
  554. if (!commit.getName().equals(linearParent)) {
  555. // only follow linear branch commits
  556. continue;
  557. }
  558. }
  559. Date date = commit.getCommitDate();
  560. String dateStr = df.format(date);
  561. if (!dailydigests.containsKey(dateStr)) {
  562. dailydigests.put(dateStr, new DailyLogEntry(repositoryName, date));
  563. }
  564. DailyLogEntry digest = dailydigests.get(dateStr);
  565. if (commit.getParentCount() == 0) {
  566. linearParent = null;
  567. digest.updateRef(branch, ReceiveCommand.Type.CREATE);
  568. } else {
  569. linearParent = commit.getParents()[0].getId().getName();
  570. digest.updateRef(branch, ReceiveCommand.Type.UPDATE, linearParent, commit.getName());
  571. }
  572. RepositoryCommit repoCommit = digest.addCommit(commit);
  573. if (repoCommit != null) {
  574. List<RefModel> matchedRefs = allRefs.get(commit.getId());
  575. repoCommit.setRefs(matchedRefs);
  576. if (!ArrayUtils.isEmpty(matchedRefs)) {
  577. for (RefModel ref : matchedRefs) {
  578. if (ref.getName().startsWith(Constants.R_TAGS)) {
  579. // treat tags as special events in the log
  580. if (!tags.containsKey(dateStr)) {
  581. UserModel tagUser = newUserModelFrom(commit.getAuthorIdent());
  582. Date tagDate = commit.getAuthorIdent().getWhen();
  583. tags.put(dateStr, new DailyLogEntry(repositoryName, tagDate, tagUser));
  584. }
  585. RefLogEntry tagEntry = tags.get(dateStr);
  586. tagEntry.updateRef(ref.getName(), ReceiveCommand.Type.CREATE);
  587. RepositoryCommit rc = repoCommit.clone(ref.getName());
  588. tagEntry.addCommit(rc);
  589. } else if (ref.getName().startsWith(Constants.R_PULL)) {
  590. // treat pull requests as special events in the log
  591. if (!pulls.containsKey(dateStr)) {
  592. UserModel commitUser = newUserModelFrom(commit.getAuthorIdent());
  593. Date commitDate = commit.getAuthorIdent().getWhen();
  594. pulls.put(dateStr, new DailyLogEntry(repositoryName, commitDate, commitUser));
  595. }
  596. RefLogEntry pullEntry = pulls.get(dateStr);
  597. pullEntry.updateRef(ref.getName(), ReceiveCommand.Type.CREATE);
  598. RepositoryCommit rc = repoCommit.clone(ref.getName());
  599. pullEntry.addCommit(rc);
  600. }
  601. }
  602. }
  603. }
  604. }
  605. }
  606. List<DailyLogEntry> list = new ArrayList<DailyLogEntry>(dailydigests.values());
  607. list.addAll(tags.values());
  608. //list.addAll(pulls.values());
  609. Collections.sort(list);
  610. return list;
  611. }
  612. /**
  613. * Returns the list of commits separated by ref (e.g. each ref has it's own
  614. * PushLogEntry object for each day).
  615. *
  616. * @param repositoryName
  617. * @param repository
  618. * @param minimumDate
  619. * @param the timezone to use when aggregating commits by date
  620. * @return a list of push log entries separated by ref and date
  621. */
  622. public static List<DailyLogEntry> getDailyLogByRef(String repositoryName, Repository repository,
  623. Date minimumDate, TimeZone timezone) {
  624. // break the push log into ref push logs and then merge them back into a list
  625. Map<String, List<DailyLogEntry>> refMap = new HashMap<String, List<DailyLogEntry>>();
  626. List<DailyLogEntry> pushes = getDailyLog(repositoryName, repository, minimumDate, 0, -1, timezone);
  627. for (DailyLogEntry push : pushes) {
  628. for (String ref : push.getChangedRefs()) {
  629. if (!refMap.containsKey(ref)) {
  630. refMap.put(ref, new ArrayList<DailyLogEntry>());
  631. }
  632. // construct new ref-specific push log entry
  633. DailyLogEntry refPush = new DailyLogEntry(push.repository, push.date, push.user);
  634. refPush.updateRef(ref, push.getChangeType(ref), push.getOldId(ref), push.getNewId(ref));
  635. refPush.addCommits(push.getCommits(ref));
  636. refMap.get(ref).add(refPush);
  637. }
  638. }
  639. // merge individual ref pushes into master list
  640. List<DailyLogEntry> refPushLog = new ArrayList<DailyLogEntry>();
  641. for (List<DailyLogEntry> refPush : refMap.values()) {
  642. for (DailyLogEntry entry : refPush) {
  643. if (entry.getCommitCount() > 0) {
  644. refPushLog.add(entry);
  645. }
  646. }
  647. }
  648. // sort ref push log
  649. Collections.sort(refPushLog);
  650. return refPushLog;
  651. }
  652. }