Source code for stouputils.continuous_delivery.pyproject
""" Utilities for reading, writing and managing pyproject.toml files.
This module provides functions to handle pyproject.toml files, including reading,
writing, version management and TOML formatting capabilities.
- read_pyproject: Read the pyproject.toml file.
- write_pyproject: Write to the pyproject.toml file.
- format_toml_lists: Format TOML lists with proper indentation.
- increment_version_from_input: Increment the patch version number.
- increment_version_from_pyproject: Increment version in pyproject.toml.
- get_version_from_pyproject: Get version from pyproject.toml.
.. image:: https://raw.githubusercontent.com/Stoupy51/stouputils/refs/heads/main/assets/continuous_delivery/pyproject_module.gif
:alt: stouputils pyproject examples
"""
# Imports
from typing import Any
import toml
from ..io import super_open
[docs]
def read_pyproject(pyproject_path: str) -> dict[str, Any]:
""" Read the pyproject.toml file.
Args:
pyproject_path: Path to the pyproject.toml file.
Returns:
dict[str, Any]: The content of the pyproject.toml file.
"""
return toml.load(pyproject_path)
[docs]
def write_pyproject(pyproject_path: str, pyproject_content: dict[str, Any]) -> None:
""" Write to the pyproject.toml file with properly indented lists. """
content: str = "\n" + toml.dumps(pyproject_content) + "\n"
content = format_toml_lists(content) # Apply formatting
with super_open(pyproject_path, "w") as file:
file.write(content)
[docs]
def increment_version_from_pyproject(pyproject_path: str) -> None:
""" Increment the version in the pyproject.toml file.
Args:
pyproject_path: Path to the pyproject.toml file.
"""
pyproject_content: dict[str, Any] = read_pyproject(pyproject_path)
pyproject_content["project"]["version"] = increment_version_from_input(pyproject_content["project"]["version"])
write_pyproject(pyproject_path, pyproject_content)
[docs]
def get_version_from_pyproject(pyproject_path: str) -> str:
""" Get the version from the pyproject.toml file.
Args:
pyproject_path: Path to the pyproject.toml file.
Returns:
str: The version. (ex: "0.1.0")
"""
return read_pyproject(pyproject_path)["project"]["version"]