Makefile - How should I extract the version number embedded in `pyproject.toml`?

Viewed 637

I have a python project with a pyproject.toml file. Typically I store the project's version number in pyproject.toml like this:

% grep version pyproject.toml 
version = "0.0.2"
%

I want to get that version number into a Makefile variable regardless of how many spaces wind up around the version terms.

What should I do to extract the pyproject.toml version string into a Makefile environment variable called VERSION?

3 Answers

This seemed to work out the best... I put this in my Makefile

# grep the version from pyproject.toml, squeeze multiple spaces, delete double
#   and single quotes, get 3rd val. This command tolerates 
#   multiple whitespace sequences around the version number
VERSION := $(shell grep -m 1 version pyproject.toml | tr -s ' ' | tr -d '"' | tr -d "'" | cut -d' ' -f3)

Special thanks to @charl-botha for the -m 1 grep argument... both gnu and bsd grep support -m in this context.

If that's all that file really contains, that's sufficiently close to makefile syntax that you can just include it as a makefile:

include pyproject.toml
all: ; echo 'version = $(version)'

$ make
echo 'version = "0.0.2"'
version = "0.0.2"

If you don't want to, or can't, do that, I'd use sed for it:

VERSION := $(shell sed -n 's/^ *version.*=.*"\([^"]*\)".*/\1/p' pyproject.toml)
all: ; echo 'version = $(VERSION)'

$ make
echo 'version = 0.0.2'
version = 0.0.2

If you have a Python available with the tomli package installed, or you're on Python 3.11 with toml built-in (in which case you would import tomllib instead of tomli), and your pyproject.toml follows poetry convention, something like the following would work well:

VERSION := $(shell python -c 'import tomli; print(tomli.load(open("pyproject.toml", "rb"))["tool"]["poetry"]["version"])')

Test on command-line with simply:

python -c 'import tomli; print(tomli.load(open("pyproject.toml", "rb"))["tool"]["poetry"]["version"])'

Obviously you can easily adapt the location of the desired version entry in the case of other pyproject.toml conventions.

BTW, tomllib is in fact tomli, see https://peps.python.org/pep-0680/#rationale

Related