| 1 |
import json |
| 2 |
from typing import IO, Any |
| 3 |
|
| 4 |
import click |
| 5 |
|
| 6 |
import black |
| 7 |
|
| 8 |
|
| 9 |
def generate_schema_from_click( |
| 10 |
cmd: click.Command, |
| 11 |
) -> dict[str, Any]: |
| 12 |
result: dict[str, dict[str, Any]] = {} |
| 13 |
for param in cmd.params: |
| 14 |
if not isinstance(param, click.Option) or param.is_eager: |
| 15 |
continue |
| 16 |
|
| 17 |
assert param.name |
| 18 |
name = param.name.replace("_", "-") |
| 19 |
|
| 20 |
result[name] = {} |
| 21 |
|
| 22 |
match param.type: |
| 23 |
case click.types.IntParamType(): |
| 24 |
result[name]["type"] = "integer" |
| 25 |
case click.types.StringParamType() | click.types.Path(): |
| 26 |
result[name]["type"] = "string" |
| 27 |
case click.types.Choice(choices=choices): |
| 28 |
result[name]["enum"] = choices |
| 29 |
case click.types.BoolParamType(): |
| 30 |
result[name]["type"] = "boolean" |
| 31 |
case _: |
| 32 |
msg = f"{param.type!r} not a known type for {param}" |
| 33 |
raise TypeError(msg) |
| 34 |
|
| 35 |
if param.multiple: |
| 36 |
result[name] = {"type": "array", "items": result[name]} |
| 37 |
|
| 38 |
result[name]["description"] = param.help |
| 39 |
|
| 40 |
default = param.to_info_dict()["default"] |
| 41 |
if default is not None and not param.multiple: |
| 42 |
result[name]["default"] = default |
| 43 |
|
| 44 |
return result |
| 45 |
|
| 46 |
|
| 47 |
@click.command(context_settings={"help_option_names": ["-h", "--help"]}) |
| 48 |
@click.option("--schemastore", is_flag=True, help="SchemaStore format") |
| 49 |
@click.option("--outfile", type=click.File(mode="w"), help="Write to file") |
| 50 |
def main(schemastore: bool, outfile: IO[str]) -> None: |
| 51 |
properties = generate_schema_from_click(black.main) |
| 52 |
del properties["line-ranges"] |
| 53 |
|
| 54 |
schema: dict[str, Any] = { |
| 55 |
"$schema": "http://json-schema.org/draft-07/schema#", |
| 56 |
"$id": ( |
| 57 |
"https://github.com/psf/black/blob/main/src/black/resources/black.schema.json" |
| 58 |
), |
| 59 |
"$comment": "tool.black table in pyproject.toml", |
| 60 |
"type": "object", |
| 61 |
"additionalProperties": False, |
| 62 |
"properties": properties, |
| 63 |
} |
| 64 |
|
| 65 |
if schemastore: |
| 66 |
schema["$id"] = "https://json.schemastore.org/partial-black.json" |
| 67 |
# The precise list of unstable features may change frequently, so don't |
| 68 |
# bother putting it in SchemaStore |
| 69 |
schema["properties"]["enable-unstable-feature"]["items"] = {"type": "string"} |
| 70 |
|
| 71 |
print(json.dumps(schema, indent=2), file=outfile) |
| 72 |
|
| 73 |
|
| 74 |
if __name__ == "__main__": |
| 75 |
main() |