skfmt 0.1.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.
skfmt/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """Public API for the SKILL formatter."""
2
+
3
+ from .formatter import FormatResult, format_range, format_source
4
+ from .identity import CONFIG_NAME, DIST_NAME, LANG_ENV, TOOL_NAME
5
+ from .options import CATEGORIES, Options
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = [
10
+ "CATEGORIES",
11
+ "CONFIG_NAME",
12
+ "DIST_NAME",
13
+ "LANG_ENV",
14
+ "Options",
15
+ "FormatResult",
16
+ "TOOL_NAME",
17
+ "format_range",
18
+ "format_source",
19
+ ]
skfmt/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
skfmt/ast.py ADDED
@@ -0,0 +1,67 @@
1
+ """A small concrete syntax tree for SKILL source."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+
9
+ @dataclass(slots=True)
10
+ class Node:
11
+ kind: str
12
+ value: str = ""
13
+ children: list[Node] = field(default_factory=list)
14
+ start: int = 0
15
+ end: int = 0
16
+ line: int = 0
17
+ blank_before: int = 0
18
+ inline: bool = False
19
+ style: str = ""
20
+ meta: dict[str, Any] = field(default_factory=dict)
21
+
22
+ def canonical(self) -> str:
23
+ """Layout-insensitive structure used to verify formatting safety."""
24
+ if self.kind in {"atom", "string"}:
25
+ return self.value
26
+ if self.kind == "comment":
27
+ return ""
28
+ if self.kind == "opaque":
29
+ return f"<opaque:{self.value}>"
30
+ if self.kind == "seq":
31
+ return "(" + " ".join(c.canonical() for c in self.children if c.kind != "comment") + ")"
32
+ if self.kind == "call":
33
+ head = self.value
34
+ args = " ".join(c.canonical() for c in self.children if c.kind != "comment")
35
+ return f"({head} {args})" if args else f"({head})"
36
+ if self.kind == "plist":
37
+ items = " ".join(c.canonical() for c in self.children if c.kind != "comment")
38
+ return f"({items})" if items else "()"
39
+ if self.kind == "group":
40
+ return f"(group {self.children[0].canonical()})"
41
+ if self.kind == "index":
42
+ return f"(index {self.children[0].canonical()} {self.children[1].canonical()})"
43
+ if self.kind == "prefix":
44
+ return f"({self.value} {self.children[0].canonical()})"
45
+ if self.kind in {"binary", "assign"}:
46
+ return f"({self.value} {self.children[0].canonical()} {self.children[1].canonical()})"
47
+ if self.kind in {"unary", "postfix"}:
48
+ return f"({self.value} {self.children[0].canonical()})"
49
+ return f"<{self.kind}:{self.value}>"
50
+
51
+ def comments(self) -> list[str]:
52
+ out: list[str] = []
53
+ if self.kind == "comment":
54
+ out.append(self.value)
55
+ for child in self.children:
56
+ out.extend(child.comments())
57
+ return out
58
+
59
+ def walk(self) -> list[Node]:
60
+ out = [self]
61
+ for child in self.children:
62
+ out.extend(child.walk())
63
+ return out
64
+
65
+
66
+ def sequence(children: list[Node]) -> Node:
67
+ return Node("seq", children=children)
skfmt/cli.py ADDED
@@ -0,0 +1,604 @@
1
+ """Command line interface for skfmt."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import difflib
7
+ import os
8
+ import sys
9
+ import tempfile
10
+ from pathlib import Path
11
+ from typing import Any, NoReturn, cast
12
+
13
+ from . import __version__
14
+ from .config import (
15
+ ConfigError,
16
+ config_key_spec,
17
+ config_option_value,
18
+ find_config,
19
+ format_config_value,
20
+ load_config,
21
+ render_template,
22
+ set_config_text,
23
+ )
24
+ from .formatter import FormatError, FormatResult, format_range, format_source
25
+ from .i18n import TEXTS, detect_language
26
+ from .i18n import text as tr
27
+ from .identity import CONFIG_NAME, TOOL_NAME
28
+ from .options import CATEGORIES, Options
29
+ from .ui import Console, RawDescriptionRichHelpFormatter, Syntax
30
+
31
+
32
+ def _parse_line_range(text: str, lang: str = "en") -> tuple[int | None, int | None]:
33
+ if ":" not in text:
34
+ raise argparse.ArgumentTypeError(tr(lang, "err_range_format"))
35
+ left, right = text.split(":", 1)
36
+ try:
37
+ start = int(left) if left else None
38
+ end = int(right) if right else None
39
+ except ValueError as exc:
40
+ raise argparse.ArgumentTypeError(tr(lang, "err_range_integer")) from exc
41
+ if start is not None and start < 1:
42
+ raise argparse.ArgumentTypeError(tr(lang, "err_range_one_based"))
43
+ if end is not None and end < 1:
44
+ raise argparse.ArgumentTypeError(tr(lang, "err_range_one_based"))
45
+ if start is not None and end is not None and end < start:
46
+ raise argparse.ArgumentTypeError(tr(lang, "err_range_order"))
47
+ return start, end
48
+
49
+
50
+ def _parse_categories(text: str, lang: str = "en") -> set[str]:
51
+ names = {part.strip() for part in text.split(",") if part.strip()}
52
+ unknown = names - set(CATEGORIES)
53
+ if unknown:
54
+ joined = ", ".join(sorted(unknown))
55
+ raise argparse.ArgumentTypeError(tr(lang, "err_category_unknown").format(names=joined))
56
+ return names
57
+
58
+
59
+ def _parse_width(text: str, lang: str = "en") -> int:
60
+ try:
61
+ value = int(text)
62
+ except ValueError as exc:
63
+ raise argparse.ArgumentTypeError(tr(lang, "err_width_integer")) from exc
64
+ if value < 20:
65
+ raise argparse.ArgumentTypeError(tr(lang, "err_width_minimum"))
66
+ return value
67
+
68
+
69
+ def build_parser(lang: str | None = None) -> argparse.ArgumentParser:
70
+ lang = lang or detect_language()
71
+ strings = {key: tr(lang, key) for key in TEXTS[lang]}
72
+
73
+ class LocalizedFormatter(RawDescriptionRichHelpFormatter):
74
+ def add_usage(self, usage, actions, groups, prefix=None): # type: ignore[no-untyped-def]
75
+ super().add_usage(
76
+ usage,
77
+ actions,
78
+ groups,
79
+ prefix=strings["usage"] if prefix is None else prefix,
80
+ )
81
+
82
+ formatter_cls: Any = LocalizedFormatter
83
+
84
+ class LocalizedParser(argparse.ArgumentParser):
85
+ def error(self, message: str) -> NoReturn:
86
+ self.print_usage(sys.stderr)
87
+ self.exit(2, f"{self.prog}: {strings['error_label']}: {message}\n")
88
+
89
+ def parse_line_range(value: str) -> tuple[int | None, int | None]:
90
+ return _parse_line_range(value, lang)
91
+
92
+ def parse_categories(value: str) -> set[str]:
93
+ return _parse_categories(value, lang)
94
+
95
+ def parse_width(value: str) -> int:
96
+ return _parse_width(value, lang)
97
+
98
+ def add_help_option(target: argparse.ArgumentParser) -> None:
99
+ target.add_argument("-h", "--help", action="help", help=strings["help"])
100
+
101
+ def add_language_options(
102
+ target: argparse.ArgumentParser, *, suppress_default: bool = False
103
+ ) -> None:
104
+ default = argparse.SUPPRESS if suppress_default else False
105
+ language = target.add_mutually_exclusive_group()
106
+ language.add_argument(
107
+ "--zh", action="store_true", default=default, help=strings["force_zh"]
108
+ )
109
+ language.add_argument(
110
+ "--en", action="store_true", default=default, help=strings["force_en"]
111
+ )
112
+
113
+ def set_titles(target: argparse.ArgumentParser, positional: str) -> None:
114
+ target._positionals.title = positional
115
+ target._optionals.title = strings["options"]
116
+
117
+ common = LocalizedParser(add_help=False)
118
+ common.add_argument("paths", nargs="*", metavar="PATH", help=strings["paths"])
119
+ common.add_argument(
120
+ "--lines",
121
+ action="append",
122
+ type=parse_line_range,
123
+ metavar="A:B",
124
+ help=strings["lines"],
125
+ )
126
+ common.add_argument(
127
+ "--line-width",
128
+ type=parse_width,
129
+ dest="line_width",
130
+ metavar="N",
131
+ help=strings["line_width"],
132
+ )
133
+ common.add_argument("--base-indent", type=int, metavar="N", help=strings["base_indent"])
134
+ common.add_argument("--stdin-path", metavar="PATH", help=strings["stdin_path"])
135
+ common.add_argument("--only", type=parse_categories, metavar="CATS", help=strings["only"])
136
+ common.add_argument("--skip", type=parse_categories, metavar="CATS", help=strings["skip"])
137
+ common.add_argument("--config", type=Path, metavar="PATH", help=strings["config"])
138
+ common.add_argument("--strict", action="store_true", help=strings["strict"])
139
+ common.add_argument("--best-effort", action="store_true", help=strings["best_effort"])
140
+ common.add_argument("-q", "--quiet", action="store_true", help=strings["quiet"])
141
+ common.add_argument("-v", "--verbose", action="store_true", help=strings["verbose"])
142
+
143
+ parser = LocalizedParser(
144
+ prog=TOOL_NAME,
145
+ description=strings["description"],
146
+ formatter_class=formatter_cls,
147
+ add_help=False,
148
+ )
149
+ parser.add_argument(
150
+ "--version",
151
+ action="version",
152
+ version=f"{TOOL_NAME} {__version__}",
153
+ help=strings["version"],
154
+ )
155
+ add_help_option(parser)
156
+ add_language_options(parser)
157
+ set_titles(parser, strings["commands"])
158
+
159
+ subparsers = parser.add_subparsers(
160
+ dest="command",
161
+ required=True,
162
+ title=strings["commands"],
163
+ )
164
+
165
+ format_parser = subparsers.add_parser(
166
+ "format",
167
+ parents=[common],
168
+ add_help=False,
169
+ help=strings["command_format"],
170
+ description=strings["format_description"],
171
+ formatter_class=formatter_cls,
172
+ )
173
+ set_titles(format_parser, strings["positional"])
174
+ format_parser.add_argument("-w", "--write", action="store_true", help=strings["write"])
175
+ add_language_options(format_parser, suppress_default=True)
176
+ add_help_option(format_parser)
177
+
178
+ for name, command_help, description in (
179
+ ("check", strings["command_check"], strings["check_description"]),
180
+ ("diff", strings["command_diff"], strings["diff_description"]),
181
+ ):
182
+ sub = subparsers.add_parser(
183
+ name,
184
+ parents=[common],
185
+ add_help=False,
186
+ help=command_help,
187
+ description=description,
188
+ formatter_class=formatter_cls,
189
+ )
190
+ set_titles(sub, strings["positional"])
191
+ add_language_options(sub, suppress_default=True)
192
+ add_help_option(sub)
193
+
194
+ config_parser = subparsers.add_parser(
195
+ "config",
196
+ add_help=False,
197
+ help=strings["command_config"],
198
+ description=strings["config_description"],
199
+ formatter_class=formatter_cls,
200
+ )
201
+ set_titles(config_parser, strings["commands"])
202
+ add_language_options(config_parser, suppress_default=True)
203
+ add_help_option(config_parser)
204
+ config_sub = config_parser.add_subparsers(
205
+ dest="config_command",
206
+ required=True,
207
+ title=strings["commands"],
208
+ )
209
+
210
+ def add_config_leaf(
211
+ name: str,
212
+ help_text: str,
213
+ description: str,
214
+ *,
215
+ with_config: bool = True,
216
+ ) -> argparse.ArgumentParser:
217
+ leaf = config_sub.add_parser(
218
+ name,
219
+ add_help=False,
220
+ help=help_text,
221
+ description=description,
222
+ formatter_class=formatter_cls,
223
+ )
224
+ set_titles(leaf, strings["positional"])
225
+ if with_config:
226
+ leaf.add_argument(
227
+ "--config",
228
+ type=Path,
229
+ metavar="PATH",
230
+ default=argparse.SUPPRESS,
231
+ help=strings["config_file"],
232
+ )
233
+ add_language_options(leaf, suppress_default=True)
234
+ add_help_option(leaf)
235
+ return leaf
236
+
237
+ add_config_leaf(
238
+ "template",
239
+ strings["config_template"],
240
+ strings["config_template"],
241
+ with_config=False,
242
+ )
243
+ get_parser = add_config_leaf("get", strings["config_get"], strings["config_get"])
244
+ get_parser.add_argument("key", metavar="KEY", help=strings["config_key"])
245
+ set_parser = add_config_leaf("set", strings["config_set"], strings["config_set"])
246
+ set_parser.add_argument("key", metavar="KEY", help=strings["config_key"])
247
+ set_parser.add_argument("value", metavar="VALUE", help=strings["config_value"])
248
+ add_config_leaf("trace", strings["config_trace"], strings["config_trace"])
249
+
250
+ return parser
251
+
252
+
253
+ def _apply_cli_options(args: argparse.Namespace, options: Options) -> Options:
254
+ cats = set(options.categories)
255
+ if args.only is not None:
256
+ cats = set(args.only)
257
+ if "wrapping" in cats:
258
+ cats.update({"indent", "spacing", "comments"})
259
+ if "comments" in cats:
260
+ cats.add("indent")
261
+ if args.skip is not None:
262
+ cats -= set(args.skip)
263
+ unknown = options.unknown
264
+ if args.strict:
265
+ unknown = "error"
266
+ elif args.best_effort:
267
+ unknown = "conservative"
268
+ return Options(
269
+ width=args.line_width if args.line_width is not None else options.width,
270
+ indent=options.indent,
271
+ base_indent=args.base_indent if args.base_indent is not None else options.base_indent,
272
+ categories=frozenset(cats),
273
+ unknown=unknown,
274
+ in_scheme=options.in_scheme,
275
+ case_mode=options.case_mode,
276
+ hanging=options.hanging,
277
+ config_path=options.config_path,
278
+ warnings=list(options.warnings),
279
+ )
280
+
281
+
282
+ def _auto_base_indent(text: str) -> int:
283
+ widths = []
284
+ for line in text.splitlines():
285
+ if not line.strip():
286
+ continue
287
+ widths.append(len(line) - len(line.lstrip(" ")))
288
+ return min(widths) if widths else 0
289
+
290
+
291
+ def _format_text(text: str, args: argparse.Namespace, options: Options) -> FormatResult:
292
+ opts = _apply_cli_options(args, options)
293
+ if args.lines:
294
+ return format_range(text, args.lines, opts)
295
+ if opts.base_indent is None and not args.paths:
296
+ opts = Options(
297
+ width=opts.width,
298
+ indent=opts.indent,
299
+ base_indent=_auto_base_indent(text),
300
+ categories=opts.categories,
301
+ unknown=opts.unknown,
302
+ in_scheme=opts.in_scheme,
303
+ case_mode=opts.case_mode,
304
+ hanging=opts.hanging,
305
+ config_path=opts.config_path,
306
+ warnings=list(opts.warnings),
307
+ )
308
+ return format_source(text, opts)
309
+
310
+
311
+ def _write_atomic(path: Path, text: str) -> None:
312
+ directory = path.parent
313
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{TOOL_NAME}-", dir=directory)
314
+ try:
315
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
316
+ handle.write(text)
317
+ os.replace(tmp_name, path)
318
+ except BaseException:
319
+ try:
320
+ os.unlink(tmp_name)
321
+ except OSError:
322
+ pass
323
+ raise
324
+
325
+
326
+ def _expand_inputs(raw_paths: list[str], lang: str) -> tuple[list[Path], bool]:
327
+ paths: list[Path] = []
328
+ failed = False
329
+ for raw in raw_paths:
330
+ path = Path(raw)
331
+ if not path.is_dir():
332
+ paths.append(path)
333
+ continue
334
+ found = sorted(
335
+ {*path.rglob("*.il"), *path.rglob("*.ils")},
336
+ key=lambda item: str(item),
337
+ )
338
+ if not found:
339
+ print(f"{path}: {tr(lang, 'no_skill_files')}", file=sys.stderr)
340
+ failed = True
341
+ paths.extend(found)
342
+ return paths, failed
343
+
344
+
345
+ def _print_warnings(path: str, warnings: list[str], quiet: bool, lang: str) -> None:
346
+ if quiet:
347
+ return
348
+ label = tr(lang, "warning_label")
349
+ for warning in warnings:
350
+ print(f"{path}: {label}: {warning}", file=sys.stderr)
351
+
352
+
353
+ def _print_verbose(args: argparse.Namespace, path: str, changed: bool, lang: str) -> None:
354
+ if not args.verbose:
355
+ return
356
+ key = "verbose_changed" if changed else "verbose_unchanged"
357
+ print(tr(lang, key).format(path=path), file=sys.stderr)
358
+
359
+
360
+ def _reconfigure_stdio() -> None:
361
+ for stream in (sys.stdout, sys.stderr):
362
+ reconfigure = getattr(stream, "reconfigure", None)
363
+ if callable(reconfigure):
364
+ cast(Any, stream).reconfigure(encoding="utf-8", errors="replace", newline="\n")
365
+
366
+
367
+ def _read_stdin() -> bytes:
368
+ """Read stdin until EOF; POSIX ttys send EOF with Ctrl+D."""
369
+ try:
370
+ return sys.stdin.buffer.read()
371
+ except (OSError, ValueError):
372
+ return b""
373
+
374
+
375
+ def _diff(path: str, before: str, after: str) -> str:
376
+ return "".join(
377
+ difflib.unified_diff(
378
+ before.splitlines(keepends=True),
379
+ after.splitlines(keepends=True),
380
+ fromfile=path,
381
+ tofile=path + " (formatted)",
382
+ )
383
+ )
384
+
385
+
386
+ def _active_config_path(raw: Path | None, cwd: Path, create: bool) -> Path | None:
387
+ if raw is not None:
388
+ if not create and not raw.is_file():
389
+ raise ConfigError(f"cannot read {raw}")
390
+ return raw
391
+ found = find_config(cwd)
392
+ if found is not None:
393
+ return found
394
+ return cwd / CONFIG_NAME if create else None
395
+
396
+
397
+ def _print_config_template(lang: str) -> None:
398
+ template = render_template(lang).rstrip("\n")
399
+ if Console is None or Syntax is None:
400
+ print(template, end="")
401
+ return
402
+ console = Console(soft_wrap=True)
403
+ console.print(
404
+ Syntax(
405
+ template,
406
+ "toml",
407
+ theme="ansi_dark",
408
+ line_numbers=False,
409
+ word_wrap=False,
410
+ background_color=None,
411
+ ),
412
+ end="",
413
+ )
414
+
415
+
416
+ def _run_config(args: argparse.Namespace, lang: str) -> int:
417
+ command = args.config_command
418
+ if command == "template":
419
+ _print_config_template(lang)
420
+ return 0
421
+ cwd = Path.cwd()
422
+ raw_config = getattr(args, "config", None)
423
+ try:
424
+ if command == "get":
425
+ spec = config_key_spec(args.key)
426
+ path = _active_config_path(raw_config, cwd, create=False)
427
+ options = load_config(path, cwd)
428
+ print(format_config_value(config_option_value(options, args.key), spec))
429
+ return 0
430
+ if command == "trace":
431
+ path = _active_config_path(raw_config, cwd, create=False)
432
+ if path is not None:
433
+ print(path.resolve())
434
+ return 0
435
+ if command == "set":
436
+ path = _active_config_path(raw_config, cwd, create=True)
437
+ if path is None:
438
+ raise ConfigError("cannot determine configuration file")
439
+ old = path.read_text(encoding="utf-8") if path.is_file() else ""
440
+ _write_atomic(path, set_config_text(old, args.key, args.value))
441
+ print(tr(lang, "config_updated").format(path=path.resolve()))
442
+ return 0
443
+ except (ConfigError, OSError) as exc:
444
+ print(f"{TOOL_NAME}: {exc}", file=sys.stderr)
445
+ return 2
446
+ return 2
447
+
448
+
449
+ def _prescan_language(argv: list[str]) -> str | None:
450
+ for arg in argv:
451
+ if arg == "--":
452
+ break
453
+ if arg == "--zh":
454
+ return "zh"
455
+ if arg == "--en":
456
+ return "en"
457
+ return None
458
+
459
+
460
+ def _main(arguments: list[str]) -> int:
461
+ parser = build_parser(_prescan_language(arguments))
462
+ args = parser.parse_args(arguments)
463
+ lang = "zh" if args.zh else "en" if args.en else detect_language()
464
+ if args.zh and args.en:
465
+ parser.error(tr(lang, "err_language_flags"))
466
+ if args.command == "config":
467
+ return _run_config(args, lang)
468
+
469
+ write = getattr(args, "write", False)
470
+ if args.only is not None and args.skip is not None:
471
+ parser.error(tr(lang, "err_only_skip"))
472
+ if args.strict and args.best_effort:
473
+ parser.error(tr(lang, "err_strict_best_effort"))
474
+ if args.quiet and args.verbose:
475
+ parser.error(tr(lang, "err_quiet_verbose"))
476
+
477
+ stdin_mode = not args.paths or args.paths == ["-"]
478
+ if "-" in args.paths and len(args.paths) > 1:
479
+ parser.error(tr(lang, "err_dash_mixed"))
480
+ if args.stdin_path and not stdin_mode:
481
+ parser.error(tr(lang, "err_stdin_path"))
482
+ if write and stdin_mode:
483
+ parser.error(tr(lang, "err_write_stdin"))
484
+ if args.lines and len(args.paths) > 1:
485
+ parser.error(tr(lang, "err_lines_one_file"))
486
+ if args.lines and any(Path(raw).is_dir() for raw in args.paths):
487
+ parser.error(tr(lang, "err_lines_one_file"))
488
+
489
+ scan_failed = False
490
+ paths: list[Path] = []
491
+ if not stdin_mode:
492
+ paths, scan_failed = _expand_inputs(args.paths, lang)
493
+ if not paths and scan_failed:
494
+ return 2
495
+ if args.lines and len(paths) != 1:
496
+ parser.error(tr(lang, "err_lines_one_file"))
497
+ if args.command == "format" and not write and len(paths) != 1:
498
+ parser.error(tr(lang, "err_multiple_need_action"))
499
+
500
+ start = Path(args.stdin_path).parent if args.stdin_path else Path.cwd()
501
+ try:
502
+ options = load_config(args.config, start)
503
+ except ConfigError as exc:
504
+ print(f"{TOOL_NAME}: {exc}", file=sys.stderr)
505
+ return 2
506
+ if args.verbose:
507
+ if options.config_path:
508
+ print(tr(lang, "verbose_config").format(path=options.config_path), file=sys.stderr)
509
+ else:
510
+ print(tr(lang, "verbose_no_config"), file=sys.stderr)
511
+
512
+ if stdin_mode:
513
+ raw = _read_stdin()
514
+ try:
515
+ text = raw.decode("utf-8-sig")
516
+ except UnicodeDecodeError as exc:
517
+ print(f"stdin: {exc}", file=sys.stderr)
518
+ if args.command == "format":
519
+ sys.stdout.buffer.write(raw)
520
+ return 2
521
+ try:
522
+ result = _format_text(text, args, options)
523
+ except FormatError as exc:
524
+ print(f"stdin: {exc}", file=sys.stderr)
525
+ if args.command == "format":
526
+ sys.stdout.buffer.write(raw)
527
+ return 2
528
+ _print_warnings("stdin", result.warnings, args.quiet, lang)
529
+ if args.command == "diff":
530
+ diff = _diff("stdin", text, result.text)
531
+ _print_verbose(args, "stdin", result.text != text, lang)
532
+ if diff:
533
+ sys.stdout.write(diff)
534
+ return 1
535
+ return 0
536
+ if args.command == "check":
537
+ _print_verbose(args, "stdin", result.text != text, lang)
538
+ if result.text != text:
539
+ print("stdin: " + tr(lang, "would_reformat"))
540
+ return 1
541
+ return 0
542
+ sys.stdout.write(result.text)
543
+ _print_verbose(args, "stdin", result.text != text, lang)
544
+ return 0
545
+
546
+ failures = 1 if scan_failed else 0
547
+ changed = 0
548
+ for path in paths:
549
+ try:
550
+ raw = path.read_bytes()
551
+ text = raw.decode("utf-8-sig")
552
+ except (OSError, UnicodeDecodeError) as exc:
553
+ print(f"{path}: {exc}", file=sys.stderr)
554
+ failures = 1
555
+ continue
556
+ try:
557
+ result = _format_text(text, args, options)
558
+ except FormatError as exc:
559
+ print(f"{path}: {exc}", file=sys.stderr)
560
+ failures = 1
561
+ continue
562
+ _print_warnings(str(path), result.warnings, args.quiet, lang)
563
+ changed_now = result.text != text
564
+ if args.command == "format" and not write:
565
+ sys.stdout.write(result.text)
566
+ _print_verbose(args, str(path), changed_now, lang)
567
+ continue
568
+ if not changed_now:
569
+ _print_verbose(args, str(path), False, lang)
570
+ continue
571
+ changed += 1
572
+ if args.command == "format" and write:
573
+ try:
574
+ _write_atomic(path, result.text)
575
+ except OSError as exc:
576
+ print(f"{path}: {exc}", file=sys.stderr)
577
+ failures = 1
578
+ continue
579
+ elif args.command == "diff":
580
+ sys.stdout.write(_diff(str(path), text, result.text))
581
+ elif args.command == "check":
582
+ print(f"{path}: {tr(lang, 'would_reformat')}")
583
+ _print_verbose(args, str(path), True, lang)
584
+
585
+ if failures:
586
+ return 2
587
+ if args.command in {"check", "diff"} and changed:
588
+ return 1
589
+ return 0
590
+
591
+
592
+ def main(argv: list[str] | None = None) -> int:
593
+ _reconfigure_stdio()
594
+ arguments = list(sys.argv[1:] if argv is None else argv)
595
+ try:
596
+ return _main(arguments)
597
+ except KeyboardInterrupt:
598
+ lang = _prescan_language(arguments) or detect_language()
599
+ print(f"{TOOL_NAME}: {tr(lang, 'interrupted')}", file=sys.stderr)
600
+ return 130
601
+
602
+
603
+ if __name__ == "__main__":
604
+ raise SystemExit(main())