Skip to content
Python
2.4 KB
Raw Blame
#!/usr/bin/env python3
"""Generate dependency-free Rust constants from the shared JSON registry."""
import argparse
import json
import pathlib
import re
import subprocess
import sys

root = pathlib.Path(__file__).resolve().parents[1]
data = json.loads((root / "attributes.json").read_text())
attributes = data["attributes"]
keys, constants = set(), set()
lines = [
    "// Generated by scripts/generate-attributes.py; edit attributes.json instead.",
    "//! Shared privacy/type registry for recording instrumentation and OTLP export.",
    "#[derive(Clone, Copy, Debug, PartialEq, Eq)]",
    "pub enum CaptureClass { Resource, Typed, Identity, Metadata, Full }",
    "#[derive(Clone, Copy, Debug, PartialEq, Eq)]",
    "pub enum Kind { String, Int, Bool, Double }",
    "pub struct Field { pub key: &'static str, pub kind: Kind, "
    "pub capture: CaptureClass, pub metric_dimension: bool }",
    f'pub const VERSION: &str = {json.dumps(data["version"])};',
    f'pub const SEMCONV: &str = {json.dumps(data["semconv_version"])};',
]
for field in attributes:
    name, key = field["constant"], field["key"]
    assert re.fullmatch("[A-Z][A-Z0-9_]*", name)
    assert name not in constants and key not in keys
    assert field["capture"] in {"resource", "typed", "identity", "metadata", "full"}
    assert field["type"] in {"string", "int", "bool", "double"}
    assert isinstance(field["metric_dimension"], bool)
    keys.add(key)
    constants.add(name)
    lines.append(f"pub const {name}: &str = {json.dumps(key)};")
lines.append("pub static FIELDS: &[Field] = &[")
for field in attributes:
    lines.append(
        f'Field {{key:{field["constant"]},kind:Kind::{field["type"].title()},'
        f'capture:CaptureClass::{field["capture"].title()},'
        f'metric_dimension:{str(field["metric_dimension"]).lower()}}},'
    )
lines.extend([
    "];",
    "pub fn field(key: &str) -> Option<&'static Field> { FIELDS.iter().find(|f| f.key == key) }",
])
# Match the repository's formatting; no network or package generation needed.
text = subprocess.check_output(
    ["rustfmt", "--edition", "2021"], input="\n".join(lines) + "\n", text=True
)
parser = argparse.ArgumentParser()
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
output = root / "src/attributes.rs"
if args.check:
    if not output.exists() or output.read_text() != text:
        sys.exit("Generated attribute registry is stale")
else:
    output.write_text(text)