実行環境のOSに依存しないHugoで作成したサイトのビルドとデプロイを一括で行うスクリプトを開発した話
この記事では、開発したHugoで作成したサイトのビルドとデプロイを一括で行うスクリプトを紹介します。
この記事では、開発したHugoで作成したサイトのビルドとデプロイを一括で行うスクリプトを紹介します。
過去にも似たような記事を書いていますが、今回は実行環境のOSに依存しないものにしています。
この記事の内容です。
対象読者
- Hugoで作成したサイトのビルドおよびデプロイをいちいちコマンドを打って行いたくない方
環境
- WSL2 (Ubuntu 22.04)
- Node.js (v18.1.0)
前提条件
- Node.jsインストール済み
開発したスクリプトについて
いちいちコマンドを順番に打ってビルドやデプロイを行いたくなかったため、以下のスクリプトを開発しました。
よければ自由にお使いください + カスタマイズしてください。
使用方法は、本スクリプトをHugoプロジェクトのルートディレクトリへ配置し、
node deploy.js
を実行するだけです。
事前準備として、publicディレクトリをGitHub Pagesのリポジトリを紐づけておく必要があります。
本スクリプトの内容です。
行っていることはシンプルで、以下のことを行っているだけです。
- Hugoサイトをビルド
- 最新情報に更新されたpublicディレクトリへ移動し、git add、commit、pushを順に実行
(コミットメッセージは年月日)This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersconst path = require("path"); const { execSync } = require("child_process"); const execSyncWithConsoleLog = (command) => { try { const stdout = execSync(command); const stdoutStr = stdout.toString(); if (0 < stdoutStr.length) console.log(stdoutStr); return 0; } catch (error) { console.log(`\x1b[31m${error.message}`); return error.status; } }; const zeroPadding = (num, len) => { return ("000" + num).slice(-len); }; const getNowStr = () => { const d = new Date(); const fullYear = d.getFullYear(); const month = zeroPadding(d.getMonth() + 1, 2); const date = zeroPadding(d.getDate(), 2); const hours = zeroPadding(d.getHours(), 2); const minutes = zeroPadding(d.getMinutes(), 2); const seconds = zeroPadding(d.getSeconds(), 2); const timezoneOffset = zeroPadding(d.getTimezoneOffset() / -60, 2); const timezoneOffsetRemainder = zeroPadding(d.getTimezoneOffset() % -60, 2); return `${fullYear}-${month}-${date} ${hours}:${minutes}:${seconds} +${timezoneOffset}:${timezoneOffsetRemainder}`; }; const sourcePath = process.cwd(); try { // Go to this script file directory. process.chdir(__dirname); // Build the project. execSyncWithConsoleLog("hugo"); // Go to public directory. process.chdir(path.join(__dirname, "public")); // Add changes to git. execSyncWithConsoleLog("git add ."); // Commit. const commitResultStatus = execSyncWithConsoleLog( `git commit -m "Site updated: ${getNowStr()}"` ); if (0 !== commitResultStatus) { console.log( "\x1b[31mProbably your branch is up to date with 'origin/master'. Or some other errors happened." ); process.exit(1); } // Push source and build repos. execSyncWithConsoleLog("git push origin master"); console.log("\x1b[36mThe web page has been updated!"); } finally { // Return to the path before executing this script. process.chdir(sourcePath); }
ブログがGitHub Pagesでホストされていると、そもそもスクリプトが不要な話
ブログがGitHub Pagesでホストされている場合、そもそも、こういったスクリプトを作成しなくてもGitHub Actionsを使用したら同様のことを行えそうでした。
どういった設定を行えばよいのかは以下の公式サイトにすべて記載されているので、そちらを参照ください。
gohugo.io
