name: Build and publish package

on:
  - push
  - pull_request

jobs:
  build:
    runs-on: ubuntu-latest
    name: Build LNT package
    steps:
    - uses: actions/checkout@v5
      with:
        fetch-depth: 0 # fetch all history including tags -- necessary to determine the version from SCM
        persist-credentials: false
    - name: Set up Python
      uses: actions/setup-python@v5
      with:
        python-version: "3.10"
    # We only build a source distribution because binary distributions for Linux can't be uploaded
    # to PyPI. Our source distribution is trivial to build anyway.
    - name: Build the source tarball
      run: |
        python -m pip install build
        python -m build --sdist
    - name: Store the distribution packages
      uses: actions/upload-artifact@v4
      with:
        name: python-package-distributions
        path: dist/


  publish-to-testpypi:
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/') # only publish to TestPyPI on tag pushes

    name: Publish LNT to TestPyPI
    needs: [build]
    environment:
      name: testpypi
      url: https://test.pypi.org/p/llvm-lnt
    permissions:
      id-token: write

    steps:
    - name: Download distributions
      uses: actions/download-artifact@v4
      with:
        name: python-package-distributions
        path: dist/
    - name: Publish LNT to TestPyPI
      uses: pypa/gh-action-pypi-publish@release/v1
      with:
        repository-url: https://test.pypi.org/legacy/
        verbose: true


  publish-to-pypi:
    runs-on: ubuntu-latest
    name: Publish LNT to PyPI
    if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes
    needs: [build]
    environment:
      name: pypi
      url: https://pypi.org/p/llvm-lnt
    permissions:
      id-token: write

    steps:
    - name: Download distributions
      uses: actions/download-artifact@v4
      with:
        name: python-package-distributions
        path: dist/
    - name: Publish LNT to PyPI
      uses: pypa/gh-action-pypi-publish@release/v1
      with:
        verbose: true
