🤖

GitHub Actions でファイル内の日付を自動更新する

2023/01/05に公開

概要

Markdown で書いた記事の frontmatter に記述する last_modified_date を手動で更新するのが地味に煩わしいので、GitHub Actions で自動更新してくれるようにしました。

https://github.com/Kampachi-dev/cpdocs/blob/main/.github/workflows/update_modified.yml

順序としては、

  • 最新とその1つ前の commit を取得する
  • 比較して .md に変更が入っていれば、最終更新日を sed で上書き
  • 上書きしたファイルがあれば、自動で push

となっています。

各ステップの解説

- name: checkout
  uses: actions/checkout@v3
  with:
    fetch-depth: 2

fetch-depth2 にすることで、最新とその1つ前の commit を取得しておきます。

- name: overwrite last_modified_date
  run: |
    today=`date "+%Y-%m-%d"`
    files=($(git diff --name-only --diff-filter=AM HEAD^ HEAD -- '**.md'))
    for file in ${files[@]}; do sed -i "s/last_modified_date:.*/last_modified_date: ${today}/" $file; done

git diff で取得した変更点を、files に配列として格納します。
それぞれのファイルで、sed を使って last_modified_date を今日の日付に書き換えます。

- name: commit and push changes
  run: |
    git config user.name "github-actions[bot]"
    git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
    if (git diff --shortstat | grep '[0-9]'); then \
      git add .; \
      git commit -m "Update last_modified_date"; \
      git push origin HEAD:${GITHUB_REF}; \
    fi

github-actions[bot] に push してほしかったので、そのためのユーザ設定をします。

if (git diff --shortstat | grep '[0-9]'); は、変更があったときのみ push を実現するためのものです。
https://zenn.dev/lollipop_onl/articles/eoz-gha-push-diffs

Discussion