Skip to content

topmark.toml.defaults

topmark / toml / defaults

Helpers for TopMark's bundled/default TOML documents.

This module is intentionally separate from topmark.toml.loaders. It does not load TOML from arbitrary on-disk user config files. Instead, it owns the bundled template and the code-defined default TopMark TOML document used when the annotated template is unavailable.

Today, build_default_topmark_toml_table() assembles one complete TOML-serializable default TopMark document in a single place. Over time, this should evolve toward merging smaller domain-scoped default fragments such as: - layered config defaults - persisted writer-option defaults - config-resolution/discovery defaults (for example strict mode)

The current helper remains the single centralized assembly point for those partial defaults until that split is implemented.

DefaultTomlTemplateText dataclass

DefaultTomlTemplateText(*, toml_text, error=None)

Loaded default TOML template text and fallback metadata.

Attributes:

Name Type Description
toml_text str

The TOML document text to emit.

error Exception | None

The exception raised while reading the bundled template, if any. Callers may surface this as a user-facing warning.

load_default_topmark_template_toml_text

load_default_topmark_template_toml_text()

Load the bundled default TOML config template as text.

This reads the annotated template bundled with TopMark (topmark-example.toml) and returns it as UTF-8 text.

Unlike build_default_topmark_toml_table(), this helper preserves the template's comments and formatting (when the packaged resource is available).

If the packaged template cannot be read, the function falls back to a generated TOML document built from TopMark's default TOML document (build_default_topmark_toml_table). The returned result includes the exception raised while reading the packaged template.

Returns:

Type Description
DefaultTomlTemplateText

Loaded default TOML template text and fallback metadata.

Notes
  • This function performs I/O and logs a warning on fallback, but it does not print to stdout/stderr.
  • User-facing warnings should be emitted by CLI emitters.
Source code in src/topmark/toml/defaults.py
def load_default_topmark_template_toml_text() -> DefaultTomlTemplateText:
    """Load the bundled default TOML config *template* as text.

    This reads the annotated template bundled with TopMark
    (``topmark-example.toml``) and returns it as UTF-8 text.

    Unlike `build_default_topmark_toml_table()`, this helper preserves the template's
    comments and formatting (when the packaged resource is available).

    If the packaged template cannot be read, the function falls back to a
    generated TOML document built from TopMark's default TOML document
    (`build_default_topmark_toml_table`). The returned result includes the
    exception raised while reading the packaged template.

    Returns:
        Loaded default TOML template text and fallback metadata.

    Notes:
        - This function performs I/O and logs a warning on fallback, but it does
          not print to stdout/stderr.
        - User-facing warnings should be emitted by CLI emitters.
    """
    # Attempt to read the annotated bundled template; preserve comments and formatting.
    # This is the preferred source for human-facing outputs.
    resource: Traversable = files(EXAMPLE_TOPMARK_TOML_PACKAGE).joinpath(EXAMPLE_TOPMARK_TOML_NAME)
    err: Exception | None = None

    try:
        toml_text: str = resource.read_text(encoding="utf8")
        # Strip the TopMark header block (if present) so config-init output starts
        # at the actual template content.
        #
        # We remove everything up to and including the line `# topmark:header:end`.
        # Keep any subsequent blank line trimming conservative.
        lines: list[str] = toml_text.splitlines(keepends=True)
        for i, line in enumerate(lines):
            if line.strip() == f"# {TOPMARK_END_MARKER}":
                toml_text = "".join(lines[i + 1 :])
                # Remove leading blank lines introduced by stripping.
                toml_text = toml_text.lstrip("\n")
                break
    except OSError as exc:
        # Fallback: the packaged annotated template is missing/unreadable.
        # Generate a usable document from the centralized default TOML dict.
        err = exc
        logger.warning("Cannot read packaged default config template %s: %s", resource, exc)

        generated: str = render_toml_table(build_default_topmark_toml_table())

        # Make the fallback explicit in the generated output, without breaking TOML.
        notice: str = (
            "# NOTE: The packaged default configuration template 'topmark-example.toml' "
            "could not be read.\n"
            f"# Reason: {exc}\n"
            "# The content below was generated from TopMark built-in defaults and "
            "may not include the usual comments/formatting.\n\n"
        )
        trailer: str = "\n# NOTE: End of generated defaults (template was missing/unreadable).\n"
        toml_text = f"{notice}{generated}{trailer}"

    return DefaultTomlTemplateText(
        toml_text=toml_text,
        error=err,
    )

build_default_topmark_toml_table

build_default_topmark_toml_table()

Return TopMark's default TOML document as a plain-Python table.

This helper intentionally performs no I/O.

The bundled file topmark-example.toml is an annotated template intended for human-facing output (for example topmark config init). The actual default TopMark TOML document is assembled in code so TopMark can still operate when the packaged template is missing or unreadable.

Today, this helper assembles one centralized TOML-serializable default document that includes both layered config defaults and persisted writer defaults. In the future, the implementation may delegate to smaller domain-scoped helpers and then merge those partial TOML tables here.

If you need the annotated template with comments and formatting preserved, use load_default_topmark_template_toml_text() and read the returned DefaultTomlTemplateText.toml_text field.

Returns:

Type Description
TomlTable

A new TOML-table-compatible dictionary containing the default TopMark

TomlTable

TOML document.

Source code in src/topmark/toml/defaults.py
def build_default_topmark_toml_table() -> TomlTable:
    """Return TopMark's default TOML document as a plain-Python table.

    This helper intentionally performs **no I/O**.

    The bundled file `topmark-example.toml` is an annotated template intended
    for human-facing output (for example `topmark config init`). The actual
    default TopMark TOML document is assembled in code so TopMark can still
    operate when the packaged template is missing or unreadable.

    Today, this helper assembles one centralized TOML-serializable default
    document that includes both layered config defaults and persisted writer
    defaults. In the future, the implementation may delegate to smaller
    domain-scoped helpers and then merge those partial TOML tables here.

    If you need the annotated template with comments and formatting preserved,
    use `load_default_topmark_template_toml_text()` and read the returned
    `DefaultTomlTemplateText.toml_text` field.

    Returns:
        A new TOML-table-compatible dictionary containing the default TopMark
        TOML document.
    """
    # Keep this document small and stable: it is the centralized default
    # TopMark TOML document assembled in code.
    return {
        **_build_default_config_metadata_toml(),
        **_build_default_layered_config_toml(),
        **_build_default_writer_toml(),
    }

render_default_topmark_toml_text

render_default_topmark_toml_text(*, for_pyproject)

Render the centralized default TopMark TOML document as text.

This helper is I/O-free: it serializes the TOML table returned by build_default_topmark_toml_table(). It does not preserve the annotated template's comments or formatting.

Note

The rendered content is the default TopMark TOML document, not execution-only RunOptions.

Parameters:

Name Type Description Default
for_pyproject bool

If True, nest the output under [tool.topmark].

required

Returns:

Type Description
str

TOML document text.

Source code in src/topmark/toml/defaults.py
def render_default_topmark_toml_text(
    *,
    for_pyproject: bool,
) -> str:
    """Render the centralized default TopMark TOML document as text.

    This helper is I/O-free: it serializes the TOML table returned by
    `build_default_topmark_toml_table()`. It does not preserve the annotated template's
    comments or formatting.

    Note:
        The rendered content is the default TopMark TOML document,
        not execution-only `RunOptions`.

    Args:
        for_pyproject: If `True`, nest the output under `[tool.topmark]`.

    Returns:
        TOML document text.
    """
    toml_text: str = render_toml_table(build_default_topmark_toml_table())
    if for_pyproject:
        toml_text = nest_toml_under_section(
            toml_text,
            "tool.topmark",
        )  # Raises ValueError, TomlParseError, TomlSurgeryError

    return toml_text