Skip to content

Instantly share code, notes, and snippets.

@lisez
Last active January 9, 2024 15:10
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save lisez/41cebe4eb9190a5c5e879fee5933beb1 to your computer and use it in GitHub Desktop.
Save lisez/41cebe4eb9190a5c5e879fee5933beb1 to your computer and use it in GitHub Desktop.
如何使用 Github Actions 自動部署 Hugo
# link: https://sujingjhong.com/posts/how-to-deploy-hugo-automatically-with-github-actions/
# author: lisez <mm4324@gmail.com>
name: Auto publish to public site
# 只有推送到 master 才自動化
on:
push:
branches:
- master
jobs:
hugo-publish:
name: publish content to public site
runs-on: ubuntu-latest
steps:
# 使用當前的 repo
- name: checkout private repo
uses: actions/checkout@v3
with:
# 因為目前的 repo 有使用到 submodule,所以 submodule 也要一併同步
# 不然原本的 repo 是沒有 submodule 的內容
submodules: true
token: ${{ secrets.GITHUB_PAT }}
# 我的公開網站是放置在另一個 repo 所以這裡也要 clone 一份下來處理
# 因為我 Hugo 預設是產生檔案到 public 資料夾,所以這邊我也是 clone 到那裡
- name: checkout public repo
uses: actions/checkout@v3
with:
# 這裡是那個網站在 github 上的 repo 名稱
repository: lisez/sujingjhong.com
path: public
# 記得去產生一把 personal access token 放到 repo 的 secrets 裡
# 然後我 secrets 裡的名稱就叫 GITHUB_PAT,用別的名稱的話記得改掉
# 參考 https://help.github.com/en/actions/automating-your-workflow-with-github-actions/authenticating-with-the-github_token
# 權限:
# Repository access: 選擇對象 repository
# Repository permissions: Contents: Read and Write
token: ${{ secrets.GITHUB_PAT }}
# 使用別人做好的 Hugo Actions
- name: setup hugo
uses: peaceiris/actions-hugo@v2
with:
hugo-version: latest
extended: true
# 開始用 Hugo 產生檔案囉
- name: build content to public site
working-directory: ./
# --cleanDestinationDir 清除舊檔案
run: hugo --minify --gc --cleanDestinationDir
# 將檔案 commit 到 網站 repo
- name: deploy and publish updates
working-directory: ./public
# user.email 還有 user.name 可以取自己喜歡的,一定要設定不然會出錯
run: |
# 當 git 有更動時才進行動作
if [[ `git status --porcelain` ]]; then
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git add . -A
git commit -m "[chore] Auto publish"
git push origin
else
echo "content no changes"
fi
@arguskao
Copy link

arguskao commented May 3, 2020

感謝您,實在太需要了!

@arguskao
Copy link

arguskao commented May 7, 2020

請問是不是要弄Hugo 的話,得把程式分成兩個repo嗎?

@lisez
Copy link
Author

lisez commented May 16, 2020

請問是不是要弄Hugo 的話,得把程式分成兩個repo嗎?

理論上應該可以 commit 自己的 repo
不過因為我沒有此需求,你可以研究看看

@lisez
Copy link
Author

lisez commented May 30, 2022

改用 actions/checkout@v3 原生內建 checkout submodules

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment