name: Build and test PyBDSF

on:
  pull_request:
  push:
    branches: ["master"]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v6
    - uses: actions/setup-python@v6
      with:
        python-version: "3.12"

    - name: Get environment variables from pyproject.toml
      shell: python
      run: |
        import os, re, tomllib

        with open("pyproject.toml", "rb") as f:
            toml = tomllib.load(f)

        # Extract key-value pairs from the environment used by cibuildwheel
        matches = re.findall(
            r'(\w+)=(".*?"|\S+)',
            toml["tool"]["cibuildwheel"]["environment"]
        )

        # Add every key-value pair to the environment, so that if a value contains an
        # environment variable, it can be expanded before it is added to GITHUB_ENV.
        # This is needed, because variables in GITHUB_ENV will not be expanded.
        with open(os.environ["GITHUB_ENV"], "a") as f:
          for key, value in matches:
            value = os.path.expandvars(value.strip('"'))
            os.environ[key] = value
            f.write(f"{key}={value}\n")

    - name: Build and install Boost
      run: |
        cibuildwheel/before_all.sh
        cibuildwheel/before_build.sh

    - name: Build and install PyBDSF
      run: |
        python -m pip install .

    - name: Test PyBDSF
      run: |
        cd test && python tbdsf_process_image.py
