James Moger
2011-06-01 a1ea877042b93949ef244b96e8affd65cc3f89c1
src/com/gitblit/utils/JGitUtils.java
@@ -21,9 +21,7 @@
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -73,16 +71,15 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gitblit.wicket.models.Metric;
import com.gitblit.wicket.models.PathModel;
import com.gitblit.wicket.models.PathModel.PathChangeModel;
import com.gitblit.wicket.models.RefModel;
import com.gitblit.wicket.models.TicketModel;
import com.gitblit.wicket.models.TicketModel.Comment;
import com.gitblit.models.PathModel;
import com.gitblit.models.PathModel.PathChangeModel;
import com.gitblit.models.RefModel;
import com.gitblit.models.TicketModel;
import com.gitblit.models.TicketModel.Comment;
public class JGitUtils {
   private static final Logger LOGGER = LoggerFactory.getLogger(JGitUtils.class);
   static final Logger LOGGER = LoggerFactory.getLogger(JGitUtils.class);
   public static Repository createRepository(File repositoriesFolder, String name, boolean bare) {
      Git git = Git.init().setDirectory(new File(repositoriesFolder, name)).setBare(bare).call();
@@ -100,11 +97,11 @@
   public static List<String> getNestedRepositories(File repositoriesFolder, File folder,
         boolean exportAll, boolean readNested) {
      String basefile = repositoriesFolder.getAbsolutePath();
      List<String> list = new ArrayList<String>();
      if (folder == null || !folder.exists()) {
         return list;
      }
      String basefile = repositoriesFolder.getAbsolutePath();
      for (File file : folder.listFiles()) {
         if (file.isDirectory() && !file.getName().equalsIgnoreCase(Constants.DOT_GIT)) {
            // if this is a git repository add it to the list
@@ -169,25 +166,30 @@
   }
   public static Date getFirstChange(Repository r, String branch) {
      try {
         RevCommit commit = getFirstCommit(r, branch);
         if (commit == null) {
            // fresh repository
            return new Date(r.getDirectory().lastModified());
      RevCommit commit = getFirstCommit(r, branch);
      if (commit == null) {
         if (r == null || !r.getDirectory().exists()) {
            return new Date(0);
         }
         return getCommitDate(commit);
      } catch (Throwable t) {
         LOGGER.error("Failed to determine first change", t);
         // fresh repository
         return new Date(r.getDirectory().lastModified());
      }
      return null;
      return getCommitDate(commit);
   }
   public static boolean hasCommits(Repository r) {
      return new File(r.getDirectory(), Constants.R_HEADS).list().length > 0;
      if (r != null && r.getDirectory().exists()) {
         return new File(r.getDirectory(), Constants.R_HEADS).list().length > 0;
      }
      return false;
   }
   public static Date getLastChange(Repository r) {
      if (!hasCommits(r)) {
         // null repository
         if (r == null) {
            return new Date(0);
         }
         // fresh repository
         return new Date(r.getDirectory().lastModified());
      }
@@ -368,30 +370,41 @@
      }
      try {
         final RevWalk rw = new RevWalk(r);
         RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
         RevTree parentTree = parent.getTree();
         RevTree commitTree = commit.getTree();
         final TreeWalk walk = new TreeWalk(r);
         walk.reset();
         walk.setRecursive(true);
         walk.addTree(parentTree);
         walk.addTree(commitTree);
         walk.setFilter(TreeFilter.ANY_DIFF);
         if (commit.getParentCount() == 0) {
            walk.addTree(commitTree);
            while (walk.next()) {
               list.add(new PathChangeModel(walk.getPathString(), walk.getPathString(), 0,
                     walk.getRawMode(0), commit.getId().getName(), ChangeType.ADD));
            }
         } else {
            RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
            RevTree parentTree = parent.getTree();
            walk.addTree(parentTree);
            walk.addTree(commitTree);
            walk.setFilter(TreeFilter.ANY_DIFF);
         RawTextComparator cmp = RawTextComparator.DEFAULT;
         DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
         df.setRepository(r);
         df.setDiffComparator(cmp);
         df.setDetectRenames(true);
         List<DiffEntry> diffs = df.scan(parentTree, commitTree);
         for (DiffEntry diff : diffs) {
            if (diff.getChangeType().equals(ChangeType.DELETE)) {
               list.add(new PathChangeModel(diff.getOldPath(), diff.getOldPath(), 0, diff
                     .getNewMode().getBits(), commit.getId().getName(), diff.getChangeType()));
            } else {
               list.add(new PathChangeModel(diff.getNewPath(), diff.getNewPath(), 0, diff
                     .getNewMode().getBits(), commit.getId().getName(), diff.getChangeType()));
            RawTextComparator cmp = RawTextComparator.DEFAULT;
            DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
            df.setRepository(r);
            df.setDiffComparator(cmp);
            df.setDetectRenames(true);
            List<DiffEntry> diffs = df.scan(parentTree, commitTree);
            for (DiffEntry diff : diffs) {
               if (diff.getChangeType().equals(ChangeType.DELETE)) {
                  list.add(new PathChangeModel(diff.getOldPath(), diff.getOldPath(), 0, diff
                        .getNewMode().getBits(), commit.getId().getName(), diff
                        .getChangeType()));
               } else {
                  list.add(new PathChangeModel(diff.getNewPath(), diff.getNewPath(), 0, diff
                        .getNewMode().getBits(), commit.getId().getName(), diff
                        .getChangeType()));
               }
            }
         }
      } catch (Throwable t) {
@@ -460,132 +473,6 @@
      }
   }
   public static String getCommitDiff(Repository r, RevCommit commit, DiffOutputType outputType) {
      return getCommitDiff(r, null, commit, null, outputType);
   }
   public static String getCommitDiff(Repository r, RevCommit commit, String path,
         DiffOutputType outputType) {
      return getCommitDiff(r, null, commit, path, outputType);
   }
   public static String getCommitDiff(Repository r, RevCommit baseCommit, RevCommit commit,
         DiffOutputType outputType) {
      return getCommitDiff(r, baseCommit, commit, null, outputType);
   }
   public static String getCommitDiff(Repository r, RevCommit baseCommit, RevCommit commit,
         String path, DiffOutputType outputType) {
      try {
         RevTree baseTree;
         if (baseCommit == null) {
            final RevWalk rw = new RevWalk(r);
            RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
            rw.dispose();
            baseTree = parent.getTree();
         } else {
            baseTree = baseCommit.getTree();
         }
         RevTree commitTree = commit.getTree();
         final TreeWalk walk = new TreeWalk(r);
         walk.reset();
         walk.setRecursive(true);
         walk.addTree(baseTree);
         walk.addTree(commitTree);
         walk.setFilter(TreeFilter.ANY_DIFF);
         final ByteArrayOutputStream os = new ByteArrayOutputStream();
         RawTextComparator cmp = RawTextComparator.DEFAULT;
         DiffFormatter df;
         switch (outputType) {
         case GITWEB:
            df = new GitWebDiffFormatter(os);
            break;
         case GITBLIT:
            df = new GitBlitDiffFormatter(os);
            break;
         case PLAIN:
         default:
            df = new DiffFormatter(os);
            break;
         }
         df.setRepository(r);
         df.setDiffComparator(cmp);
         df.setDetectRenames(true);
         List<DiffEntry> diffs = df.scan(baseTree, commitTree);
         if (path != null && path.length() > 0) {
            for (DiffEntry diff : diffs) {
               if (diff.getNewPath().equalsIgnoreCase(path)) {
                  df.format(diff);
                  break;
               }
            }
         } else {
            df.format(diffs);
         }
         String diff;
         if (df instanceof GitWebDiffFormatter) {
            // workaround for complex private methods in DiffFormatter
            diff = ((GitWebDiffFormatter) df).getHtml();
         } else {
            diff = os.toString();
         }
         df.flush();
         return diff;
      } catch (Throwable t) {
         LOGGER.error("failed to generate commit diff!", t);
      }
      return null;
   }
   public static String getCommitPatch(Repository r, RevCommit baseCommit, RevCommit commit,
         String path) {
      try {
         RevTree baseTree;
         if (baseCommit == null) {
            final RevWalk rw = new RevWalk(r);
            RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
            baseTree = parent.getTree();
         } else {
            baseTree = baseCommit.getTree();
         }
         RevTree commitTree = commit.getTree();
         final TreeWalk walk = new TreeWalk(r);
         walk.reset();
         walk.setRecursive(true);
         walk.addTree(baseTree);
         walk.addTree(commitTree);
         walk.setFilter(TreeFilter.ANY_DIFF);
         final ByteArrayOutputStream os = new ByteArrayOutputStream();
         RawTextComparator cmp = RawTextComparator.DEFAULT;
         PatchFormatter df = new PatchFormatter(os);
         df.setRepository(r);
         df.setDiffComparator(cmp);
         df.setDetectRenames(true);
         List<DiffEntry> diffs = df.scan(baseTree, commitTree);
         if (path != null && path.length() > 0) {
            for (DiffEntry diff : diffs) {
               if (diff.getNewPath().equalsIgnoreCase(path)) {
                  df.format(diff);
                  break;
               }
            }
         } else {
            df.format(diffs);
         }
         String diff = df.getPatch(commit);
         df.flush();
         return diff;
      } catch (Throwable t) {
         LOGGER.error("failed to generate commit diff!", t);
      }
      return null;
   }
   private static PathModel getPathModel(TreeWalk walk, String basePath, RevCommit commit) {
      String name;
      long size = 0;
@@ -628,10 +515,6 @@
         return "missing";
      }
      return "" + mode;
   }
   public static boolean isTreeFromMode(int mode) {
      return FileMode.TREE.equals(mode);
   }
   public static List<RevCommit> getRevLog(Repository r, int maxCount) {
@@ -892,67 +775,6 @@
         rw.dispose();
      }
      return false;
   }
   public static List<Metric> getDateMetrics(Repository r) {
      Metric total = new Metric("TOTAL");
      final Map<String, Metric> metricMap = new HashMap<String, Metric>();
      if (hasCommits(r)) {
         final List<RefModel> tags = getTags(r, -1);
         final Map<ObjectId, RefModel> tagMap = new HashMap<ObjectId, RefModel>();
         for (RefModel tag : tags) {
            tagMap.put(tag.getCommitId(), tag);
         }
         try {
            RevWalk walk = new RevWalk(r);
            ObjectId object = r.resolve(Constants.HEAD);
            RevCommit firstCommit = getFirstCommit(r, Constants.HEAD);
            RevCommit lastCommit = walk.parseCommit(object);
            int diffDays = (lastCommit.getCommitTime() - firstCommit.getCommitTime())
                  / (60 * 60 * 24);
            total.duration = diffDays;
            DateFormat df;
            if (diffDays <= 90) {
               // Days
               df = new SimpleDateFormat("yyyy-MM-dd");
            } else if (diffDays > 90 && diffDays < 365) {
               // Weeks
               df = new SimpleDateFormat("yyyy-MM (w)");
            } else {
               // Months
               df = new SimpleDateFormat("yyyy-MM");
            }
            walk.markStart(lastCommit);
            Iterable<RevCommit> revlog = walk;
            for (RevCommit rev : revlog) {
               Date d = getCommitDate(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) {
            LOGGER.error("Failed to mine log history for metrics", t);
         }
      }
      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));
      }
      metrics.add(0, total);
      return metrics;
   }
   public static RefModel getTicketsBranch(Repository r) {