|
| 1 | +import argparse |
| 2 | +from dataclasses import dataclass |
| 3 | +from .errors import ArgumentError |
| 4 | + |
| 5 | + |
| 6 | +@dataclass |
| 7 | +class ConfigConfig: |
| 8 | + name: str |
| 9 | + clazz: type | list |
| 10 | + default: object |
| 11 | + description: str |
| 12 | + |
| 13 | + |
| 14 | +OPTIONS = [ |
| 15 | + ConfigConfig("padding", float, 10, |
| 16 | + "Amount of padding to add on the edges."), |
| 17 | + ConfigConfig("scale", float, 15, |
| 18 | + "Scale at which to enlarge the entire diagram by."), |
| 19 | + ConfigConfig("stroke_width", float, 2, "Width of the lines"), |
| 20 | + ConfigConfig("stroke", str, "black", "Color of the lines."), |
| 21 | + ConfigConfig("label", ["", "VL", "L", "V"], "VL", |
| 22 | + "Component label style (L=include label, V=include value, VL=both)"), |
| 23 | + ConfigConfig("nolabels", bool, False, |
| 24 | + "Turns off labels on all components, except for part numbers on ICs."), |
| 25 | +] |
| 26 | + |
| 27 | + |
| 28 | +def add_config_arguments(a: argparse.ArgumentParser): |
| 29 | + "Register all the config options on the argument parser." |
| 30 | + for opt in OPTIONS: |
| 31 | + if isinstance(opt.clazz, list): |
| 32 | + a.add_argument( |
| 33 | + "--" + opt.name, |
| 34 | + help=opt.description, |
| 35 | + choices=opt.clazz, |
| 36 | + default=opt.default) |
| 37 | + else: |
| 38 | + a.add_argument( |
| 39 | + "--" + opt.name, |
| 40 | + help=opt.description, |
| 41 | + type=opt.clazz, |
| 42 | + default=opt.default) |
| 43 | + |
| 44 | + |
| 45 | +def apply_config_defaults(options: dict) -> dict: |
| 46 | + "Merge the defaults and ensure the options are the right type." |
| 47 | + for opt in OPTIONS: |
| 48 | + if opt.name not in options: |
| 49 | + options[opt.name] = opt.default |
| 50 | + continue |
| 51 | + if isinstance(opt.clazz, list): |
| 52 | + if options[opt.name] not in opt.clazz: |
| 53 | + raise ArgumentError( |
| 54 | + f"config option {opt.name}: invalid choice: {options[opt.name]} " |
| 55 | + f"(valid options are {', '.join(map(repr, opt.clazz))})") |
| 56 | + continue |
| 57 | + try: |
| 58 | + options[opt.name] = opt.clazz(options[opt.name]) |
| 59 | + except ValueError as err: |
| 60 | + raise ArgumentError(f"config option {opt.name}: " |
| 61 | + f"invalid {opt.clazz.__name__} value: " |
| 62 | + f"{options[opt.name]}") from err |
| 63 | + return options |
0 commit comments