58 lines
1.7 KiB
Python
58 lines
1.7 KiB
Python
|
|
import argparse
|
||
|
|
import json
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
|
||
|
|
SCRIPT_DIR = Path(__file__).resolve().parent
|
||
|
|
DEFAULT_INPUT_FILE = SCRIPT_DIR / "servo_config.yaml"
|
||
|
|
DEFAULT_OUTPUT_FILE = SCRIPT_DIR / "servo_config.json"
|
||
|
|
|
||
|
|
|
||
|
|
def parse_args():
|
||
|
|
parser = argparse.ArgumentParser(description="Convert a servo YAML config to JSON.")
|
||
|
|
parser.add_argument("input", nargs="?", type=Path, default=DEFAULT_INPUT_FILE)
|
||
|
|
parser.add_argument("output", nargs="?", type=Path, default=DEFAULT_OUTPUT_FILE)
|
||
|
|
return parser.parse_args()
|
||
|
|
|
||
|
|
|
||
|
|
def convert_yaml_to_json(input_file, output_file):
|
||
|
|
try:
|
||
|
|
import yaml
|
||
|
|
except ModuleNotFoundError as exc:
|
||
|
|
raise RuntimeError(
|
||
|
|
"PyYAML is required. Install it with: python -m pip install PyYAML"
|
||
|
|
) from exc
|
||
|
|
|
||
|
|
input_file = Path(input_file).resolve()
|
||
|
|
output_file = Path(output_file).resolve()
|
||
|
|
|
||
|
|
with input_file.open("r", encoding="utf-8") as stream:
|
||
|
|
data = yaml.safe_load(stream)
|
||
|
|
|
||
|
|
if not isinstance(data, dict):
|
||
|
|
raise ValueError("Servo config root must be a YAML mapping.")
|
||
|
|
|
||
|
|
# These helper nodes only exist to support YAML anchors and merge keys.
|
||
|
|
data.pop("default_driver", None)
|
||
|
|
data.pop("default_control", None)
|
||
|
|
|
||
|
|
output_file.parent.mkdir(parents=True, exist_ok=True)
|
||
|
|
with output_file.open("w", encoding="utf-8") as stream:
|
||
|
|
json.dump(data, stream, indent=2, ensure_ascii=False)
|
||
|
|
stream.write("\n")
|
||
|
|
|
||
|
|
return output_file
|
||
|
|
|
||
|
|
|
||
|
|
def main():
|
||
|
|
args = parse_args()
|
||
|
|
try:
|
||
|
|
output_file = convert_yaml_to_json(args.input, args.output)
|
||
|
|
except Exception as exc:
|
||
|
|
raise SystemExit(f"YAML conversion failed: {exc}") from exc
|
||
|
|
print(f"Generated {output_file}")
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
main()
|