Search code examples
pythontravis-cipypi

Travis pypi package version


I've setted up travis.ci to automatically deploy to pypi a package when a push to master is tagged.

The problem is that in my setup.py I've to specify the package version, and sometimes I forget that resulting in a non deployed package (or does Pypi overwrites the old one?)

Nevertheless, Is there a way to match the package version on pypi as the tag that is assigned to the commit?


Solution

  • I have already done it in one of my projects.

    [EDIT N°2] I wrote a little tutorial you can find here: https://github.com/73VW/Publishing-to-PyPI-with-pbr-and-Travis

    V1. Using PBR

    You can find it here on Github.

    What Travis basically does is the following:

    • Check if commit has a tag
    • If so, check the format with a regex (/(\d+\.)?(\d+\.)?(\*|\d+)$/)
    • If the tag is something like 1.0.0 it uses it for pypi version.

      You can still transform the regex to also match tags like v1.0.0. Use something like /v?(\d+\.)?(\d+\.)?(\*|\d+)$/

      [EDIT N°3] This was completely wrong, PBR can't define version if the tag doesn't match what is described here https://docs.openstack.org/pbr/3.1.0/semver.html.

    I use PBR to do this.

    A library for managing setuptools packaging needs in a consistent manner.

    Check the following files in my repository:

    If you still have troubles, feel free to tag me (@73VW) on github or ask directly here.

    Have a nice day.

    [EDIT]

    V2. Using sed

    In git you can get the last tag with the following command git describe --abbrev=0 --tags

    Thereby, if your setup is something like the following:

    from setuptools import setup
    ...
    
    setup(
        ...
        version='NEWVERSIONHERE',
        ...
    )
    

    You could use a shell script to replace NEWVERSIONHERE by your tag version.

    I tried the following (locally, not on Travis) and it works.

    #!/bin/sh
    
    set -xe
    TAG=$(git describe --abbrev=0 --tags)
    
    sed -i "s/NEWVERSIONHERE/${TAG}/g" setup.py
    

    The -i flag is used to find and replace in place. Thereby it changes in the file you have specified.

    Simply put this code in a shell script, don't forget to chmod it in order to be able to run it, and run it from Travis.

    Example .travis.yml file:

    dist: trusty
    sudo: required
    
    language: python
    python: 3.6
    
    cache: apt
    
    install:
      - pip install -r requirements.txt
      - chmod 777 YOURSCRIPT.sh
    
    script:
      - your tests here
      - ./YOURSCRIPT.sh
    
    deploy:
      skip_cleanup: true
      provider: pypi
      distributions: sdist bdist_wheel
      on:
        tags: true
        branch:
          - master
          - /(\d+\.)?(\d+\.)?(\*|\d+)$/
      user: YOUR PYPI USERNAME
      password:
      secure: YOUR PYPI ENCODED PASSWORD
    

    Hope this helps!