Skip to content

livery.workshop._categories

livery.workshop._categories

The two questions the workshop asks about a path, on two axes.

A path's category says what it is to its package: source, test, test support, configuration, and whatever a table adds, prose, example, asset, nav. Its channel says who wrote it and where to edit it: rendered, generated, materialised, seed, contract, yours. Neither answer can be read off the other, so the vocabularies stay apart: category_of answers the first, and channel_of the second from the rules register_channels adds.

A category rule is a pattern in a table, since nothing a category needs reads state: an extension declares its own table under [categories] in its extension.toml, and the base's two tables are data here, BASE_RULES beneath every package's extensions and WORKSPACE_RULES for the workspace's own unit. A channel rule is a callable with a rank, since it reads the delivery manifest, the emitted set and the template source.

The most specific category rule wins. Between rules of one specificity from two tables, the nearer table wins: of the extensions a package holds, the one later in composition order, where an extension comes after the extensions it requires and the others go alphabetically, and the base's table last. Two rules of one table and one specificity that claim one path for different categories, or from different extensions, refuse naming both, so two checkouts of one commit answer alike and the order a table lists its rules in settles nothing in silence. A package's contract may reassign its own paths among the categories, [categories] vendored = ["docs/assets/vendor/**"], and that table wins over every rule of its extensions and the base.

Classes:

Name Description
CategoryError

Two rules claim one path at one level; the message names both.

CategoryRule

One pattern's claim on a category.

Category

A path's category, and who supplied the rule that answered.

Provenance

One file's channel answer: the channel, the source, the edit path.

ChannelRule

One callable's claim on the channel axis.

Channel

A path's channel answer and who supplied it.

Functions:

Name Description
specificity

pattern's specificity: the literal characters it names, then its segments.

matches

Whether pattern claims path, a relative posix path.

category_rules

The rules that answer for a package holding extensions, the nearest first.

workspace_rules

The rules that answer for the workspace's own unit: its table alone.

extension_rules

The category rules extension declares, in a table named after it.

category_of

Say what path, relative to package's directory, is to the package.

register_channels

Register channel rules; a rule of the same name is replaced.

channel_rules

Every channel rule, highest rank first, registration order within a rank.

channel_of

Who wrote relative inside root, or None when no rule claims it.

known_categories

The four builtin categories, and every category the base's two tables name.

Attributes:

Name Type Description
SOURCE
TEST
TEST_SUPPORT
CONFIGURATION
EXAMPLE
WORKSPACE
BASE_TABLE
ChannelJudge
BASE_RULES tuple[CategoryRule, ...]
WORKSPACE_RULES tuple[CategoryRule, ...]

SOURCE module-attribute

SOURCE = 'source'

TEST module-attribute

TEST = 'test'

TEST_SUPPORT module-attribute

TEST_SUPPORT = 'test-support'

CONFIGURATION module-attribute

CONFIGURATION = 'configuration'

EXAMPLE module-attribute

EXAMPLE = 'example'

WORKSPACE module-attribute

WORKSPACE = 'workspace'

BASE_TABLE module-attribute

BASE_TABLE = 'base'

ChannelJudge module-attribute

ChannelJudge = Callable[[Path, Path, 'frozenset[str] | None'], 'Provenance | None']

BASE_RULES module-attribute

BASE_RULES: tuple[CategoryRule, ...] = tuple(CategoryRule(BASE_TABLE, pattern, category, _BASE) for pattern, category in (('docs/**/*.md', 'prose'), ('docs/nav.toml', 'nav'), ('docs/assets/**', 'asset'), ('docs/examples/**/*.py', EXAMPLE), ('docs/_generated/**', 'generated'), ('**', CONFIGURATION)))

WORKSPACE_RULES module-attribute

WORKSPACE_RULES: tuple[CategoryRule, ...] = tuple(CategoryRule(WORKSPACE, pattern, category, _BASE) for pattern, category in (('tests/**/test_*.py', TEST), ('tests/**/*_test.py', TEST), ('tests/**', TEST_SUPPORT), ('notes/**', 'notes'), ('docs/**', 'site'), ('zensical.toml', 'site'), ('README.md', 'readme'), ('**', CONFIGURATION)))

CategoryError

Bases: ValueError

Two rules claim one path at one level; the message names both.

Two category rules of one table and one specificity, or two channel rules of one rank.

CategoryRule dataclass

CategoryRule(table: str, pattern: str, category: str, extension: str)

One pattern's claim on a category.

Attributes:

Name Type Description
table str

The table the rule belongs to: the extension that declares it, or base or workspace, the base's two.

pattern str

A path pattern relative to the package, src/**, tests/**/test_*.py, **.

category str

The label the pattern claims.

extension str

The extension that supplied the rule; the base's own is livery.workshop.

table instance-attribute

table: str

pattern instance-attribute

pattern: str

category instance-attribute

category: str

extension instance-attribute

extension: str

specificity property

specificity: tuple[int, int]

How specific the pattern is: its literal characters, then its segments.

Category dataclass

Category(name: str, supplier: str, pattern: str)

A path's category, and who supplied the rule that answered.

Attributes:

Name Type Description
name str

The category.

supplier str

The extension whose rule answered, or the package for its own contract's exception.

pattern str

The pattern that matched.

name instance-attribute

name: str

supplier instance-attribute

supplier: str

pattern instance-attribute

pattern: str

Provenance dataclass

Provenance(channel: str, source: str, edit: str)

One file's channel answer: the channel, the source, the edit path.

Attributes:

Name Type Description
channel str

The owning channel's short name.

source str

Where the content comes from.

edit str

What to change, and through which verb.

channel instance-attribute

channel: str

source instance-attribute

source: str

edit instance-attribute

edit: str

ChannelRule dataclass

ChannelRule(name: str, judge: ChannelJudge, rank: int, extension: str)

One callable's claim on the channel axis.

Attributes:

Name Type Description
name str

The rule's name, for a refusal.

judge ChannelJudge

Answers for a path, or None when the rule does not claim it; called with the root, the relative path, and the emitted set when the caller computed one.

rank int

Higher ranks answer first; two rules of one rank both answering refuse naming both.

extension str

The extension that registered the rule.

name instance-attribute

name: str

judge instance-attribute

judge: ChannelJudge

rank instance-attribute

rank: int

extension instance-attribute

extension: str

Channel dataclass

Channel(provenance: Provenance, supplier: str)

A path's channel answer and who supplied it.

Attributes:

Name Type Description
provenance Provenance

The answer.

supplier str

The extension whose rule answered.

provenance instance-attribute

provenance: Provenance

supplier instance-attribute

supplier: str

specificity

specificity(pattern: str) -> tuple[int, int]

pattern's specificity: the literal characters it names, then its segments.

tests/**/test_*.py names 13 characters and beats tests/** with 5, which beats ** with none; a longer path prefix beats a shorter one the same way.

Source code in packages/workshop/src/livery/workshop/_categories.py
def specificity(pattern: str) -> tuple[int, int]:
    """*pattern*'s specificity: the literal characters it names, then its segments.

    ``tests/**/test_*.py`` names 13 characters and beats ``tests/**``
    with 5, which beats ``**`` with none; a longer path prefix beats
    a shorter one the same way.
    """
    literal = sum(
        len(segment.replace("*", "").replace("?", "")) for segment in pattern.split("/")
    )
    return (literal, len(pattern.split("/")))

matches

matches(pattern: str, path: str) -> bool

Whether pattern claims path, a relative posix path.

Source code in packages/workshop/src/livery/workshop/_categories.py
def matches(pattern: str, path: str) -> bool:
    """Whether *pattern* claims *path*, a relative posix path."""
    return _regex(pattern).match(path) is not None

category_rules

category_rules(extensions: Iterable[str]) -> tuple[CategoryRule, ...]

The rules that answer for a package holding extensions, the nearest first.

Each extension's declared table, the one later in composition order first, then the base's table. While the extensions' declared order has no start, they come in alphabetical order. An extension nothing installed declares adds no rule.

Source code in packages/workshop/src/livery/workshop/_categories.py
def category_rules(extensions: Iterable[str]) -> tuple[CategoryRule, ...]:
    """The rules that answer for a package holding *extensions*, the nearest first.

    Each extension's declared table, the one later in composition
    order first, then the base's table. While the extensions' declared
    order has no start, they come in alphabetical order. An extension
    nothing installed declares adds no rule.
    """
    from livery.workshop._composition import order_or_sorted
    from livery.workshop._extensions import installed_declaration

    found: list[CategoryRule] = []
    for name in reversed(order_or_sorted(extensions, installed_declaration)):
        found.extend(extension_rules(name))
    found.extend(BASE_RULES)
    return tuple(found)

workspace_rules

workspace_rules() -> tuple[CategoryRule, ...]

The rules that answer for the workspace's own unit: its table alone.

Source code in packages/workshop/src/livery/workshop/_categories.py
def workspace_rules() -> tuple[CategoryRule, ...]:
    """The rules that answer for the workspace's own unit: its table alone."""
    return WORKSPACE_RULES

extension_rules

extension_rules(extension: str) -> tuple[CategoryRule, ...]

The category rules extension declares, in a table named after it.

Empty for an extension nothing installed declares.

Source code in packages/workshop/src/livery/workshop/_categories.py
def extension_rules(extension: str) -> tuple[CategoryRule, ...]:
    """The category rules *extension* declares, in a table named after it.

    Empty for an extension nothing installed declares.
    """
    from livery.workshop._extensions import installed_declaration

    declared = installed_declaration(extension)
    if declared is None:
        return ()
    return tuple(
        CategoryRule(extension, pattern, category, extension)
        for category, patterns in declared.categories
        for pattern in patterns
    )

category_of

category_of(package: Package, path: str) -> Category

Say what path, relative to package's directory, is to the package.

The package's own [categories] exception answers first. Then the most specific rule of the tables that answer for the package wins, and between rules of one specificity the nearer table's: the extension later in composition order, the base's table last. Nothing matching is configuration, which the base's table also says last. The base's table names the documentation's paths (prose, nav, asset, example, generated) and everything else configuration; the extensions a package holds name the rest, such as source and test. The workspace's own tests (livery.workshop.WORKSPACE_TESTS) are answered by one table of the base's alone, in which a file under tests/ is test or test-support.

Returns:

Type Description
Category

The category's name, who supplied the rule that answered, and

Category

the pattern that matched.

Raises:

Type Description
CategoryError

a ValueError, when two rules of one specificity and one table claim path for different categories or from different extensions.

Source code in packages/workshop/src/livery/workshop/_categories.py
def category_of(package: Package, path: str) -> Category:
    """Say what *path*, relative to *package*'s directory, is to the package.

    The package's own ``[categories]`` exception answers first. Then
    the most specific rule of the tables that answer for the package
    wins, and between rules of one specificity the nearer table's: the
    extension later in composition order, the base's table last.
    Nothing matching is configuration, which the base's table also says
    last. The base's table names the documentation's paths (``prose``,
    ``nav``, ``asset``, ``example``, ``generated``) and everything else
    ``configuration``; the extensions a package holds name the rest,
    such as ``source`` and ``test``. The workspace's own tests
    ([livery.workshop.WORKSPACE_TESTS][]) are answered by one table of
    the base's alone, in which a file under ``tests/`` is ``test`` or
    ``test-support``.

    Returns:
        The category's name, who supplied the rule that answered, and
        the pattern that matched.

    Raises:
        CategoryError: a ValueError, when two rules of one specificity
            and one table claim *path* for different categories or from
            different extensions.
    """
    for category, patterns in package.categories:
        for pattern in patterns:
            if matches(pattern, path):
                return Category(category, "the package", pattern)
    rules = _package_rules(package)
    best: list[tuple[int, CategoryRule]] = []
    tables = {
        name: index for index, name in enumerate(dict.fromkeys(r.table for r in rules))
    }
    for rule in rules:
        if not matches(rule.pattern, path):
            continue
        if not best:
            best = [(tables[rule.table], rule)]
            continue
        _, current = best[0]
        if rule.specificity > current.specificity:
            best = [(tables[rule.table], rule)]
        elif rule.specificity == current.specificity:
            best.append((tables[rule.table], rule))
    if not best:
        return Category(CONFIGURATION, _BASE, "")
    nearest = min(depth for depth, _ in best)
    at_nearest = [rule for depth, rule in best if depth == nearest]
    if len(at_nearest) > 1 and any(
        rule.category != at_nearest[0].category
        or rule.extension != at_nearest[0].extension
        for rule in at_nearest
    ):
        first, second = at_nearest[0], at_nearest[1]
        raise CategoryError(
            f"{package.path}/{path}: two rules of one specificity claim it,"
            f" {first.pattern!r} as {first.category} ({first.extension}) and"
            f" {second.pattern!r} as {second.category} ({second.extension});"
            " the more specific pattern wins, so one of them names the file"
            " more closely"
        )
    rule = at_nearest[0]
    return Category(rule.category, rule.extension, rule.pattern)

register_channels

register_channels(rules: Iterable[ChannelRule]) -> None

Register channel rules; a rule of the same name is replaced.

Source code in packages/workshop/src/livery/workshop/_categories.py
def register_channels(rules: Iterable[ChannelRule]) -> None:
    """Register channel *rules*; a rule of the same name is replaced."""
    for rule in rules:
        _CHANNELS[:] = [known for known in _CHANNELS if known.name != rule.name]
        _CHANNELS.append(rule)

channel_rules

channel_rules() -> tuple[ChannelRule, ...]

Every channel rule, highest rank first, registration order within a rank.

Source code in packages/workshop/src/livery/workshop/_categories.py
def channel_rules() -> tuple[ChannelRule, ...]:
    """Every channel rule, highest rank first, registration order within a rank."""
    return tuple(sorted(_CHANNELS, key=lambda rule: -rule.rank))

channel_of

channel_of(root: Path, relative: Path, *, emitted: frozenset[str] | None = None) -> Channel | None

Who wrote relative inside root, or None when no rule claims it.

Raises:

Type Description
CategoryError

when two rules of one rank both claim the path.

Source code in packages/workshop/src/livery/workshop/_categories.py
def channel_of(
    root: Path, relative: Path, *, emitted: frozenset[str] | None = None
) -> Channel | None:
    """Who wrote *relative* inside *root*, or None when no rule claims it.

    Raises:
        CategoryError: when two rules of one rank both claim the path.
    """
    ranked: dict[int, list[ChannelRule]] = {}
    for rule in channel_rules():
        ranked.setdefault(rule.rank, []).append(rule)
    for rank in sorted(ranked, reverse=True):
        answers = [
            (rule, answer)
            for rule in ranked[rank]
            if (answer := rule.judge(root, relative, emitted)) is not None
        ]
        if len(answers) > 1:
            (first, _), (second, _) = answers[0], answers[1]
            raise CategoryError(
                f"{relative.as_posix()}: two channel rules of rank {rank} claim"
                f" it, {first.name} ({first.extension}) and {second.name}"
                f" ({second.extension}); give one the higher rank"
            )
        if answers:
            rule, answer = answers[0]
            return Channel(answer, rule.extension)
    return None

known_categories

known_categories() -> frozenset[str]

The four builtin categories, and every category the base's two tables name.

Source code in packages/workshop/src/livery/workshop/_categories.py
def known_categories() -> frozenset[str]:
    """The four builtin categories, and every category the base's two tables name."""
    found = {SOURCE, TEST, TEST_SUPPORT, CONFIGURATION}
    found.update(rule.category for rule in (*BASE_RULES, *WORKSPACE_RULES))
    return frozenset(found)