Source code for fleetmesh_schema

"""fleetmesh_schema: the published schema files as an installable package.

The files are the ones at the root of the schema repo - `schema/` (the digest
set: constants, kinds, messages, DIGEST, PROTOCOLS, conformance) and
`schemas/` (the JSON Schema documents). This package carries them, nothing
more: a path for anything that opens files itself, and one cached loader for
the JSON. Standard library only, no I/O at import time.

In a checkout the two directories are reached through the symlinks beside
this file; installed, they are package data at the same relative place, so
`files()` is the same path arithmetic either way.
"""
from __future__ import annotations

import functools
import json
import os
from typing import Any

HERE = os.path.dirname(os.path.abspath(__file__))
SCHEMA_DIR = os.path.join(HERE, 'schema')      # constants.json, kinds.json, messages.json, DIGEST ...
SCHEMAS_DIR = os.path.join(HERE, 'schemas')    # JSON Schema documents by plane


[docs]def path(name: str) -> str: """Absolute path of a file under schema/ (constants.json, kinds.json, DIGEST ...).""" return os.path.join(SCHEMA_DIR, name)
[docs]def schema_path(*parts: str) -> str: """Absolute path of a JSON Schema document under schemas/ (plane, ..., file).""" return os.path.join(SCHEMAS_DIR, *parts)
[docs]@functools.lru_cache(maxsize=None) def load_json(name: str) -> Any: """Parse one file under schema/, once; every importer sees the same object. The path is in any error so a broken install names itself.""" p = path(name) try: with open(p, encoding='utf-8') as fh: return json.load(fh) except (OSError, json.JSONDecodeError) as e: raise RuntimeError('cannot read schema file %s: %s' % (p, e)) from e
[docs]@functools.lru_cache(maxsize=None) def text(name: str) -> str: """One file under schema/ as stripped text (DIGEST, PROTOCOLS).""" try: with open(path(name), encoding='utf-8') as fh: return fh.read().strip() except OSError as e: raise RuntimeError('cannot read schema file %s: %s' % (path(name), e)) from e
[docs]def digest() -> str: """The protocol version digest, schema/DIGEST.""" return text('DIGEST')
__all__ = ['SCHEMA_DIR', 'SCHEMAS_DIR', 'path', 'schema_path', 'load_json', 'text', 'digest']