Groovy编程实现读取Github仓库指定目录下子文件夹最新git commit对应文件内容
Groovy 遍历Git仓库指定目录读取最新commit文件实现方案
前置依赖
本实现基于JGit库完成Git操作,Groovy可无缝调用该Java库,依赖引入方式如下:
- Gradle项目依赖:
implementation 'org.eclipse.jgit:org.eclipse.jgit:6.8.0.202311291450-r' - Groovy脚本直接引入:
在脚本开头加@Grab('org.eclipse.jgit:org.eclipse.jgit:6.8.0.202311291450-r')
实现步骤
- 打开本地已克隆的Git仓库实例
- 遍历目标根目录FOLDER1下的所有一级子文件夹
- 针对每个子文件夹,查询该路径下最新的Git commit ID
- 从最新commit中读取该子文件夹下所有文件的内容
完整可运行代码
@Grab('org.eclipse.jgit:org.eclipse.jgit:6.8.0.202311291450-r') import org.eclipse.jgit.api.Git import org.eclipse.jgit.lib.Repository import org.eclipse.jgit.lib.ObjectLoader import org.eclipse.jgit.treewalk.TreeWalk import org.eclipse.jgit.treewalk.filter.PathFilter import org.eclipse.jgit.revwalk.RevCommit // 配置项,替换为你的实际路径 def localRepoPath = "/path/to/your/local/repository" // 本地Git仓库根目录路径 def targetRootFolder = "FOLDER1" // 要遍历的根目录名称 Git git = null try { // 打开Git仓库 git = Git.open(new File(localRepoPath)) Repository repo = git.getRepository() // 遍历FOLDER1下的所有一级子文件夹 new File(localRepoPath, targetRootFolder).eachDir { subDir -> // 计算子文件夹相对于仓库根目录的相对路径 def subDirRelPath = new File(targetRootFolder, subDir.getName()).getPath() println "处理子目录:${subDirRelPath}" // 查询该子目录下最新的commit RevCommit latestCommit = git.log() .addPath(subDirRelPath) .setMaxCount(1) .call() .first() if (!latestCommit) { println "该目录无commit记录,跳过:${subDirRelPath}" return } def latestCommitId = latestCommit.getId().getName() println "该目录最新commit ID:${latestCommitId}" // 遍历该commit下子目录内的所有文件,读取内容 TreeWalk treeWalk = new TreeWalk(repo) treeWalk.addTree(latestCommit.getTree()) treeWalk.setRecursive(true) treeWalk.setFilter(PathFilter.create(subDirRelPath)) while (treeWalk.next()) { if (!treeWalk.isSubtree()) { // 排除子目录,只处理文件 def filePath = treeWalk.getPathString() println "读取文件:${filePath}" // 读取文件内容 ObjectLoader loader = repo.open(treeWalk.getObjectId(0)) def fileContent = new String(loader.getBytes(), "UTF-8") // 这里可以对fileContent做自定义处理 println "文件内容:\n${fileContent}\n------------------------" } } treeWalk.close() } } catch (Exception e) { e.printStackTrace() } finally { if (git != null) { git.close() } }
注意事项
- 本方案默认你已经将目标Github仓库克隆到本地,如需直接操作远程仓库无需克隆,可调整代码使用JGit的远程操作API,但执行效率会远低于本地操作
- 代码默认文件编码为UTF-8,如果你仓库文件使用其他编码,可自行修改编码参数
- 如需跳过指定后缀的文件,可在遍历文件时增加后缀判断逻辑
内容的提问来源于stack exchange,提问作者Sarthak Goyal
相关产品推荐
相关产品推荐

