Search code examples
github-actionspypi

How to avoid invalid version numbers when publishing to TestPyPI in GitHub Actions?


I want to set up my Python project on GitHub for automatic publications to PyPI using GitHub Actions following this guide. This includes publishing to the TestPyPI server with every push. For this, I get the error:

400 The use of local versions in <Version('0.1.dev1+g18d1902')> is not allowed

As far as I can tell, the problem is the use of the Git hash in the version number. For example here the recommendation is to remove that part from the version number. However, there is no hint on how to achieve this. Also, I expect that this would cause the problem of duplicate packages.

So, how do I properly implement this?

For reference, here is the respective section of the YAML file (which is very similar to the one in the guide):

  publish-to-testpypi:
    name: Publish to TestPyPI
    needs:
    - build
    runs-on: ubuntu-latest

    environment:
      name: testpypi
      url: https://test.pypi.org/p/{{package name}}

    permissions:
      id-token: write

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


Solution

  • The solution for me was to change the way local versions are generated with setuptools_scm. Specifically, changed the respective entry in the pyproject.toml to:

    [tool.setuptools_scm]
    write_to = {{…}}
    local_scheme = "no-local-version"
    

    The latter drops the pluses and creates versions like 0.1.dev1.

    Unfortunately, as those do not change every time, I have to change the respective parts of my CI YAML file as follows:

    -name: Publish distribution to TestPyPI
     uses: pypa/gh-action-pypi-publish@release/v1
     with:
       skip-existing: true
       verbose: true
       repository-url: https://test.pypi.org/legacy/
    

    However, by skipping I miss testing the entire publishing step. On the other hand, the part of the guide that recommends publishing every version on TestPyPI is currently under scrutiny.