ejaan 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.
ejaan/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Pemeriksa ejaan bahasa Indonesia."""
2
+
3
+ from .rules import Finding, check_text
4
+
5
+ __all__ = ["Finding", "check_text"]
ejaan/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import run
2
+
3
+ raise SystemExit(run())
ejaan/cli.py ADDED
@@ -0,0 +1,260 @@
1
+ import argparse
2
+ import codecs
3
+ import difflib
4
+ import os
5
+ import re
6
+ import stat
7
+ import sys
8
+ from importlib.metadata import version
9
+ from pathlib import Path
10
+ from typing import NoReturn
11
+
12
+ from .config import Config, ConfigError, load_config, validate_rules
13
+ from .fix import apply_fixes, file_fingerprint, write_atomic
14
+ from .report import FileReport, render, terminal_text
15
+ from .rules import RULES, DirectiveError, Finding, Severity, check_text
16
+
17
+ _MARKDOWN = {".md", ".markdown", ".mdown"}
18
+ _DOCUMENTS = _MARKDOWN | {".txt"}
19
+ _SKIP_DIRECTORIES = set(
20
+ ".git .hg .svn node_modules .venv venv .tox .nox __pycache__ .mypy_cache "
21
+ ".ruff_cache .pytest_cache .next dist build target vendor custom_components".split()
22
+ )
23
+ _MAX_BYTES = 1024 * 1024
24
+ _LINE_BREAK = re.compile(r"\r\n|\r|\n")
25
+ _READ_FLAGS = (
26
+ os.O_RDONLY
27
+ | getattr(os, "O_BINARY", 0)
28
+ | getattr(os, "O_NOFOLLOW", 0)
29
+ | getattr(os, "O_NONBLOCK", 0)
30
+ )
31
+
32
+
33
+ class _Parser(argparse.ArgumentParser):
34
+ def error(self, message: str) -> NoReturn:
35
+ raise ConfigError(message)
36
+
37
+
38
+ def _parser() -> argparse.ArgumentParser:
39
+ parser = _Parser(prog="ejaan", description="Periksa ejaan bahasa Indonesia secara offline.")
40
+ parser.add_argument("paths", nargs="*", metavar="PATH", help="berkas atau direktori")
41
+ edit = parser.add_mutually_exclusive_group()
42
+ edit.add_argument("--fix", action="store_true", help="tulis perbaikan otomatis")
43
+ edit.add_argument("--diff", action="store_true", help="tampilkan diff tanpa menulis")
44
+ parser.add_argument("--format", choices=("text", "json", "github"), default="text")
45
+ parser.add_argument("--select", metavar="RULES", help="periksa daftar aturan ini saja")
46
+ parser.add_argument("--ignore", metavar="RULES", help="abaikan daftar aturan ini")
47
+ config = parser.add_mutually_exclusive_group()
48
+ config.add_argument("--config", type=Path, metavar="PATH", help="pilih berkas konfigurasi")
49
+ config.add_argument("--no-config", action="store_true", help="abaikan konfigurasi")
50
+ info = parser.add_mutually_exclusive_group()
51
+ info.add_argument("--list-rules", action="store_true", help="tampilkan daftar aturan")
52
+ info.add_argument("--explain", metavar="RULE", help="jelaskan satu aturan")
53
+ parser.add_argument(
54
+ "-v", "--verbose", action="store_true", help="laporkan berkas yang dilewati"
55
+ )
56
+ parser.add_argument("--version", action="version", version=f"%(prog)s {version('ejaan')}")
57
+ return parser
58
+
59
+
60
+ def _selection(args: argparse.Namespace, config: Config) -> dict[str, Severity]:
61
+ select = [name.strip() for name in args.select.split(",")] if args.select is not None else None
62
+ ignore = [name.strip() for name in args.ignore.split(",")] if args.ignore is not None else []
63
+ validate_rules([*(select or []), *ignore])
64
+ return {
65
+ name: (
66
+ "off"
67
+ if name in ignore or (select is not None and name not in select)
68
+ else config.rules.get(name, rule.default)
69
+ )
70
+ for name, rule in RULES.items()
71
+ }
72
+
73
+
74
+ def _error(message: str) -> None:
75
+ print(f"ejaan: {terminal_text(message)}", file=sys.stderr)
76
+
77
+
78
+ def _display(path: Path, cwd: Path) -> str:
79
+ return path.relative_to(cwd).as_posix() if path.is_relative_to(cwd) else path.as_posix()
80
+
81
+
82
+ def _paths(
83
+ args: argparse.Namespace, config: Config, cwd: Path
84
+ ) -> tuple[list[tuple[Path, Path]], list[str]]:
85
+ chosen: dict[Path, Path] = {}
86
+ errors = []
87
+ roots = (
88
+ [Path(path) for path in args.paths]
89
+ or [config.root / path for path in config.include]
90
+ or [cwd]
91
+ )
92
+
93
+ def onerror(error: OSError | RuntimeError) -> None:
94
+ errors.append(str(error))
95
+
96
+ def skip(path: Path, why: str) -> None:
97
+ if args.verbose:
98
+ _error(f"lewati {_display(path, cwd)}: {why}")
99
+
100
+ for root in roots:
101
+ path = Path(os.path.abspath(root))
102
+ if config.excluded(path):
103
+ skip(path, "exclude")
104
+ continue
105
+ try:
106
+ real = path.resolve(strict=True)
107
+ mode = real.stat().st_mode
108
+ except (OSError, RuntimeError) as error:
109
+ onerror(error)
110
+ continue
111
+ if config.excluded(real):
112
+ skip(path, "target termasuk exclude")
113
+ continue
114
+ if stat.S_ISREG(mode):
115
+ chosen.setdefault(real, path)
116
+ continue
117
+ if not stat.S_ISDIR(mode):
118
+ errors.append(f"{path}: bukan berkas biasa atau direktori")
119
+ continue
120
+ if path.is_symlink():
121
+ skip(path, "symlink direktori")
122
+ continue
123
+ for directory, dirs, files in os.walk(real, onerror=onerror):
124
+ base = Path(directory)
125
+ for name in sorted(dirs):
126
+ subdir = base / name
127
+ if name in _SKIP_DIRECTORIES or config.excluded(subdir) or subdir.is_symlink():
128
+ skip(subdir, "direktori dikecualikan atau symlink")
129
+ dirs.remove(name)
130
+ dirs.sort()
131
+ for name in sorted(files):
132
+ item = base / name
133
+ if item.suffix.lower() not in _DOCUMENTS:
134
+ continue
135
+ if config.excluded(item) or item.is_symlink():
136
+ skip(item, "berkas dikecualikan atau symlink")
137
+ continue
138
+ chosen.setdefault(item, item)
139
+ return sorted(chosen.items(), key=lambda item: item[1].as_posix()), errors
140
+
141
+
142
+ def _read(path: Path) -> tuple[bytes, os.stat_result]:
143
+ info = path.lstat()
144
+ if not stat.S_ISREG(info.st_mode):
145
+ raise OSError("bukan berkas biasa")
146
+ if info.st_size > _MAX_BYTES:
147
+ return b"", info
148
+ with os.fdopen(os.open(path, _READ_FLAGS), "rb") as stream:
149
+ opened = os.fstat(stream.fileno())
150
+ # Windows can report different ctime values for a path and its open descriptor.
151
+ if (
152
+ not stat.S_ISREG(opened.st_mode)
153
+ or not os.path.samestat(info, opened)
154
+ or file_fingerprint(path.lstat()) != file_fingerprint(info)
155
+ ):
156
+ raise OSError("berkas berubah sebelum dibaca")
157
+ content = stream.read(_MAX_BYTES + 1)
158
+ if file_fingerprint(os.fstat(stream.fileno())) != file_fingerprint(opened):
159
+ raise OSError("berkas berubah selama dibaca")
160
+ return content, info
161
+
162
+
163
+ def _unified_diff(path: str, before: str, after: str) -> str:
164
+ def lines(text: str) -> list[str]:
165
+ normalized = _LINE_BREAK.sub("\n", text)
166
+ parts = normalized.split("\n")
167
+ return [part + "\n" for part in parts[:-1]] + ([parts[-1]] if parts[-1] else [])
168
+
169
+ display = terminal_text(path)
170
+ delta = difflib.unified_diff(lines(before), lines(after), f"a/{display}", f"b/{display}")
171
+ return "".join(
172
+ "\t".join(map(terminal_text, line.removesuffix("\n").split("\t")))
173
+ + "\n"
174
+ + ("" if line.endswith("\n") else "\\n")
175
+ for line in delta
176
+ )
177
+
178
+
179
+ def main(argv: list[str] | None = None) -> int:
180
+ try:
181
+ args = _parser().parse_intermixed_args(argv)
182
+ if args.list_rules:
183
+ for name, rule in RULES.items():
184
+ fixable = "tersedia" if rule.fixable else "tidak tersedia"
185
+ print(f"{name:20} {rule.default:5} auto-fix {fixable}")
186
+ return 0
187
+ if args.explain is not None:
188
+ validate_rules([args.explain])
189
+ rule = RULES[args.explain]
190
+ print(f"{args.explain}: {rule.description}\n{rule.example}\nRujukan: {rule.source}")
191
+ return 0
192
+ if args.diff and args.format != "text":
193
+ raise ConfigError("--diff hanya dapat digabungkan dengan format text")
194
+ cwd = Path.cwd()
195
+ config = load_config(cwd, explicit=args.config, disabled=args.no_config)
196
+ selected = _selection(args, config)
197
+ paths, errors = _paths(args, config, cwd)
198
+ except (OSError, ValueError) as error:
199
+ _error(str(error))
200
+ return 2
201
+
202
+ reports = []
203
+ proposed = False
204
+ for real, logical in paths:
205
+ path = _display(logical, cwd)
206
+ try:
207
+ raw, info = _read(real)
208
+ if max(info.st_size, len(raw)) > _MAX_BYTES or b"\0" in raw[:8192]:
209
+ if args.verbose:
210
+ _error(f"lewati {path}: berkas biner atau lebih besar dari 1 MiB")
211
+ continue
212
+ encoding = "utf-8-sig" if raw.startswith(codecs.BOM_UTF8) else "utf-8"
213
+ text = raw.decode(encoding)
214
+
215
+ def check(source: str) -> list[Finding]:
216
+ return check_text(
217
+ source,
218
+ markdown=logical.suffix.lower() in _MARKDOWN,
219
+ severities=selected,
220
+ ignore_words=config.ignore_words,
221
+ extra_words=config.extra_words,
222
+ )
223
+
224
+ findings = check(text)
225
+ if args.fix or args.diff:
226
+ fixed = apply_fixes(text, findings)
227
+ if fixed != text:
228
+ if args.diff:
229
+ print(_unified_diff(path, text, fixed), end="")
230
+ proposed = True
231
+ else:
232
+ remaining = check(fixed)
233
+ write_atomic(real, fixed.encode(encoding), info)
234
+ text, findings = fixed, remaining
235
+ if any(item.replacement is not None for item in remaining):
236
+ _error(f"{path}: masih ada perbaikan otomatis setelah satu lintasan")
237
+ reports.append(FileReport(path, text, findings))
238
+ except (DirectiveError, OSError, UnicodeError) as error:
239
+ errors.append(f"{path}: {error}")
240
+
241
+ if not reports and not errors:
242
+ errors.append("tidak ada berkas teks yang dapat diperiksa")
243
+ for message in errors:
244
+ _error(message)
245
+ if not args.diff:
246
+ color = sys.stdout.isatty() and "NO_COLOR" not in os.environ
247
+ color = color and (os.name != "nt" or bool(os.environ.get("TERM")))
248
+ if output := render(reports, args.format, color=color):
249
+ print(output)
250
+ if errors:
251
+ return 2
252
+ return int(proposed or any(report.findings for report in reports))
253
+
254
+
255
+ def run() -> int:
256
+ if os.name == "nt":
257
+ for stream in (sys.stdout, sys.stderr):
258
+ if not stream.isatty():
259
+ stream.reconfigure(encoding="utf-8", errors="backslashreplace")
260
+ return main()
ejaan/config.py ADDED
@@ -0,0 +1,138 @@
1
+ import os
2
+ import stat
3
+ import tomllib
4
+ from collections.abc import Iterable
5
+ from dataclasses import dataclass, field
6
+ from difflib import get_close_matches
7
+ from pathlib import Path
8
+ from typing import get_args
9
+
10
+ from .data import WORD_FORM
11
+ from .rules import RULES, Severity
12
+
13
+
14
+ class ConfigError(ValueError):
15
+ pass
16
+
17
+
18
+ def validate_rules(names: Iterable[str]) -> None:
19
+ for name in names:
20
+ if name not in RULES:
21
+ matches = get_close_matches(name, RULES, n=1)
22
+ hint = f"; maksud Anda {matches[0]!r}?" if matches else ""
23
+ raise ConfigError(f"aturan tak dikenal: {name!r}{hint}")
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Config:
28
+ root: Path
29
+ include: tuple[str, ...] = ()
30
+ exclude: tuple[str, ...] = ()
31
+ rules: dict[str, Severity] = field(default_factory=dict)
32
+ ignore_words: frozenset[str] = frozenset()
33
+ extra_words: dict[str, str] = field(default_factory=dict)
34
+
35
+ def excluded(self, path: Path) -> bool:
36
+ try:
37
+ relative = path.relative_to(self.root)
38
+ except ValueError:
39
+ return False
40
+ return any(
41
+ Path(entry) in map(Path, relative.parts)
42
+ if len(Path(entry).parts) == 1
43
+ else relative.is_relative_to(entry)
44
+ for entry in self.exclude
45
+ )
46
+
47
+
48
+ def _table(value: object, label: str, allowed: set[str] | None = None) -> dict:
49
+ if not isinstance(value, dict):
50
+ raise ConfigError(f"{label} harus berupa tabel TOML")
51
+ if allowed is not None and (unknown := value.keys() - allowed):
52
+ raise ConfigError(f"kunci tak dikenal pada {label}: {', '.join(sorted(unknown))}")
53
+ return value
54
+
55
+
56
+ def _strings(value: object, label: str) -> tuple[str, ...]:
57
+ if not isinstance(value, list) or not all(
58
+ isinstance(item, str) and item.strip() and item.isprintable() for item in value
59
+ ):
60
+ raise ConfigError(f"{label} harus berupa daftar teks tak kosong")
61
+ return tuple(value)
62
+
63
+
64
+ def _paths(value: object, label: str) -> tuple[str, ...]:
65
+ entries = _strings(value, label)
66
+ for entry in entries:
67
+ path = Path(entry)
68
+ if path.anchor or ".." in path.parts:
69
+ raise ConfigError(f"{label} hanya menerima path relatif di bawah direktori config")
70
+ if label == "exclude" and not path.parts:
71
+ raise ConfigError("exclude tidak menerima direktori config itu sendiri")
72
+ return tuple(str(Path(entry)) for entry in entries)
73
+
74
+
75
+ def _words(value: str, label: str) -> str:
76
+ if not isinstance(value, str) or not WORD_FORM.fullmatch(value):
77
+ raise ConfigError(
78
+ f"{label} harus berupa kata atau frasa tanpa tanda baca selain tanda hubung"
79
+ )
80
+ return value.lower()
81
+
82
+
83
+ def _read_config(path: Path, *, pyproject: bool) -> Config | None:
84
+ try:
85
+ flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
86
+ with os.fdopen(os.open(path, flags), "rb") as stream:
87
+ if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode):
88
+ raise ConfigError("konfigurasi bukan berkas biasa")
89
+ document = tomllib.load(stream)
90
+ if pyproject:
91
+ table = document.get("tool", {})
92
+ if not isinstance(table, dict) or "ejaan" not in table:
93
+ return None
94
+ document = table["ejaan"]
95
+ data = _table(document, "config ejaan", {"include", "exclude", "rules", "words"})
96
+ rules = _table(data.get("rules", {}), "rules")
97
+ validate_rules(tuple(rules))
98
+ for name, value in rules.items():
99
+ if value not in get_args(Severity):
100
+ raise ConfigError(f"rules.{name} harus bernilai error, warn, atau off")
101
+ words = _table(data.get("words", {}), "words", {"ignore", "extra"})
102
+ ignore = _strings(words.get("ignore", []), "words.ignore")
103
+ extra = {}
104
+ for wrong, right in _table(words.get("extra", {}), "words.extra").items():
105
+ key = _words(wrong, "kunci words.extra")
106
+ if key in extra:
107
+ raise ConfigError(f"kunci words.extra berulang: {key!r}")
108
+ extra[key] = _words(right, f"words.extra.{key}")
109
+ return Config(
110
+ root=path.parent,
111
+ include=_paths(data.get("include", []), "include"),
112
+ exclude=_paths(data.get("exclude", []), "exclude"),
113
+ rules=rules,
114
+ ignore_words=frozenset(_words(word, "words.ignore") for word in ignore),
115
+ extra_words=extra,
116
+ )
117
+ except (OSError, UnicodeError, ValueError) as error:
118
+ raise ConfigError(f"{path}: {error}") from error
119
+
120
+
121
+ def load_config(cwd: Path, *, explicit: Path | None = None, disabled: bool = False) -> Config:
122
+ if disabled:
123
+ return Config(cwd)
124
+ if explicit is not None:
125
+ path = Path(os.path.abspath(explicit))
126
+ config = _read_config(path, pyproject=path.name == "pyproject.toml")
127
+ if config is None:
128
+ raise ConfigError(f"{path}: tabel [tool.ejaan] tidak ditemukan")
129
+ return config
130
+ for directory in (cwd, *cwd.parents):
131
+ for filename in ("ejaan.toml", "pyproject.toml"):
132
+ candidate = directory / filename
133
+ if candidate.exists():
134
+ if config := _read_config(candidate, pyproject=filename == "pyproject.toml"):
135
+ return config
136
+ if (directory / ".git").exists():
137
+ break
138
+ return Config(cwd)
@@ -0,0 +1,77 @@
1
+ salah baku jenis sumber catatan
2
+ akte akta kata KBBI:akte 2026-11-27
3
+ aktifitas aktivitas kata KBBI:aktifitas 2026-11-27
4
+ amandemen amendemen kata KBBI:amandemen 2026-11-27
5
+ analisa analisis kata KBBI:analisa 2026-11-27
6
+ apotik apotek kata KBBI:apotik 2026-11-27
7
+ atlit atlet kata KBBI:atlit 2026-11-27
8
+ azas asas kata KBBI:azas 2026-11-27
9
+ cinderamata cendera mata frasa KBBI:cinderamata 2026-11-27
10
+ defenisi definisi kata KBBI:defenisi 2026-11-27
11
+ detil detail kata KBBI:detil 2026-11-27
12
+ diagnosa diagnosis kata KBBI:diagnosa 2026-11-27
13
+ ekstrim ekstrem kata KBBI:ekstrim 2026-11-27
14
+ fikir pikir kata KBBI:fikir 2026-11-27
15
+ frustasi frustrasi kata KBBI:frustasi 2026-11-27
16
+ hakekat hakikat kata KBBI:hakekat 2026-11-27
17
+ hektar hektare kata KBBI:hektar 2026-11-27
18
+ hipotesa hipotesis kata KBBI:hipotesa 2026-11-27
19
+ hisap isap kata KBBI:hisap 2026-11-27
20
+ idzin izin kata KBBI:idzin 2026-11-27
21
+ ijin izin kata KBBI:ijin 2026-11-27
22
+ insyaf insaf kata KBBI:insyaf 2026-11-27
23
+ interprestasi interpretasi kata KBBI:interprestasi 2026-11-27
24
+ jadual jadwal kata KBBI:jadual 2026-11-27
25
+ kadaluarsa kedaluwarsa kata KBBI:kadaluarsa 2026-11-27
26
+ karir karier kata KBBI:karir 2026-11-27
27
+ katagori kategori kata KBBI:katagori 2026-11-27
28
+ kerjasama kerja sama frasa KBBI:kerjasama 2026-11-27
29
+ komoditi komoditas kata KBBI:komoditi 2026-11-27
30
+ konkrit konkret kata KBBI:konkrit 2026-11-27
31
+ konperensi konferensi kata KBBI:konperensi 2026-11-27
32
+ kreatifitas kreativitas kata KBBI:kreatifitas 2026-11-27
33
+ kwalitas kualitas kata KBBI:kwalitas 2026-11-27
34
+ kwantitas kuantitas kata KBBI:kwantitas 2026-11-27
35
+ kwitansi kuitansi kata KBBI:kwitansi 2026-11-27
36
+ menganalisa menganalisis kata KBBI:menganalisa 2026-11-27
37
+ milyar miliar kata KBBI:milyar 2026-11-27
38
+ moderen modern kata KBBI:moderen 2026-11-27
39
+ musium museum kata KBBI:musium 2026-11-27
40
+ nasehat nasihat kata KBBI:nasehat 2026-11-27
41
+ negri negeri kata KBBI:negri 2026-11-27
42
+ nomer nomor kata KBBI:nomer 2026-11-27
43
+ omset omzet kata KBBI:omset 2026-11-27
44
+ otopsi autopsi kata KBBI:otopsi 2026-11-27
45
+ pondasi fondasi kata KBBI:pondasi 2026-11-27
46
+ praktek praktik kata KBBI:praktek 2026-11-27
47
+ produktifitas produktivitas kata KBBI:produktifitas 2026-11-27
48
+ propinsi provinsi kata KBBI:propinsi 2026-11-27
49
+ rapih rapi kata KBBI:rapih 2026-11-27
50
+ rejeki rezeki kata KBBI:rejeki 2026-11-27
51
+ resiko risiko kata KBBI:resiko 2026-11-27
52
+ saos saus kata KBBI:saos 2026-11-27
53
+ sekedar sekadar kata KBBI:sekedar 2026-11-27
54
+ seksama saksama kata KBBI:seksama 2026-11-27
55
+ selebritis selebritas kata KBBI:selebritis 2026-11-27
56
+ sertipikat sertifikat kata KBBI:sertipikat 2026-11-27
57
+ shalat salat kata KBBI:shalat 2026-11-27
58
+ sholat salat kata KBBI:sholat 2026-11-27
59
+ silahkan silakan kata KBBI:silahkan 2026-11-27
60
+ sintesa sintesis kata KBBI:sintesa 2026-11-27
61
+ standarisasi standardisasi kata KBBI:standarisasi 2026-11-27
62
+ subyek subjek kata KBBI:subyek 2026-11-27
63
+ tahta takhta kata KBBI:tahta 2026-11-27
64
+ tauladan teladan kata KBBI:tauladan 2026-11-27
65
+ tehnik teknik kata KBBI:tehnik 2026-11-27
66
+ tehnologi teknologi kata KBBI:tehnologi 2026-11-27
67
+ tentram tenteram kata KBBI:tentram 2026-11-27
68
+ teoritis teoretis kata KBBI:teoritis 2026-11-27
69
+ terimakasih terima kasih frasa KBBI:terimakasih 2026-11-27
70
+ terlanjur telanjur kata KBBI:terlanjur 2026-11-27
71
+ trampil terampil kata KBBI:trampil 2026-11-27
72
+ tropi trofi kata KBBI:tropi 2026-11-27
73
+ umroh umrah kata KBBI:umroh 2026-11-27
74
+ ustad ustaz kata KBBI:ustad 2026-11-27
75
+ vidio video kata KBBI:vidio 2026-11-27
76
+ walikota wali kota frasa KBBI:walikota 2026-11-27
77
+ zinah zina kata KBBI:zinah 2026-11-27
ejaan/data.py ADDED
@@ -0,0 +1,17 @@
1
+ import csv
2
+ import re
3
+ from functools import cache
4
+ from importlib.resources import files
5
+ from types import MappingProxyType
6
+
7
+ WORD_FORM = re.compile(r"[^\W\d_]+(?:[ -][^\W\d_]+)*")
8
+
9
+
10
+ @cache
11
+ def standard_words() -> MappingProxyType[str, str]:
12
+ with (
13
+ files("ejaan").joinpath("data", "kata-baku.tsv").open(encoding="utf-8", newline="") as file
14
+ ):
15
+ return MappingProxyType(
16
+ {row["salah"]: row["baku"] for row in csv.DictReader(file, delimiter="\t")}
17
+ )
ejaan/fix.py ADDED
@@ -0,0 +1,50 @@
1
+ import os
2
+ import stat
3
+ import tempfile
4
+ from collections.abc import Iterable
5
+ from pathlib import Path
6
+
7
+ from .rules import Finding
8
+
9
+
10
+ def apply_fixes(text: str, findings: Iterable[Finding]) -> str:
11
+ chunks = []
12
+ offset = 0
13
+ for finding in sorted(findings, key=lambda item: (item.start, -item.end, item.rule)):
14
+ if finding.replacement is None or finding.start < offset:
15
+ continue
16
+ chunks.extend((text[offset : finding.start], finding.replacement))
17
+ offset = finding.end
18
+ return "".join([*chunks, text[offset:]])
19
+
20
+
21
+ def file_fingerprint(info: os.stat_result) -> tuple[int, ...]:
22
+ return (
23
+ info.st_dev,
24
+ info.st_ino,
25
+ info.st_mode,
26
+ info.st_nlink,
27
+ info.st_size,
28
+ info.st_mtime_ns,
29
+ info.st_ctime_ns,
30
+ )
31
+
32
+
33
+ def write_atomic(path: Path, content: bytes, original: os.stat_result) -> None:
34
+ if original.st_nlink > 1:
35
+ raise OSError("berkas memiliki hard link")
36
+ mode = stat.S_IMODE(original.st_mode)
37
+ if not mode & (stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH) or not os.access(path, os.W_OK):
38
+ raise PermissionError("berkas hanya dapat dibaca")
39
+
40
+ fd, temporary_name = tempfile.mkstemp(dir=path.parent)
41
+ temporary = Path(temporary_name)
42
+ try:
43
+ with os.fdopen(fd, "wb") as file:
44
+ file.write(content)
45
+ temporary.chmod(mode)
46
+ if file_fingerprint(path.lstat()) != file_fingerprint(original):
47
+ raise OSError("berkas berubah selama diperiksa")
48
+ os.replace(temporary, path)
49
+ finally:
50
+ temporary.unlink(missing_ok=True)