通过 GitHub Actions 编译 Lazarus 项目

理论上 Lazarus 是支持交叉编译的,但官方发行的默认版本并没有打包不同平台所依赖的各组件。比如在 Windows 平台上将编译目标设为 Linux 时,编译器会报错:Can’t find unit system used by fcllaz ——缺少 Linux 平台上的预编译文件。

虽然可以使用 fpcupdeluxe (GitHub) 项目安装支持交叉编译的 Lazarus 工具链,不过这个工具似乎不支持命令行环境下的配置和安装。

建议还是不要折腾,老老实实使用不同平台的 Lazarus 一对一编译,特别是对于 Windows 和 Linux 这两种差异较大的平台。

使用第三方 Actions 编译

在 Marketplace 中搜索 “Lazarus” 可以找到三条结果。推荐使用 Setup Lazarus environment。使用这个 Actions 可以非常简单地在不同目标平台上进行编译:

yamlname: build

on:
  pull_request:
  push:
    paths-ignore:
      - "README.md"
    branches:
      - master
      - releases/*

jobs:
  build:
    runs-on: ${{ matrix.operating-system }}
    strategy:
      matrix:
        operating-system: [windows-latest, ubuntu-latest, macos-latest]
        lazarus-versions: [dist, stable, 2.2.0, 2.0.12, 2.0.10, 2.0.8, 2.0.6]
    steps:
      - name: Checkout source code
        uses: actions/checkout@v4
      - name: Install Lazarus
        uses: gcarreno/setup-lazarus@v3
        with:
          lazarus-version: ${{ matrix.lazarus-versions }}
          include-packages: "Synapse 40.1"
          with-cache: true
      - name: Build the Main Application
        if: ${{ matrix.operating-system != 'macos-latest' }}
        run: lazbuild -B "src/lazaruswithgithubactions.lpi"
      - name: Build the Main Application (macOS)
        if: ${{ matrix.operating-system == 'macos-latest' }}
        run: lazbuild -B --ws=cocoa "src/lazaruswithgithubactions.lpi"
      - name: Build the Unit Tests Application
        run: lazbuild -B "tests/testconsoleapplication.lpi"
      - name: Run the Unit Tests Application
        run: bin/testconsoleapplication "--all" "--format=plain"

仅 Windows 平台编译

虽然 GitHub 官方文档里并没有提及 Windows Runner 预安装了 WinGet,但实测是可以使用的。不过 WinGet 安装 Lazarus 的缺点是不会设置环境变量,需要在脚本中指定路径。

下面的示例包含安装 Lazarus 环境、下载在线包、编译目标三大步骤:

yamlbuild:
  runs-on: windows-latest
  steps:
    - uses: actions/checkout@v4
    - name: Install Lazarus
      run: |
        winget install Lazarus.Lazarus --silent --accept-source-agreements --accept-package-agreements
    - name: Download thirdparty packages
      shell: pwsh
      run: |
        # 从 https://packages.lazarus-ide.org/ 下载第三方包
        Invoke-WebRequest -Uri "https://packages.lazarus-ide.org/ATSynEdit.zip" -OutFile "ATSynEdit.zip"
        7z x ATSynEdit.zip -y
        # 从 Git 仓库下载第三方包
        # git clone --depth 1 https://github.com/Alexey-T/ATSynEdit
    - name: Build packages and projects
      shell: pwsh
      run: |
        $lazbuild="C:\lazarus\lazbuild.exe"
        & $lazbuild --pcp=C:\lazarus\configs --lazarusdir=C:\lazarus ATSynEdit\atsynedit\atsynedit_package.lpk
        & $lazbuild --pcp=C:\lazarus\configs --lazarusdir=C:\lazarus --bm=Release src\myproject.lpi