如何在Gradle任务中通过GrGit获取目录下文件的Git最后修改时间
问题原因
原有代码无输出的核心原因是git.log方法的paths参数需要传入相对于Git仓库根目录的相对路径,而你传入的f.name仅为文件本身的名称,不包含上层目录路径,Git无法匹配到对应的提交记录,因此返回空列表没有输出。
正确实现代码
def git = org.ajoberstar.grgit.Grgit.open dir: project.rootDir task showGit() { doFirst { def scanDir = file("$project.rootDir/src/main/java/some/folder") scanDir.listFiles().each { f -> // 跳过子目录,仅处理文件 if (!f.isFile()) return // 生成相对于Git根目录的路径,统一分隔符适配多系统 def relativePath = f.relativeTo(project.rootDir).toString().replace('\\', '/') def fileCommits = git.log(includes: ['HEAD'], paths: [relativePath]) if (fileCommits) { def latestCommit = fileCommits.first() println "$f.name -> Author: ${latestCommit.author.name} - Date: ${latestCommit.date.format('dd.MM.yyyy HH:mm')}" } else { println "$f.name -> 无Git提交记录" } } } }
实现说明
- 调用
f.relativeTo(project.rootDir)生成文件相对于Git仓库根目录的路径,保证paths参数可以正确匹配到提交记录 - 新增文件判断逻辑,跳过扫描目录下的子文件夹,避免无效查询
- 兼容Windows系统的路径分隔符,统一替换为
/格式 - 新增无提交记录的分支处理,避免未提交的文件无任何输出
- 直接取提交列表的第一条结果,即为该文件的最后一次更新记录,无需遍历所有提交
内容的提问来源于stack exchange,提问作者injecteer
相关产品推荐
相关产品推荐

