class FormatRegistry:
def __init__(
self,
ops: Registry[type[Op]] | None = None,
writers: Registry[type[Writer]] | None = None,
) -> None:
self.ops = ops if ops is not None else default_ops()
self.writers = writers if writers is not None else default_writers()
def readers(self) -> list[type[Op]]:
return [op for op in self.ops if op.n_inputs == 0 and getattr(op, "format_id", "")]
def formats(self) -> list[Format]:
result: dict[str, Format] = {}
for op in self.readers():
fid = getattr(op, "format_id", "")
exts = getattr(op, "extensions", ())
result[fid] = Format(fid, str(op.title), exts, op, None)
for writer in self.writers:
current = result.get(writer.id)
if current is None:
result[writer.id] = Format(
writer.id, str(writer.title), writer.extensions, None, writer
)
else:
exts = tuple(dict.fromkeys((*current.extensions, *writer.extensions)))
result[writer.id] = Format(current.id, current.title, exts, current.reader, writer)
return list(result.values())
def reader_for(self, path: str | pathlib.Path) -> type[Op]:
suffix = pathlib.Path(path).suffix.lower()
for op in self.readers():
if suffix in getattr(op, "extensions", ()):
return op
msg = f"no reader for {suffix!r} files"
raise KeyError(msg)
def writer_for(self, path: str | pathlib.Path) -> type[Writer]:
suffix = pathlib.Path(path).suffix.lower()
for writer in self.writers:
if suffix in writer.extensions:
return writer
msg = f"no writer for {suffix!r} files"
raise KeyError(msg)
def read(self, session: Session, path: str | pathlib.Path, **options: Any):
"""Add a reader node for `path` (reader chosen by extension)."""
op = self.reader_for(path)
return session.add(op.record(path=str(path), **options))
def write(
self,
session: Session,
node_id: str,
path: str | pathlib.Path,
**options: Any,
) -> None:
writer = self.writer_for(path)
writer.write(session, node_id, path, writer.Params(**options))