Is there a way to set a mandatory option, when not...
# plugins
h
Is there a way to set a mandatory option, when not provided will raise a generic error? It can be tricky to validate all inputs, because some of them are not consumed by the goal rule...
a
turns out this did exist https://github.com/pantsbuild/pants/commit/091b1c04a2ec30b84fbf6f190d1dc85f30eda3c4 Looks like the suggested method is ValueError but i bet you could whip something up with dataclasses
It's my second day messing with pants plugins but this is what i worked up so far . What it's lacking is that if you are missing two options then it'll only report the first. you can work around it, though. I haven't tested optional fields but that's a standard dataclass feature
Copy code
class MysubSystem(Subsystem):
    alias = "sub"
    ...
    opt1  = StrOption(...)
    opt2 = StrOption(...)


@dataclass(frozen=True)
class MyOptions:
    required_fields = ("opt1", "opt2",)
    opt1: str
    opt2: str 


@rule(desc="…)
def resolve_options(sub: MysubSystem) -> MyOptions:
    for r in MyOptions.required_fields:
        if sub.options.get(r) is None:
            raise ValueError("—sub-" + r + " required")

    return MyOptions(**{x.name: sub.options.get(x.name) for x in dataclasses.fields(MyOptions)})

@rule(desc="action")
async def action(
    opts: MyOptions,
) -> ...:
h
Nice find! I don't like raising exceptions in a plugin because it leads to a not very nice user experience but oh well...