wpilibsuite / allwpilib

Official Repository of WPILibJ and WPILibC
https://wpilib.org/
Other
1.03k stars 607 forks source link

[wpilib] Pregenerate PWM motor controllers #6742

Closed pjreiniger closed 2 weeks ago

pjreiniger commented 3 weeks ago

Fixes #6739

TheTripleV commented 2 weeks ago

Consider using pathlib instead of wrangling names manually. The trailing backslash vs no trailing backslash can bite someone who tries to update it in the future.

Do explicitly set utf-8 as the encoding on file operations in case someone tries to run this on Windows. Python on Windows will switch to utf-8 by default (ignoring locale) in 2026.

gpt conversion doing both for example ```py #!/usr/bin/env python3 # Copyright (c) FIRST and other WPILib contributors. # Open Source Software; you can modify and/or share it under the terms of # the WPILib BSD license file in the root directory of this project. import argparse import json import sys from pathlib import Path from jinja2 import Environment, FileSystemLoader def render_template(template, output_dir, filename, controller): output_dir_path = Path(output_dir) output_dir_path.mkdir(parents=True, exist_ok=True) (output_dir_path / filename).write_text(template.render(controller), encoding="utf-8") def generate_pwm_motor_controllers(output_root, template_root): template_root_path = Path(template_root) with (template_root_path / "pwm_motor_controllers.json").open(encoding="utf-8") as f: controllers = json.load(f) env = Environment( loader=FileSystemLoader(str(template_root_path)), autoescape=False, keep_trailing_newline=True, ) root_path = Path(output_root) / "main/java/edu/wpi/first/wpilibj/motorcontrol" template = env.get_template("pwm_motor_controller.java.jinja") for controller in controllers: controller_name = f"{controller['name']}.java" render_template(template, root_path, controller_name, controller) def main(argv): script_path = Path(__file__).resolve() dirname = script_path.parent parser = argparse.ArgumentParser() parser.add_argument( "--output_directory", help="Optional. If set, will output the generated files to this directory, otherwise it will use a path relative to the script", default=dirname / "src/generated", ) parser.add_argument( "--template_root", help="Optional. If set, will use this directory as the root for the jinja templates", default=dirname / "src/generate", ) args = parser.parse_args(argv) generate_pwm_motor_controllers(args.output_directory, args.template_root) if __name__ == "__main__": main(sys.argv[1:]) ```