You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在带多操作系统选择的GitHub Actions工作流中减少代码重复?

优化GitHub Actions工作流:减少重复并支持操作系统选择

可以用GitHub Actions的**矩阵(matrix)**功能解决这个问题,既能消除重复代码,又能保留选择单个或全部操作系统的灵活性。下面是优化后的工作流配置:

name: CI Workflow

on:
  workflow_dispatch:
    inputs:
      os_selection:
        description: '选择要运行工作流的操作系统(Linux、macOS、Windows 或全部)'
        required: true
        default: 'all'
        type: choice
        options:
          - linux
          - macos
          - windows
          - all

jobs:
  build-and-test:
    strategy:
      matrix:
        # 映射用户选择的选项到实际的Runner镜像
        os:
          - { name: 'linux', runner: 'ubuntu-latest' }
          - { name: 'macos', runner: 'macos-latest' }
          - { name: 'windows', runner: 'windows-latest' }
    runs-on: ${{ matrix.os.runner }}
    # 判断当前操作系统是否匹配用户选择,或用户选了全部
    if: ${{ github.event.inputs.os_selection == matrix.os.name || github.event.inputs.os_selection == 'all' }}
    steps:
      - name: 检出代码
        uses: actions/checkout@v2

      - name: 设置Node.js(按需使用)
        uses: actions/setup-node@v2
        with:
          node-version: '18'

      - name: 安装依赖
        run: npm install

      - name: 运行测试
        run: node test.js

关键优化点说明:

  • 矩阵复用:通过strategy.matrix定义操作系统的映射关系,只需要编写一套执行步骤,所有操作系统自动复用逻辑
  • 条件过滤:用if表达式判断当前矩阵项是否匹配用户选择的操作系统,实现单个或全部运行的需求
  • 易维护性:后续修改步骤或新增操作系统,只需在矩阵中调整配置,无需重复复制代码块

内容的提问来源于stack exchange,提问作者Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 09:10:13