月度归档: 2019 年 2 月

  • 使用JGit获取变更细节

    有时候多个项目在一个代码仓库中,可能每个文件夹都是一个项目。如果每次使用CI自动部署的话就需要判断最近的改动属于哪个文件夹/项目。

    通过JGit直接获取两个commit之间的diff然后判断是比较直接的方法,具体使用哪两个commit就看需要的。可以使用CI系统上一次成功构建的commit sha,也可以直接使用最近两天的commit的。

    代码如下:

    Repository repo = FileRepositoryBuilder.create(new File(basePath + ".git"));
    Git git = new Git(repo);
    ObjectReader reader = repo.newObjectReader();
    ObjectId newObjectId = repo.resolve("HEAD^{tree}");
    ObjectId oldObjectId = repo.resolve(successSha + "^{tree}");
    
    
    System.out.println("Starting diff " + oldObjectId + " : " +