Пример #1
0
 private String getLatestDiff(Repository repo, ObjectId oldTreeId, ObjectId newTreeId)
     throws IOException {
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   try (DiffFormatter fmt = new DiffFormatter(out)) {
     fmt.setRepository(repo);
     fmt.format(oldTreeId, newTreeId);
     fmt.flush();
     return out.toString();
   }
 }
Пример #2
0
 /**
  * @see org.eclipse.jgit.diff.DiffFormatter#writeLine(char, org.eclipse.jgit.diff.RawText, int)
  */
 protected void writeLine(char prefix, RawText text, int cur) throws IOException {
   if (prefix == ' ') {
     super.writeLine(prefix, text, cur);
     stream.flushLine();
   } else {
     Type type = prefix == '+' ? Type.ADD : Type.REMOVE;
     int start = stream.offset;
     super.writeLine(prefix, text, cur);
     stream.flushLine();
     addRange(type, start, stream.offset);
   }
 }
 @Override
 public void flush() throws IOException {
   if (truncated) {
     os.resetTo(truncateTo);
   }
   super.flush();
 }
Пример #4
0
 /** @see org.eclipse.jgit.diff.DiffFormatter#writeHunkHeader(int, int, int, int) */
 protected void writeHunkHeader(int aStartLine, int aEndLine, int bStartLine, int bEndLine)
     throws IOException {
   int start = stream.offset;
   super.writeHunkHeader(aStartLine, aEndLine, bStartLine, bEndLine);
   stream.flushLine();
   addRange(Type.HUNK, start, stream.offset);
 }
Пример #5
0
  public void buildCompositeCommits() throws IOException {
    revWalk = new RevWalk(repository);
    ByteArrayOutputStream diffTexts = new ByteArrayOutputStream();
    DiffFormatter df = new DiffFormatter(diffTexts);
    df.setRepository(repository);
    df.setDiffComparator(RawTextComparator.WS_IGNORE_ALL);
    df.setContext(0);
    df.setDiffAlgorithm(DiffAlgorithm.getAlgorithm(SupportedAlgorithm.HISTOGRAM));
    df.setDetectRenames(true);
    for (int idx = 0; idx < _commits.size(); idx++) {
      RevCommit commit = revWalk.parseCommit(_commits.get(idx));
      int p_count = commit.getParentCount();
      if (p_count == 0) {
        throw new RuntimeException("commit with no parent ?!?!");
      }
      RevCommit p = revWalk.parseCommit(commit.getParent(0).getId());
      List<DiffEntry> diffs = df.scan(p.getTree(), commit.getTree());
      for (DiffEntry d : diffs) {
        CompositeDiff cd = new CompositeDiff(d, commit);

        if (ParsingUtils.isSourceFile(d.getOldPath())
            || ParsingUtils.isSourceFile(d.getNewPath())) {
          extractCodeEdits(diffTexts, df, d, cd);
        }
        _diffs.add(cd);
      }
    }
    revWalk.release();
  }
Пример #6
0
 /**
  * @see org.eclipse.jgit.diff.DiffFormatter#formatGitDiffFirstHeaderLine(ByteArrayOutputStream o,
  *     ChangeType type, String oldPath, String newPath)
  */
 @Override
 protected void formatGitDiffFirstHeaderLine(
     ByteArrayOutputStream o, final ChangeType type, final String oldPath, final String newPath)
     throws IOException {
   stream.flushLine();
   int offset = stream.offset;
   int start = o.size();
   super.formatGitDiffFirstHeaderLine(o, type, oldPath, newPath);
   int end = o.size();
   addRange(Type.HEADLINE, offset + start, offset + end);
 }
 @Override
 public void format(DiffEntry ent) throws IOException {
   currentPath = diffStat.addPath(ent);
   nofLinesCurrent = 0;
   isOff = false;
   entry = ent;
   if (!truncated) {
     totalNofLinesPrevious = totalNofLinesCurrent;
     if (globalDiffLimit > 0 && totalNofLinesPrevious > globalDiffLimit) {
       truncated = true;
       isOff = true;
     }
     truncateTo = os.size();
   } else {
     isOff = true;
   }
   if (truncated) {
     skipped.add(ent);
   } else {
     // Produce a header here and now
     String path;
     String id;
     if (ChangeType.DELETE.equals(ent.getChangeType())) {
       path = ent.getOldPath();
       id = ent.getOldId().name();
     } else {
       path = ent.getNewPath();
       id = ent.getNewId().name();
     }
     StringBuilder sb =
         new StringBuilder(
             MessageFormat.format(
                 "<div class='header'><div class=\"diffHeader\" id=\"n{0}\"><i class=\"icon-file\"></i> ",
                 id));
     sb.append(StringUtils.escapeForHtml(path, false)).append("</div></div>");
     sb.append("<div class=\"diff\"><table cellpadding='0'><tbody>\n");
     os.write(sb.toString().getBytes());
   }
   // Keep formatting, but if off, don't produce anything anymore. We just keep on counting.
   super.format(ent);
   if (!truncated) {
     // Close the table
     os.write("</tbody></table></div>\n".getBytes());
   }
 }
Пример #8
0
 private void extractCodeEdits(
     ByteArrayOutputStream diffTexts, DiffFormatter df, DiffEntry d, CompositeDiff cd)
     throws IOException {
   df.format(d);
   String[] lines = diffTexts.toString().split("\n");
   for (int i = 0; i < lines.length; i++) {
     StringBuffer block = new StringBuffer(250);
     if (lines[i].startsWith("diff")
         && (lines[i].contains(cd.getNewPath()) || lines[i].contains(cd.getOldPath()))) {
       block.append(lines[i]);
       i++;
       while (i < lines.length && !lines[i].startsWith("diff")) {
         block.append(lines[i] + "\n");
         i++;
       }
       addCodeEditEntriesForDiffText(cd, block.toString());
       i--;
     }
   }
 }
Пример #9
0
  public static List<PathChangeModel> getFilesInCommit(Repository repository, RevCommit commit) {
    List<PathChangeModel> list = new ArrayList<PathChangeModel>();
    if (!hasCommits(repository)) {
      return list;
    }
    RevWalk rw = new RevWalk(repository);
    try {
      if (commit == null) {
        ObjectId object = getDefaultBranch(repository);
        commit = rw.parseCommit(object);
      }

      if (commit.getParentCount() == 0) {
        TreeWalk tw = new TreeWalk(repository);
        tw.reset();
        tw.setRecursive(true);
        tw.addTree(commit.getTree());
        while (tw.next()) {
          list.add(
              new PathChangeModel(
                  tw.getPathString(),
                  tw.getPathString(),
                  0,
                  tw.getRawMode(0),
                  commit.getId().getName(),
                  ChangeType.ADD));
        }
        tw.release();
      } else {
        RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
        DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
        df.setRepository(repository);
        df.setDiffComparator(RawTextComparator.DEFAULT);
        df.setDetectRenames(true);
        List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree());
        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) {
      // todo
      Logger.error(t, t.getMessage());
    } finally {
      rw.dispose();
    }
    return list;
  }
Пример #10
0
  protected String doDiff(Git git, String objectId, String baseObjectId, String path) {
    Repository r = git.getRepository();
    /*
            RevCommit commit = JGitUtils.getCommit(r, objectId);

            ObjectId current;
            if (isNotBlank(objectId)) {
                current = BlobUtils.getId(r, objectId, blobPath);
            } else {
                current = CommitUtils.getHead(r).getId();
            }
            ObjectId previous;
            if (isNotBlank(baseObjectId)) {
                previous = BlobUtils.getId(r, baseObjectId, blobPath);
            } else {
                RevCommit revCommit = CommitUtils.getCommit(r, current);
                RevCommit[] parents = revCommit.getParents();
                if (parents.length == 0) {
                    throw new IllegalArgumentException("No parent commits!");
                } else {
                    previous = parents[0];
                }
            }
            Collection<Edit> changes = BlobUtils.diff(r, previous, current);

            // no idea how to format Collection<Edit> :)

    */

    RevCommit commit;
    if (Strings.isNotBlank(objectId)) {
      commit = CommitUtils.getCommit(r, objectId);
    } else {
      commit = CommitUtils.getHead(r);
    }
    RevCommit baseCommit = null;
    if (Strings.isNotBlank(baseObjectId)) {
      baseCommit = CommitUtils.getCommit(r, baseObjectId);
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    RawTextComparator cmp = RawTextComparator.DEFAULT;
    DiffFormatter formatter = new DiffFormatter(buffer);
    formatter.setRepository(r);
    formatter.setDiffComparator(cmp);
    formatter.setDetectRenames(true);

    RevTree commitTree = commit.getTree();
    RevTree baseTree;
    try {
      if (baseCommit == null) {
        if (commit.getParentCount() > 0) {
          final RevWalk rw = new RevWalk(r);
          RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
          rw.dispose();
          baseTree = parent.getTree();
        } else {
          // FIXME initial commit. no parent?!
          baseTree = commitTree;
        }
      } else {
        baseTree = baseCommit.getTree();
      }

      List<DiffEntry> diffEntries = formatter.scan(baseTree, commitTree);
      if (path != null && path.length() > 0) {
        for (DiffEntry diffEntry : diffEntries) {
          if (diffEntry.getNewPath().equalsIgnoreCase(path)) {
            formatter.format(diffEntry);
            break;
          }
        }
      } else {
        formatter.format(diffEntries);
      }
      formatter.flush();
      return buffer.toString();
    } catch (IOException e) {
      throw new RuntimeIOException(e);
    }
  }
Пример #11
0
  /**
   * Returns the diff between two commits for the specified file.
   *
   * @param repository
   * @param baseCommit if base commit is null the diff is to the primary parent of the commit.
   * @param commit
   * @param path if the path is specified, the diff is restricted to that file or folder. if
   *     unspecified, the diff is for the entire commit.
   * @param outputType
   * @return the diff
   */
  public static DiffOutput getDiff(
      Repository repository,
      RevCommit baseCommit,
      RevCommit commit,
      String path,
      DiffOutputType outputType) {
    DiffStat stat = null;
    String diff = null;
    try {
      final ByteArrayOutputStream os = new ByteArrayOutputStream();
      RawTextComparator cmp = RawTextComparator.DEFAULT;
      DiffFormatter df;
      switch (outputType) {
        case HTML:
          df = new GitBlitDiffFormatter(os, commit.getName());
          break;
        case PLAIN:
        default:
          df = new DiffFormatter(os);
          break;
      }
      df.setRepository(repository);
      df.setDiffComparator(cmp);
      df.setDetectRenames(true);

      RevTree commitTree = commit.getTree();
      RevTree baseTree;
      if (baseCommit == null) {
        if (commit.getParentCount() > 0) {
          final RevWalk rw = new RevWalk(repository);
          RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
          rw.dispose();
          baseTree = parent.getTree();
        } else {
          // FIXME initial commit. no parent?!
          baseTree = commitTree;
        }
      } else {
        baseTree = baseCommit.getTree();
      }

      List<DiffEntry> diffEntries = df.scan(baseTree, commitTree);
      if (path != null && path.length() > 0) {
        for (DiffEntry diffEntry : diffEntries) {
          if (diffEntry.getNewPath().equalsIgnoreCase(path)) {
            df.format(diffEntry);
            break;
          }
        }
      } else {
        df.format(diffEntries);
      }
      if (df instanceof GitBlitDiffFormatter) {
        // workaround for complex private methods in DiffFormatter
        diff = ((GitBlitDiffFormatter) df).getHtml();
        stat = ((GitBlitDiffFormatter) df).getDiffStat();
      } else {
        diff = os.toString();
      }
      df.flush();
    } catch (Throwable t) {
      try {
        error(t, repository, "failed to generate commit diff!");
      } catch (Exception e) {
      }
    }

    return new DiffOutput(outputType, diff, stat);
  }
Пример #12
0
 @Override
 public void format(final EditList edits, final RawText a, final RawText b) throws IOException {
   // Flush header before formatting of edits begin
   stream.flushLine();
   super.format(edits, a, b);
 }
Пример #13
0
  public String getDiffText(String str) {
    int filenubs = 0;
    int lines = 0;
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    File gitDir = new File("F:/work/demo-rio/.git");
    Repository repository = null;
    try {
      if (git == null) {
        git = Git.open(gitDir);
      }
    } catch (Exception e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    try {
      String cid = str;
      repository = builder.setGitDir(gitDir).readEnvironment().findGitDir().build();
      RevWalk walk = new RevWalk(repository);
      ObjectId objId = ObjectId.fromString(cid);
      RevCommit commit = walk.parseCommit(objId);
      System.out.println(commit.getFullMessage());

      TreeWalk tw = new TreeWalk(repository);

      RevCommit[] parent_commits = commit.getParents();
      if (parent_commits.length == 0) {
        throw new Exception("当前只有一个版本");
      }

      ObjectId objId2 = parent_commits[0].toObjectId();
      RevCommit paren_commit = walk.parseCommit(objId2);
      tw.addTree(paren_commit.getTree());
      tw.addTree(commit.getTree());
      tw.setRecursive(true);

      ByteArrayOutputStream out = new ByteArrayOutputStream();
      DiffFormatter df = new DiffFormatter(out);
      df.setRepository(git.getRepository());
      RenameDetector rd = new RenameDetector(repository);
      rd.addAll(DiffEntry.scan(tw));
      List<DiffEntry> diffEntries = rd.compute();
      if (diffEntries != null || diffEntries.size() != 0) {

        Iterator<DiffEntry> iterator = new ArrayList<DiffEntry>(diffEntries).iterator();
        DiffEntry diffEntry = null;
        while (iterator.hasNext()) {
          diffEntry = iterator.next();
          String changeType = diffEntry.getChangeType().toString();
          String type = "";
          if (changeType.equals("DELETE")) {
            type = ConfigUtil.getFileType(diffEntry.getOldPath());
            filenubs++;
            System.out.println(diffEntry.getOldPath());
          } else {
            type = ConfigUtil.getFileType(diffEntry.getNewPath());
            filenubs++;
            System.out.println(diffEntry.getNewPath());
          }
          // 检查文件的后缀
          // System.out.println(type);
          if (fileTypes.contains(type)) {
            df.format(diffEntry);
            String diffText = out.toString("UTF-8");
            lines += scanDiffText(diffText);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return filenubs + "&" + lines;
    // System.out.println("the changed file nubs: "+ filenubs);
    // System.out.println("the changed linr nubs: "+ lines);
  }