Source code for jitxlib.gerber.plugin

"""JITX export plugin: write a Gerber fabrication data set from a design.

Registration is an import side effect of the decorator, reached through the
`jitx-plugin` entry point. The CLI derives its flags from the keyword
parameters of `export`, so everything settable from the command line is a
flat scalar; a caller that needs more - a configured naming strategy, the
written file set back - uses `jitxlib.gerber.export_gerber` directly.
"""

from logging import getLogger
from pathlib import Path
from typing import TYPE_CHECKING, override

import jitx.log
import jitx.plugin

from .format.compat import Compat
from .format.model import DrillFormat

if TYPE_CHECKING:
    from jitx.run import RuntimeDesign

logger = getLogger(__name__)

# No `from __future__ import annotations` in this module, deliberately. The
# CLI builds its options from `inspect.signature(plugin.export)`, and with
# postponed evaluation every annotation arrives as a string that typer
# cannot resolve - which fails the whole `design export` command group, not
# just this plugin.


def _drill_format(value: str) -> "DrillFormat":
    """Resolve the `--drill-format` flag.

    Exactly one format per data set: a job file that offers a CAM system the
    same drill span in two formats is a job file that invites drilling it
    twice.

    Raises:
        ValueError: the format is not one this exporter writes, listing the
            ones it does.
    """
    from .format.model import DrillFormat

    try:
        return DrillFormat(value)
    except ValueError:
        supported = ", ".join(sorted(f.value for f in DrillFormat))
        raise ValueError(
            f"Unknown drill format {value!r}; this exporter writes: {supported}"
        ) from None


def _compat(names: list[str] | None) -> "Compat":
    """Resolve the repeatable `--compat` flag.

    Raises:
        ValueError: a name is not a known adjustment, listing the known ones.
    """
    from .format.compat import Compat

    return Compat.from_names(names or ())


def _output(output: Path | None, design_name: str) -> Path:
    """The output path: the one given, or `<cwd>/<scrubbed name>`.

    A given path ending in `.zip` is an archive and anything else is a
    directory; the default is a directory, since a default that silently
    produced an archive would be a surprise rather than a convenience.
    """
    from .format.naming import legal_stem

    if output is not None:
        return Path(output).absolute()
    return Path.cwd() / legal_stem(design_name)


[docs] @jitx.plugin.Export.register("gerber") class GerberExport(jitx.plugin.Export): """Export Gerber X2/X3 fabrication data."""
[docs] @override def preflight( self, *, output: Path | None = None, overwrite: bool = False, names: str = "descriptive", drill_format: str = "gerber", compat: list[str] | None = None, ) -> None: """Reject an unusable request before the design is instantiated. The naming scheme, the drill format and the compatibility adjustments are checked here because an unknown one is a usage error and should not cost a design build. The output guard can only run when `--output` was given, since the default path depends on the design name; the real enforcement is in the writer, which knows the exact set of paths it is about to write. """ from .format.naming import strategy from .format.pack import is_archive strategy(names) _drill_format(drill_format) _compat(compat) if output is not None and not overwrite: path = Path(output).absolute() if is_archive(path): if path.is_dir(): raise ValueError(f"Output path {path} is a directory") elif path.exists() and not path.is_dir(): raise ValueError(f"Output path {path} is not a directory")
[docs] @override def export( self, design: "RuntimeDesign", *, output: Path | None = None, overwrite: bool = False, names: str = "descriptive", drill_format: str = "gerber", compat: list[str] | None = None, ) -> None: # `--compat a --compat b` arrives as ['a', 'b'], and as None when # the flag is absent from .extract.job import export as run directory = _output(output, design.name) result = run( design, output=directory, naming_scheme=names, overwrite=overwrite, drill_format=_drill_format(drill_format), compat=_compat(compat), ) # notice level so the result reaches both the console and the run's # log file, unlike print jitx.log.notice( logger, "Wrote %d Gerber files %s %s", len(result.files), "into" if result.archive else "to", result.root, )