name: 🚀 自动部署 Hexo 博客 on: # 🌿 推送到 main 分支时触发 push: branches: - main # 🎉 发布新版本时触发 release: types: - published # ⏯️ 手动触发(Actions 页面点击运行) workflow_dispatch: # 🕎 设置时区为中国标准时间 env: TZ: Asia/Shanghai jobs: deploy: runs-on: ubuntu-latest steps: # 🔁 检出代码(使用最新 v4,更安全高效) - name: 🔎 检查分支 uses: actions/checkout@v4 # 🧠 缓存 node_modules(v4 支持更优压缩) - name: 🧠 缓存项目依赖 uses: actions/cache@v4 with: path: node_modules key: ${{ runner.os }}-nodeModules-${{ hashFiles('package-lock.json', 'package.json') }} restore-keys: | ${{ runner.os }}-nodeModules- # 🏗️ 安装 Node.js 并自动缓存 npm 全局工具 - name: 🛠️ 安装 Node.js 环境 uses: actions/setup-node@v4 with: node-version: "22.x" cache: "npm" # ✅ 自动缓存 npm,加速全局包安装 # 📥 全局安装 Hexo CLI(锁定版本,避免意外升级) - name: 📥 安装 Hexo CLI run: npm install -g hexo-cli@latest # 推荐生产环境使用固定版本如 @6.3.0 # ⚙️ 安装项目依赖(仅当缓存未命中) - name: ⚙️ 安装项目依赖 if: steps.cache.outputs.cache-hit != 'true' run: npm ci # ✅ CI 环境最佳选择:快速、一致、可靠 # 🧹 清理旧构建文件 - name: 🧹 清理文件树 run: npm run clean # 🏗️ 生成静态文件(含压缩) - name: 🏗️ 构建静态站点 run: npm run build # 🚀 部署到 GitHub Pages(推送到 page 分支) - name: 🚀 部署到 GitHub Pages run: | # 确保 public 目录存在 mkdir -p public cd public # 初始化 Git git init git config user.name "${{ github.actor }}" git config user.email "${{ github.actor }}@users.noreply.github.com" # 添加所有文件 git add . # 提交更改(若无变更则跳过) local_time=$(date +"%Z %Y-%m-%d %A %H:%M:%S") commit_msg="${{ github.event.head_commit.message }} ·· [$local_time]" git commit -m "$commit_msg" || echo "➡️ 无变更,跳过提交" # 强制推送到远程 page 分支 git remote add origin "https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git" git push --force --quiet origin main:page env: # 确保 GITHUB_TOKEN 权限足够(默认 actions 有写权限) GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}