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
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.
Example:
>>> content = read_pyproject("pyproject.toml")
>>> "." in content["project"]["version"]
True
"""
from msgspec import toml
with open(pyproject_path) as file:
content = file.read()
return toml.decode(content)
[docs]
def write_pyproject(path: str, content: dict[str, Any]) -> None:
""" Write to the pyproject.toml file with properly indented lists.
Args:
path: Path to the pyproject.toml file.
content: Content to write to the pyproject.toml file.
"""
from msgspec.toml import _import_tomli_w # pyright: ignore[reportPrivateUsage]
toml = _import_tomli_w()
string: str = "\n" + toml.dumps(content) + "\n"
string = format_toml_lists(string) # Apply formatting
with super_open(path, "w") as file:
file.write(string)
[docs]
def increment_version_from_pyproject(path: str) -> None:
""" Increment the version in the pyproject.toml file.
Args:
path: Path to the pyproject.toml file.
"""
pyproject_content: dict[str, Any] = read_pyproject(path)
pyproject_content["project"]["version"] = increment_version_from_input(pyproject_content["project"]["version"])
write_pyproject(path, pyproject_content)
[docs]
def get_version_from_pyproject(path: str) -> str:
""" Get the version from the pyproject.toml file.
Args:
path: Path to the pyproject.toml file.
Returns:
str: The version. (ex: "0.1.0")
"""
return read_pyproject(path)["project"]["version"]