sqlalign 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sqlalign/cli.py ADDED
@@ -0,0 +1,360 @@
1
+ import argparse
2
+ import difflib
3
+ import sys
4
+ from fnmatch import fnmatch
5
+ from pathlib import Path
6
+
7
+ from sqlalign import configfile
8
+ from sqlalign.formatter import format_sql
9
+ from sqlalign.lint import LintUnavailable, lint, version_warning
10
+ from sqlalign.sqlfluffconfig import sqlfluff_config
11
+ from sqlalign.style import PRESETS, SUPPORTED_DIALECTS, Style
12
+
13
+
14
+ def _is_excluded(path: Path, root: Path, patterns: list[str]) -> bool:
15
+ """Whether `path` matches any exclude glob, tested against its path relative
16
+ to the directory being expanded (posix separators, `fnmatch` semantics)."""
17
+ try:
18
+ rel = path.relative_to(root).as_posix()
19
+ except ValueError:
20
+ rel = path.as_posix()
21
+ return any(fnmatch(rel, pat) or fnmatch(path.name, pat) for pat in patterns)
22
+
23
+
24
+ def _expand(names, cli_excludes: list[str], isolated: bool,
25
+ explicit_config: Path | None) -> list[Path]:
26
+ """Turn the command-line arguments into the list of files to format.
27
+
28
+ A directory expands to its `*.sql` files, recursively and in sorted order so
29
+ a run is reproducible. Exclude patterns come from `--exclude` plus the
30
+ `exclude` key of the config discovered at that directory: file selection is
31
+ resolved per ROOT, before the per-file style resolution, because which files
32
+ to touch cannot sensibly vary file by file.
33
+
34
+ A file named explicitly on the command line is never excluded: asking for it
35
+ by name is a clearer signal of intent than a pattern in a config.
36
+ """
37
+ out: list[Path] = []
38
+ for name in names:
39
+ path = Path(name)
40
+ if not path.is_dir():
41
+ out.append(path)
42
+ continue
43
+ patterns = list(cli_excludes)
44
+ if not isolated:
45
+ config = explicit_config or configfile.find_config(path)
46
+ if config is not None:
47
+ patterns += configfile.load_excludes(config)
48
+ out.extend(f for f in sorted(path.rglob("*.sql"))
49
+ if not _is_excluded(f, path, patterns))
50
+ return out
51
+
52
+
53
+ def _report(seen: int, declined: int, causes: dict[tuple[str, str], int]) -> str:
54
+ """The coverage summary.
55
+
56
+ A passthrough is safe but INVISIBLE: it warns on stderr and exits 0, so a CI
57
+ run stays green with any fraction of a repository unformatted. Counting them
58
+ is what turns "sqlalign formatted your SQL" into a number, and turns the
59
+ remaining gaps into a ranked list of what to implement next: measured on
60
+ the team's own SQL rather than guessed at.
61
+ """
62
+ formatted = seen - declined
63
+ pct = f"{formatted / seen * 100:.1f}%" if seen else "n/a"
64
+ lines = [f" {seen:,} statements {formatted:,} formatted ({pct}) "
65
+ f"{declined:,} declined"]
66
+ if causes:
67
+ lines += ["", " declined by cause"]
68
+ width = max(len(kind) for kind, _ in causes)
69
+ for (kind, reason), count in sorted(causes.items(), key=lambda kv: (-kv[1], kv[0])):
70
+ lines.append(f" {count:>4} {kind:<{width}} {reason}")
71
+ return "\n".join(lines)
72
+
73
+
74
+ def _version() -> str:
75
+ """The installed version, or a marker when running from a source tree that
76
+ was never installed."""
77
+ from importlib.metadata import PackageNotFoundError, version
78
+ try:
79
+ return version("sqlalign")
80
+ except PackageNotFoundError: # running from a checkout
81
+ return "unknown"
82
+
83
+
84
+ def build_parser() -> argparse.ArgumentParser:
85
+ """The CLI parser. Split out of `main` so the docs generator and the
86
+ tests can introspect it without running a command."""
87
+ p = argparse.ArgumentParser(prog="sqlalign")
88
+ p.add_argument("--version", action="version", version=f"sqlalign {_version()}",
89
+ help="print the version and exit")
90
+ # `nargs="*"` rather than "+" so `--print-sqlfluff-config` can run with no
91
+ # file at all; every other mode still requires one (checked below).
92
+ p.add_argument("files", nargs="*", help="files or directories (a directory is "
93
+ "searched recursively for *.sql)")
94
+ output_mode = p.add_mutually_exclusive_group()
95
+ output_mode.add_argument("--check", action="store_true",
96
+ help="do not write; exit 1 if any file would change")
97
+ output_mode.add_argument("--stdout", action="store_true",
98
+ help="write the result to stdout instead of the file")
99
+ output_mode.add_argument("--diff", action="store_true",
100
+ help="write nothing; print a unified diff of what would "
101
+ "change (exit 1 if anything would)")
102
+ p.add_argument("--dialect", choices=sorted(SUPPORTED_DIALECTS), default="postgres",
103
+ help="the SQL dialect to parse and print (default: postgres)")
104
+ p.add_argument("--line-ending", choices=["auto", "lf", "crlf"], default="auto",
105
+ help="line endings to write: auto preserves the file's own (default)")
106
+ # Config-file plumbing.
107
+ p.add_argument("--config", type=Path,
108
+ help="use this config file instead of discovering one")
109
+ p.add_argument("--exclude", action="append", metavar="GLOB",
110
+ help="skip files matching this glob when expanding a directory "
111
+ "(repeatable; also settable as `exclude` in a config file)")
112
+ p.add_argument("--isolated", action="store_true",
113
+ help="ignore any config file and use the built-in defaults")
114
+ p.add_argument("--show-config", action="store_true",
115
+ help="print the effective settings as TOML and exit")
116
+ p.add_argument("--gui", action="store_true",
117
+ help="(experimental) open the settings panel with a live preview, and exit")
118
+ p.add_argument("--report", action="store_true",
119
+ help="print a coverage summary: how many statements were "
120
+ "formatted, and what the rest declined on")
121
+ p.add_argument("--max-declines", type=int, metavar="N",
122
+ help="exit 1 if more than N statements are passed through "
123
+ "unformatted (implies --report)")
124
+ p.add_argument("--lint", action="store_true",
125
+ help="after formatting, run sqlfluff over the result "
126
+ "(needs the optional `sqlalign[lint]` extra)")
127
+ p.add_argument("--print-sqlfluff-config", action="store_true",
128
+ help="print a .sqlfluff that lets sqlfluff run alongside "
129
+ "sqlalign without fighting it, and exit")
130
+ p.add_argument("--no-strict-config", action="store_true",
131
+ help="warn on unknown config keys instead of failing")
132
+ p.add_argument("--preset", choices=sorted(PRESETS),
133
+ help="named starting point; config keys and flags layer on top")
134
+ # Style knobs. Every one defaults to None so "not passed" is distinguishable
135
+ # from "passed the same value as the default": otherwise a config file
136
+ # could never be overridden, or (worse) could never take effect at all.
137
+ p.add_argument("--width", type=int,
138
+ help="column the formatter tries to stay inside; 0 turns it off")
139
+ p.add_argument("--blank-lines-between-statements", type=int, metavar="N",
140
+ help="force N blank lines between every pair of statements "
141
+ "(default: one only between two multi-line statements)")
142
+ p.add_argument("--no-align", action="store_const", const=False, dest="align",
143
+ help="emit one space between tokens instead of aligning them into "
144
+ "columns (same line structure, no padding)")
145
+ p.add_argument("--no-protect-templating", action="store_const", const=False,
146
+ dest="protect_templating",
147
+ help="do not mask Jinja/dbt template expressions before formatting")
148
+ p.add_argument("--no-format-bodies", action="store_const", const=False,
149
+ dest="format_dollar_bodies",
150
+ help="leave dollar-quoted ($$) procedure and function bodies untouched")
151
+ p.add_argument("--align-targets",
152
+ help="comma-separated alignment targets to keep. Default is every "
153
+ "target except table_names, which is opt-in because it pads "
154
+ "the FROM/JOIN keyword out to a shared table column. "
155
+ "Valid: aliases, table_names, operators, join_conditions, "
156
+ "case_results, column_types, column_constraints")
157
+ p.add_argument("--comma-position", choices=["leading", "trailing"],
158
+ help="where the separator comma sits in a stacked list (default: leading)")
159
+ p.add_argument("--boolean-operator-position", choices=["leading", "trailing"],
160
+ help="where AND/OR sit when a predicate spans lines (default: leading)")
161
+ p.add_argument("--on-placement", choices=["inline", "own_line"],
162
+ help="whether a JOIN ON rides the table line or drops below it")
163
+ p.add_argument("--select-placement", choices=["inline", "own_line"],
164
+ help="whether the first select item rides the SELECT line")
165
+ p.add_argument("--select-indent", type=int, metavar="N",
166
+ help="columns the select list indents under "
167
+ "--select-placement own_line (default: 2)")
168
+ p.add_argument("--body-blank-lines", type=int, metavar="N",
169
+ help="blank lines between the elements of a $$ body (default: 1)")
170
+ p.add_argument("--clause-keyword-align", choices=["left", "river"],
171
+ help="root clause keywords flush left, or right-aligned to a river")
172
+ p.add_argument("--river-gutter", type=int, metavar="N",
173
+ help="column a river right-aligns clause keywords to (default: 6)")
174
+ p.add_argument("--keyword-case", choices=["upper", "lower"],
175
+ help="case for keywords, function names and types (default: upper)")
176
+ p.add_argument("--neq-style", choices=["!=", "<>"],
177
+ help="spelling for the not-equal operator (default: !=)")
178
+ p.add_argument("--table-alias-style", choices=["bare", "as"],
179
+ help="print a table alias as `t a` (bare) or `t AS a`")
180
+ p.add_argument("--decimal-style", choices=["NUMERIC", "DECIMAL"],
181
+ help="spelling for the NUMERIC/DECIMAL type (default: NUMERIC)")
182
+ return p
183
+
184
+
185
+ def main(argv: list[str] | None = None) -> int:
186
+ p = build_parser()
187
+ args = p.parse_args(argv)
188
+
189
+ overrides = {
190
+ "preset": args.preset,
191
+ "width": args.width,
192
+ "blank_lines_between_statements": args.blank_lines_between_statements,
193
+ "align": args.align,
194
+ "align_targets": args.align_targets,
195
+ "format_dollar_bodies": args.format_dollar_bodies,
196
+ "protect_templating": args.protect_templating,
197
+ "neq_style": args.neq_style,
198
+ "decimal_style": args.decimal_style,
199
+ "table_alias_style": args.table_alias_style,
200
+ "select_placement": args.select_placement,
201
+ "select_indent": args.select_indent,
202
+ "body_blank_lines": args.body_blank_lines,
203
+ "clause_keyword_align": args.clause_keyword_align,
204
+ "river_gutter": args.river_gutter,
205
+ "keyword_case": args.keyword_case,
206
+ "comma_position": args.comma_position,
207
+ "boolean_operator_position": args.boolean_operator_position,
208
+ "on_placement": args.on_placement,
209
+ }
210
+
211
+ def style_for(path: Path) -> Style:
212
+ """Settings for one input file: house defaults < config file < flags.
213
+ Resolved per file so one invocation can span repos with different
214
+ configs."""
215
+ style, _source, warns = configfile.resolve(
216
+ path, overrides, explicit=args.config, isolated=args.isolated,
217
+ strict=not args.no_strict_config)
218
+ for w in warns:
219
+ print(f"sqlalign: {w}", file=sys.stderr)
220
+ return style
221
+
222
+ if args.gui:
223
+ from sqlalign.gui import run
224
+ return run(args.dialect)
225
+
226
+ if not args.files and not (args.print_sqlfluff_config or args.gui):
227
+ p.error("the following arguments are required: files")
228
+
229
+ if args.print_sqlfluff_config:
230
+ # Resolved against the first file like --show-config, so the generated
231
+ # config reflects the style that actually applies there rather than the
232
+ # built-in defaults. With no file given, the defaults are the honest
233
+ # answer: there is no directory to discover a config from.
234
+ try:
235
+ style = (configfile.resolve(
236
+ Path(args.files[0]), overrides, explicit=args.config,
237
+ isolated=args.isolated, strict=not args.no_strict_config)[0]
238
+ if args.files else configfile.build_style({}, overrides))
239
+ except configfile.ConfigError as e:
240
+ p.error(str(e))
241
+ print(sqlfluff_config(style, args.dialect), end="")
242
+ return 0
243
+
244
+ if args.show_config:
245
+ try:
246
+ style, source, warns = configfile.resolve(
247
+ Path(args.files[0]), overrides, explicit=args.config,
248
+ isolated=args.isolated, strict=not args.no_strict_config)
249
+ except configfile.ConfigError as e:
250
+ p.error(str(e))
251
+ for w in warns:
252
+ print(f"sqlalign: {w}", file=sys.stderr)
253
+ print(f"# {source}" if source else "# built-in defaults (no config file found)")
254
+ print(configfile.describe(style))
255
+ return 0
256
+
257
+ try:
258
+ targets = _expand(args.files, args.exclude or [], args.isolated, args.config)
259
+ except configfile.ConfigError as e:
260
+ p.error(str(e))
261
+
262
+ if args.lint:
263
+ try:
264
+ warning = version_warning()
265
+ except LintUnavailable as e:
266
+ print(f"sqlalign: {e}", file=sys.stderr)
267
+ return 2
268
+ if warning:
269
+ print(f"sqlalign: {warning}", file=sys.stderr)
270
+
271
+ seen = declined = 0
272
+ causes: dict[tuple[str, str], int] = {}
273
+
274
+ rc = 0
275
+ for path in targets:
276
+ name = str(path)
277
+ try:
278
+ # newline="" disables universal-newline translation so CRLF/CR bytes
279
+ # survive into `original` and can be detected below (v1 is LF-only).
280
+ with path.open(newline="") as f:
281
+ original = f.read()
282
+ except OSError as e:
283
+ print(f"sqlalign: {e}", file=sys.stderr)
284
+ rc = 2
285
+ continue
286
+ try:
287
+ style = style_for(path)
288
+ except configfile.ConfigError as e: # a broken config must not be guessed past
289
+ print(f"sqlalign: {e}", file=sys.stderr)
290
+ rc = 2
291
+ continue
292
+ # CRLF files are formatted normally: normalize to LF for the engine, then
293
+ # restore the file's own ending on the way out (--line-ending overrides).
294
+ # A LONE "\r" (classic-Mac) is not a line ending this tool models, so those
295
+ # files still pass through untouched rather than being silently rewritten.
296
+ source_ending = "crlf" if "\r\n" in original else "lf"
297
+ normalized = original.replace("\r\n", "\n")
298
+ if "\r" in normalized:
299
+ print(f"sqlalign: {name}: lone CR line endings — passed through untouched",
300
+ file=sys.stderr)
301
+ if args.stdout:
302
+ sys.stdout.write(original)
303
+ continue
304
+ try:
305
+ result = format_sql(normalized, args.dialect, style)
306
+ except Exception as e: # parse/safety failures surface as exit 2, file untouched
307
+ print(f"sqlalign: {name}: {e}", file=sys.stderr)
308
+ rc = 2
309
+ continue
310
+ seen += result.statements
311
+ declined += len(result.declines)
312
+ for d in result.declines:
313
+ causes[(d.kind, d.reason)] = causes.get((d.kind, d.reason), 0) + 1
314
+ for w in result.warnings:
315
+ print(f"sqlalign: {name}: {w}", file=sys.stderr)
316
+ # Restore line endings before comparing or writing, so a CRLF file that is
317
+ # already formatted compares equal (and --check does not report a spurious
318
+ # diff on every line) instead of differing purely by "\r".
319
+ target_ending = source_ending if args.line_ending == "auto" else args.line_ending
320
+ formatted = result.text.replace("\n", "\r\n") if target_ending == "crlf" else result.text
321
+ if args.stdout:
322
+ sys.stdout.write(formatted)
323
+ elif args.check or args.diff:
324
+ # Both write nothing and report through the exit code; they differ in
325
+ # what they print. --check names the files that would change (enough
326
+ # for CI to be actionable without burying the log in diffs); --diff
327
+ # shows the change itself.
328
+ if formatted != original:
329
+ if args.diff:
330
+ sys.stdout.writelines(difflib.unified_diff(
331
+ original.splitlines(keepends=True),
332
+ formatted.splitlines(keepends=True),
333
+ fromfile=name, tofile=f"{name} (formatted)"))
334
+ else:
335
+ print(f"would reformat {name}")
336
+ rc = max(rc, 1)
337
+ elif formatted != original:
338
+ with open(path, "w", newline="") as f:
339
+ f.write(formatted)
340
+
341
+ if args.lint:
342
+ # Lint what would be written, so --check and --stdout report on the
343
+ # formatted result rather than on whatever is currently on disk.
344
+ code, out, err = lint(path, formatted, style, args.dialect)
345
+ sys.stdout.write(out)
346
+ sys.stderr.write(err)
347
+ if code:
348
+ rc = max(rc, 1)
349
+
350
+ if args.report or args.max_declines is not None:
351
+ print(_report(seen, declined, causes))
352
+ if args.max_declines is not None and declined > args.max_declines:
353
+ print(f"sqlalign: {declined} declined, over the --max-declines limit of "
354
+ f"{args.max_declines}", file=sys.stderr)
355
+ rc = max(rc, 1)
356
+ return rc
357
+
358
+
359
+ if __name__ == "__main__":
360
+ sys.exit(main())
sqlalign/commas.py ADDED
@@ -0,0 +1,58 @@
1
+ """Comma position (`Style.comma_position`) — an IR transform, not a text rewrite.
2
+
3
+ House style stacks a list with the separator comma leading each continuation
4
+ line; `trailing` moves it to the end of the preceding line:
5
+
6
+ SELECT a SELECT a,
7
+ , b b
8
+ , c c
9
+
10
+ **Why this is done on the IR rather than on printed text.** Both shipped
11
+ implementations of this option in the wild were post-hoc rewrites over
12
+ already-formatted strings, and both were removed by their own authors
13
+ (sql-formatter dropped `commaPosition` in v14). A string pass cannot reliably
14
+ tell a separator comma from a comma inside `NUMERIC(10, 2)`, a function call, or
15
+ a string literal, and it cannot know which physical line ends a multi-line item.
16
+ Here every separator comma is emitted by its handler as its own segment tagged
17
+ `kind="comma"` at the head of the continuation line, so this pass only has to
18
+ move a known segment: no parsing, no guessing.
19
+
20
+ The relocation target is simply the previous line, which is correct even for
21
+ multi-line items (a CASE, a scalar subquery, a window): the next item's
22
+ comma-head line always directly follows the previous item's LAST line, so
23
+ "previous line" *is* "where that item ended".
24
+
25
+ Tagged `kind="comma"` with no `scope`, so the alignment resolver ignores these
26
+ segments entirely (it only considers a segment with both a scope and a kind).
27
+ """
28
+ from sqlalign.ir import Line, split_trailing_comments
29
+
30
+ COMMA_KIND = "comma"
31
+
32
+
33
+ def apply_comma_position(lines: list[Line], position: str) -> list[Line]:
34
+ """Relocate separator commas per `position`. Mutates and returns `lines`."""
35
+ if position == "leading":
36
+ return lines # handlers already emit the house form
37
+ for i, line in enumerate(lines):
38
+ if not line.segs or line.segs[0].kind != COMMA_KIND:
39
+ continue
40
+ head = line.segs[0]
41
+ # Blank the comma but keep its width, so the term stays in the same
42
+ # column it occupies under leading commas.
43
+ head.text = " " * len(head.text)
44
+ # Walk back past blank lines: CTEs are separated by one, so the comma
45
+ # belongs on the preceding CTE's `)` line, not on the empty line.
46
+ j = i - 1
47
+ while j >= 0 and not lines[j].segs:
48
+ j -= 1
49
+ if j >= 0:
50
+ # Glued onto the existing segment's text, never appended as its own
51
+ # Seg: render() puts a space between segs, which would give `a ,`.
52
+ # Before any trailing comment, for the same reason `joiner_head`
53
+ # does: a comma appended past a `--` is inside it, and the list
54
+ # loses its separator.
55
+ content, comments = split_trailing_comments(lines[j].segs)
56
+ content[-1].text += ","
57
+ lines[j].segs[:] = [*content, *comments]
58
+ return lines
sqlalign/config.py ADDED
@@ -0,0 +1,28 @@
1
+ import sys
2
+ from dataclasses import dataclass
3
+
4
+
5
+ @dataclass(frozen=True)
6
+ class Width:
7
+ width: int = 100
8
+ grace: int = 5
9
+ floor: int = 60
10
+
11
+ # `width = 0` means OFF: never break for length. It is a sentinel rather
12
+ # than a separate boolean because the two are the same decision: a team
13
+ # that does not wrap has no width to state, and because published guides
14
+ # disagree so hard on the number (50/80/88/100/120) that "none of the above"
15
+ # is a real position. GitLab's is `off`.
16
+ OFF = 0
17
+
18
+ def limit(self, anchor: int) -> int:
19
+ """Effective break threshold for a construct anchored at column `anchor`.
20
+
21
+ With the width off this is effectively infinite, so nothing wraps for
22
+ length. Layout still breaks where the STRUCTURE says to: one select
23
+ item per line, a clause per line, because those are not width
24
+ decisions; only the length-driven breaks go away.
25
+ """
26
+ if self.width == self.OFF:
27
+ return sys.maxsize
28
+ return max(self.width, anchor + self.floor) + self.grace
sqlalign/configfile.py ADDED
@@ -0,0 +1,194 @@
1
+ """Config-file discovery, parsing, and precedence.
2
+
3
+ Every style knob was CLI-only until now, which meant a team could not commit its
4
+ own style: the whole point of having the knobs. Settings come from, in
5
+ increasing precedence:
6
+
7
+ built-in house defaults < config file < command-line flags
8
+
9
+ A config file is either a `.sqlalign.toml` (keys at top level) or a
10
+ `pyproject.toml` carrying a `[tool.sqlalign]` table. Discovery walks up from the
11
+ directory of the file being formatted and takes the first of either, so a repo
12
+ can hold one config at its root and a subdirectory can override it.
13
+
14
+ Unknown keys are a hard ERROR rather than a silent no-op: a typo'd key in a
15
+ committed config would otherwise mean a team believes it has a setting it does
16
+ not have, and would only discover it from a surprising diff. `--no-strict-config`
17
+ downgrades that to a warning for the case where a config is shared with a newer
18
+ sqlalign that knows keys this one does not.
19
+ """
20
+ import tomllib
21
+ from pathlib import Path
22
+
23
+ from sqlalign.config import Width
24
+ from sqlalign.style import PRESETS, Style
25
+
26
+ FILENAME = ".sqlalign.toml"
27
+ PYPROJECT = "pyproject.toml"
28
+
29
+ # Keys accepted in a config file, mapped to how they are read. `width` becomes a
30
+ # Width; `align_targets` becomes a frozenset. Everything else is passed through
31
+ # to Style, which validates the VALUE (this module only validates the KEY).
32
+ _SCALAR_KEYS = frozenset({
33
+ "align", "format_dollar_bodies", "neq_style", "decimal_style",
34
+ "comma_position", "boolean_operator_position", "on_placement",
35
+ "protect_templating", "table_alias_style",
36
+ "select_placement", "select_indent",
37
+ "clause_keyword_align", "river_gutter", "body_blank_lines",
38
+ "blank_lines_between_statements",
39
+ "keyword_case",
40
+ })
41
+ KNOWN_KEYS = _SCALAR_KEYS | {"width", "align_targets", "preset", "exclude",
42
+ "blank_lines_between_statements"}
43
+
44
+ # `exclude` selects FILES rather than style, so it is read separately and never
45
+ # reaches Style. Kept in KNOWN_KEYS so a config carrying it is still valid.
46
+ _NON_STYLE_KEYS = frozenset({"exclude"})
47
+
48
+
49
+ def load_excludes(path: Path, *, strict: bool = True) -> list[str]:
50
+ """The `exclude` glob patterns from a config file, if any."""
51
+ settings, _ = load_settings(path, strict=strict)
52
+ patterns = settings.get("exclude", [])
53
+ if isinstance(patterns, str):
54
+ patterns = [patterns]
55
+ if not isinstance(patterns, list) or not all(isinstance(p, str) for p in patterns):
56
+ raise ConfigError(f"{path}: exclude must be a list of glob patterns")
57
+ return patterns
58
+
59
+
60
+ class ConfigError(ValueError):
61
+ """A config file exists but cannot be used as written."""
62
+
63
+
64
+ def find_config(start: Path) -> Path | None:
65
+ """First `.sqlalign.toml`, or `pyproject.toml` with a `[tool.sqlalign]`
66
+ table, at or above `start`'s directory. None if there is none."""
67
+ start = start.resolve()
68
+ directory = start if start.is_dir() else start.parent
69
+ for folder in [directory, *directory.parents]:
70
+ candidate = folder / FILENAME
71
+ if candidate.is_file():
72
+ return candidate
73
+ pyproject = folder / PYPROJECT
74
+ if pyproject.is_file() and _pyproject_table(pyproject) is not None:
75
+ return pyproject
76
+ return None
77
+
78
+
79
+ def _pyproject_table(path: Path):
80
+ try:
81
+ with path.open("rb") as fh:
82
+ return tomllib.load(fh).get("tool", {}).get("sqlalign")
83
+ except (OSError, tomllib.TOMLDecodeError):
84
+ return None
85
+
86
+
87
+ def load_settings(path: Path, *, strict: bool = True) -> tuple[dict, list[str]]:
88
+ """Read `path` into a settings dict. Returns `(settings, warnings)`."""
89
+ try:
90
+ with path.open("rb") as fh:
91
+ data = tomllib.load(fh)
92
+ except OSError as e:
93
+ raise ConfigError(f"{path}: {e}") from e
94
+ except tomllib.TOMLDecodeError as e:
95
+ raise ConfigError(f"{path}: invalid TOML: {e}") from e
96
+
97
+ if path.name == PYPROJECT:
98
+ data = data.get("tool", {}).get("sqlalign", {})
99
+
100
+ warnings = []
101
+ unknown = sorted(set(data) - KNOWN_KEYS)
102
+ if unknown:
103
+ message = (f"{path}: unknown setting(s) {unknown}; "
104
+ f"valid: {sorted(KNOWN_KEYS)}")
105
+ if strict:
106
+ raise ConfigError(message)
107
+ warnings.append(message)
108
+ return {k: v for k, v in data.items() if k in KNOWN_KEYS}, warnings
109
+
110
+
111
+ def build_style(settings: dict, overrides: dict | None = None) -> Style:
112
+ """Compose a Style from file settings plus command-line overrides, with the
113
+ overrides winning. Type errors are reported against the key that caused
114
+ them, so a bad config says which line to fix."""
115
+ merged = {**settings, **{k: v for k, v in (overrides or {}).items() if v is not None}}
116
+
117
+ # A preset supplies the BASE, which explicit keys then layer over: so
118
+ # `preset = "compact"` plus `comma_position = "trailing"` means both, not one
119
+ # or the other.
120
+ for key in _NON_STYLE_KEYS: # file selection, not style
121
+ merged.pop(key, None)
122
+ preset = merged.pop("preset", None)
123
+ if preset is not None:
124
+ if preset not in PRESETS:
125
+ raise ConfigError(f"unknown preset {preset!r}; valid: {sorted(PRESETS)}")
126
+ merged = {**PRESETS[preset], **merged}
127
+
128
+ kwargs = {}
129
+ if "width" in merged:
130
+ if not isinstance(merged["width"], int) or isinstance(merged["width"], bool):
131
+ raise ConfigError(f"width must be an integer, got {merged['width']!r}")
132
+ kwargs["width"] = Width(width=merged["width"])
133
+ if "align_targets" in merged:
134
+ targets = merged["align_targets"]
135
+ if isinstance(targets, str): # CLI passes a list already
136
+ targets = [t.strip() for t in targets.split(",") if t.strip()]
137
+ if not isinstance(targets, (list, tuple, frozenset, set)):
138
+ raise ConfigError(f"align_targets must be a list, got {targets!r}")
139
+ kwargs["align_targets"] = frozenset(targets)
140
+ for key in _SCALAR_KEYS:
141
+ if key in merged:
142
+ kwargs[key] = merged[key]
143
+
144
+ try:
145
+ return Style(**kwargs)
146
+ except ValueError as e: # Style validates values
147
+ raise ConfigError(str(e)) from e
148
+
149
+
150
+ def resolve(path: Path, overrides: dict | None = None, *,
151
+ explicit: Path | None = None, isolated: bool = False,
152
+ strict: bool = True) -> tuple[Style, Path | None, list[str]]:
153
+ """The full resolution for one input file: discover (unless `isolated` or an
154
+ `explicit` config is given), load, merge, validate. Returns
155
+ `(style, config_path_used, warnings)`."""
156
+ if isolated:
157
+ return build_style({}, overrides), None, []
158
+ config_path = explicit if explicit is not None else find_config(path)
159
+ if config_path is None:
160
+ return build_style({}, overrides), None, []
161
+ settings, warnings = load_settings(config_path, strict=strict)
162
+ return build_style(settings, overrides), config_path, warnings
163
+
164
+
165
+ def describe(style: Style) -> str:
166
+ """The effective settings, as the TOML a user could paste into a config."""
167
+ lines = [
168
+ f"width = {style.width.width}",
169
+ f"align = {str(style.align).lower()}",
170
+ "align_targets = [" + ", ".join(f'"{t}"' for t in sorted(style.align_targets)) + "]",
171
+ f'comma_position = "{style.comma_position}"',
172
+ f'boolean_operator_position = "{style.boolean_operator_position}"',
173
+ f'on_placement = "{style.on_placement}"',
174
+ f'select_placement = "{style.select_placement}"',
175
+ f"select_indent = {style.select_indent}",
176
+ f'clause_keyword_align = "{style.clause_keyword_align}"',
177
+ f"river_gutter = {style.river_gutter}",
178
+ f"body_blank_lines = {style.body_blank_lines}",
179
+ f"format_dollar_bodies = {str(style.format_dollar_bodies).lower()}",
180
+ f'neq_style = "{style.neq_style}"',
181
+ f'decimal_style = "{style.decimal_style}"',
182
+ f'table_alias_style = "{style.table_alias_style}"',
183
+ f'keyword_case = "{style.keyword_case}"',
184
+ f"protect_templating = {str(style.protect_templating).lower()}",
185
+ # An unset value has no TOML spelling, so it is emitted COMMENTED OUT
186
+ # rather than as `= # unset`, which is not valid TOML: the output of
187
+ # --show-config has to be loadable as a config, and a round-trip test
188
+ # asserts exactly that.
189
+ (f"blank_lines_between_statements = {style.blank_lines_between_statements}"
190
+ if style.blank_lines_between_statements is not None else
191
+ "# blank_lines_between_statements is unset: one blank line between two\n"
192
+ "# multi-line statements, none otherwise. Set an integer to force a count."),
193
+ ]
194
+ return "\n".join(lines)