"""The `lcsc.lock.json` record of per-part metadata, keyed by C-number.
A design's catalogue parts need facts that are neither in the design nor
derivable from it, starting with the rotation JLCPCB expects and the
catalogue footprint an `LCSCLandpattern` is built from. Measuring or fetching
those reaches the network, which a build should not do every time, and the
answer should be reviewable in a diff rather than hidden in a cache. So they
are recorded in a file in the project, read on every build and extended when
a new part appears.
The file is data the user owns: an entry a human writes or edits is
authoritative, and anything this module does not understand is preserved
untouched.
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from logging import getLogger
from pathlib import Path
from typing import Any
logger = getLogger(__name__)
BASENAME = "lcsc.lock.json"
VERSION = 1
"""Format version, so a later change can migrate rather than guess."""
[docs]
class LockError(Exception):
"""A lock file that cannot be read."""
[docs]
@dataclass
class Lock:
"""Per-part metadata, keyed by LCSC C-number.
Args:
path: where the file lives, whether or not it exists yet.
parts: the `parts` mapping, C-number to a record. Records may hold
keys this version does not know about.
extra: top-level keys other than `version` and `parts`, kept so that
writing the file back does not discard them.
"""
path: Path
parts: dict[str, dict[str, Any]]
extra: dict[str, Any]
[docs]
def orientation(self, partnumber: str) -> float | None:
"""The recorded orientation for a C-number, if it has one."""
value = self.parts.get(partnumber, {}).get("orientation")
return float(value) if isinstance(value, (int, float)) else None
[docs]
def orientations(self) -> dict[str, float]:
"""Every recorded orientation, keyed by C-number."""
found = {}
for partnumber in self.parts:
value = self.orientation(partnumber)
if value is not None:
found[partnumber] = value
return found
[docs]
def record(self, orientations: dict[str, float]) -> None:
"""Add measured orientations, leaving every other field in place.
Existing orientations are not overwritten: the file is the authority,
and a caller that has measured one already knew it was missing.
"""
for partnumber, angle in orientations.items():
entry = self.parts.setdefault(partnumber, {})
entry.setdefault("orientation", angle)
[docs]
def project() -> Path:
"""The JITX project directory, where the lock file lives.
Falls back to the working directory when nothing is run from inside a
project, so neither a build nor an export fails over where to keep its
record.
"""
from jitx.project import NotAJitxProject, discover
try:
return discover(".").root
except NotAJitxProject:
logger.debug("No JITX project found; using the working directory")
return Path.cwd()
[docs]
def path(project_root: Path | None = None) -> Path:
"""Where the lock file lives, for a project root or the discovered one."""
return (project() if project_root is None else project_root) / BASENAME
[docs]
def read(file: Path) -> Lock:
"""Read a lock file, or return an empty one if it does not exist.
Raises:
LockError: the file exists but is not a lock file this can read. A
corrupt file is not silently replaced, because rewriting it would
destroy whatever a user had put there.
"""
if not file.is_file():
return Lock(path=file, parts={}, extra={})
try:
data = json.loads(file.read_text())
except (OSError, ValueError) as exc:
raise LockError(f"{file} could not be read: {exc}") from exc
if not isinstance(data, dict):
raise LockError(f"{file} is not a JSON object")
version = data.get("version", VERSION)
if not isinstance(version, int) or version > VERSION:
raise LockError(
f"{file} is version {version!r}, which this version of "
f"jitxlib-jlcpcb does not understand (it writes version {VERSION})"
)
raw = data.get("parts", {})
if not isinstance(raw, dict):
raise LockError(f"{file} has a `parts` key that is not an object")
parts: dict[str, dict[str, Any]] = {}
for key, entry in raw.items():
if not isinstance(entry, dict):
raise LockError(f"{file} entry for {key!r} is not an object")
parts[str(key)] = dict(entry)
extra = {k: v for k, v in data.items() if k not in ("version", "parts")}
return Lock(path=file, parts=parts, extra=extra)
WIDTH = 120
"""Where `render` stops keeping a value on one line.
Wider than code would be, because this is a data file: one pad of a recorded
footprint on one line is what makes a diff of it readable.
"""
[docs]
def render(value: Any, indent: int = 0) -> str:
"""`value` as indented JSON, keeping a short list on one line.
`json.dumps(indent=2)` puts every number of every coordinate on a line of
its own, which turns a recorded footprint into thousands of lines and a
diff into something no one reads. Anything that fits stays on one line
instead, so a footprint reads as a list of pads and a path as a list of
points.
"""
flat = json.dumps(value)
if indent + len(flat) <= WIDTH or not isinstance(value, (dict, list)) or not value:
return flat
pad = " " * (indent + 2)
if isinstance(value, dict):
items = [
f"{pad}{json.dumps(str(k))}: {render(v, indent + 2)}"
for k, v in value.items()
]
return "{\n" + ",\n".join(items) + "\n" + " " * indent + "}"
items = [f"{pad}{render(v, indent + 2)}" for v in value]
return "[\n" + ",\n".join(items) + "\n" + " " * indent + "]"
[docs]
def write(lock: Lock) -> None:
"""Write a lock file, sorted so that a diff shows only what changed."""
data: dict[str, Any] = {"version": VERSION, **lock.extra}
data["parts"] = {key: lock.parts[key] for key in sorted(lock.parts)}
lock.path.parent.mkdir(parents=True, exist_ok=True)
# A trailing newline so the file is a well-formed text file and does not
# show up as "no newline at end of file" in every diff.
lock.path.write_text(render(data) + "\n")