GitHub

primitive

API reference for primitive.

How one command-line string becomes a value (Effect's Primitive).

A Primitive[A] has a tag ("Boolean", "Int", ...) used for help and completions, and parse: the effect turning the text into an A or failing with a message for the user. Flags and arguments are built on them; most programs never touch one directly::

yield from primitive.integer.parse("42")  # 42

Values

AttributeTypeDescription
booleanPrimitive[bool]

true / yes / on / 1 / y and false / no / off / 0 / n.

finitePrimitive[float]

A finite number, as JavaScript reads one (1e3, -42.5).

integerPrimitive[int]

An integer (1e3 is 1000; 3.14 is not one).

date_Primitive[datetime]

A date as JavaScript's Date reads it, as a UTC datetime: ISO 8601 (a date alone is midnight UTC, a date-time without an offset local time) or V8's other forms (Jan 15 2024, 1/15/2024 10:00 PM).

stringPrimitive[str]
redactedPrimitive[Redacted[str]]

The text, wrapped so it never shows in logs or output.

file_textPrimitive[str]

The contents of the file at the path.

key_value_pairPrimitive[dict[str, str]]

key=value (the value may hold more =), as a one-entry dict.

neverPrimitive[Never]

Accepts nothing.

Types

TypeDefinitionDescription
PathTypetype PathType = Literal['file', 'directory', 'either']
FileFormattype FileFormat = Literal['ini', 'json', 'toml', 'yaml']

Classes

Functions

is_true_literal

is_true_literal(value) -> bool
ParameterTypeDescription
valuestr

Returns bool

def is_true_literal(value: str) -> bool:
    return value in _TRUE_LITERALS

is_false_literal

is_false_literal(value) -> bool
ParameterTypeDescription
valuestr

Returns bool

def is_false_literal(value: str) -> bool:
    return value in _FALSE_LITERALS

choice

choice[A](choices) -> Primitive[A]

One of the keys, giving its value; otherwise fails with the keys.

ParameterTypeDescription
choicesSequence[tuple[str, A]]

Returns Primitive[A]

def choice[A](choices: Sequence[tuple[str, A]]) -> Primitive[A]:
    """One of the keys, giving its value; otherwise fails with the keys."""
    mapping = dict(choices)
    valid = " | ".join(stringify(key) for key, _ in choices)

    def parse(value: str) -> Effect[A, str]:
        if value in mapping:
            return succeed(mapping[value])
        return fail(valid)

    return Primitive("Choice", parse, choice_keys=tuple(key for key, _ in choices))

path

path(path_type, must_exist=False) -> Primitive[str]

A path, resolved to an absolute one. With must_exist it must exist; an existing path must be of path_type.

ParameterTypeDescription
path_typePathType
must_existbool = False

Returns Primitive[str]

def path(path_type: PathType, must_exist: bool = False) -> Primitive[str]:
    """A path, resolved to an absolute one. With ``must_exist`` it must
    exist; an existing path must be of ``path_type``."""

    def parse(value: str) -> Effect[str, str, Environment]:
        def body():
            fs = yield from FileSystem()
            absolute = yield from _absolute(value)
            exists = yield from fs.exists(absolute).map_error(
                lambda e: f"Failed to check path existence: {e.message}"
            )
            if must_exist and not exists:
                return (yield from fail(f"Path does not exist: {absolute}"))
            if exists and path_type != "either":
                info = yield from fs.stat(absolute).map_error(
                    lambda e: f"Failed to stat path: {e.message}"
                )
                if path_type == "file" and info.type != "File":
                    return (yield from fail(f"Path is not a file: {absolute}"))
                if path_type == "directory" and info.type != "Directory":
                    return (yield from fail(f"Path is not a directory: {absolute}"))
            return absolute

        return gen(body)

    return Primitive("Path", parse, path_type=path_type)

file_parse

file_parse(format=None) -> Primitive[object]

The parsed contents of the file at the path: INI, JSON, TOML or YAML, by format or else the file's extension (.yml is YAML too).

ParameterTypeDescription
formatFileFormat | None = None

Returns Primitive[object]

def file_parse(format: FileFormat | None = None) -> Primitive[object]:
    """The parsed contents of the file at the path: INI, JSON, TOML or YAML,
    by ``format`` or else the file's extension (``.yml`` is YAML too)."""

    def parse(file_path: str) -> Effect[object, str, Environment]:
        def body():
            file_format = format or file_path.rsplit(".", 1)[-1]
            parser = _FILE_PARSERS.get(file_format)
            if parser is None:
                return (yield from fail(f"Unsupported file format: {file_format}"))
            content = yield from _read_file_text(file_path)
            try:
                return parser(content)
            except Exception as error:
                return (
                    yield from fail(
                        f"Failed to parse '.{file_format}' file content: {_js_error_text(error)}"
                    )
                )

        return gen(body)

    return Primitive("FileParse", parse)

file_schema

file_schema[A](schema, *, format=None, error_formatter=None) -> Primitive[A]

The file's parsed contents (as file_parse) decoded by schema; a decoding failure is error_formatter(issue) or the schema error's message.

ParameterTypeDescription
schemaCodec[A, object, Environment, object]
formatFileFormat | None = None
error_formatterCallable[[Issue], str] | None = None

Returns Primitive[A]

def file_schema[A](
    schema: Codec[A, object, Environment, object],
    *,
    format: FileFormat | None = None,
    error_formatter: Callable[[Issue], str] | None = None,
) -> Primitive[A]:
    """The file's parsed contents (as ``file_parse``) decoded by ``schema``;
    a decoding failure is ``error_formatter(issue)`` or the schema error's
    message."""
    decode = S.decode_unknown_effect(schema)
    parse_file = file_parse(format).parse

    def parse(file_path: str) -> Effect[A, str, Environment]:
        def body():
            content = yield from parse_file(file_path)
            return (
                yield from decode(content).map_error(
                    lambda error: error_formatter(error.issue) if error_formatter else error.message
                )
            )

        return gen(body)

    return Primitive("FileSchema", parse)

type_name

type_name(primitive) -> str

The name help shows for the primitive's values.

ParameterTypeDescription
primitivePrimitive[Any]

Returns str

def type_name(primitive: Primitive[Any]) -> str:
    """The name help shows for the primitive's values."""
    return _TYPE_NAMES.get(primitive.tag, "value")

is_boolean

is_boolean(primitive) -> bool
ParameterTypeDescription
primitivePrimitive[Any]

Returns bool

def is_boolean(primitive: Primitive[Any]) -> bool:
    return primitive.tag == "Boolean"