ukr-dev-kit 0.2.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.
- ukr_dev_kit/__init__.py +7 -0
- ukr_dev_kit/cli.py +50 -0
- ukr_dev_kit/skills/ukr-data/SKILL.md +80 -0
- ukr_dev_kit/skills/ukr-data/references/validators.md +179 -0
- ukr_dev_kit/skills/ukr-data/scripts/ukr_data.py +630 -0
- ukr_dev_kit/skills/ukr-i18n/SKILL.md +61 -0
- ukr_dev_kit/skills/ukr-i18n/references/formats.md +75 -0
- ukr_dev_kit/skills/ukr-i18n/references/plurals.md +144 -0
- ukr_dev_kit/skills/ukr-i18n/references/ui-glossary.md +97 -0
- ukr_dev_kit/skills/ukr-i18n/scripts/i18n_check.py +479 -0
- ukr_dev_kit/skills/ukr-proofread/SKILL.md +67 -0
- ukr_dev_kit/skills/ukr-proofread/references/it-glossary.md +101 -0
- ukr_dev_kit/skills/ukr-proofread/references/style-guide.md +64 -0
- ukr_dev_kit/skills/ukr-proofread/references/typography.md +36 -0
- ukr_dev_kit/skills/ukr-proofread/rules/calque.txt +45 -0
- ukr_dev_kit/skills/ukr-proofread/rules/style.txt +13 -0
- ukr_dev_kit/skills/ukr-proofread/rules/surzhyk.txt +75 -0
- ukr_dev_kit/skills/ukr-proofread/rules/term.txt +17 -0
- ukr_dev_kit/skills/ukr-proofread/scripts/ukr_lint.py +826 -0
- ukr_dev_kit/skills/ukr-voice/SKILL.md +120 -0
- ukr_dev_kit/skills/ukr-voice/assets/gemini_voices.json +32 -0
- ukr_dev_kit/skills/ukr-voice/assets/presets.json +52 -0
- ukr_dev_kit/skills/ukr-voice/references/holos.md +46 -0
- ukr_dev_kit/skills/ukr-voice/references/markup.md +48 -0
- ukr_dev_kit/skills/ukr-voice/scripts/gemini_tts.py +157 -0
- ukr_dev_kit/skills/ukr-voice/scripts/holos_engine.py +356 -0
- ukr_dev_kit/skills/ukr-voice/scripts/markup.py +163 -0
- ukr_dev_kit/skills/ukr-voice/scripts/subtitles.py +210 -0
- ukr_dev_kit/skills/ukr-voice/scripts/ukr_voice.py +767 -0
- ukr_dev_kit-0.2.0.dist-info/METADATA +54 -0
- ukr_dev_kit-0.2.0.dist-info/RECORD +34 -0
- ukr_dev_kit-0.2.0.dist-info/WHEEL +4 -0
- ukr_dev_kit-0.2.0.dist-info/entry_points.txt +5 -0
- ukr_dev_kit-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""ukr-lint — вичитка українських текстів: суржик, кальки, типографіка, змішані алфавіти.
|
|
3
|
+
|
|
4
|
+
Лише стандартна бібліотека Python 3.10+. Працює з текстом, Markdown, JSON/ARB, YAML, .po, .properties,
|
|
5
|
+
XML/HTML/Vue і рядками в коді (JS/TS, Python, C#, Java, Kotlin, Swift, Dart, Go, PHP, Ruby).
|
|
6
|
+
|
|
7
|
+
ukr_lint.py README.md docs/ src/locales/uk.json # файли й теки
|
|
8
|
+
ukr_lint.py -t "Прийміть участь у міроприємстві" # текст із командного рядка
|
|
9
|
+
echo "текст" | ukr_lint.py --stdin
|
|
10
|
+
ukr_lint.py --diff origin/main # лише рядки, змінені відносно гілки
|
|
11
|
+
ukr_lint.py --staged # лише те, що додано в індекс git
|
|
12
|
+
ukr_lint.py --fix docs/ # виправити безпечне (типографіка, алфавіти)
|
|
13
|
+
ukr_lint.py --format json|github ... # для інструментів і GitHub Actions
|
|
14
|
+
ukr_lint.py --rules [слово] # список правил; --explain ID — пояснення
|
|
15
|
+
|
|
16
|
+
Рівні: error — явна помилка; warning — найімовірніше помилка, залежить від контексту;
|
|
17
|
+
hint — стилістична порада (показується з --level hint).
|
|
18
|
+
Код виходу: 0 — чисто; 1 — є помилки (з --strict — і попередження); 2 — помилка запуску.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import bisect
|
|
24
|
+
import fnmatch
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import subprocess
|
|
29
|
+
import sys
|
|
30
|
+
from dataclasses import dataclass, field
|
|
31
|
+
from typing import Callable, Iterable, Iterator, Optional
|
|
32
|
+
|
|
33
|
+
__version__ = '0.2.0'
|
|
34
|
+
|
|
35
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
36
|
+
RULES_DIR = os.path.join(os.path.dirname(HERE), 'rules')
|
|
37
|
+
|
|
38
|
+
LEVELS = {'hint': 0, 'warning': 1, 'error': 2}
|
|
39
|
+
LEVEL_UK = {'error': 'помилка', 'warning': 'увага', 'hint': 'порада'}
|
|
40
|
+
CATEGORY_UK = {'surzhyk': 'суржик', 'calque': 'калька', 'style': 'правопис', 'term': 'термін',
|
|
41
|
+
'typography': 'типографіка', 'alphabet': 'алфавіт', 'euphony': 'милозвучність'}
|
|
42
|
+
|
|
43
|
+
CYR = 'А-Яа-яЁёІіЇїЄєҐґ'
|
|
44
|
+
UK_ONLY = 'ІіЇїЄєҐґ'
|
|
45
|
+
RU_ONLY = 'ЫыЭэЪъЁё'
|
|
46
|
+
ARCHAIC = 'ѢѣѤѥѦѧѪѫѴѵѲѳꙖꙗ' # дореформені й давньоруські літери
|
|
47
|
+
APOS = "ʼ’'‘`ʹ′"
|
|
48
|
+
HAS_CYR = re.compile(f'[{CYR}]')
|
|
49
|
+
LB = f"(?<![\\w{APOS}-])"
|
|
50
|
+
RB = f"(?![\\w{APOS}])"
|
|
51
|
+
|
|
52
|
+
SKIP_DIRS = {'.git', 'node_modules', 'dist', 'build', 'out', '.next', '.nuxt', '.output', 'vendor', '.venv',
|
|
53
|
+
'venv', '__pycache__', '.idea', '.vscode', 'coverage', 'target', 'bin', 'obj', '.gradle', 'Pods'}
|
|
54
|
+
TEXT_EXT = {'.md', '.markdown', '.mdx', '.txt', '.rst', '.adoc', '.csv'}
|
|
55
|
+
JSON_EXT = {'.json', '.arb', '.jsonc'}
|
|
56
|
+
YAML_EXT = {'.yml', '.yaml'}
|
|
57
|
+
MARKUP_EXT = {'.html', '.htm', '.vue', '.svelte', '.xml', '.xhtml', '.astro'}
|
|
58
|
+
CODE_EXT = {'.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.py', '.cs', '.java', '.kt', '.kts', '.swift', '.dart',
|
|
59
|
+
'.go', '.php', '.rb', '.rs', '.c', '.cc', '.cpp', '.h', '.hpp', '.m', '.scala', '.strings', '.cshtml',
|
|
60
|
+
'.razor', '.resx'}
|
|
61
|
+
OTHER_EXT = {'.po', '.pot', '.properties', '.ftl'}
|
|
62
|
+
ALL_EXT = TEXT_EXT | JSON_EXT | YAML_EXT | MARKUP_EXT | CODE_EXT | OTHER_EXT
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ════════════════════════════════════ дані ════════════════════════════════════
|
|
66
|
+
@dataclass
|
|
67
|
+
class Issue:
|
|
68
|
+
start: int # позиція в тексті сегмента
|
|
69
|
+
end: int
|
|
70
|
+
level: str
|
|
71
|
+
rule: str # «категорія/ключ»
|
|
72
|
+
message: str
|
|
73
|
+
suggestion: str = ''
|
|
74
|
+
fix: Optional[str] = None # заміна для [start:end], якщо виправлення безпечне
|
|
75
|
+
# заповнюється під час звіту
|
|
76
|
+
path: str = ''
|
|
77
|
+
line: int = 0
|
|
78
|
+
col: int = 0
|
|
79
|
+
excerpt: str = ''
|
|
80
|
+
|
|
81
|
+
def as_dict(self) -> dict:
|
|
82
|
+
return {'path': self.path, 'line': self.line, 'col': self.col, 'level': self.level, 'rule': self.rule,
|
|
83
|
+
'text': self.excerpt, 'message': self.message, 'suggestion': self.suggestion,
|
|
84
|
+
'fixable': self.fix is not None}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class Segment:
|
|
89
|
+
"""Шматок тексту для перевірки. kind='raw' — точний зріз файлу (offset), kind='json' — розкодований рядок
|
|
90
|
+
JSON; виправлення тоді перекодовуються в токен token=(start, end)."""
|
|
91
|
+
text: str
|
|
92
|
+
offset: int
|
|
93
|
+
kind: str = 'raw'
|
|
94
|
+
token: tuple = ()
|
|
95
|
+
code: bool = False # рядок із коду: лапки й апострофи там можуть бути синтаксисом — без автозамін
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass
|
|
99
|
+
class Rule:
|
|
100
|
+
id: str
|
|
101
|
+
level: str
|
|
102
|
+
regex: re.Pattern
|
|
103
|
+
suggestion: str
|
|
104
|
+
explanation: str
|
|
105
|
+
category: str
|
|
106
|
+
pattern: str = ''
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass
|
|
110
|
+
class Config:
|
|
111
|
+
apostrophe: str = 'ʼ'
|
|
112
|
+
disable: list = field(default_factory=list)
|
|
113
|
+
ignore: list = field(default_factory=list)
|
|
114
|
+
allow: list = field(default_factory=list)
|
|
115
|
+
levels: dict = field(default_factory=dict)
|
|
116
|
+
path: str = ''
|
|
117
|
+
|
|
118
|
+
def enabled(self, rule: str) -> bool:
|
|
119
|
+
cat = rule.split('/', 1)[0]
|
|
120
|
+
return not any(d in (rule, cat, rule.split('/', 1)[-1]) for d in self.disable)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def load_config(start: str, explicit: Optional[str] = None) -> Config:
|
|
124
|
+
"""Шукає .ukr-lint.json від теки start угору до кореня git-репозиторію чи файлової системи."""
|
|
125
|
+
path = explicit
|
|
126
|
+
if not path:
|
|
127
|
+
d = os.path.abspath(start)
|
|
128
|
+
while True:
|
|
129
|
+
cand = os.path.join(d, '.ukr-lint.json')
|
|
130
|
+
if os.path.isfile(cand):
|
|
131
|
+
path = cand
|
|
132
|
+
break
|
|
133
|
+
if os.path.isdir(os.path.join(d, '.git')) or os.path.dirname(d) == d:
|
|
134
|
+
break
|
|
135
|
+
d = os.path.dirname(d)
|
|
136
|
+
cfg = Config()
|
|
137
|
+
if path:
|
|
138
|
+
try:
|
|
139
|
+
data = json.load(open(path, encoding='utf-8'))
|
|
140
|
+
except (OSError, ValueError) as e:
|
|
141
|
+
raise SystemExit(f'ukr-lint: не вдалося прочитати {path}: {e}')
|
|
142
|
+
for k in ('apostrophe', 'disable', 'ignore', 'allow', 'levels'):
|
|
143
|
+
if k in data:
|
|
144
|
+
setattr(cfg, k, data[k])
|
|
145
|
+
cfg.path = path
|
|
146
|
+
return cfg
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
# ════════════════════════════════════ правила-словники ════════════════════════════════════
|
|
150
|
+
def load_rules(rules_dir: str = RULES_DIR) -> list:
|
|
151
|
+
"""Читає rules/*.txt. Рядок: «ключ | рівень | шаблон | заміна | пояснення».
|
|
152
|
+
Шаблон — регулярний вираз без урахування регістру; межі слова додаються автоматично,
|
|
153
|
+
пробіл у шаблоні означає «будь-які пробіли». Заміна, що починається з «=», — шаблон re.expand
|
|
154
|
+
(\\1, \\2…): таке правило виправляється автоматично (--fix). Розділювач — « | » з пробілами, тож «|» без пробілів
|
|
155
|
+
лишається альтернативою в регулярному виразі."""
|
|
156
|
+
rules = []
|
|
157
|
+
seen = set()
|
|
158
|
+
for name in sorted(os.listdir(rules_dir)):
|
|
159
|
+
if not name.endswith('.txt'):
|
|
160
|
+
continue
|
|
161
|
+
category = name[:-4]
|
|
162
|
+
for n, line in enumerate(open(os.path.join(rules_dir, name), encoding='utf-8'), 1):
|
|
163
|
+
line = line.strip()
|
|
164
|
+
if not line or line.startswith('#'):
|
|
165
|
+
continue
|
|
166
|
+
parts = [p.strip() for p in line.split(' | ')]
|
|
167
|
+
if len(parts) != 5:
|
|
168
|
+
raise SystemExit(f'{name}:{n}: очікую 5 полів через « | », маю {len(parts)}')
|
|
169
|
+
key, level, pattern, suggestion, explanation = parts
|
|
170
|
+
if level not in LEVELS:
|
|
171
|
+
raise SystemExit(f'{name}:{n}: невідомий рівень «{level}»')
|
|
172
|
+
rid = f'{category}/{key}'
|
|
173
|
+
if rid in seen:
|
|
174
|
+
raise SystemExit(f'{name}:{n}: правило {rid} уже є')
|
|
175
|
+
seen.add(rid)
|
|
176
|
+
body = pattern.replace(' ', r'\s+')
|
|
177
|
+
try:
|
|
178
|
+
rx = re.compile(f'{LB}(?:{body}){RB}', re.I)
|
|
179
|
+
except re.error as e:
|
|
180
|
+
raise SystemExit(f'{name}:{n}: поганий шаблон: {e}')
|
|
181
|
+
rules.append(Rule(rid, level, rx, suggestion, explanation, category, pattern))
|
|
182
|
+
return rules
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# ════════════════════════════════════ вбудовані перевірки ════════════════════════════════════
|
|
186
|
+
L2C = dict(zip('aceiopxyABCEHIKMOPTXïÏ', 'асеіорхуАВСЕНІКМОРТХїЇ'))
|
|
187
|
+
C2L = {v: k for k, v in L2C.items()}
|
|
188
|
+
WORD_MIXED = re.compile(f"[A-Za-zïÏ{CYR}{ARCHAIC}]+")
|
|
189
|
+
LAT = re.compile('[A-Za-zïÏ]')
|
|
190
|
+
CYR_RE = re.compile(f'[{CYR}]')
|
|
191
|
+
|
|
192
|
+
V = 'аеєиіїоуюяАЕЄИІЇОУЮЯ'
|
|
193
|
+
C = 'бвгґджзйклмнпрстфхцчшщьБВГҐДЖЗЙКЛМНПРСТФХЦЧШЩЬ'
|
|
194
|
+
|
|
195
|
+
BUILTIN_DOC = {
|
|
196
|
+
'alphabet/mixed': ('error', 'Слово змішує латиницю й кирилицю (схожі літери: a/а, i/і, o/о, p/р, c/с…). '
|
|
197
|
+
'Такі слова не знаходить пошук, їх не розпізнає перевірка правопису й озвучка.'),
|
|
198
|
+
'alphabet/russian-letter': ('error', 'У слові є літера, якої немає в українській абетці: ы, э, ъ, ё.'),
|
|
199
|
+
'alphabet/russian-text': ('hint', 'Шматок схожий на російський текст (є ы/э/ъ/ё й немає і/ї/є/ґ) — пропущено.'),
|
|
200
|
+
'typography/apostrophe': ('warning', 'Апостроф — один символ на весь проєкт. Рекомендовано ʼ (U+02BC): '
|
|
201
|
+
'це літера, тож слово «пʼять» не розривається в пошуку й виділенні. '
|
|
202
|
+
'Інший вибір задайте в .ukr-lint.json: {"apostrophe": "’"}.'),
|
|
203
|
+
'typography/quotes': ('warning', 'Українські лапки — «ялинки»; внутрішні — „лапки“. Прямі "…" та англійські “…” — ні.'),
|
|
204
|
+
'typography/dash': ('warning', 'Між словами — тире «—» з пробілами, а не дефіс «-».'),
|
|
205
|
+
'typography/en-dash': ('hint', 'Між словами в українському тексті — довге тире «—».'),
|
|
206
|
+
'typography/ellipsis': ('hint', 'Три крапки — один символ «…».'),
|
|
207
|
+
'typography/space-before': ('error', 'Перед комою, знаком оклику чи питання пробілу немає. (Пробіл перед « : » і « ; » '
|
|
208
|
+
'у бібліографічних записях вимагає ДСТУ 8302 — його не чіпаємо.)'),
|
|
209
|
+
'typography/space-after': ('warning', 'Після коми чи крапки з комою потрібен пробіл.'),
|
|
210
|
+
'typography/double-space': ('hint', 'Подвійний пробіл усередині речення.'),
|
|
211
|
+
'typography/repeat': ('warning', 'Слово повторено двічі поспіль — схоже на описку.'),
|
|
212
|
+
'typography/number-format': ('hint', 'В українських текстах тисячі відділяють пробілом (нерозривним), '
|
|
213
|
+
'дробову частину — комою: 1 234 567,89.'),
|
|
214
|
+
'typography/decimal-point': ('hint', 'Десятковий знак в українському тексті — кома: 3,5 млн.'),
|
|
215
|
+
'typography/currency': ('hint', 'Знак гривні ставлять після суми: 100 ₴ (або «100 грн»).'),
|
|
216
|
+
'euphony/v-u': ('hint', 'Чергування у/в: між голосними — «в», між приголосними — «у» (Правопис, § 23).'),
|
|
217
|
+
'euphony/i-j': ('hint', 'Чергування і/й: після голосного перед приголосним — «й», між приголосними — «і».'),
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
REPEAT_OK = {'так', 'ну', 'ось', 'ще', 'дуже', 'ага', 'годі', 'ой', 'ах', 'ох', 'ха', 'хі', 'ну-ну', 'тук', 'та',
|
|
221
|
+
'ля', 'бла', 'кап', 'тік', 'біп'}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _issues_builtin(text: str, cfg: Config, code: bool) -> Iterator[Issue]:
|
|
225
|
+
pref = cfg.apostrophe
|
|
226
|
+
|
|
227
|
+
# ── алфавіти ──
|
|
228
|
+
for m in WORD_MIXED.finditer(text):
|
|
229
|
+
w = m.group()
|
|
230
|
+
lat = len(LAT.findall(w))
|
|
231
|
+
cyr = len(CYR_RE.findall(w))
|
|
232
|
+
if lat and cyr:
|
|
233
|
+
if cyr >= lat and all(ch in L2C for ch in w if LAT.match(ch)):
|
|
234
|
+
fix = ''.join(L2C.get(ch, ch) if LAT.match(ch) else ch for ch in w)
|
|
235
|
+
elif lat > cyr and all(ch in C2L for ch in w if CYR_RE.match(ch)):
|
|
236
|
+
fix = ''.join(C2L.get(ch, ch) if CYR_RE.match(ch) else ch for ch in w)
|
|
237
|
+
else:
|
|
238
|
+
fix = None
|
|
239
|
+
yield Issue(m.start(), m.end(), 'error', 'alphabet/mixed',
|
|
240
|
+
f'«{w}» змішує латиницю й кирилицю', fix or '', fix)
|
|
241
|
+
elif cyr and re.search(f'[{RU_ONLY}]', w) and not re.search(f'[{ARCHAIC}]|[ъЪ]$', w):
|
|
242
|
+
yield Issue(m.start(), m.end(), 'error', 'alphabet/russian-letter',
|
|
243
|
+
f'«{w}»: літера {", ".join(sorted(set(re.findall(f"[{RU_ONLY}]", w))))} — не з української абетки')
|
|
244
|
+
|
|
245
|
+
# ── апостроф ──
|
|
246
|
+
for m in re.finditer(f"(?<=[бпвмфрзкгґхжчшщтдлнсцБПВМФРЗКГҐХЖЧШЩТДЛНСЦ])([{APOS}\"])(?=[яюєїЯЮЄЇ])", text):
|
|
247
|
+
if m.group(1) != pref and not (code and m.group(1) in '"\''):
|
|
248
|
+
yield Issue(m.start(), m.end(), 'warning', 'typography/apostrophe',
|
|
249
|
+
f'апостроф «{m.group(1)}» → «{pref}»', pref, pref)
|
|
250
|
+
|
|
251
|
+
# ── лапки ──
|
|
252
|
+
for m in re.finditer(r'"([^"\n]{1,300}?)"|“([^“”\n]{1,300}?)”', text):
|
|
253
|
+
inner = m.group(1) if m.group(1) is not None else m.group(2)
|
|
254
|
+
if not HAS_CYR.search(inner) or inner.strip() != inner:
|
|
255
|
+
continue
|
|
256
|
+
fix = None if code and m.group(1) is not None else f'«{inner}»'
|
|
257
|
+
yield Issue(m.start(), m.end(), 'warning', 'typography/quotes', 'лапки — «ялинки»', f'«{inner}»', fix)
|
|
258
|
+
|
|
259
|
+
# ── тире ──
|
|
260
|
+
for m in re.finditer(r'(?<=[\w»)”"!?.…])([ \t]+)(-{1,2}|–)([ \t]+)(?=[\w«(„"])', text):
|
|
261
|
+
left, right = text[max(0, m.start() - 20):m.start()], text[m.end():m.end() + 20]
|
|
262
|
+
if not (HAS_CYR.search(left) or HAS_CYR.search(right)):
|
|
263
|
+
continue
|
|
264
|
+
if re.search(r'\d$', left) and re.match(r'\d', right):
|
|
265
|
+
continue # «5 - 3» — це, найпевніше, арифметика
|
|
266
|
+
if m.group(2) == '–':
|
|
267
|
+
yield Issue(m.start(), m.end(), 'hint', 'typography/en-dash', 'між словами — «—»', ' — ', ' — ')
|
|
268
|
+
else:
|
|
269
|
+
yield Issue(m.start(), m.end(), 'warning', 'typography/dash', 'дефіс між словами → тире «—»', ' — ', ' — ')
|
|
270
|
+
|
|
271
|
+
# ── три крапки ──
|
|
272
|
+
for m in re.finditer(r'(?<![./\\])\.\.\.(?![./\w])', text):
|
|
273
|
+
if HAS_CYR.search(text[max(0, m.start() - 30):m.end() + 30]):
|
|
274
|
+
yield Issue(m.start(), m.end(), 'hint', 'typography/ellipsis', '«...» → «…»', '…', '…')
|
|
275
|
+
|
|
276
|
+
# ── пробіли ──
|
|
277
|
+
# лише перед , ! ? — пробіл перед « : » і « ; » вимагає бібліографічний стандарт ДСТУ 8302
|
|
278
|
+
for m in re.finditer(f'(?<=[{CYR}»)])[ \t]+(?=[,!?](?:\\s|$|[»)”"]))', text):
|
|
279
|
+
yield Issue(m.start(), m.end(), 'error', 'typography/space-before', 'зайвий пробіл перед розділовим знаком',
|
|
280
|
+
'', '')
|
|
281
|
+
for m in re.finditer(f'(?<=[{CYR}])([,;])(?=[{CYR}])', text):
|
|
282
|
+
yield Issue(m.start(), m.end(), 'warning', 'typography/space-after', 'після розділового знака потрібен пробіл',
|
|
283
|
+
m.group(1) + ' ', m.group(1) + ' ')
|
|
284
|
+
if not code:
|
|
285
|
+
for m in re.finditer(f'(?<=[{CYR},.;:!?»])[ ]{{2,}}(?=[{CYR}«])', text):
|
|
286
|
+
yield Issue(m.start(), m.end(), 'hint', 'typography/double-space', 'подвійний пробіл', ' ', ' ')
|
|
287
|
+
|
|
288
|
+
# ── повтор слова ──
|
|
289
|
+
for m in re.finditer(f"(?<![\\w{APOS}-])([{CYR}{APOS}]{{2,}})[ \\t]+(\\1)(?![\\w{APOS}-])", text, re.I):
|
|
290
|
+
if m.group(1).lower() in REPEAT_OK:
|
|
291
|
+
continue
|
|
292
|
+
yield Issue(m.start(), m.end(), 'warning', 'typography/repeat', f'«{m.group(1)}» двічі поспіль',
|
|
293
|
+
m.group(1), m.group(1))
|
|
294
|
+
|
|
295
|
+
# ── числа й гроші ──
|
|
296
|
+
if HAS_CYR.search(text):
|
|
297
|
+
for m in re.finditer(r'(?<![\d.,])\d{1,3}(?:,\d{3})+(?:\.\d+)?(?![\d.,])', text):
|
|
298
|
+
uk = m.group().replace(',', ' ').replace('.', ',')
|
|
299
|
+
yield Issue(m.start(), m.end(), 'hint', 'typography/number-format', f'«{m.group()}» → «{uk}»', uk)
|
|
300
|
+
for m in re.finditer(r'(?<![\d.,])\d+\.\d+(?=\s*(?:млн|млрд|тис|%|грн|кг|км|см|мм|ГБ|МБ|ТБ|хв|год|с\b|м\b|л\b))',
|
|
301
|
+
text):
|
|
302
|
+
yield Issue(m.start(), m.end(), 'hint', 'typography/decimal-point', f'«{m.group()}» → «{m.group().replace(".", ",")}»',
|
|
303
|
+
m.group().replace('.', ','))
|
|
304
|
+
for m in re.finditer(r'₴\s?\d[\d\s ,.]*', text):
|
|
305
|
+
yield Issue(m.start(), m.end(), 'hint', 'typography/currency', 'знак ₴ — після суми',
|
|
306
|
+
m.group()[1:].strip() + ' ₴')
|
|
307
|
+
|
|
308
|
+
# ── милозвучність ──
|
|
309
|
+
for m in re.finditer(f'(?<=[{V}]) (у) (?=[{V}])', text):
|
|
310
|
+
yield Issue(m.start(1), m.end(1), 'hint', 'euphony/v-u', 'між голосними — «в»', 'в', 'в')
|
|
311
|
+
for m in re.finditer(f'(?<=[{C}]) (в) (?=[{C}])', text):
|
|
312
|
+
yield Issue(m.start(1), m.end(1), 'hint', 'euphony/v-u', 'між приголосними — «у»', 'у', 'у')
|
|
313
|
+
for m in re.finditer(f'(?<=[{V}]) (і) (?=[бвгґджзклмнпрстфхцчшщ])', text):
|
|
314
|
+
yield Issue(m.start(1), m.end(1), 'hint', 'euphony/i-j', 'після голосного перед приголосним — «й»', 'й', 'й')
|
|
315
|
+
for m in re.finditer(f'(?<=[{C}]) (й) (?=[{C}])', text):
|
|
316
|
+
yield Issue(m.start(1), m.end(1), 'hint', 'euphony/i-j', 'між приголосними — «і»', 'і', 'і')
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def is_russian(text: str) -> bool:
|
|
320
|
+
return bool(re.search(f'[{RU_ONLY}]', text)) and not re.search(f'[{UK_ONLY}]', text)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
_SENTENCE = re.compile(r'[^\n.!?]+(?:[.!?]+|$)', re.M)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
_RU_ENDING = re.compile(r'(?<![\w-])[а-яё]{2,}(?:ая|яя|ой|ый|ые|ие|ии|ого|его)(?![\w-])', re.I)
|
|
327
|
+
_RU_AND = re.compile(r'(?<![\w-])и(?![\w-])')
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def looks_russian(s: str) -> bool:
|
|
331
|
+
"""Речення схоже на російське: немає і/ї/є/ґ, і є ы/э/ъ/ё, сполучник «и» або кілька типових
|
|
332
|
+
російських закінчень (-ая, -ой, -ии, -ый…). Текст у [квадратних дужках] не враховується."""
|
|
333
|
+
s = re.sub(r'\[[^\]]*(?:\]|$)', ' ', s)
|
|
334
|
+
if re.search(f'[{UK_ONLY}ʼ’\']', s) or not HAS_CYR.search(s):
|
|
335
|
+
return False
|
|
336
|
+
if re.search(f'[{RU_ONLY}]', s) or _RU_AND.search(s):
|
|
337
|
+
return True
|
|
338
|
+
return len(_RU_ENDING.findall(s)) >= 2
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def foreign_spans(text: str) -> list:
|
|
342
|
+
"""Речення російською чи в дореформеній орфографії всередині українського тексту (цитати,
|
|
343
|
+
бібліографія), а також цитати в «ялинках» із російськими літерами — їх не перевіряємо:
|
|
344
|
+
це не помилки, а інша мова."""
|
|
345
|
+
spans = []
|
|
346
|
+
for m in _SENTENCE.finditer(text):
|
|
347
|
+
s = m.group()
|
|
348
|
+
if looks_russian(s) or re.search(f'[{ARCHAIC}]', s):
|
|
349
|
+
spans.append((m.start(), m.end()))
|
|
350
|
+
for m in re.finditer(r'«[^«»\n]{1,80}»', text):
|
|
351
|
+
if re.search(f'[{RU_ONLY}{ARCHAIC}]', m.group()):
|
|
352
|
+
spans.append((m.start(), m.end()))
|
|
353
|
+
return spans
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
# ════════════════════════════════════ ядро ════════════════════════════════════
|
|
357
|
+
class Linter:
|
|
358
|
+
def __init__(self, cfg: Optional[Config] = None, rules: Optional[list] = None):
|
|
359
|
+
self.cfg = cfg or Config()
|
|
360
|
+
self.rules = rules if rules is not None else load_rules()
|
|
361
|
+
self.allow = {w.lower() for w in self.cfg.allow}
|
|
362
|
+
|
|
363
|
+
def check_text(self, text: str, code: bool = False) -> list:
|
|
364
|
+
"""Перевіряє один шматок тексту. Повертає Issue з позиціями в цьому тексті."""
|
|
365
|
+
if not HAS_CYR.search(text):
|
|
366
|
+
return []
|
|
367
|
+
masked = mask(text, code)
|
|
368
|
+
if is_russian(masked):
|
|
369
|
+
return [Issue(0, min(len(text), 40), 'hint', 'alphabet/russian-text', BUILTIN_DOC['alphabet/russian-text'][1])]
|
|
370
|
+
out = list(_issues_builtin(masked, self.cfg, code))
|
|
371
|
+
foreign = foreign_spans(masked)
|
|
372
|
+
for r in self.rules:
|
|
373
|
+
for m in r.regex.finditer(masked):
|
|
374
|
+
if r.suggestion.startswith('='): # шаблон заміни → безпечне виправлення
|
|
375
|
+
fix = m.expand(r.suggestion[1:])
|
|
376
|
+
if m.group()[:1].isupper() and fix[:1].islower():
|
|
377
|
+
fix = fix[:1].upper() + fix[1:]
|
|
378
|
+
out.append(Issue(m.start(), m.end(), r.level, r.id, f'«{m.group()}» → «{fix}»', fix, fix))
|
|
379
|
+
else:
|
|
380
|
+
out.append(Issue(m.start(), m.end(), r.level, r.id, f'«{m.group()}» → {r.suggestion}',
|
|
381
|
+
r.suggestion))
|
|
382
|
+
res = []
|
|
383
|
+
for i in out:
|
|
384
|
+
if not self.cfg.enabled(i.rule):
|
|
385
|
+
continue
|
|
386
|
+
frag = text[i.start:i.end]
|
|
387
|
+
if frag.lower() in self.allow or MASK in masked[i.start:i.end]:
|
|
388
|
+
continue
|
|
389
|
+
if any(a <= i.start < b for a, b in foreign):
|
|
390
|
+
continue
|
|
391
|
+
i.level = self.cfg.levels.get(i.rule, i.level)
|
|
392
|
+
res.append(i)
|
|
393
|
+
res.sort(key=lambda i: (i.start, -LEVELS[i.level]))
|
|
394
|
+
return res
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
MASK = ''
|
|
398
|
+
_MASKS = [
|
|
399
|
+
re.compile(r'https?://[^\s)<>"\'»]+|www\.[^\s)<>"\'»]+'), # адреси
|
|
400
|
+
re.compile(r'[\w.+-]+@[\w-]+\.[\w.-]+'), # пошта
|
|
401
|
+
re.compile(r'\{\{[^{}]*\}\}|\{[A-Za-z_$][\w.$]*\}|%\(\w+\)[sdif]|%\d*\$?[sdif@]|\$\{[^}]*\}|:[a-z_]\w*(?=\W|$)'),
|
|
402
|
+
re.compile(r'</?[A-Za-z][^<>]*>'), # HTML-теги
|
|
403
|
+
]
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
_CODE_MASKS = [
|
|
407
|
+
re.compile(r'\\(?:u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|.)'), # \n, \", \u0456 у рядках коду
|
|
408
|
+
re.compile(r'\$?\{[^{}\n]*\}'), # вирази f-рядків і шаблонів
|
|
409
|
+
]
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def mask(text: str, code: bool = False) -> str:
|
|
413
|
+
"""Замінює те, що не є людським текстом (адреси, плейсхолдери, теги, а в коді — екранування й вирази
|
|
414
|
+
{…}), символом MASK тієї ж довжини."""
|
|
415
|
+
for rx in (_CODE_MASKS if code else []) + _MASKS:
|
|
416
|
+
text = rx.sub(lambda m: MASK * len(m.group()), text)
|
|
417
|
+
return text
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
# ════════════════════════════════════ розбір файлів ════════════════════════════════════
|
|
421
|
+
_CODE_STR = re.compile(r'"(?:[^"\\\n]|\\.)*"|\'(?:[^\'\\\n]|\\.)*\'|`(?:[^`\\]|\\.)*`'
|
|
422
|
+
r'|//[^\n]*|#[^\n]*|/\*.*?\*/|<!--.*?-->', re.S)
|
|
423
|
+
_JSON_STR = re.compile(r'"(?:[^"\\]|\\.)*"')
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def segments(path: str, text: str) -> Iterator[Segment]:
|
|
427
|
+
ext = os.path.splitext(path)[1].lower()
|
|
428
|
+
if ext in JSON_EXT:
|
|
429
|
+
yield from _json_segments(text)
|
|
430
|
+
elif ext in YAML_EXT or ext == '.properties':
|
|
431
|
+
yield from _kv_segments(text, ext)
|
|
432
|
+
elif ext in ('.po', '.pot'):
|
|
433
|
+
for m in _CODE_STR.finditer(text):
|
|
434
|
+
line_start = text.rfind('\n', 0, m.start()) + 1
|
|
435
|
+
head = text[line_start:m.start()].strip()
|
|
436
|
+
if m.group()[0] == '"' and not head.startswith(('msgid', 'msgctxt', '#')):
|
|
437
|
+
if head == '' and _prev_kw(text, line_start) in ('msgid', 'msgctxt'):
|
|
438
|
+
continue
|
|
439
|
+
yield Segment(m.group()[1:-1], m.start() + 1, code=True)
|
|
440
|
+
elif ext in MARKUP_EXT:
|
|
441
|
+
yield from _markup_segments(text)
|
|
442
|
+
elif ext in CODE_EXT:
|
|
443
|
+
for m in _CODE_STR.finditer(text):
|
|
444
|
+
s = m.group()
|
|
445
|
+
if not HAS_CYR.search(s):
|
|
446
|
+
continue
|
|
447
|
+
if s[0] in '"\'`':
|
|
448
|
+
yield Segment(s[1:-1], m.start() + 1, code=True)
|
|
449
|
+
else:
|
|
450
|
+
yield Segment(s, m.start(), code=True)
|
|
451
|
+
elif ext in ('.md', '.markdown', '.mdx'):
|
|
452
|
+
yield Segment(_mask_markdown(text), 0)
|
|
453
|
+
else:
|
|
454
|
+
yield Segment(text, 0)
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _prev_kw(text: str, line_start: int) -> str:
|
|
458
|
+
"""Для рядків-продовжень у .po: до якого ключового слова належить рядок."""
|
|
459
|
+
pos = line_start
|
|
460
|
+
while pos > 0:
|
|
461
|
+
prev = text.rfind('\n', 0, pos - 1) + 1
|
|
462
|
+
line = text[prev:pos].strip()
|
|
463
|
+
if not line.startswith('"'):
|
|
464
|
+
return line.split(' ', 1)[0].split('[', 1)[0]
|
|
465
|
+
pos = prev
|
|
466
|
+
return ''
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _mask_markdown(text: str) -> str:
|
|
470
|
+
"""Код у Markdown (блоки ``` та `рядковий`) і посилання ](…) не перевіряємо."""
|
|
471
|
+
def blank(m):
|
|
472
|
+
return re.sub(r'[^\n]', MASK, m.group())
|
|
473
|
+
text = re.sub(r'^[ \t]*(```|~~~).*?^[ \t]*\1[^\n]*$', blank, text, flags=re.S | re.M)
|
|
474
|
+
text = re.sub(r'(`+)[^`\n]+?\1', blank, text)
|
|
475
|
+
text = re.sub(r'\]\([^)\n]*\)', blank, text)
|
|
476
|
+
text = re.sub(r'^---\n.*?\n---$', blank, text, count=1, flags=re.S)
|
|
477
|
+
return text
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def _json_segments(text: str) -> Iterator[Segment]:
|
|
481
|
+
for m in _JSON_STR.finditer(text):
|
|
482
|
+
after = text[m.end():m.end() + 40].lstrip()
|
|
483
|
+
if after.startswith(':'):
|
|
484
|
+
continue # ключ, а не значення
|
|
485
|
+
try:
|
|
486
|
+
val = json.loads(m.group())
|
|
487
|
+
except ValueError:
|
|
488
|
+
continue
|
|
489
|
+
if HAS_CYR.search(val):
|
|
490
|
+
yield Segment(val, m.start() + 1, kind='json', token=(m.start(), m.end()))
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def _kv_segments(text: str, ext: str) -> Iterator[Segment]:
|
|
494
|
+
pos = 0
|
|
495
|
+
for line in text.splitlines(True):
|
|
496
|
+
body = line.rstrip('\r\n')
|
|
497
|
+
if ext == '.properties':
|
|
498
|
+
mm = re.match(r'\s*[^#!\s][^=:]*?\s*[=:]\s*(.*)$', body)
|
|
499
|
+
else:
|
|
500
|
+
mm = re.match(r'\s*(?:-\s+)?(?:[\w.\-]+|"[^"]*"|\'[^\']*\')\s*:\s+(.*)$', body) \
|
|
501
|
+
or re.match(r'\s*-\s+(.*)$', body) or re.match(r'\s*(?!#)(.+)$', body)
|
|
502
|
+
if mm and HAS_CYR.search(mm.group(1)):
|
|
503
|
+
val, start = mm.group(1), pos + mm.start(1)
|
|
504
|
+
if ext != '.properties':
|
|
505
|
+
if re.match(r'\s*#', body):
|
|
506
|
+
pos += len(line)
|
|
507
|
+
continue
|
|
508
|
+
cm = re.search(r'\s+#.*$', val)
|
|
509
|
+
if cm and not re.match(r'^["\']', val):
|
|
510
|
+
val = val[:cm.start()]
|
|
511
|
+
if len(val) >= 2 and val[0] == val[-1] and val[0] in '"\'':
|
|
512
|
+
val, start = val[1:-1], start + 1
|
|
513
|
+
yield Segment(val, start, code=True)
|
|
514
|
+
pos += len(line)
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _markup_segments(text: str) -> Iterator[Segment]:
|
|
518
|
+
blanked = re.sub(r'<(script|style)\b.*?</\1>', lambda m: ' ' * len(m.group()), text, flags=re.S | re.I)
|
|
519
|
+
for m in re.finditer(r'>([^<>]+)<', blanked):
|
|
520
|
+
if HAS_CYR.search(m.group(1)):
|
|
521
|
+
yield Segment(text[m.start(1):m.end(1)], m.start(1))
|
|
522
|
+
for m in re.finditer(r'<[^<>]+>', blanked):
|
|
523
|
+
for a in re.finditer(r'=\s*"([^"]*)"|=\s*\'([^\']*)\'', m.group()):
|
|
524
|
+
g = 1 if a.group(1) is not None else 2
|
|
525
|
+
if HAS_CYR.search(a.group(g)):
|
|
526
|
+
yield Segment(a.group(g), m.start() + a.start(g), code=True)
|
|
527
|
+
for m in re.finditer(r'<script\b[^>]*>(.*?)</script>', text, flags=re.S | re.I):
|
|
528
|
+
for s in _CODE_STR.finditer(m.group(1)):
|
|
529
|
+
if HAS_CYR.search(s.group()) and s.group()[0] in '"\'`':
|
|
530
|
+
yield Segment(s.group()[1:-1], m.start(1) + s.start() + 1, code=True)
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
# ════════════════════════════════════ файл: перевірка й виправлення ════════════════════════════════════
|
|
534
|
+
_DISABLE_BLOCK = re.compile(r'ukr-lint-disable(?!-)(.*?)(?:ukr-lint-enable|\Z)', re.S)
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def ignored_lines(text: str) -> set:
|
|
538
|
+
lines = text.split('\n')
|
|
539
|
+
res = set()
|
|
540
|
+
for n, l in enumerate(lines, 1):
|
|
541
|
+
if 'ukr-lint-disable-line' in l:
|
|
542
|
+
res.add(n)
|
|
543
|
+
if 'ukr-lint-disable-next-line' in l:
|
|
544
|
+
res.add(n + 1)
|
|
545
|
+
for m in _DISABLE_BLOCK.finditer(text):
|
|
546
|
+
a = text.count('\n', 0, m.start()) + 1
|
|
547
|
+
b = text.count('\n', 0, m.end()) + 1
|
|
548
|
+
res.update(range(a, b + 1))
|
|
549
|
+
return res
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
class FileResult:
|
|
553
|
+
def __init__(self, path: str, text: str, issues: list):
|
|
554
|
+
self.path, self.text, self.issues = path, text, issues
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def lint_file(linter: Linter, path: str, text: str, only_lines: Optional[set] = None) -> tuple:
|
|
558
|
+
"""Повертає (issues, edits): edits — список (start, end, заміна) у координатах файлу."""
|
|
559
|
+
starts = [0] + [m.end() for m in re.finditer('\n', text)]
|
|
560
|
+
skip = ignored_lines(text)
|
|
561
|
+
issues, edits = [], []
|
|
562
|
+
for seg in segments(path, text):
|
|
563
|
+
found = linter.check_text(seg.text, seg.code)
|
|
564
|
+
if not found:
|
|
565
|
+
continue
|
|
566
|
+
seg_fixes = []
|
|
567
|
+
for i in found:
|
|
568
|
+
pos = seg.offset + (i.start if seg.kind == 'raw' else 0)
|
|
569
|
+
line = bisect.bisect_right(starts, pos)
|
|
570
|
+
col = pos - starts[line - 1] + 1
|
|
571
|
+
if line in skip or (only_lines is not None and line not in only_lines):
|
|
572
|
+
continue
|
|
573
|
+
i.path, i.line, i.col = path, line, col
|
|
574
|
+
i.excerpt = seg.text[i.start:i.end].replace('\n', ' ')
|
|
575
|
+
issues.append(i)
|
|
576
|
+
if i.fix is not None:
|
|
577
|
+
seg_fixes.append(i)
|
|
578
|
+
if seg_fixes:
|
|
579
|
+
edits.extend(_segment_edits(seg, seg_fixes))
|
|
580
|
+
return issues, edits
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _segment_edits(seg: Segment, fixes: list) -> list:
|
|
584
|
+
chosen, last = [], -1
|
|
585
|
+
for i in sorted(fixes, key=lambda i: (i.start, -LEVELS[i.level])):
|
|
586
|
+
if i.start >= last:
|
|
587
|
+
chosen.append(i)
|
|
588
|
+
last = i.end
|
|
589
|
+
if seg.kind == 'raw':
|
|
590
|
+
return [(seg.offset + i.start, seg.offset + i.end, i.fix) for i in chosen]
|
|
591
|
+
new = seg.text
|
|
592
|
+
for i in reversed(chosen):
|
|
593
|
+
new = new[:i.start] + i.fix + new[i.end:]
|
|
594
|
+
return [(seg.token[0], seg.token[1], json.dumps(new, ensure_ascii=False))]
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def apply_edits(text: str, edits: list) -> str:
|
|
598
|
+
last = len(text) + 1
|
|
599
|
+
for s, e, r in sorted(edits, key=lambda x: x[0], reverse=True):
|
|
600
|
+
if e <= last:
|
|
601
|
+
text = text[:s] + r + text[e:]
|
|
602
|
+
last = s
|
|
603
|
+
return text
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
# ════════════════════════════════════ git і пошук файлів ════════════════════════════════════
|
|
607
|
+
def git(*args: str) -> str:
|
|
608
|
+
try:
|
|
609
|
+
return subprocess.run(['git', *args], check=True, capture_output=True, text=True).stdout
|
|
610
|
+
except (OSError, subprocess.CalledProcessError) as e:
|
|
611
|
+
msg = getattr(e, 'stderr', '') or str(e)
|
|
612
|
+
raise SystemExit(f'ukr-lint: git {" ".join(args)} — {msg.strip()}')
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def changed_lines(base: Optional[str], staged: bool) -> dict:
|
|
616
|
+
"""{файл: {номери доданих рядків}} з git diff -U0."""
|
|
617
|
+
args = ['diff', '-U0', '--no-color', '--no-ext-diff', '--diff-filter=AMR']
|
|
618
|
+
args += ['--cached'] if staged else [base or 'HEAD']
|
|
619
|
+
root = git('rev-parse', '--show-toplevel').strip()
|
|
620
|
+
res, cur = {}, None
|
|
621
|
+
for line in git(*args).splitlines():
|
|
622
|
+
if line.startswith('+++ '):
|
|
623
|
+
p = line[4:]
|
|
624
|
+
cur = None if p == '/dev/null' else os.path.relpath(os.path.join(root, p[2:] if p.startswith('b/') else p))
|
|
625
|
+
if cur:
|
|
626
|
+
res.setdefault(cur, set())
|
|
627
|
+
elif line.startswith('@@') and cur:
|
|
628
|
+
m = re.match(r'@@ -\S+ \+(\d+)(?:,(\d+))? @@', line)
|
|
629
|
+
if m:
|
|
630
|
+
a, n = int(m.group(1)), int(m.group(2) or 1)
|
|
631
|
+
res[cur].update(range(a, a + n))
|
|
632
|
+
return {p: ls for p, ls in res.items() if ls and os.path.isfile(p)}
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
def iter_files(paths: Iterable[str], cfg: Config) -> Iterator[str]:
|
|
636
|
+
for p in paths:
|
|
637
|
+
if os.path.isdir(p):
|
|
638
|
+
for root, dirs, files in os.walk(p):
|
|
639
|
+
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS and not d.startswith('.'))
|
|
640
|
+
for f in sorted(files):
|
|
641
|
+
fp = os.path.join(root, f)
|
|
642
|
+
if os.path.splitext(f)[1].lower() in ALL_EXT and not _ignored(fp, cfg):
|
|
643
|
+
yield fp
|
|
644
|
+
elif os.path.isfile(p):
|
|
645
|
+
yield p # явно названий файл перевіряємо завжди
|
|
646
|
+
else:
|
|
647
|
+
print(f'ukr-lint: немає такого файлу: {p}', file=sys.stderr)
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def _ignored(path: str, cfg: Config) -> bool:
|
|
651
|
+
rel = os.path.relpath(path).replace(os.sep, '/')
|
|
652
|
+
return any(fnmatch.fnmatch(rel, g) or fnmatch.fnmatch(os.path.basename(rel), g) for g in cfg.ignore)
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
# ════════════════════════════════════ звіт ════════════════════════════════════
|
|
656
|
+
def plural(n: int, one: str, few: str, many: str) -> str:
|
|
657
|
+
if n % 10 == 1 and n % 100 != 11:
|
|
658
|
+
return one
|
|
659
|
+
if 2 <= n % 10 <= 4 and not 12 <= n % 100 <= 14:
|
|
660
|
+
return few
|
|
661
|
+
return many
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
class Out:
|
|
665
|
+
def __init__(self, color: bool):
|
|
666
|
+
self.c = color
|
|
667
|
+
|
|
668
|
+
def __call__(self, s: str, code: str) -> str:
|
|
669
|
+
return f'\033[{code}m{s}\033[0m' if self.c else s
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def report_text(issues: list, rules_by_id: dict, verbose: bool, color: bool, fixable_hint: bool = True) -> None:
|
|
673
|
+
o = Out(color)
|
|
674
|
+
tone = {'error': '31', 'warning': '33', 'hint': '36'}
|
|
675
|
+
cur = None
|
|
676
|
+
for i in issues:
|
|
677
|
+
if i.path != cur:
|
|
678
|
+
cur = i.path
|
|
679
|
+
print('\n' + o(i.path or '<текст>', '1;4'))
|
|
680
|
+
loc = o(f'{i.line}:{i.col}'.rjust(7), '2')
|
|
681
|
+
lvl = o(LEVEL_UK[i.level].ljust(7), tone[i.level])
|
|
682
|
+
cat, key = i.rule.split('/', 1)
|
|
683
|
+
tail = o(f'[{CATEGORY_UK.get(cat, cat)}/{key}]', '2')
|
|
684
|
+
fix = o(' ✎', '32') if i.fix is not None else ''
|
|
685
|
+
print(f'{loc} {lvl} {i.message}{fix} {tail}')
|
|
686
|
+
if verbose:
|
|
687
|
+
exp = rules_by_id[i.rule].explanation if i.rule in rules_by_id else BUILTIN_DOC.get(i.rule, ('', ''))[1]
|
|
688
|
+
if exp:
|
|
689
|
+
print(' ' * 18 + o(exp, '2'))
|
|
690
|
+
n = {k: sum(1 for i in issues if i.level == k) for k in LEVELS}
|
|
691
|
+
files = len({i.path for i in issues})
|
|
692
|
+
if not issues:
|
|
693
|
+
print(o('✔ Чисто: проблем не знайдено.', '32'))
|
|
694
|
+
return
|
|
695
|
+
parts = []
|
|
696
|
+
if n['error']:
|
|
697
|
+
parts.append(o(f'{n["error"]} {plural(n["error"], "помилка", "помилки", "помилок")}', '31'))
|
|
698
|
+
if n['warning']:
|
|
699
|
+
parts.append(o(f'{n["warning"]} {plural(n["warning"], "попередження", "попередження", "попереджень")}', '33'))
|
|
700
|
+
if n['hint']:
|
|
701
|
+
parts.append(o(f'{n["hint"]} {plural(n["hint"], "порада", "поради", "порад")}', '36'))
|
|
702
|
+
fx = sum(1 for i in issues if i.fix is not None)
|
|
703
|
+
where = f' у {files} {plural(files, "файлі", "файлах", "файлах")}' if files > 1 else ''
|
|
704
|
+
print(f'\n{"✖" if n["error"] else "⚠"} ' + ', '.join(parts) + where + '.'
|
|
705
|
+
+ (f' {fx} можна виправити автоматично: --fix (позначено ✎).' if fx and fixable_hint else ''))
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def report_github(issues: list) -> None:
|
|
709
|
+
kind = {'error': 'error', 'warning': 'warning', 'hint': 'notice'}
|
|
710
|
+
for i in issues:
|
|
711
|
+
msg = i.message.replace('%', '%25').replace('\n', '%0A')
|
|
712
|
+
print(f'::{kind[i.level]} file={i.path},line={i.line},col={i.col},title=ukr-lint {i.rule}::{msg}')
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
# ════════════════════════════════════ CLI ════════════════════════════════════
|
|
716
|
+
def main(argv: Optional[list] = None) -> int:
|
|
717
|
+
ap = argparse.ArgumentParser(prog='ukr-lint', description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
718
|
+
ap.add_argument('paths', nargs='*', help='файли або теки')
|
|
719
|
+
ap.add_argument('-t', '--text', help='перевірити цей текст')
|
|
720
|
+
ap.add_argument('--stdin', action='store_true', help='прочитати текст зі stdin')
|
|
721
|
+
ap.add_argument('--diff', nargs='?', const='HEAD', metavar='BASE', help='лише рядки, змінені відносно BASE (типово HEAD)')
|
|
722
|
+
ap.add_argument('--staged', action='store_true', help='лише рядки, додані в індекс git')
|
|
723
|
+
ap.add_argument('--fix', action='store_true', help='застосувати безпечні виправлення (✎)')
|
|
724
|
+
ap.add_argument('--format', choices=['text', 'json', 'github'], default='text')
|
|
725
|
+
ap.add_argument('--level', choices=list(LEVELS), default='warning', help='мінімальний рівень (типово warning)')
|
|
726
|
+
ap.add_argument('--strict', action='store_true', help='код виходу 1 і на попередження')
|
|
727
|
+
ap.add_argument('-v', '--verbose', action='store_true', help='пояснення до кожної знахідки')
|
|
728
|
+
ap.add_argument('--apostrophe', help='символ апострофа проєкту (типово ʼ)')
|
|
729
|
+
ap.add_argument('--config', help='шлях до .ukr-lint.json')
|
|
730
|
+
ap.add_argument('--no-color', action='store_true')
|
|
731
|
+
ap.add_argument('--rules', nargs='?', const='', metavar='ПОШУК', help='показати правила')
|
|
732
|
+
ap.add_argument('--explain', metavar='ID', help='пояснити правило')
|
|
733
|
+
ap.add_argument('--version', action='version', version=f'ukr-lint {__version__}')
|
|
734
|
+
a = ap.parse_args(argv)
|
|
735
|
+
|
|
736
|
+
cfg = load_config(os.getcwd(), a.config)
|
|
737
|
+
if a.apostrophe:
|
|
738
|
+
cfg.apostrophe = a.apostrophe
|
|
739
|
+
rules = load_rules()
|
|
740
|
+
by_id = {r.id: r for r in rules}
|
|
741
|
+
color = (sys.stdout.isatty() or bool(os.environ.get('FORCE_COLOR'))) and not a.no_color and not os.environ.get('NO_COLOR')
|
|
742
|
+
|
|
743
|
+
if a.rules is not None:
|
|
744
|
+
q = a.rules.lower()
|
|
745
|
+
rows = [(r.id, r.level, r.suggestion, r.explanation) for r in rules] + \
|
|
746
|
+
[(k, v[0], '', v[1]) for k, v in BUILTIN_DOC.items()]
|
|
747
|
+
rows = [r for r in rows if q in ' '.join(r).lower()]
|
|
748
|
+
for rid, lvl, sug, exp in rows:
|
|
749
|
+
print(f'{rid:38s} {lvl:8s} {sug}')
|
|
750
|
+
print(f'\n{len(rows)} {plural(len(rows), "правило", "правила", "правил")}')
|
|
751
|
+
return 0
|
|
752
|
+
if a.explain:
|
|
753
|
+
r = by_id.get(a.explain)
|
|
754
|
+
if r:
|
|
755
|
+
print(f'{r.id} ({r.level})\nЗаміна: {r.suggestion}\n{r.explanation}\nШаблон: {r.pattern}')
|
|
756
|
+
elif a.explain in BUILTIN_DOC:
|
|
757
|
+
print(f'{a.explain} ({BUILTIN_DOC[a.explain][0]})\n{BUILTIN_DOC[a.explain][1]}')
|
|
758
|
+
else:
|
|
759
|
+
print(f'Немає правила {a.explain}. Список: --rules', file=sys.stderr)
|
|
760
|
+
return 2
|
|
761
|
+
return 0
|
|
762
|
+
|
|
763
|
+
linter = Linter(cfg, rules)
|
|
764
|
+
minlvl = LEVELS[a.level]
|
|
765
|
+
issues = []
|
|
766
|
+
|
|
767
|
+
if a.text is not None or a.stdin:
|
|
768
|
+
text = a.text if a.text is not None else sys.stdin.read()
|
|
769
|
+
found, edits = lint_file(linter, '<текст>.txt', text)
|
|
770
|
+
issues = [i for i in found if LEVELS[i.level] >= minlvl]
|
|
771
|
+
for i in issues:
|
|
772
|
+
i.path = ''
|
|
773
|
+
if a.fix:
|
|
774
|
+
sys.stdout.write(apply_edits(text, [e for e in edits]))
|
|
775
|
+
return 0
|
|
776
|
+
else:
|
|
777
|
+
only = None
|
|
778
|
+
if a.diff or a.staged:
|
|
779
|
+
only = changed_lines(a.diff, a.staged)
|
|
780
|
+
files = [p for p in (a.paths and list(iter_files(a.paths, cfg)) or only) if p in only]
|
|
781
|
+
files = [p for p in files if os.path.splitext(p)[1].lower() in ALL_EXT and not _ignored(p, cfg)]
|
|
782
|
+
else:
|
|
783
|
+
if not a.paths:
|
|
784
|
+
ap.print_help()
|
|
785
|
+
return 2
|
|
786
|
+
files = list(iter_files(a.paths, cfg))
|
|
787
|
+
fixed_files = 0
|
|
788
|
+
for p in files:
|
|
789
|
+
try:
|
|
790
|
+
text = open(p, encoding='utf-8').read()
|
|
791
|
+
except (UnicodeDecodeError, OSError):
|
|
792
|
+
continue
|
|
793
|
+
found, edits = lint_file(linter, p, text, only.get(p) if only is not None else None)
|
|
794
|
+
if a.fix and edits:
|
|
795
|
+
new = text
|
|
796
|
+
for _ in range(3): # виправлення можуть відкрити наступні
|
|
797
|
+
new2 = apply_edits(new, edits)
|
|
798
|
+
if new2 == new:
|
|
799
|
+
break
|
|
800
|
+
new = new2
|
|
801
|
+
found, edits = lint_file(linter, p, new, only.get(p) if only is not None else None)
|
|
802
|
+
edits = [e for e in edits]
|
|
803
|
+
if new != text:
|
|
804
|
+
open(p, 'w', encoding='utf-8').write(new)
|
|
805
|
+
fixed_files += 1
|
|
806
|
+
issues += [i for i in found if LEVELS[i.level] >= minlvl]
|
|
807
|
+
if a.fix and a.format == 'text':
|
|
808
|
+
print(f'Виправлено файлів: {fixed_files}.' if fixed_files else 'Нічого виправляти автоматично.')
|
|
809
|
+
|
|
810
|
+
if a.format == 'json':
|
|
811
|
+
print(json.dumps([i.as_dict() for i in issues], ensure_ascii=False, indent=2))
|
|
812
|
+
elif a.format == 'github':
|
|
813
|
+
report_github(issues)
|
|
814
|
+
else:
|
|
815
|
+
report_text(issues, by_id, a.verbose, color, not a.fix)
|
|
816
|
+
bad = any(i.level == 'error' for i in issues) or (a.strict and any(i.level == 'warning' for i in issues))
|
|
817
|
+
return 1 if bad else 0
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
if __name__ == '__main__':
|
|
821
|
+
try:
|
|
822
|
+
sys.exit(main())
|
|
823
|
+
except KeyboardInterrupt:
|
|
824
|
+
sys.exit(130)
|
|
825
|
+
except BrokenPipeError:
|
|
826
|
+
sys.exit(0)
|