Simple versioning with git tags
· One min read
A frequently asked question on Pants Slack is how to set a version - such as for a docker image, helm chart or Python distribution - based on git state.
Pants does have various solutions for this, but they tend to be too complicated, or too limited:
- Generating version tags from Git
- Custom
python_artifact()
kwargs - vcs_version target
- Using env vars to include dynamic data in tags
It turns out there is a hack that elegantly solves this problem. To make it
work we need one more pants feature hidden in the
docs
— the .pants.bootstrap
file. It makes it possible to automatically set the
VERSION
env var right before pants starts:
.pants.bootstrap
#!/bin/sh
VERSION="${VERSION:-$(git describe --tags --dirty --match "[0-9\.]*" || echo 0.0.1)}"
export VERSION
Now we can use the env var everywhere!
To set docker_image tag:
docker_image(
name="image",
image_tags=[env("VERSION")],
)
To pass docker_image build arg:
docker_image(
name="image",
extra_build_args=["VERSION=" + env("VERSION")],
)
To set python_distribution version:
python_distribution(
name="mydist",
provides=python_artifact(
name="mydist",
version=env("VERSION"),
),
)
To set helm_chart version:
helm_chart(
version=env("VERSION"),
)