forked from sqlfluff/sqlfluff
-
Notifications
You must be signed in to change notification settings - Fork 4
/
generate_parse_fixture_yml.py
162 lines (134 loc) · 5.03 KB
/
generate_parse_fixture_yml.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
"""Utility to generate yml files for all the parsing examples."""
import multiprocessing
import os
import fnmatch
import re
import click
from typing import Callable, Dict, List, Optional, TypeVar
import yaml
from conftest import (
compute_parse_tree_hash,
get_parse_fixtures,
parse_example_file,
ParseExample,
)
from sqlfluff.core.errors import SQLParseError
S = TypeVar("S")
def distribute_work(work_items: List[S], work_fn: Callable[[S], None]) -> None:
"""Distribute work and ignore results."""
with multiprocessing.Pool(multiprocessing.cpu_count()) as pool:
for _ in pool.imap_unordered(work_fn, work_items):
pass
def _create_yaml_path(example: ParseExample) -> str:
dialect, sqlfile = example
root, _ = os.path.splitext(sqlfile)
path = os.path.join("test", "fixtures", "dialects", dialect, root + ".yml")
return path
def _is_matching_new_criteria(example: ParseExample):
"""Is the Yaml doesn't exist or is older than the SQL."""
yaml_path = _create_yaml_path(example)
if not os.path.exists(yaml_path):
return True
sql_path = os.path.join(
"test",
"fixtures",
"dialects",
example.dialect,
example.sqlfile,
)
return os.path.getmtime(yaml_path) < os.path.getmtime(sql_path)
def generate_one_parse_fixture(example: ParseExample) -> None:
"""Parse example SQL file, write parse tree to YAML file."""
dialect, sqlfile = example
tree = parse_example_file(dialect, sqlfile)
_hash = compute_parse_tree_hash(tree)
# Remove the .sql file extension
path = _create_yaml_path(example)
with open(path, "w", newline="\n") as f:
r: Optional[Dict[str, Optional[str]]] = None
if not tree:
f.write("")
return
# Check we don't have any base types or unparsable sections
types = tree.type_set()
if "base" in types:
raise SQLParseError(f"Unnamed base section when parsing: {f.name}")
if "unparsable" in types:
for unparsable in tree.iter_unparsables():
print("Found unparsable segment...")
print(unparsable.stringify())
raise SQLParseError(f"Could not parse: {f.name}")
records = tree.as_record(code_only=True, show_raw=True)
assert records, "TypeGuard"
r = dict([("_hash", _hash), *list(records.items())])
print(
"# YML test files are auto-generated from SQL files and should not be "
"edited by",
'# hand. To help enforce this, the "hash" field in the file must match '
"a hash",
"# computed by SQLFluff when running the tests. Please run",
"# `python test/generate_parse_fixture_yml.py` to generate them after "
"adding or",
"# altering SQL files.",
file=f,
sep="\n",
)
yaml.dump(r, f, default_flow_style=False, sort_keys=False)
return
def gather_file_list(
dialect: Optional[str] = None,
glob_match_pattern: Optional[str] = None,
new_only: bool = False,
) -> List[ParseExample]:
"""Gather the list of files to generate fixtures for. Apply filters as required."""
parse_success_examples, _ = get_parse_fixtures()
if new_only:
parse_success_examples = [
example
for example in parse_success_examples
if _is_matching_new_criteria(example)
]
if dialect:
dialect = dialect.lower()
parse_success_examples = [
example for example in parse_success_examples if example[0] == dialect
]
if len(parse_success_examples) == 0:
raise ValueError(f'Unknown Dialect "{dialect}"')
if not glob_match_pattern:
return parse_success_examples
regex = re.compile(fnmatch.translate(glob_match_pattern))
return [
example
for example in parse_success_examples
if regex.match(example[1]) is not None
]
@click.command()
@click.option(
"--filter", "-f", default=None, help="A glob filter to apply to file names."
)
@click.option("--dialect", "-d", default=None, help="Filter to a given dialect.")
@click.option(
"--new-only",
"new_only",
is_flag=True,
default=False,
help="Only create missing fixtures.",
)
def generate_parse_fixtures(
filter: Optional[str], dialect: Optional[str], new_only: bool
):
"""Generate fixture or a subset based on dialect or filename glob match."""
filter_str = filter or "*"
dialect_str = dialect or "all"
print("Match Pattern Received:")
print(f"\tfilter={filter_str} dialect={dialect_str} new-only={new_only}")
parse_success_examples = gather_file_list(dialect, filter, new_only)
print(f"Found {len(parse_success_examples)} file(s) to generate")
distribute_work(parse_success_examples, generate_one_parse_fixture)
print(f"Fixture built: {len(parse_success_examples)}")
def main():
"""Find all example SQL files, parse and create YAML files."""
generate_parse_fixtures()
if __name__ == "__main__":
main()