-
Notifications
You must be signed in to change notification settings - Fork 209
Automate enum sync for spec files #291
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
MonkeyCanCode
wants to merge
2
commits into
apache:main
Choose a base branch
from
MonkeyCanCode:automate_enum_sync
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+198
−2
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,196 @@ | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, | ||
| # software distributed under the License is distributed on an | ||
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| # KIND, either express or implied. See the License for the | ||
| # specific language governing permissions and limitations | ||
| # under the License. | ||
|
|
||
| """ | ||
| Generate enums for spec.yaml from osi-schema.json. | ||
|
|
||
| Usage: | ||
| python3 scripts/generate-spec-types.py --check # exit 1 if spec.yaml is out of sync | ||
| python3 scripts/generate-spec-types.py --apply # update spec.yaml in-place | ||
| """ | ||
|
|
||
| import difflib | ||
| import json | ||
| import sys | ||
| import argparse | ||
| from pathlib import Path | ||
|
|
||
| try: | ||
| import yaml | ||
| except ImportError: | ||
| print("Missing dependency. Install with: pip install PyYAML") | ||
| sys.exit(1) | ||
|
|
||
| REPO = Path(__file__).resolve().parent.parent | ||
| SCHEMA = REPO / "core-spec" / "osi-schema.json" | ||
| SPEC = REPO / "core-spec" / "spec.yaml" | ||
|
|
||
| SECTIONS = [ | ||
| { | ||
| "key": "dialects", | ||
| "schema_path": ["$defs", "Dialect", "enum"], | ||
| "comment_col": 28, | ||
| "header": "# Supported expression language dialects", | ||
| "descriptions": { | ||
| "ANSI_SQL": "Standard SQL dialect", | ||
| "SNOWFLAKE": "Snowflake", | ||
| "MDX": "Multi-Dimensional Expressions", | ||
| "TABLEAU": "Tableau", | ||
| "DATABRICKS": "Databricks SQL", | ||
| "MAQL": "GoodData MAQL (Multi-Dimensional Analytical Query Language)", | ||
| "BIGQUERY": "Google BigQuery GoogleSQL", | ||
| }, | ||
| }, | ||
| { | ||
| "key": "datatypes", | ||
| "schema_path": ["$defs", "DataType", "enum"], | ||
| "comment_col": 28, | ||
| "header": "# Supported logical data types for fields and metrics", | ||
| "descriptions": { | ||
| "String": "Variable-length Unicode character data", | ||
| "Integer": "Exact integral number", | ||
| "Decimal": "Exact base-10 number", | ||
| "Float": "Approximate floating-point number", | ||
| "Boolean": "Logical two-valued truth type", | ||
| "Date": "Calendar date without time of day", | ||
| "Time": "Time of day without a date or timezone", | ||
| "DateTime": "Date and time without a timezone or offset", | ||
| "DateTimeTz": "Instant identified using offset or timezone context", | ||
| "Opaque": "Known type outside the portable vocabulary", | ||
| }, | ||
| }, | ||
| ] | ||
|
|
||
|
|
||
| def _schema_values(section: dict) -> list[str]: | ||
| path = section["schema_path"] | ||
| with open(SCHEMA) as f: | ||
| data = json.load(f) | ||
| for part in path: | ||
| data = data[part] | ||
| return list(data) | ||
|
|
||
|
|
||
| def _generate_block(section: dict, values: list[str]) -> str: | ||
| key = section["key"] | ||
| comment_col = section["comment_col"] | ||
| descs = section["descriptions"] | ||
| ref = ".".join(section["schema_path"]) | ||
|
|
||
| lines = [ | ||
| section["header"], | ||
| "# Auto-generated from osi-schema.json ({}).".format(ref), | ||
| "{}:".format(key), | ||
| ] | ||
| for v in values: | ||
| desc = descs.get(v) | ||
|
MonkeyCanCode marked this conversation as resolved.
|
||
| if desc is None: | ||
| print(f"Warning: no description for '{key}' value '{v}'", file=sys.stderr) | ||
| entry = ' - "{}"'.format(v) | ||
| if desc: | ||
| pad = max(1, comment_col - len(entry)) | ||
| lines.append('{}{}# {}'.format(entry, " " * pad, desc)) | ||
| else: | ||
| lines.append(entry) | ||
|
|
||
| return "\n".join(lines) + "\n\n" | ||
|
|
||
|
|
||
| def _replace_section(text: str, key: str, block: str) -> str: | ||
| lines = text.splitlines(keepends=True) | ||
|
|
||
| key_idx = None | ||
| for idx, line in enumerate(lines): | ||
| if line.rstrip() == f"{key}:": | ||
| key_idx = idx | ||
| break | ||
|
|
||
| if key_idx is None: | ||
| print(f"Error: '{key}:' not found in spec.yaml", file=sys.stderr) | ||
| sys.exit(1) | ||
|
|
||
| start = key_idx | ||
| idx = key_idx - 1 | ||
| while idx >= 0 and lines[idx].strip() == "": | ||
| start = idx | ||
| idx -= 1 | ||
| while idx >= 0 and lines[idx].lstrip().startswith("#"): | ||
| start = idx | ||
| idx -= 1 | ||
|
|
||
| end = key_idx + 1 | ||
| while end < len(lines) and (lines[end].strip() == "" or lines[end][0].isspace()): | ||
| end += 1 | ||
|
|
||
| return "".join(lines[:start]) + block + "".join(lines[end:]) | ||
|
|
||
|
|
||
| def _render(text: str) -> str: | ||
| for section in SECTIONS: | ||
| values = _schema_values(section) | ||
| block = _generate_block(section, values) | ||
| text = _replace_section(text, section["key"], block) | ||
|
|
||
| # parse and validate before returning | ||
| try: | ||
| list(yaml.safe_load_all(text)) | ||
| except yaml.YAMLError as e: | ||
| print(f"Error: Generated YAML is invalid: {e}", file=sys.stderr) | ||
| sys.exit(1) | ||
| return text | ||
|
|
||
|
|
||
| def _apply(): | ||
| rendered = _render(SPEC.read_text()) | ||
| SPEC.write_text(rendered) | ||
| print(f"Wrote {SPEC}", file=sys.stderr) | ||
|
|
||
|
|
||
| def _check() -> list: | ||
| current = SPEC.read_text() | ||
| rendered = _render(current) | ||
| if current == rendered: | ||
| return 0 | ||
|
|
||
| diff = difflib.unified_diff( | ||
| current.splitlines(keepends=True), | ||
| rendered.splitlines(keepends=True), | ||
| fromfile=f"{SPEC} (current)", | ||
| tofile=f"{SPEC} (expected)" | ||
| ) | ||
| sys.stderr.writelines(diff) | ||
| print(f"{SPEC} is out of sync with {SCHEMA}. Run --apply to fix.", file=sys.stderr) | ||
| return 1 | ||
|
|
||
|
|
||
| def main(): | ||
| parser = argparse.ArgumentParser() | ||
| group = parser.add_mutually_exclusive_group() | ||
| group.add_argument("--check", action="store_true", help="Check spec.yaml is in sync") | ||
| group.add_argument("--apply", action="store_true", help="Update spec.yaml in-place") | ||
| args = parser.parse_args() | ||
|
|
||
| if args.apply: | ||
| _apply() | ||
| return | ||
| if args.check: | ||
| sys.exit(_check()) | ||
| parser.print_help() | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The per-value descriptions are hardcoded here.
osi-schema.jsononly carries a singledescriptionper enum (e.g."Supported SQL and expression language dialects"), not per-value text — so today they genuinely can't be read from the schema.Consequence: when a new value is added to the schema,
--applyemits it as a bare entry with no comment, and someone has to remember to add its description to this dict. I confirmed this by appendingNEWSQLto the schema:So the manual-sync burden isn't eliminated, just relocated. A cleaner long-term design would put per-value descriptions in the schema (single source of truth) and generate both. Not a blocker for this PR — just worth calling out.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For sure, those appears to be added manually assuming as I was not able to find where they were coming from. Now to your point with add those into the schema, we would need to change the schema here. I think we should start a ML on this before making change here as it is a breaking change due to lack of native per enum value description support. In this case, no change will be apply here and I will start a ML for adding this support. WDYT?