Skip to content

Formats

provide.foundation.file.formats

TODO: Add module docstring.

Functions

read_json

read_json(
    path: Path | str,
    default: Any = None,
    encoding: str = "utf-8",
) -> Any

Read JSON file with error handling.

Parameters:

Name Type Description Default
path Path | str

JSON file path

required
default Any

Default value if file doesn't exist or is invalid

None
encoding str

Text encoding

'utf-8'

Returns:

Type Description
Any

Parsed JSON data or default value

Source code in provide/foundation/file/formats.py
def read_json(
    path: Path | str,
    default: Any = None,
    encoding: str = "utf-8",
) -> Any:
    """Read JSON file with error handling.

    Args:
        path: JSON file path
        default: Default value if file doesn't exist or is invalid
        encoding: Text encoding

    Returns:
        Parsed JSON data or default value

    """
    content = safe_read_text(path, default="", encoding=encoding)

    if not content:
        log.debug("Empty or missing JSON file, returning default", path=str(path))
        return default

    try:
        return json_loads(content)
    except Exception as e:
        log.warning("Invalid JSON file", path=str(path), error=str(e))
        return default

read_toml

read_toml(
    path: Path | str,
    default: Any = None,
    encoding: str = "utf-8",
) -> dict[str, Any]

Read TOML file with error handling.

Parameters:

Name Type Description Default
path Path | str

TOML file path

required
default Any

Default value if file doesn't exist or is invalid

None
encoding str

Text encoding

'utf-8'

Returns:

Type Description
dict[str, Any]

Parsed TOML data or default value

Source code in provide/foundation/file/formats.py
def read_toml(
    path: Path | str,
    default: Any = None,
    encoding: str = "utf-8",
) -> dict[str, Any]:
    """Read TOML file with error handling.

    Args:
        path: TOML file path
        default: Default value if file doesn't exist or is invalid
        encoding: Text encoding

    Returns:
        Parsed TOML data or default value

    """
    content = safe_read_text(path, default="", encoding=encoding)

    if not content:
        log.debug("Empty or missing TOML file, returning default", path=str(path))
        return default if default is not None else {}

    try:
        return toml_loads(content)
    except Exception as e:
        log.warning("Invalid TOML file", path=str(path), error=str(e))
        return default if default is not None else {}

read_yaml

read_yaml(
    path: Path | str,
    default: Any = None,
    encoding: str = "utf-8",
) -> Any

Read YAML file with error handling.

Parameters:

Name Type Description Default
path Path | str

YAML file path

required
default Any

Default value if file doesn't exist or is invalid

None
encoding str

Text encoding

'utf-8'

Returns:

Type Description
Any

Parsed YAML data or default value

Source code in provide/foundation/file/formats.py
def read_yaml(
    path: Path | str,
    default: Any = None,
    encoding: str = "utf-8",
) -> Any:
    """Read YAML file with error handling.

    Args:
        path: YAML file path
        default: Default value if file doesn't exist or is invalid
        encoding: Text encoding

    Returns:
        Parsed YAML data or default value

    """
    try:
        import yaml  # noqa: F401
    except ImportError:
        log.warning("PyYAML not installed, returning default")
        return default

    content = safe_read_text(path, default="", encoding=encoding)

    if not content:
        log.debug("Empty or missing YAML file, returning default", path=str(path))
        return default

    try:
        return yaml_loads(content)
    except Exception as e:
        log.warning("Invalid YAML file", path=str(path), error=str(e))
        return default

write_json

write_json(
    path: Path | str,
    data: Any,
    indent: int = 2,
    sort_keys: bool = False,
    atomic: bool = True,
    encoding: str = "utf-8",
) -> None

Write JSON file, optionally atomic.

Parameters:

Name Type Description Default
path Path | str

JSON file path

required
data Any

Data to serialize

required
indent int

Indentation level (None for compact)

2
sort_keys bool

Whether to sort dictionary keys

False
atomic bool

Use atomic write

True
encoding str

Text encoding

'utf-8'
Source code in provide/foundation/file/formats.py
def write_json(
    path: Path | str,
    data: Any,
    indent: int = 2,
    sort_keys: bool = False,
    atomic: bool = True,
    encoding: str = "utf-8",
) -> None:
    """Write JSON file, optionally atomic.

    Args:
        path: JSON file path
        data: Data to serialize
        indent: Indentation level (None for compact)
        sort_keys: Whether to sort dictionary keys
        atomic: Use atomic write
        encoding: Text encoding

    """
    path = Path(path)

    try:
        content = json_dumps(data, indent=indent, sort_keys=sort_keys, ensure_ascii=False)

        if atomic:
            atomic_write_text(path, content, encoding=encoding)
        else:
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_text(content, encoding=encoding)

        log.debug("Wrote JSON file", path=str(path), atomic=atomic)
    except Exception as e:
        log.error("Failed to write JSON file", path=str(path), error=str(e))
        raise

write_toml

write_toml(
    path: Path | str,
    data: dict[str, Any],
    atomic: bool = True,
    encoding: str = "utf-8",
) -> None

Write TOML file, optionally atomic.

Parameters:

Name Type Description Default
path Path | str

TOML file path

required
data dict[str, Any]

Data to serialize (must be a dictionary)

required
atomic bool

Use atomic write

True
encoding str

Text encoding

'utf-8'
Source code in provide/foundation/file/formats.py
def write_toml(
    path: Path | str,
    data: dict[str, Any],
    atomic: bool = True,
    encoding: str = "utf-8",
) -> None:
    """Write TOML file, optionally atomic.

    Args:
        path: TOML file path
        data: Data to serialize (must be a dictionary)
        atomic: Use atomic write
        encoding: Text encoding

    """
    try:
        import tomli_w  # noqa: F401
    except ImportError as e:
        raise ImportError("tomli-w is required for TOML write operations") from e

    path = Path(path)

    try:
        content = toml_dumps(data)

        if atomic:
            atomic_write_text(path, content, encoding=encoding)
        else:
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_text(content, encoding=encoding)

        log.debug("Wrote TOML file", path=str(path), atomic=atomic)
    except Exception as e:
        log.error("Failed to write TOML file", path=str(path), error=str(e))
        raise

write_yaml

write_yaml(
    path: Path | str,
    data: Any,
    atomic: bool = True,
    encoding: str = "utf-8",
    default_flow_style: bool = False,
) -> None

Write YAML file, optionally atomic.

Parameters:

Name Type Description Default
path Path | str

YAML file path

required
data Any

Data to serialize

required
atomic bool

Use atomic write

True
encoding str

Text encoding

'utf-8'
default_flow_style bool

Use flow style (JSON-like) instead of block style

False
Source code in provide/foundation/file/formats.py
def write_yaml(
    path: Path | str,
    data: Any,
    atomic: bool = True,
    encoding: str = "utf-8",
    default_flow_style: bool = False,
) -> None:
    """Write YAML file, optionally atomic.

    Args:
        path: YAML file path
        data: Data to serialize
        atomic: Use atomic write
        encoding: Text encoding
        default_flow_style: Use flow style (JSON-like) instead of block style

    """
    try:
        import yaml  # noqa: F401
    except ImportError as e:
        raise ImportError("PyYAML is required for YAML operations") from e

    path = Path(path)

    try:
        content = yaml_dumps(
            data,
            default_flow_style=default_flow_style,
            allow_unicode=True,
            sort_keys=False,
        )

        if atomic:
            atomic_write_text(path, content, encoding=encoding)
        else:
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_text(content, encoding=encoding)

        log.debug("Wrote YAML file", path=str(path), atomic=atomic)
    except Exception as e:
        log.error("Failed to write YAML file", path=str(path), error=str(e))
        raise