lgit-cli 5.5.0__py3-none-any.whl → 5.6.0__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.
- lgit/__init__.py +1 -1
- lgit/api.py +2 -0
- lgit/cli.py +53 -4
- lgit/format_build.py +316 -0
- lgit/format_data.py +371 -0
- lgit/format_infra.py +538 -0
- lgit/format_markdown.py +203 -0
- lgit/format_markup.py +195 -0
- lgit/format_paths.py +103 -0
- lgit/format_tree.py +328 -0
- lgit/format_web.py +591 -0
- lgit/git.py +9 -0
- lgit/patch.py +3 -11
- lgit/reformat.py +1164 -0
- lgit/resources/commit_types.json +7 -7
- lgit/resources/prompts/summary.md +13 -16
- lgit/resources/validation_data.json +1 -1
- lgit/style.py +11 -0
- lgit/syntax_tree.py +179 -0
- lgit/validation.py +22 -2
- {lgit_cli-5.5.0.dist-info → lgit_cli-5.6.0.dist-info}/METADATA +53 -1
- {lgit_cli-5.5.0.dist-info → lgit_cli-5.6.0.dist-info}/RECORD +25 -15
- {lgit_cli-5.5.0.dist-info → lgit_cli-5.6.0.dist-info}/WHEEL +0 -0
- {lgit_cli-5.5.0.dist-info → lgit_cli-5.6.0.dist-info}/entry_points.txt +0 -0
- {lgit_cli-5.5.0.dist-info → lgit_cli-5.6.0.dist-info}/licenses/LICENSE +0 -0
lgit/__init__.py
CHANGED
lgit/api.py
CHANGED
|
@@ -238,6 +238,7 @@ async def generate_summary_from_analysis(
|
|
|
238
238
|
prefix_len = len(commit_type) + 2 + (len(scope) + 2 if scope else 0)
|
|
239
239
|
chars = max(20, config.summary_guideline - prefix_len)
|
|
240
240
|
details = "\n".join(f"- {detail}" for detail in analysis.body_texts()) or f"- {analysis.summary or ''}"
|
|
241
|
+
heading = strip_type_prefix(str(analysis.summary or ""), commit_type, scope).rstrip(" .")
|
|
241
242
|
system_prompt, user_prompt = render_prompt(
|
|
242
243
|
"summary",
|
|
243
244
|
{
|
|
@@ -245,6 +246,7 @@ async def generate_summary_from_analysis(
|
|
|
245
246
|
"scope": scope,
|
|
246
247
|
"chars": chars,
|
|
247
248
|
"user_context": user_context or "",
|
|
249
|
+
"draft": heading,
|
|
248
250
|
"details": details,
|
|
249
251
|
"stat": condense_stat(stat, max_files=30),
|
|
250
252
|
},
|
lgit/cli.py
CHANGED
|
@@ -18,7 +18,7 @@ from typing import Any
|
|
|
18
18
|
|
|
19
19
|
import httpx
|
|
20
20
|
|
|
21
|
-
from . import cache, git, pricing, profile, repo, style, synthesis
|
|
21
|
+
from . import cache, git, pricing, profile, reformat, repo, style, synthesis
|
|
22
22
|
from .analysis import ScopeAnalyzer, extract_scope_candidates
|
|
23
23
|
from .api import (
|
|
24
24
|
generate_analysis_with_map_reduce,
|
|
@@ -115,6 +115,12 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
115
115
|
"--fast", "-f", action="store_true", help="use one LLM call to generate the complete commit message"
|
|
116
116
|
)
|
|
117
117
|
routes.add_argument("--rewrite", action="store_true", help="rewrite recent commit messages")
|
|
118
|
+
routes.add_argument(
|
|
119
|
+
"--fmt",
|
|
120
|
+
action="store_true",
|
|
121
|
+
help="commit only the formatting-only part of pending changes as a style commit, without any LLM call",
|
|
122
|
+
)
|
|
123
|
+
routes.add_argument("--fmt-explain", action="store_true", help="show why --fmt skipped pending files")
|
|
118
124
|
routes.add_argument("--test", action="store_true", help="run fixture-test mode")
|
|
119
125
|
|
|
120
126
|
rewrite = parser.add_argument_group("rewrite")
|
|
@@ -175,6 +181,7 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
|
|
175
181
|
def main(argv: Sequence[str] | None = None) -> int:
|
|
176
182
|
"""Console-script entry point."""
|
|
177
183
|
try:
|
|
184
|
+
style.configure_output()
|
|
178
185
|
args = parse_args(argv)
|
|
179
186
|
return asyncio.run(run_cli(args))
|
|
180
187
|
except KeyboardInterrupt:
|
|
@@ -211,6 +218,8 @@ async def run_cli(args: argparse.Namespace) -> int:
|
|
|
211
218
|
with profile.section("ensure_git_repo", collector):
|
|
212
219
|
git.ensure_git_repo(args.dir)
|
|
213
220
|
|
|
221
|
+
if args.fmt:
|
|
222
|
+
return _run_fmt(args, config)
|
|
214
223
|
if _wants_rewrite(args):
|
|
215
224
|
return await _run_rewrite(args, config)
|
|
216
225
|
if _wants_compose(args):
|
|
@@ -373,6 +382,41 @@ async def _run_standard(args: argparse.Namespace, config: CommitConfig) -> int:
|
|
|
373
382
|
return 0
|
|
374
383
|
|
|
375
384
|
|
|
385
|
+
def _run_fmt(args: argparse.Namespace, config: CommitConfig) -> int:
|
|
386
|
+
"""Commit the formatting-only regions of every pending modification; everything else stays pending."""
|
|
387
|
+
|
|
388
|
+
plan = reformat.plan_formatting(args.dir, explain=args.fmt_explain)
|
|
389
|
+
for path, reason in plan.skipped:
|
|
390
|
+
print(f" {path}: {reason}")
|
|
391
|
+
if plan.partially_staged and not args.fmt_explain:
|
|
392
|
+
style.status(
|
|
393
|
+
f"{style.info('›')} "
|
|
394
|
+
f"{style.dim(f'Skipped {len(plan.partially_staged)} files with both staged and unstaged changes')}"
|
|
395
|
+
)
|
|
396
|
+
if not plan.files:
|
|
397
|
+
print("No formatting-only changes found.")
|
|
398
|
+
return 0
|
|
399
|
+
message = _build_reformat_commit([file.path for file in plan.files], config, args)
|
|
400
|
+
partial = sum(not file.complete for file in plan.files)
|
|
401
|
+
style.status(
|
|
402
|
+
f"{style.info('›')} "
|
|
403
|
+
f"{style.dim(f'{len(plan.files)} files with formatting-only changes ({partial} keep other changes pending)')}"
|
|
404
|
+
)
|
|
405
|
+
if args.dry_run:
|
|
406
|
+
for file in plan.files:
|
|
407
|
+
print(f" {file.path}{'' if file.complete else ' (partial)'}")
|
|
408
|
+
_print_message(message, title="DRY RUN")
|
|
409
|
+
return 0
|
|
410
|
+
text = message.format_commit_message()
|
|
411
|
+
if args.signoff or config.signoff:
|
|
412
|
+
text = git.append_signoff_trailer(text, args.dir)
|
|
413
|
+
commit = reformat.commit_formatting(plan, text, args.dir, sign=bool(args.sign or config.gpg_sign))
|
|
414
|
+
print(style.success(f"{style.icons.SUCCESS} Committed {message.format_commit_message()} as {commit[:8]}"))
|
|
415
|
+
if args.push:
|
|
416
|
+
git.run_git(["push"], cwd=args.dir)
|
|
417
|
+
return 0
|
|
418
|
+
|
|
419
|
+
|
|
376
420
|
async def _run_compose(args: argparse.Namespace, config: CommitConfig) -> int:
|
|
377
421
|
from .compose import run_compose_mode
|
|
378
422
|
|
|
@@ -408,7 +452,7 @@ def _print_llm_spend() -> None:
|
|
|
408
452
|
line = f"LLM cost: ${spend.cost_usd:.4f} ({tokens})"
|
|
409
453
|
if spend.saved_usd > 0:
|
|
410
454
|
line += f", saved ${spend.saved_usd:.4f} via cache"
|
|
411
|
-
|
|
455
|
+
style.status(style.dim(line))
|
|
412
456
|
|
|
413
457
|
|
|
414
458
|
def _compact_count(count: int) -> str:
|
|
@@ -647,7 +691,7 @@ async def _generate_standard_workflow(
|
|
|
647
691
|
if use_map_reduce:
|
|
648
692
|
analysis_diff = diff
|
|
649
693
|
elif len(diff) > int(config.max_diff_length):
|
|
650
|
-
|
|
694
|
+
style.status(style.warning(f"Applying smart truncation (diff size: {len(diff)} characters)"))
|
|
651
695
|
analysis_diff = smart_truncate_diff(diff, int(config.max_diff_length), config, token_counter)
|
|
652
696
|
else:
|
|
653
697
|
analysis_diff = diff
|
|
@@ -1162,6 +1206,7 @@ def _validate_arg_conflicts(parser: argparse.ArgumentParser, args: argparse.Name
|
|
|
1162
1206
|
selected_routes = [
|
|
1163
1207
|
name
|
|
1164
1208
|
for name, active in (
|
|
1209
|
+
("--fmt", bool(args.fmt)),
|
|
1165
1210
|
("--compose", _wants_compose(args)),
|
|
1166
1211
|
("--rewrite", _wants_rewrite(args)),
|
|
1167
1212
|
("--test", _wants_test(args)),
|
|
@@ -1171,7 +1216,11 @@ def _validate_arg_conflicts(parser: argparse.ArgumentParser, args: argparse.Name
|
|
|
1171
1216
|
if len(selected_routes) > 1:
|
|
1172
1217
|
parser.error(f"conflicting modes: {' and '.join(selected_routes)}")
|
|
1173
1218
|
if args.fast and selected_routes:
|
|
1174
|
-
parser.error("--fast cannot be combined with compose, rewrite, or test mode")
|
|
1219
|
+
parser.error("--fast cannot be combined with fmt, compose, rewrite, or test mode")
|
|
1220
|
+
if args.fmt_explain and not args.fmt:
|
|
1221
|
+
parser.error("--fmt-explain requires --fmt")
|
|
1222
|
+
if args.fmt and (args.mode != Mode.STAGED.value or args.amend):
|
|
1223
|
+
parser.error("--fmt commits pending changes on top of HEAD; it cannot be combined with --mode or --amend")
|
|
1175
1224
|
if args.mode == Mode.COMMIT.value and not args.target:
|
|
1176
1225
|
parser.error("--target is required with --mode commit")
|
|
1177
1226
|
if args.test_add and not args.test_name:
|
lgit/format_build.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""Conservative source-positioned comparisons for shell and build files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import warnings
|
|
9
|
+
from collections.abc import Iterator
|
|
10
|
+
|
|
11
|
+
from tree_sitter import Node
|
|
12
|
+
|
|
13
|
+
from .format_data import Event, FormatDocument, Key
|
|
14
|
+
from .syntax_tree import parse_packed
|
|
15
|
+
|
|
16
|
+
_GRAMMARS = {
|
|
17
|
+
"shell": "bash",
|
|
18
|
+
"fish": "fish",
|
|
19
|
+
"powershell": "powershell",
|
|
20
|
+
"make": "make",
|
|
21
|
+
"cmake": "cmake",
|
|
22
|
+
"starlark": "python",
|
|
23
|
+
}
|
|
24
|
+
_OPAQUE = {
|
|
25
|
+
"bash": frozenset(
|
|
26
|
+
{
|
|
27
|
+
"string",
|
|
28
|
+
"raw_string",
|
|
29
|
+
"ansi_c_string",
|
|
30
|
+
"translated_string",
|
|
31
|
+
"regex",
|
|
32
|
+
"extglob_pattern",
|
|
33
|
+
"expansion",
|
|
34
|
+
"heredoc_redirect",
|
|
35
|
+
}
|
|
36
|
+
),
|
|
37
|
+
"fish": frozenset(
|
|
38
|
+
{"single_quote_string", "double_quote_string", "escape_sequence", "brace_expansion", "variable_expansion"}
|
|
39
|
+
),
|
|
40
|
+
"powershell": frozenset({"string_literal", "generic_token", "stop_parsing", "verbatim_command_argument"}),
|
|
41
|
+
"make": frozenset(
|
|
42
|
+
{
|
|
43
|
+
"recipe",
|
|
44
|
+
"text",
|
|
45
|
+
"raw_text",
|
|
46
|
+
"ifeq_directive",
|
|
47
|
+
"ifneq_directive",
|
|
48
|
+
"define_directive",
|
|
49
|
+
"function_call",
|
|
50
|
+
"variable_reference",
|
|
51
|
+
}
|
|
52
|
+
),
|
|
53
|
+
"cmake": frozenset({"argument", "bracket_comment"}),
|
|
54
|
+
"python": frozenset({"string", "concatenated_string"}),
|
|
55
|
+
}
|
|
56
|
+
_COMMENTS = frozenset({"comment", "line_comment", "block_comment", "bracket_comment"})
|
|
57
|
+
_SHELL_OPERATORS = frozenset({"|", "|&", "&&", "||", ";", "&", ";;", ";&", ";;&"})
|
|
58
|
+
_REDIRECT_OPERATORS = frozenset({"<", ">", ">>", "<&", ">&", ">|", "&>", "&>>", "<>"})
|
|
59
|
+
_MAKE_OPERATORS = frozenset({":", "::", "&:", "&::", "=", ":=", "::=", ":::=", "?=", "+=", "!=", "|"})
|
|
60
|
+
_PS_EXPRESSIONS = frozenset(
|
|
61
|
+
{
|
|
62
|
+
"assignment_expression",
|
|
63
|
+
"additive_expression",
|
|
64
|
+
"multiplicative_expression",
|
|
65
|
+
"comparison_expression",
|
|
66
|
+
"logical_expression",
|
|
67
|
+
"bitwise_expression",
|
|
68
|
+
"format_expression",
|
|
69
|
+
"range_expression",
|
|
70
|
+
}
|
|
71
|
+
)
|
|
72
|
+
_PS_BLOCKS = frozenset({"statement_block", "if_statement", "else_clause", "elseif_clause"})
|
|
73
|
+
_PYTHON_COMMA_LISTS = frozenset({"argument_list", "parameters", "list", "dictionary", "set"})
|
|
74
|
+
_LAYOUT = b" \t\r\n"
|
|
75
|
+
_DOCKER_HEAD = re.compile(r"[ \t]*(?P<command>[a-zA-Z]+)[ \t]+(?P<args>.*)")
|
|
76
|
+
_DOCKER_SPACE = re.compile(r"[ \t]+")
|
|
77
|
+
_DOCKER_DIRECTIVE = re.compile(r"[ \t]*#[ \t]*(?:escape|syntax|check)[ \t]*=", re.IGNORECASE)
|
|
78
|
+
_DOCKER_ESCAPE = re.compile(r"[ \t]*#[ \t]*escape[ \t]*=[ \t]*`", re.IGNORECASE)
|
|
79
|
+
_DOCKER_JSON = frozenset({"ADD", "CMD", "COPY", "ENTRYPOINT", "RUN", "SHELL", "VOLUME"})
|
|
80
|
+
_DOCKER_ARRAY_STRING = re.compile(r'"(?:[^"\\]|\\.)*"')
|
|
81
|
+
_DOCKER_BARE_ARGS = frozenset({"ADD", "COPY", "EXPOSE", "FROM"})
|
|
82
|
+
_DOCKER_BARE = re.compile(r"[^ \t\r\n'\"\\#$`]+(?:[ \t]+[^ \t\r\n'\"\\#$`]+)*")
|
|
83
|
+
_DOCKER_PAIRS = re.compile(r"[\w.-]+=[^ =\t\r\n'\"\\#$`]+(?:[ \t]+[\w.-]+=[^ =\t\r\n'\"\\#$`]+)*", re.ASCII)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _docker_json(raw: str) -> Key | None:
|
|
87
|
+
if not raw.startswith("["):
|
|
88
|
+
return None
|
|
89
|
+
try:
|
|
90
|
+
value = json.loads(raw)
|
|
91
|
+
except ValueError, RecursionError:
|
|
92
|
+
return None
|
|
93
|
+
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
|
94
|
+
return None
|
|
95
|
+
return ("json", *(match[0] for match in _DOCKER_ARRAY_STRING.finditer(raw)))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _docker_document(text: str) -> FormatDocument | None:
|
|
99
|
+
lines = text.split("\n")
|
|
100
|
+
# The bundled grammar lacks the ADD/COPY JSON alternative. Substitute only independently
|
|
101
|
+
# validated JSON arrays, then require every substitution to be a standalone instruction.
|
|
102
|
+
json_paths: dict[int, Key] = {}
|
|
103
|
+
grammar_lines: list[str] | None = None
|
|
104
|
+
for row, line in enumerate(lines):
|
|
105
|
+
if (match := _DOCKER_HEAD.fullmatch(line.removesuffix("\r"))) is None:
|
|
106
|
+
continue
|
|
107
|
+
if match["command"].upper() in {"ADD", "COPY"} and (key := _docker_json(match["args"])) is not None:
|
|
108
|
+
json_paths[row] = key
|
|
109
|
+
if grammar_lines is None:
|
|
110
|
+
grammar_lines = lines.copy()
|
|
111
|
+
grammar_lines[row] = line[: match.start("args")] + "lgit-src lgit-dst"
|
|
112
|
+
root = parse_packed("\n".join(grammar_lines) if grammar_lines is not None else text, "dockerfile")
|
|
113
|
+
if root is None:
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
events: list[Event] = []
|
|
117
|
+
row = prefix_start = 0
|
|
118
|
+
in_prefix = True
|
|
119
|
+
for node in root.named_children:
|
|
120
|
+
start, end = node.start_point.row, node.end_point.row
|
|
121
|
+
if end > start and node.end_point.column == 0:
|
|
122
|
+
end -= 1
|
|
123
|
+
if start < row or any(line.strip(" \t\r") for line in lines[row:start]):
|
|
124
|
+
# A token on an already consumed physical line can be an inline hash that the
|
|
125
|
+
# Docker grammar calls a comment even though Docker treats it as an argument.
|
|
126
|
+
return None
|
|
127
|
+
if node.type == "comment":
|
|
128
|
+
line = lines[start]
|
|
129
|
+
if in_prefix and _DOCKER_ESCAPE.match(line):
|
|
130
|
+
# A non-default escape character changes instruction and continuation lexing.
|
|
131
|
+
return None
|
|
132
|
+
if in_prefix and _DOCKER_DIRECTIVE.match(line):
|
|
133
|
+
events.append((start, ("parser-directive", *lines[prefix_start : start + 1])))
|
|
134
|
+
prefix_start = start + 1
|
|
135
|
+
else:
|
|
136
|
+
events.append((start, ("comment", line.lstrip(" \t"))))
|
|
137
|
+
else:
|
|
138
|
+
in_prefix = False
|
|
139
|
+
line = lines[start]
|
|
140
|
+
match = _DOCKER_HEAD.fullmatch(line.removesuffix("\r"))
|
|
141
|
+
if start == end and match is not None and node.type.endswith("_instruction"):
|
|
142
|
+
command, args = match["command"].upper(), match["args"]
|
|
143
|
+
if start in json_paths:
|
|
144
|
+
if node.type != command.lower() + "_instruction":
|
|
145
|
+
return None
|
|
146
|
+
events.append((start, (command, *json_paths.pop(start))))
|
|
147
|
+
elif command in _DOCKER_JSON and (key := _docker_json(args)) is not None:
|
|
148
|
+
events.append((start, (command, *key)))
|
|
149
|
+
elif command in _DOCKER_BARE_ARGS and _DOCKER_BARE.fullmatch(args.rstrip(" \t")):
|
|
150
|
+
events.append((start, (command, "words", *_DOCKER_SPACE.split(args.rstrip(" \t")))))
|
|
151
|
+
elif command in {"ENV", "LABEL"} and _DOCKER_PAIRS.fullmatch(args.rstrip(" \t")):
|
|
152
|
+
events.append((start, (command, "values", *_DOCKER_SPACE.split(args.rstrip(" \t")))))
|
|
153
|
+
else:
|
|
154
|
+
# The inherited SHELL may not be POSIX. Preserve command text, old-style
|
|
155
|
+
# ENV values, options using quotes, and other unclassified argument text.
|
|
156
|
+
events.append((start, (command, "raw", args, line.endswith("\r"))))
|
|
157
|
+
else:
|
|
158
|
+
events.extend((i, ("docker-raw", lines[i])) for i in range(start, end + 1))
|
|
159
|
+
row = end + 1
|
|
160
|
+
if json_paths or any(line.strip(" \t\r") for line in lines[row:]):
|
|
161
|
+
return None
|
|
162
|
+
return FormatDocument.from_events(text, events)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class _TreeEvents:
|
|
166
|
+
def __init__(self, source: bytes, grammar: str) -> None:
|
|
167
|
+
self.source = source
|
|
168
|
+
self.grammar = grammar
|
|
169
|
+
|
|
170
|
+
def _gap(self, parent: Node, left: Node | None, right: Node | None, start: int, end: int) -> Key | None:
|
|
171
|
+
raw = self.source[start:end]
|
|
172
|
+
if not raw:
|
|
173
|
+
return None
|
|
174
|
+
grammar = self.grammar
|
|
175
|
+
if raw.strip(_LAYOUT) or (b"\r" in raw and (grammar in {"bash", "fish"} or b"\r" in raw.replace(b"\r\n", b""))):
|
|
176
|
+
# External scanners may consume escapes and carriage returns that the shell sees.
|
|
177
|
+
# Keep the seam, including spaces that separate words around an escaped newline.
|
|
178
|
+
return "raw-gap", raw
|
|
179
|
+
if right is not None and grammar in {"make", "python"}:
|
|
180
|
+
line_start = end - right.start_point.column
|
|
181
|
+
if line_start >= start:
|
|
182
|
+
indent = self.source[line_start:end]
|
|
183
|
+
if indent and (grammar == "make" or b"\t" in indent):
|
|
184
|
+
# A recipe prefix changes the interpretation of an entire Make line.
|
|
185
|
+
# Starlark implementations need not agree on the meaning of tabs.
|
|
186
|
+
return "indent", indent, b"\n" in raw if left is not None else False
|
|
187
|
+
if left is None or right is None:
|
|
188
|
+
return None
|
|
189
|
+
line_break = b"\n" in raw
|
|
190
|
+
if right.type in _COMMENTS or left.type in _COMMENTS:
|
|
191
|
+
if line_break:
|
|
192
|
+
return ("comment-break",)
|
|
193
|
+
return None
|
|
194
|
+
if grammar == "python":
|
|
195
|
+
return None
|
|
196
|
+
if grammar == "cmake":
|
|
197
|
+
if parent.type in {"source_file", "body"}:
|
|
198
|
+
return ("command-break",) if line_break else None
|
|
199
|
+
if left.type == "(" or right.type == ")" or (right.type == "(" and parent.type.endswith("_command")):
|
|
200
|
+
return None
|
|
201
|
+
return ("argument-gap",)
|
|
202
|
+
if line_break:
|
|
203
|
+
return ("line-break",)
|
|
204
|
+
if grammar == "make":
|
|
205
|
+
if parent.type in {"variable_assignment", "rule"} and (
|
|
206
|
+
left.type in _MAKE_OPERATORS or right.type in _MAKE_OPERATORS
|
|
207
|
+
):
|
|
208
|
+
return None
|
|
209
|
+
elif grammar == "powershell":
|
|
210
|
+
if parent.type in _PS_EXPRESSIONS or parent.type in _PS_BLOCKS:
|
|
211
|
+
return None
|
|
212
|
+
if left.type in {"|", "&&", "||"} or right.type in {"|", "&&", "||"}:
|
|
213
|
+
return None
|
|
214
|
+
if left.type == "command_argument_sep" or right.type == "command_argument_sep":
|
|
215
|
+
return None
|
|
216
|
+
else:
|
|
217
|
+
if left.type in _SHELL_OPERATORS or right.type in _SHELL_OPERATORS:
|
|
218
|
+
return None
|
|
219
|
+
if parent.type == "file_redirect" and left.type in _REDIRECT_OPERATORS:
|
|
220
|
+
return None
|
|
221
|
+
if grammar == "bash" and parent.type == "function_definition" and (left.type == ")" or right.type == "("):
|
|
222
|
+
return None
|
|
223
|
+
return ("space",)
|
|
224
|
+
|
|
225
|
+
def _children(self, node: Node) -> list[Node]:
|
|
226
|
+
children = node.children
|
|
227
|
+
if self.grammar == "powershell" and children:
|
|
228
|
+
tail = children[-1]
|
|
229
|
+
if tail.type == "command_elements" or (
|
|
230
|
+
node.type == "command_elements" and tail.type == "command_argument_sep"
|
|
231
|
+
):
|
|
232
|
+
raw = self.source[tail.start_byte : tail.end_byte]
|
|
233
|
+
if raw and not raw.strip(b" \t"):
|
|
234
|
+
children.pop()
|
|
235
|
+
return children
|
|
236
|
+
|
|
237
|
+
def events(self, node: Node, *, root: bool = False) -> Iterator[Event]:
|
|
238
|
+
row, kind = node.start_point.row, node.type
|
|
239
|
+
if not node.child_count or kind in _OPAQUE[self.grammar] or kind in _COMMENTS or kind == "command_argument_sep":
|
|
240
|
+
raw = self.source[node.start_byte : node.end_byte]
|
|
241
|
+
if root:
|
|
242
|
+
padding = b" \t\n" if self.grammar in {"bash", "fish"} else _LAYOUT
|
|
243
|
+
raw = self.source
|
|
244
|
+
if not raw.strip(padding):
|
|
245
|
+
return
|
|
246
|
+
if kind == "command_argument_sep" and raw and not raw.strip(b" \t"):
|
|
247
|
+
raw = b" "
|
|
248
|
+
elif self.grammar == "fish" and kind == "\n" and not raw.strip(b"\n"):
|
|
249
|
+
raw = b"\n"
|
|
250
|
+
yield row, ("token", kind, raw)
|
|
251
|
+
return
|
|
252
|
+
if not root:
|
|
253
|
+
yield row, ("open", kind)
|
|
254
|
+
left: Node | None = None
|
|
255
|
+
start = 0 if root else node.start_byte
|
|
256
|
+
children = self._children(node)
|
|
257
|
+
ignored_comma = _trailing_comma(children) if self.grammar == "python" and kind in _PYTHON_COMMA_LISTS else None
|
|
258
|
+
for child in children:
|
|
259
|
+
if key := self._gap(node, left, child, start, child.start_byte):
|
|
260
|
+
yield child.start_point.row, key
|
|
261
|
+
start = child.end_byte
|
|
262
|
+
if child == ignored_comma:
|
|
263
|
+
continue
|
|
264
|
+
yield from self.events(child)
|
|
265
|
+
left = child
|
|
266
|
+
if key := self._gap(node, left, None, start, len(self.source) if root else node.end_byte):
|
|
267
|
+
yield node.end_point.row, key
|
|
268
|
+
if not root:
|
|
269
|
+
yield node.end_point.row, ("close", kind)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _trailing_comma(children: list[Node]) -> Node | None:
|
|
273
|
+
# The AST guard also checks that the enclosing list retains its meaning.
|
|
274
|
+
at_end = False
|
|
275
|
+
for child in reversed(children):
|
|
276
|
+
if child.type in {")", "]", "}"}:
|
|
277
|
+
at_end = True
|
|
278
|
+
elif child.type not in _COMMENTS:
|
|
279
|
+
return child if at_end and child.type == "," else None
|
|
280
|
+
return None
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _ast_events(text: str) -> list[Event] | None:
|
|
284
|
+
try:
|
|
285
|
+
with warnings.catch_warnings(action="ignore", category=SyntaxWarning):
|
|
286
|
+
module = ast.parse(text, type_comments=True)
|
|
287
|
+
# AST dumps guard indentation and parser ambiguities without applying Python's rewrites.
|
|
288
|
+
# Separate statement keys let unrelated formatting survive mixed edits in other rules.
|
|
289
|
+
events: list[Event] = [(node.lineno - 1, ("python-statement", ast.dump(node))) for node in module.body]
|
|
290
|
+
events.extend((node.lineno - 1, ("type-ignore", node.tag)) for node in module.type_ignores)
|
|
291
|
+
return events
|
|
292
|
+
except SyntaxError, ValueError, RecursionError:
|
|
293
|
+
return None
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def build_document(text: str, format_name: str) -> FormatDocument | None:
|
|
297
|
+
"""Compare shell and build layout without evaluating code, expanding variables, or running recipes."""
|
|
298
|
+
if format_name == "dockerfile":
|
|
299
|
+
return _docker_document(text)
|
|
300
|
+
grammar = _GRAMMARS.get(format_name)
|
|
301
|
+
if grammar is None or (root := parse_packed(text, grammar)) is None:
|
|
302
|
+
return None
|
|
303
|
+
python = _ast_events(text) if grammar == "python" else []
|
|
304
|
+
if python is None:
|
|
305
|
+
return None
|
|
306
|
+
|
|
307
|
+
def events() -> Iterator[Event]:
|
|
308
|
+
if grammar in {"bash", "fish"} and text.startswith("#!"):
|
|
309
|
+
yield 0, ("shebang",)
|
|
310
|
+
yield from _TreeEvents(text.encode(), grammar).events(root, root=True)
|
|
311
|
+
yield from python
|
|
312
|
+
|
|
313
|
+
try:
|
|
314
|
+
return FormatDocument.from_events(text, events())
|
|
315
|
+
except RecursionError:
|
|
316
|
+
return None
|