0x1337
0x1337

Reputation: 1104

Create and include new file into python package

I want to use version for my package base on git describe command. For this, I created setup.py with function get_version(). This function retrieves version from .version file if it exists, else computes new package version and writes it to a new .version file. However, when I call python setup.py sdist, .version is not copying inside .tar archive. This causes error when I'm trying to install package from PyPi repo. How to properly include my .version file "on the fly" into package?

setup.py:

import pathlib
from subprocess import check_output
from setuptools import find_packages, setup


_VERSION_FILE = pathlib.Path(".version")  # Add it to .gitignore!
_GIT_COMMAND = "git describe --tags --long --dirty"
_VERSION_FORMAT = "{tag}.dev{commit_count}+{commit_hash}"


def get_version() -> str:
    """ Return version from git, write commit to file
    """
    if _VERSION_FILE.is_file():
        with _VERSION_FILE.open() as f:
            return f.readline().strip()
    output = check_output(_GIT_COMMAND.split()).decode("utf-8").strip().split("-")

    tag, count, commit = output[:3]
    dirty = len(output) == 4

    if count == "0" and not dirty:
        return tag

    version = _VERSION_FORMAT.format(tag=tag, commit_count=count, commit_hash=commit)

    with _VERSION_FILE.open("w") as f:
        print(version, file=f, end="")

    return version


_version = get_version()

setup(
    name="mypackage",
    package_data={
        "": [str(_VERSION_FILE)]
    },
    version=_version,
    packages=find_packages(exclude=["tests"]),
)

Upvotes: 1

Views: 444

Answers (2)

0x1337
0x1337

Reputation: 1104

It was a mistake in setup.py. I forgot to add file dumping in if count == "0" and not dirty:. Now it works with MANIFEST.in.

Upvotes: 1

PirateNinjas
PirateNinjas

Reputation: 2076

If you include a file called MANIFEST.in in the same directory as setup.py with include .version inside, this should get the file picked up.

Upvotes: 1

Related Questions