前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Hugo .GitInfo 的替代方案

Hugo .GitInfo 的替代方案

作者头像
eallion
发布2022-12-20 15:00:14
1.8K0
发布2022-12-20 15:00:14
举报
文章被收录于专栏:大大的小蜗牛大大的小蜗牛

警告

本文最后更新于 2021-08-06,文中内容可能已过时。

前言

今天有人问我博客页脚 footer 里的 git hash 是怎么显示的,就是页面底部里的 69d6ffe 这一串数字。

https://images.eallion.com/images/2021/08/footer.png
https://images.eallion.com/images/2021/08/footer.png

他遇到了跟我一样的坑,.GitInfo 不能正确显示。

原因

虽然 Hugo 在很早的版本里就支持通过 enableGitInfo 开启 .GitInfo 变量,但是这个变量只对 Hugo 网站文件生效,不对 content 目录生效,具体可以参考这条 Issue 里 bep 的回复:

value will only change if the content changes, correct? Yes, the GitInfo is used to set dates to individual files (which then is used to determine .Site.LastChange). Only the content files (e.g. .md) is considered here.

在一些 CI/CD 中为了节省时间、空间等,会加上 --depth=1 只克隆最新的一个 Commit 历史进行构建,这样就会有可能丢失掉 content 目录里的一些 .md 文件的 .GitInfo。在模板中引用 {{ .GitInfo.Hash }}footer.html)这样的变量时就不会显示。

如果去掉 --depth=1 从而进行完整克隆时,构建的文章页面,虽然会显示 {{ .GitInfo.Hash }},但显示的不是最新的 Commit hash。

变通方案

除了向官方反馈此问题(可能不一定被采纳),也有另外的方法可以实现。我用了一个笨方法。符合我的理念,先能干活,再谈优化。希望有更好方法的朋友可以教教我。

  1. 在 Hugo 根目录新建一个脚本 githash.sh
代码语言:javascript
复制
#!/bin/bash

hash=`git log --pretty=format:"%H" -n 1`
echo $hash
sed -i "s/69d6ffe319557706dcf4150e960e7b7e21a37d9f/$hash/g" themes/hello-friend/layouts/partials/githash.html

其中 69d6ffe319557706dcf4150e960e7b7e21a37d9f 是为了方便用脚本替换,随便写的一个字符串,与模板文件 githash.html 里的字符串对应即可。

  1. theme/layouts/partials 目录新建一个 githash.html 模板文件:
代码语言:javascript
复制
<a
    href="https://github.com/eallion/eallion.com/commit/69d6ffe319557706dcf4150e960e7b7e21a37d9f"
    target="_blank"
    rel="noopener noreferrer"
    >{{ substr "69d6ffe319557706dcf4150e960e7b7e21a37d9f" 0 7 }}</a
>
  1. footer.html 需要显示 GitHash 的位置引用这模板:
代码语言:javascript
复制
{{ partial "githash.html" . }}
  1. 构建 Hugo 前(在本地或在 CI/CD 中),先运行一次这个脚本再构建 Hugo 。
代码语言:javascript
复制
bash githash.sh
hugo --cleanDestinationDir --forceSyncStatic --gc --ignoreCache --minify --enableGitInfo

GitHub Actions Workflows:

代码语言:javascript
复制
jobs:
  build-deploy:
    runs-on: ubuntu-18.04
    steps:
    ......
      - name: Build Hugo
        run: |
+         bash githash.sh
          hugo --cleanDestinationDir --forceSyncStatic --gc --ignoreCache --minify --enableGitInfo
    ......
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-08-062,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 原因
  • 变通方案
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档