如何列出指定文件的所有提交信息并格式化输出?支持GitHub环境
列出指定文件的提交主题并格式化Git Log输出
基础命令:仅显示提交主题并按日期排序
Git默认按提交日期降序(最新提交在前)展示记录,要筛选指定文件的提交主题,直接用以下命令:
git log --oneline --follow -- <文件路径>
参数说明:
--oneline:每条提交压缩为一行,包含简短哈希和提交主题--follow:跟踪文件的重命名历史(如果文件曾更名,也能获取完整提交记录)<文件路径>:替换为你要查询的具体文件,比如src/main.py
如果需要按日期升序(最早提交在前)排列,添加--reverse参数:
git log --oneline --follow --reverse -- <文件路径>
自定义格式化输出
如果需要更灵活的输出格式(比如包含日期、作者),使用--format参数自定义输出内容:
示例1:显示ISO格式日期+提交主题
git log --follow --format="%ad: %s" --date=iso -- <文件路径>
示例2:显示简短哈希+作者+提交主题
git log --follow --format="%h | %an | %s" -- <文件路径>
常用占位符说明:
%ad:提交日期(配合--date指定格式,如iso、short、local)%s:提交主题%h:简短提交哈希%an:作者姓名%ae:作者邮箱
同样,添加--reverse可切换为升序排序。
在GitHub Actions和GitHub Pages中生效
GitHub Actions中执行
GitHub Actions运行环境默认预装Git,只需在Workflow中拉取完整仓库历史后执行命令即可。注意必须设置fetch-depth: 0,否则默认仅拉取最近1次提交:
jobs: generate-commit-log: runs-on: ubuntu-latest steps: - name: Checkout full repository history uses: actions/checkout@v4 with: fetch-depth: 0 - name: Export commit subjects to file run: git log --oneline --follow -- src/main.py > commit-log.txt - name: Save as artifact uses: actions/upload-artifact@v3 with: name: commit-log path: commit-log.txt
GitHub Pages中展示
GitHub Pages是静态页面,无法直接执行Git命令,需通过GitHub Actions生成静态内容后部署:
- 在Actions中生成包含提交历史的Markdown文件
- 将文件放入Pages的构建目录(如Jekyll的
docs或_posts) - 部署到GitHub Pages
示例生成步骤:
- name: Generate commit history markdown run: | echo "# 提交历史" > commit-history.md echo "" >> commit-history.md git log --follow --format="* %ad: %s" --date=short --reverse -- src/main.py >> commit-history.md - name: Copy to Pages directory run: cp commit-history.md docs/
内容的提问来源于stack exchange,提问作者Prinz Piuz
相关产品推荐
相关产品推荐

