github实战指南04-Actions 自动化实战

04 - GitHub Actions 自动化实战

本章目标:理解 CI/CD 原理,亲手配置一个 GitHub Actions 工作流。


一、GitHub Actions 是什么?

GitHub Actions 是 GitHub 内置的 CI/CD 平台,可以自动化构建、测试和部署。

复制代码
你推送代码
    │
    ▼
GitHub 自动执行工作流
    │
    ├── 运行测试
    ├── 代码检查
    ├── 构建项目
    └── 部署上线
    │
    ▼
结果反馈到 PR / Release 页面

二、核心概念

2.1 工作流(Workflow)

yaml 复制代码
# 工作流配置文件的位置:
# .github/workflows/ci.yml

# 一个仓库可以有多个工作流
# 每个工作流由不同的事件触发

2.2 事件(Event)

yaml 复制代码
# 触发工作流的事件
on:
  push:          # 推送代码
    branches: [main]
  pull_request:  # 创建 PR
    branches: [main]
  schedule:      # 定时触发
    - cron: '0 2 * * 1'  # 每周一凌晨 2 点
  workflow_dispatch:  # 手动触发

2.2 作业(Job)

yaml 复制代码
# 一个工作流可以包含多个作业
jobs:
  test:        # 作业 1:测试
    runs-on: ubuntu-latest
    steps: ...
  
  build:       # 作业 2:构建
    runs-on: ubuntu-latest
    needs: test  # 依赖 test 作业
    steps: ...

2.3 步骤(Step)

yaml 复制代码
# 一个作业包含多个步骤
steps:
  - name: Checkout code        # 步骤 1:检出代码
    uses: actions/checkout@v4
  
  - name: Setup Node.js        # 步骤 2:安装 Node.js
    uses: actions/setup-node@v4
    with:
      node-version: 18
  
  - name: Install dependencies # 步骤 3:安装依赖
    run: npm ci
  
  - name: Run tests            # 步骤 4:运行测试
    run: npm test

2.4 运行器(Runner)

yaml 复制代码
# GitHub 提供的虚拟机
runs-on: ubuntu-latest    # Ubuntu(最常用)
runs-on: windows-latest   # Windows
runs-on: macos-latest     # macOS

三、实战:配置第一个 CI 工作流

3.1 创建工作流文件

bash 复制代码
# 创建目录
mkdir -p .github/workflows

# 创建工作流文件
cat > .github/workflows/ci.yml << 'EOF'
name: CI

# 触发条件:推送到 main 或创建 PR
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

# 工作流中的任务
jobs:
  # 测试任务
  test:
    runs-on: ubuntu-latest
    
    steps:
      # 检出代码
      - name: Checkout code
        uses: actions/checkout@v4
      
      # 设置 Node.js
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 18
          cache: 'npm'  # 缓存 npm 依赖
      
      # 安装依赖
      - name: Install dependencies
        run: npm ci
      
      # 运行测试
      - name: Run tests
        run: npm test
EOF

3.2 创建一个简单的测试项目

bash 复制代码
# 初始化 package.json
cat > package.json << 'EOF'
{
  "name": "my-git-practice",
  "version": "1.0.0",
  "scripts": {
    "test": "node test.js"
  }
}
EOF

# 创建测试文件
cat > test.js << 'EOF'
const assert = require('assert');

// 简单的测试
function add(a, b) {
  return a + b;
}

// 运行测试
try {
  assert.strictEqual(add(1, 2), 3, '1 + 2 应该等于 3');
  assert.strictEqual(add(0, 0), 0, '0 + 0 应该等于 0');
  console.log('✅ 所有测试通过!');
  process.exit(0);
} catch (error) {
  console.error('❌ 测试失败:', error.message);
  process.exit(1);
}
EOF

3.3 提交并观察

bash 复制代码
# 提交工作流配置
git add .github/workflows/ci.yml package.json test.js
git commit -m "ci: add GitHub Actions workflow"
git push

# 现在去 GitHub 仓库页面:
# 1. 点击 "Actions" 标签
# 2. 你会看到工作流正在运行
# 3. 点击可以查看详细日志

四、实战:添加代码质量检查

4.1 添加 ESLint

bash 复制代码
# 安装 ESLint
npm init -y
npm install --save-dev eslint

# 初始化 ESLint
npx eslint --init
# 选择:
# - To check syntax and find problems
# - JavaScript
# - Node.js
# - Use a popular style guide
# - Airbnb
# - JSON
# - Yes

# 创建一个有 lint 错误的文件
cat > bad-code.js << 'EOF'
var x = 1
var y = 2
console.log(x+y)
EOF

4.2 更新工作流

yaml 复制代码
# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 18
          cache: 'npm'
      - run: npm ci
      - run: npm run lint  # 运行 lint 检查

  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 18
          cache: 'npm'
      - run: npm ci
      - run: npm test

五、实战:自动部署到 GitHub Pages

yaml 复制代码
# .github/workflows/deploy.yml
name: Deploy to GitHub Pages

on:
  push:
    branches: [main]

# 设置权限
permissions:
  contents: read
  pages: write
  id-token: write

# 部署任务
jobs:
  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      
      - name: Setup Pages
        uses: actions/configure-pages@v4
      
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: '.'  # 当前目录作为网站根目录
      
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4

六、实战:自动创建 Release

yaml 复制代码
# .github/workflows/release.yml
name: Release

on:
  push:
    tags:
      - 'v*'  # 当推送 v 开头的 tag 时触发

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write  # 需要写权限来创建 Release
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      
      - name: Create Release
        uses: softprops/action-gh-release@v1
        with:
          generate_release_notes: true  # 自动生成 release notes
          files: |
            dist/*
            *.zip

七、GitHub Actions 常用 Actions

7.1 官方 Actions

yaml 复制代码
# 代码检出
- uses: actions/checkout@v4

# 设置语言环境
- uses: actions/setup-node@v4     # Node.js
- uses: actions/setup-python@v5   # Python
- uses: actions/setup-java@v4     # Java

# 缓存依赖
- uses: actions/cache@v3
  with:
    path: ~/.npm
    key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}

# 上传制品
- uses: actions/upload-artifact@v4
  with:
    name: build-output
    path: dist/

7.2 社区 Actions

yaml 复制代码
# 代码格式化检查
- uses: pre-commit/action@v3.0.0

# 自动评论 PR
- uses: actions/github-script@v7

# 发送通知
- uses: 8398a7/action-slack@v3

八、Secrets 管理

8.1 添加 Secrets

复制代码
Settings → Secrets and variables → Actions → New repository secret

Name: API_KEY
Value: sk-1234567890

Name: DEPLOY_TOKEN
Value: your-deploy-token

8.2 在工作流中使用

yaml 复制代码
steps:
  - name: Use secret
    run: echo "Deploying with token..."
    env:
      API_KEY: ${{ secrets.API_KEY }}
      DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}

九、工作流调试技巧

9.1 启用调试日志

yaml 复制代码
# 在 Secrets 中添加:
# ACTIONS_STEP_DEBUG = true
# ACTIONS_RUNNER_DEBUG = true

9.2 手动触发工作流

yaml 复制代码
on:
  workflow_dispatch:
    inputs:
      environment:
        description: 'Deploy to environment'
        required: true
        default: 'staging'
        type: choice
        options:
          - staging
          - production

9.3 查看工作流运行日志

复制代码
1. 仓库页面 → Actions
2. 点击具体的工作流运行
3. 点击具体的 job
4. 展开每个 step 查看日志
5. 可以下载日志文件

十、实战练习

在你的 my-git-practice 仓库中完成以下操作:

bash 复制代码
# 1. 创建 CI 工作流
mkdir -p .github/workflows
cat > .github/workflows/ci.yml << 'EOF'
name: CI
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 18
      - run: npm test
EOF

# 2. 提交并推送
git add .github/
git commit -m "ci: add GitHub Actions workflow"
git push

# 3. 去 GitHub 查看 Actions 运行结果
# 4. 故意让测试失败,看 Actions 的反馈
# 5. 修复测试,再次推送,看 Actions 变绿

十一、练习清单

  • 创建一个 CI 工作流,运行测试
  • 查看 Actions 运行日志
  • 故意让 CI 失败,观察错误信息
  • 修复 CI 错误,让工作流变绿
  • 添加代码 lint 检查
  • 配置自动部署到 GitHub Pages

上一章03-Pull Request全流程实战(03-Pull Request全流程实战.md)

下一章05-Fork与开源协作

相关推荐
李小白661 小时前
第五天-计算机硬件
运维·云计算
yyuuuzz1 小时前
游戏云服务器推荐的技术选择思路
大数据·运维·服务器·游戏·云计算·aws
uhakadotcom1 小时前
结合着 fastapi 使用,anyio 通常可以如何使用 , 它和 uvloop 在性能上有啥差异
后端·面试·github
utf8mb4安全女神1 小时前
expect工具,expect脚本,实现全自动免交互登录ssh,shell脚本和expect结合使用,在多台服务器上创建1个用户【linux】
linux·运维·服务器
李白的天不白1 小时前
下载smartadmin框架
git·github
QN1幻化引擎1 小时前
RingBuffer:用"循环缓冲区"干掉KV Cache的O(n)显存膨胀
算法·github
vortex51 小时前
Alpine Linux 运行架构解析:从内核到容器的精简之道
linux·运维·架构
可乐要加冰^-^2 小时前
云雀文档下载
windows·git·github·石墨文档
江畔柳前堤2 小时前
github实战指南00-命令在哪里执行?
人工智能·线性代数·oracle·数据挖掘·github·word