~gotmax23/tomcli

448335649057361fbb7a4b0ba78a86ddf06243e7 — Maxwell G a month ago 05a2b99
formatters: add newline-keys and newline-values
M pyproject.toml => pyproject.toml +2 -0
@@ 94,7 94,9 @@ Changelog = "https://tomcli.gtmx.me/news/"
[project.entry-points."tomcli.formatters"]
default = "tomcli.formatters.builtin:default_formatter"
json = "tomcli.formatters.builtin:json_formatter"
newline-keys = "tomcli.formatters.builtin:newline_keys_formatter"
newline-list = "tomcli.formatters.builtin:newline_list_formatter"
newline-values = "tomcli.formatters.builtin:newline_values_formatter"
string = "tomcli.formatters.builtin:string_formatter"
toml = "tomcli.formatters.builtin:toml_formatter"


M src/tomcli/formatters/builtin.py => src/tomcli/formatters/builtin.py +20 -0
@@ 65,3 65,23 @@ def newline_list_formatter(obj: Any) -> str:
            )
        items.append(str(item))
    return "\n".join(items)


def newline_keys_formatter(obj: Any) -> str:
    """
    Return a newline-separated list of Mapping keys
    """
    if not isinstance(obj, Mapping):  # pragma: no cover
        raise FormatterError("The object is not a Mapping")
    obj = cast("Mapping[str, Any]", obj)
    return newline_list_formatter(list(obj.keys()))


def newline_values_formatter(obj: Any) -> str:
    """
    Return a newline-separated list of Mapping values
    """
    if not isinstance(obj, Mapping):  # pragma: no cover
        raise FormatterError("The object is not a Mapping")
    obj = cast("Mapping[str, Any]", obj)
    return newline_list_formatter(list(obj.values()))

M tests/test_formatters_builtin.py => tests/test_formatters_builtin.py +16 -1
@@ 9,7 9,11 @@ from typing import Any
import pytest

from tomcli.formatters import FormatterError, get_formatters_list
from tomcli.formatters.builtin import newline_list_formatter
from tomcli.formatters.builtin import (
    newline_keys_formatter,
    newline_list_formatter,
    newline_values_formatter,
)

if sys.version_info >= (3, 11):
    import importlib.metadata as importlib_metadata


@@ 47,3 51,14 @@ def test_newline_list_formatter():
def test_newline_list_formatter_error(obj: Any, err: str) -> None:
    with pytest.raises(FormatterError, match=err):
        newline_list_formatter(obj)


def test_newline_keys_formatter() -> None:
    keys = ["a", "b", "c"]
    out = newline_keys_formatter(dict.fromkeys(keys, 1))
    assert out.splitlines() == keys


def test_newline_values_formatter() -> None:
    out = newline_values_formatter({"a": 1, "b": 2, "c": 3})
    assert out == "\n".join(["1", "2", "3"])

M tests/test_main.py => tests/test_main.py +6 -0
@@ 27,9 27,15 @@ default
json
	Return the JSON representation of the object

newline-keys
	Return a newline-separated list of Mapping keys

newline-list
	Return a newline separated list

newline-values
	Return a newline-separated list of Mapping values

string
	Print the Python str() representation of the object