Using the JGIT, how can I retrieve the line numbers of added/deleted lines

前端 未结 3 1177
梦谈多话
梦谈多话 2021-02-20 16:56

Assuming the following piece of code is committed to a Git repository:

int test(){
   int a = 3;
   int b = 4;
   int c = a + b;
   return c;
}

3条回答
  •  醉梦人生
    2021-02-20 17:38

    You need to do the difference between the A line indexes and B line indexes from the diff result:

    int linesAdded = 0;
    int linesDeleted = 0;
    int filesChanged = 0;
    try {
        repo = new FileRepository(new File("repo/.git"));
        RevWalk rw = new RevWalk(repo);
        RevCommit commit = rw.parseCommit(repo.resolve("486817d67b")); // Any ref will work here (HEAD, a sha1, tag, branch)
        RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
        DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
        df.setRepository(repo);
        df.setDiffComparator(RawTextComparator.DEFAULT);
        df.setDetectRenames(true);
        List diffs;
        diffs = df.scan(parent.getTree(), commit.getTree());
        filesChanged = diffs.size();
        for (DiffEntry diff : diffs) {
            for (Edit edit : df.toFileHeader(diff).toEditList()) {
                linesDeleted += edit.getEndA() - edit.getBeginA();
                linesAdded += edit.getEndB() - edit.getBeginB();
            }
        }
    } catch (IOException e1) {
        throw new RuntimeException(e1);
    }
    

提交回复
热议问题