Search in sources :

Example 21 with RefModel

use of com.gitblit.models.RefModel in project gitblit by gitblit.

the class MetricUtils method getDateMetrics.

/**
	 * Returns the list of metrics for the specified commit reference, branch,
	 * or tag within the repository. If includeTotal is true, the total of all
	 * the metrics will be included as the first element in the returned list.
	 *
	 * If the dateformat is unspecified an attempt is made to determine an
	 * appropriate date format by determining the time difference between the
	 * first commit on the branch and the most recent commit. This assumes that
	 * the commits are linear.
	 *
	 * @param repository
	 * @param objectId
	 *            if null or empty, HEAD is assumed.
	 * @param includeTotal
	 * @param dateFormat
	 * @param timezone
	 * @return list of metrics
	 */
public static List<Metric> getDateMetrics(Repository repository, String objectId, boolean includeTotal, String dateFormat, TimeZone timezone) {
    Metric total = new Metric("TOTAL");
    final Map<String, Metric> metricMap = new HashMap<String, Metric>();
    if (JGitUtils.hasCommits(repository)) {
        final List<RefModel> tags = JGitUtils.getTags(repository, true, -1);
        final Map<ObjectId, RefModel> tagMap = new HashMap<ObjectId, RefModel>();
        for (RefModel tag : tags) {
            tagMap.put(tag.getReferencedObjectId(), tag);
        }
        RevWalk revWalk = null;
        try {
            // resolve branch
            ObjectId branchObject;
            if (StringUtils.isEmpty(objectId)) {
                branchObject = JGitUtils.getDefaultBranch(repository);
            } else {
                branchObject = repository.resolve(objectId);
            }
            revWalk = new RevWalk(repository);
            RevCommit lastCommit = revWalk.parseCommit(branchObject);
            revWalk.markStart(lastCommit);
            DateFormat df;
            if (StringUtils.isEmpty(dateFormat)) {
                // dynamically determine date format
                RevCommit firstCommit = JGitUtils.getFirstCommit(repository, branchObject.getName());
                int diffDays = (lastCommit.getCommitTime() - firstCommit.getCommitTime()) / (60 * 60 * 24);
                total.duration = diffDays;
                if (diffDays <= 365) {
                    // Days
                    df = new SimpleDateFormat("yyyy-MM-dd");
                } else {
                    // Months
                    df = new SimpleDateFormat("yyyy-MM");
                }
            } else {
                // use specified date format
                df = new SimpleDateFormat(dateFormat);
            }
            df.setTimeZone(timezone);
            Iterable<RevCommit> revlog = revWalk;
            for (RevCommit rev : revlog) {
                Date d = JGitUtils.getAuthorDate(rev);
                String p = df.format(d);
                if (!metricMap.containsKey(p)) {
                    metricMap.put(p, new Metric(p));
                }
                Metric m = metricMap.get(p);
                m.count++;
                total.count++;
                if (tagMap.containsKey(rev.getId())) {
                    m.tag++;
                    total.tag++;
                }
            }
        } catch (Throwable t) {
            error(t, repository, "{0} failed to mine log history for date metrics of {1}", objectId);
        } finally {
            if (revWalk != null) {
                revWalk.dispose();
            }
        }
    }
    List<String> keys = new ArrayList<String>(metricMap.keySet());
    Collections.sort(keys);
    List<Metric> metrics = new ArrayList<Metric>();
    for (String key : keys) {
        metrics.add(metricMap.get(key));
    }
    if (includeTotal) {
        metrics.add(0, total);
    }
    return metrics;
}
Also used : RefModel(com.gitblit.models.RefModel) HashMap(java.util.HashMap) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Date(java.util.Date) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) Metric(com.gitblit.models.Metric) SimpleDateFormat(java.text.SimpleDateFormat) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 22 with RefModel

use of com.gitblit.models.RefModel in project gitblit by gitblit.

the class RefLogUtils method getDailyLog.

/**
     * Returns a commit log grouped by day.
     *
     * @param repositoryName
     * @param repository
     * @param minimumDate
     * @param offset
     * @param maxCount
     * 			if < 0, all entries are returned.
     * @param the timezone to use when aggregating commits by date
     * @return a list of grouped commit log entries
     */
public static List<DailyLogEntry> getDailyLog(String repositoryName, Repository repository, Date minimumDate, int offset, int maxCount, TimeZone timezone) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    df.setTimeZone(timezone);
    Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository);
    Map<String, DailyLogEntry> tags = new HashMap<String, DailyLogEntry>();
    Map<String, DailyLogEntry> pulls = new HashMap<String, DailyLogEntry>();
    Map<String, DailyLogEntry> dailydigests = new HashMap<String, DailyLogEntry>();
    String linearParent = null;
    for (RefModel local : JGitUtils.getLocalBranches(repository, true, -1)) {
        if (!local.getDate().after(minimumDate)) {
            // branch not recently updated
            continue;
        }
        String branch = local.getName();
        List<RepositoryCommit> commits = CommitCache.instance().getCommits(repositoryName, repository, branch, minimumDate);
        linearParent = null;
        for (RepositoryCommit commit : commits) {
            if (linearParent != null) {
                if (!commit.getName().equals(linearParent)) {
                    // only follow linear branch commits
                    continue;
                }
            }
            Date date = commit.getCommitDate();
            String dateStr = df.format(date);
            if (!dailydigests.containsKey(dateStr)) {
                dailydigests.put(dateStr, new DailyLogEntry(repositoryName, date));
            }
            DailyLogEntry digest = dailydigests.get(dateStr);
            if (commit.getParentCount() == 0) {
                linearParent = null;
                digest.updateRef(branch, ReceiveCommand.Type.CREATE);
            } else {
                linearParent = commit.getParents()[0].getId().getName();
                digest.updateRef(branch, ReceiveCommand.Type.UPDATE, linearParent, commit.getName());
            }
            RepositoryCommit repoCommit = digest.addCommit(commit);
            if (repoCommit != null) {
                List<RefModel> matchedRefs = allRefs.get(commit.getId());
                repoCommit.setRefs(matchedRefs);
                if (!ArrayUtils.isEmpty(matchedRefs)) {
                    for (RefModel ref : matchedRefs) {
                        if (ref.getName().startsWith(Constants.R_TAGS)) {
                            // treat tags as special events in the log
                            if (!tags.containsKey(dateStr)) {
                                UserModel tagUser = newUserModelFrom(ref.getAuthorIdent());
                                Date tagDate = commit.getAuthorIdent().getWhen();
                                tags.put(dateStr, new DailyLogEntry(repositoryName, tagDate, tagUser));
                            }
                            RefLogEntry tagEntry = tags.get(dateStr);
                            tagEntry.updateRef(ref.getName(), ReceiveCommand.Type.CREATE);
                            RepositoryCommit rc = repoCommit.clone(ref.getName());
                            tagEntry.addCommit(rc);
                        } else if (ref.getName().startsWith(Constants.R_PULL)) {
                            // treat pull requests as special events in the log
                            if (!pulls.containsKey(dateStr)) {
                                UserModel commitUser = newUserModelFrom(ref.getAuthorIdent());
                                Date commitDate = commit.getAuthorIdent().getWhen();
                                pulls.put(dateStr, new DailyLogEntry(repositoryName, commitDate, commitUser));
                            }
                            RefLogEntry pullEntry = pulls.get(dateStr);
                            pullEntry.updateRef(ref.getName(), ReceiveCommand.Type.CREATE);
                            RepositoryCommit rc = repoCommit.clone(ref.getName());
                            pullEntry.addCommit(rc);
                        }
                    }
                }
            }
        }
    }
    List<DailyLogEntry> list = new ArrayList<DailyLogEntry>(dailydigests.values());
    list.addAll(tags.values());
    //list.addAll(pulls.values());
    Collections.sort(list);
    return list;
}
Also used : RefModel(com.gitblit.models.RefModel) ObjectId(org.eclipse.jgit.lib.ObjectId) HashMap(java.util.HashMap) DailyLogEntry(com.gitblit.models.DailyLogEntry) ArrayList(java.util.ArrayList) RepositoryCommit(com.gitblit.models.RepositoryCommit) Date(java.util.Date) RefLogEntry(com.gitblit.models.RefLogEntry) UserModel(com.gitblit.models.UserModel) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) ArrayList(java.util.ArrayList) List(java.util.List) SimpleDateFormat(java.text.SimpleDateFormat)

Example 23 with RefModel

use of com.gitblit.models.RefModel in project gitblit by gitblit.

the class RefLogUtils method getRefLogBranch.

/**
	 * Returns a RefModel for the reflog branch in the repository. If the
	 * branch can not be found, null is returned.
	 *
	 * @param repository
	 * @return a refmodel for the reflog branch or null
	 */
public static RefModel getRefLogBranch(Repository repository) {
    List<RefModel> refs = JGitUtils.getRefs(repository, "refs/");
    Ref oldRef = null;
    for (RefModel ref : refs) {
        if (ref.reference.getName().equals(GB_REFLOG)) {
            return ref;
        } else if (ref.reference.getName().equals("refs/gitblit/reflog")) {
            oldRef = ref.reference;
        } else if (ref.reference.getName().equals("refs/gitblit/pushes")) {
            oldRef = ref.reference;
        }
    }
    if (oldRef != null) {
        // rename old ref to refs/meta/gitblit/reflog
        RefRename cmd;
        try {
            cmd = repository.renameRef(oldRef.getName(), GB_REFLOG);
            cmd.setRefLogIdent(new PersonIdent("Gitblit", "gitblit@localhost"));
            cmd.setRefLogMessage("renamed " + oldRef.getName() + " => " + GB_REFLOG);
            Result res = cmd.rename();
            switch(res) {
                case RENAMED:
                    LOGGER.info(repository.getDirectory() + " " + cmd.getRefLogMessage());
                    return getRefLogBranch(repository);
                default:
                    LOGGER.error("failed to rename " + oldRef.getName() + " => " + GB_REFLOG + " (" + res.name() + ")");
            }
        } catch (IOException e) {
            LOGGER.error("failed to rename reflog", e);
        }
    }
    return null;
}
Also used : Ref(org.eclipse.jgit.lib.Ref) RefModel(com.gitblit.models.RefModel) PersonIdent(org.eclipse.jgit.lib.PersonIdent) IOException(java.io.IOException) RefRename(org.eclipse.jgit.lib.RefRename) Result(org.eclipse.jgit.lib.RefUpdate.Result)

Example 24 with RefModel

use of com.gitblit.models.RefModel in project gitblit by gitblit.

the class RefLogUtils method getRefLog.

/**
	 * Returns the list of reflog entries as they were recorded by Gitblit.
	 * Each RefLogEntry may represent multiple ref updates.
	 *
	 * @param repositoryName
	 * @param repository
	 * @param minimumDate
	 * @param offset
	 * @param maxCount
	 * 			if < 0, all entries are returned.
	 * @return a list of reflog entries
	 */
public static List<RefLogEntry> getRefLog(String repositoryName, Repository repository, Date minimumDate, int offset, int maxCount) {
    List<RefLogEntry> list = new ArrayList<RefLogEntry>();
    RefModel ref = getRefLogBranch(repository);
    if (ref == null) {
        return list;
    }
    if (maxCount == 0) {
        return list;
    }
    Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository);
    List<RevCommit> pushes;
    if (minimumDate == null) {
        pushes = JGitUtils.getRevLog(repository, GB_REFLOG, offset, maxCount);
    } else {
        pushes = JGitUtils.getRevLog(repository, GB_REFLOG, minimumDate);
    }
    for (RevCommit push : pushes) {
        if (push.getAuthorIdent().getName().equalsIgnoreCase("gitblit")) {
            // skip gitblit/internal commits
            continue;
        }
        UserModel user = newUserModelFrom(push.getAuthorIdent());
        Date date = push.getAuthorIdent().getWhen();
        RefLogEntry log = new RefLogEntry(repositoryName, date, user);
        // only report HEADS and TAGS for now
        List<PathChangeModel> changedRefs = new ArrayList<PathChangeModel>();
        for (PathChangeModel refChange : JGitUtils.getFilesInCommit(repository, push)) {
            if (refChange.path.startsWith(Constants.R_HEADS) || refChange.path.startsWith(Constants.R_TAGS)) {
                changedRefs.add(refChange);
            }
        }
        if (changedRefs.isEmpty()) {
            // skip empty commits
            continue;
        }
        list.add(log);
        for (PathChangeModel change : changedRefs) {
            switch(change.changeType) {
                case DELETE:
                    log.updateRef(change.path, ReceiveCommand.Type.DELETE);
                    break;
                default:
                    String content = JGitUtils.getStringContent(repository, push.getTree(), change.path);
                    String[] fields = content.split(" ");
                    String oldId = fields[1];
                    String newId = fields[2];
                    log.updateRef(change.path, ReceiveCommand.Type.valueOf(fields[0]), oldId, newId);
                    if (ObjectId.zeroId().getName().equals(newId)) {
                        // ref deletion
                        continue;
                    }
                    try {
                        List<RevCommit> pushedCommits = JGitUtils.getRevLog(repository, oldId, newId);
                        for (RevCommit pushedCommit : pushedCommits) {
                            RepositoryCommit repoCommit = log.addCommit(change.path, pushedCommit);
                            if (repoCommit != null) {
                                repoCommit.setRefs(allRefs.get(pushedCommit.getId()));
                            }
                        }
                    } catch (Exception e) {
                    }
            }
        }
    }
    Collections.sort(list);
    return list;
}
Also used : RefModel(com.gitblit.models.RefModel) ObjectId(org.eclipse.jgit.lib.ObjectId) PathChangeModel(com.gitblit.models.PathModel.PathChangeModel) ArrayList(java.util.ArrayList) RepositoryCommit(com.gitblit.models.RepositoryCommit) RefLogEntry(com.gitblit.models.RefLogEntry) Date(java.util.Date) ConcurrentRefUpdateException(org.eclipse.jgit.api.errors.ConcurrentRefUpdateException) IOException(java.io.IOException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) UserModel(com.gitblit.models.UserModel) ArrayList(java.util.ArrayList) List(java.util.List) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 25 with RefModel

use of com.gitblit.models.RefModel in project gitblit by gitblit.

the class CommitCache method get.

/**
	 * Returns a list of commits for the specified repository branch.
	 *
	 * @param repositoryName
	 * @param repository
	 * @param branch
	 * @param sinceDate
	 * @return a list of commits
	 */
protected List<RepositoryCommit> get(String repositoryName, Repository repository, String branch, Date sinceDate) {
    Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository, false);
    List<RevCommit> revLog = JGitUtils.getRevLog(repository, branch, sinceDate);
    List<RepositoryCommit> commits = new ArrayList<RepositoryCommit>(revLog.size());
    for (RevCommit commit : revLog) {
        RepositoryCommit commitModel = new RepositoryCommit(repositoryName, branch, commit);
        List<RefModel> commitRefs = allRefs.get(commitModel.getId());
        commitModel.setRefs(commitRefs);
        commits.add(commitModel);
    }
    return commits;
}
Also used : RefModel(com.gitblit.models.RefModel) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) RepositoryCommit(com.gitblit.models.RepositoryCommit) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

RefModel (com.gitblit.models.RefModel)32 ArrayList (java.util.ArrayList)18 ObjectId (org.eclipse.jgit.lib.ObjectId)13 Repository (org.eclipse.jgit.lib.Repository)12 RevCommit (org.eclipse.jgit.revwalk.RevCommit)12 List (java.util.List)10 IOException (java.io.IOException)8 HashMap (java.util.HashMap)8 RepositoryModel (com.gitblit.models.RepositoryModel)6 RepositoryCommit (com.gitblit.models.RepositoryCommit)5 UserModel (com.gitblit.models.UserModel)5 Date (java.util.Date)5 TreeSet (java.util.TreeSet)4 RevWalk (org.eclipse.jgit.revwalk.RevWalk)4 DateFormat (java.text.DateFormat)3 SimpleDateFormat (java.text.SimpleDateFormat)3 IndexWriter (org.apache.lucene.index.IndexWriter)3 Ref (org.eclipse.jgit.lib.Ref)3 GitBlitException (com.gitblit.GitBlitException)2 PathChangeModel (com.gitblit.models.PathModel.PathChangeModel)2