众所周知,Github Actions可以执行工作流任务,而且免费版本还具备三种系统和两种架构可选,这就非常适合拿来编译代码。

花了一些时间研究出了个编译Rust代码Github Actions Workflow文件模版,可以把简单的Rust项目分别编译成3个平台2种架构的可执行程序。

Github:Github_Actions_Rust_Workflows: 简单的Github Actions编译Rust工作流文件

工作流文件如下:

name: Build Rust Project

on:
  workflow_dispatch:

jobs:
  build:
    env:
      program_name: rust_program
    strategy:
      matrix:
        os: [windows-latest, ubuntu-latest, macos-latest]
        arch: [amd64, arm64]
    runs-on: ${{ matrix.os }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: stable

      - name: Build for rust
        shell: bash
        run: |
          #处理环境变量
          arch=${{ matrix.arch }}
          os=$RUNNER_OS
          program_name=${{ env.program_name }}
          
          #处理不同系统架构差异
          if [ "$os" == "Linux" ]; then
            if [ "$arch" == "amd64" ]; then
              target=x86_64-unknown-linux-gnu
              linker=gcc
            elif [ "$arch" == "arm64" ]; then
              target=aarch64-unknown-linux-gnu
              linker=aarch64-linux-gnu-gcc
              sudo apt-get update && sudo apt-get install -y gcc-aarch64-linux-gnu
            fi
            suffix=""
          elif [ "$os" == "Windows" ]; then
            if [ "$arch" == "amd64" ]; then
              target=x86_64-pc-windows-msvc
              linker=link.exe
            elif [ "$arch" == "arm64" ]; then
              target=aarch64-pc-windows-msvc
              linker=link.exe
            fi
            suffix=".exe"
          elif [ "$os" == "macOS" ]; then
            if [ "$arch" == "amd64" ]; then
              target=x86_64-apple-darwin
              linker=clang
            elif [ "$arch" == "arm64" ]; then
              target=aarch64-apple-darwin
              linker=clang
            fi
            suffix=""
          fi
          echo "当前环境:$os/$arch"
          echo "当前rust工具链版本"
          rustc --version

          #添加目标架构配置
          rustup target add ${target}
          mkdir -p .cargo
          cat <<EOL > "./.cargo/config.toml"
          [target.${target}]
          linker = "${linker}"
          EOL

          #开始编译
          echo "开始编译"
          echo "目标:${target}"
          cargo build --release --target=${target}

      - name: Upload Build Artifacts
        uses: actions/upload-artifact@v4
        with:
          name: ${{ env.program_name }}_${{ matrix.os }}_${{ matrix.arch }}
          path: target/*

使用说明

1. 把 .github/workflows/rust.yml 复制到你的 rust 项目仓库根目录中

2. 在 GitHub 仓库页面的 Actions 选项卡中手动点击 Run workflow 开始构建。

3. 根据rust.yml文件中matrix选择的平台架构矩阵,工作流会自动执行并构建对应平台架构的可执行文件。

4. 构建完成后,指定目录构建产物(target/)会被上传至对应的构建产物列表中,便于下载和后续使用。

注意事项

这个工作流只会把Cargo的编译产物(target/)上传到构建产物中,如果需要上传多个文件,请自行配置rust.yml中path: output/*

依赖项目

其中使用了 dtolnay/rust-toolchain 的脚本安装 stable 版本的 Rust 工具链,感谢脚本作者的辛勤维护~

枯死的灌木!