Source code for jitxlib.gerber.format.naming

"""File naming strategies and the registry behind `--names`.

Nothing else in this package builds a filename. Naming is a strategy object
selected by name, and a strategy may return `None` for a file it has no
opinion about, in which case the caller falls back to `descriptive`.

This library is fab-house agnostic and ships exactly one scheme,
`descriptive`, which is self-explanatory rather than conventional. Legacy
per-extension conventions and anything else a particular house asks for are
house policy: they belong in that house's library and register through the
`jitxlib.gerber.naming` entry-point group, where they appear under `--names`
with nothing to patch here.
"""

from __future__ import annotations

import re
from collections.abc import Callable, Sequence
from importlib.metadata import entry_points
from typing import Protocol, runtime_checkable

from .model import (
    Component,
    Copper,
    Drill,
    DrillFormat,
    FileFunction,
    FileKind,
    HoleType,
    Legend,
    Paste,
    Profile,
    Side,
    Soldermask,
)

ENTRY_POINT_GROUP = "jitxlib.gerber.naming"
"""Entry-point group an out-of-tree scheme registers itself in."""

DEFAULT = "descriptive"
"""The scheme every other one falls back to. It must be total."""

GERBER_EXT = ".gbr"
JOB_EXT = ".gbrjob"
ARCHIVE_EXT = ".zip"

DRILL_EXT: dict[DrillFormat, str] = {
    DrillFormat.XNC: ".xnc",
    DrillFormat.GERBER: GERBER_EXT,
}
"""The extension each drill format is written under.

A drill file's extension follows the format it is written in rather than
being fixed, which is why `Drill` carries the format at all: a naming scheme
branches on data it already has instead of on a string it would have to
parse.
"""


[docs] class NamingError(LookupError): """No such naming scheme."""
[docs] @runtime_checkable class FileNaming(Protocol): """A strategy that turns a file function into a filename. Implement `name` and register the class under a scheme name. A scheme is free to return `None` for any file it has no convention for; the caller falls back to `descriptive` rather than inventing a name. """
[docs] def name( self, function: FileFunction, stem: str, file_set: Sequence[FileFunction] ) -> str | None: """The complete filename for one file, or None to defer. Args: function: what the file is, as the structured description it already carries for its `TF.FileFunction` attribute, so a scheme branches on data rather than on a rendered string. stem: the scrubbed design name. Conventions that replace the extension entirely need it, which is why the strategy returns a whole filename rather than a suffix. file_set: every file function in the set being written, in emission order. Real conventions are not per-file functions of one file - whether a drill name needs decorating depends on whether the other drill file exists - so the set is passed even though many schemes will ignore it. """ ...
_schemes: dict[str, FileNaming] = {} _loaded = False
[docs] def register(scheme: str) -> Callable[[type], type]: """Register a naming strategy class under a scheme name. Mirrors how the export plugin itself registers. The class is instantiated with no arguments at registration. """ def decorator(cls: type) -> type: _schemes[scheme] = cls() return cls return decorator
def _load() -> None: """Import every distribution that advertises a naming scheme. Registration is an import side effect of the decorator, exactly as it is for the jitx export plugin, so loading the module is all this has to do. """ global _loaded if _loaded: return _loaded = True for point in entry_points(group=ENTRY_POINT_GROUP): try: point.load() except Exception as error: # pragma: no cover - depends on what is installed import logging logging.getLogger(__name__).warning( "Unable to load gerber naming scheme %s: %s", point.name, error )
[docs] def available() -> list[str]: """Every registered scheme name, sorted.""" _load() return sorted(_schemes)
[docs] def strategy(scheme: str | FileNaming) -> FileNaming: """Resolve a scheme name to its strategy, or pass a strategy through. Accepting an object as well as a name is what lets a caller hand over a configured instance without a registry round trip; the CLI only ever passes a name. Raises: NamingError: no scheme is registered under that name. """ if not isinstance(scheme, str): return scheme _load() found = _schemes.get(scheme) if found is None: raise NamingError( f"Unknown file naming scheme {scheme!r}; registered: " f"{', '.join(available())}" ) return found
_ILLEGAL = re.compile(r"[^A-Za-z0-9_+-]")
[docs] def resolve( functions: Sequence[FileFunction], stem: str, scheme: str | FileNaming = DEFAULT ) -> list[str]: """Resolve a whole file set to filenames, parallel to `functions`. A scheme that returns `None` for a file defers to `descriptive`, which is why `descriptive` must be total. Collision checking is deliberately not here: it belongs to the writer, which sees the archive name as well and is where a collision has to stop the run. """ chosen = strategy(scheme) fallback = strategy(DEFAULT) out: list[str] = [] for function in functions: found = chosen.name(function, stem, functions) if found is None: found = fallback.name(function, stem, functions) if found is None: # pragma: no cover - descriptive is total raise NamingError(f"{DEFAULT} produced no name for {function.render()}") out.append(found) return out
_SIDE = {Side.TOP: "top", Side.INNER: "inr", Side.BOTTOM: "bot"}
[docs] @register(DEFAULT) class DescriptiveNaming: """The neutral scheme: names say what the file is. Every name is `<stem>-<description><extension>`, except the job file, whose extension is its whole identity. """
[docs] def name( self, function: FileFunction, stem: str, file_set: Sequence[FileFunction] ) -> str | None: match function.kind: case FileKind.JOB: return stem + JOB_EXT case FileKind.DRILL: return f"{stem}-{_drill(function)}{_drill_ext(function)}" case _: return f"{stem}-{_descriptive(function)}{GERBER_EXT}"
def _drill_ext(function: FileFunction) -> str: """The extension for a drill file, from the format it is written in.""" if not isinstance(function, Drill): # pragma: no cover - kind implies the type return DRILL_EXT[DrillFormat.GERBER] return DRILL_EXT[function.format] def _drill(function: FileFunction) -> str: """`drill_pth`, `drill_npth`, or `drill_l<i>_l<j>` for a span. A non-plated span file takes a `_np` tail so it cannot collide with the plated file of the same span. Backdrills produce one: the stub is drilled after plating, over the sub-span that loses it. """ if not isinstance(function, Drill): # pragma: no cover - kind implies the type return "drill" if function.hole in (HoleType.PTH, HoleType.NPTH): return f"drill_{str(function.hole).lower()}" tail = "" if function.plated else "_np" return f"drill_l{function.first}_l{function.last}{tail}" def _descriptive(function: FileFunction) -> str: """A name derived from the file function's own fields. The final arm is what makes this total: a file function added in a later milestone gets a mechanical name off its rendered `TF.FileFunction` rather than falling through to `None` and recursing into its own fallback. The arms above it exist because a filename wants `cu`, `mask` and `silk` rather than `copper`, `soldermask` and `legend`, and because `Profile,NP` carries a field a filename has no use for. `silk` for a `Legend` is the one place this reaches past the spec's own word rather than shortening it. 5.6.3 defines the file function as `Legend` and glosses it "a.k.a. 'silk' or 'silkscreen'", preferring `Legend` because silkscreening is a printing process and the layer is often inkjetted instead. That reasoning governs the file function, which is emitted as `Legend` and must be; it does not govern a filename a human reads, and every other arm here already picks the colloquial word. JITX's own feature class is `Silkscreen`. """ match function: case Copper(): return f"cu_l{function.index}_{_SIDE[function.side]}" case Soldermask(): return f"mask_{_SIDE[function.side]}" case Legend(): return f"silk_{_SIDE[function.side]}" case Paste(): return f"paste_{_SIDE[function.side]}" case Profile(): return "profile" case Component(): return f"comp_{_SIDE[function.side]}" case _: return "_".join(function.render().lower().split(","))