lint-gost-tex 0.1.1__tar.gz

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.
Files changed (30) hide show
  1. lint_gost_tex-0.1.1/CHANGELOG.md +7 -0
  2. lint_gost_tex-0.1.1/CODE_OF_CONDUCT.md +17 -0
  3. lint_gost_tex-0.1.1/CONTRIBUTING.md +21 -0
  4. lint_gost_tex-0.1.1/LICENSE +21 -0
  5. lint_gost_tex-0.1.1/PKG-INFO +124 -0
  6. lint_gost_tex-0.1.1/README.md +105 -0
  7. lint_gost_tex-0.1.1/SECURITY.md +7 -0
  8. lint_gost_tex-0.1.1/examples/dictionaries/custom.txt +1 -0
  9. lint_gost_tex-0.1.1/examples/dictionaries/ru.txt +1 -0
  10. lint_gost_tex-0.1.1/examples/lint-gost-tex.toml +173 -0
  11. lint_gost_tex-0.1.1/pyproject.toml +37 -0
  12. lint_gost_tex-0.1.1/src/lint_gost_tex/__init__.py +13 -0
  13. lint_gost_tex-0.1.1/src/lint_gost_tex/__main__.py +5 -0
  14. lint_gost_tex-0.1.1/src/lint_gost_tex/cli.py +85 -0
  15. lint_gost_tex-0.1.1/src/lint_gost_tex/config.py +354 -0
  16. lint_gost_tex-0.1.1/src/lint_gost_tex/context.py +15 -0
  17. lint_gost_tex-0.1.1/src/lint_gost_tex/document.py +114 -0
  18. lint_gost_tex-0.1.1/src/lint_gost_tex/issue.py +14 -0
  19. lint_gost_tex-0.1.1/src/lint_gost_tex/rules/__init__.py +62 -0
  20. lint_gost_tex-0.1.1/src/lint_gost_tex/rules/abbrev.py +70 -0
  21. lint_gost_tex-0.1.1/src/lint_gost_tex/rules/base.py +14 -0
  22. lint_gost_tex-0.1.1/src/lint_gost_tex/rules/captions.py +46 -0
  23. lint_gost_tex-0.1.1/src/lint_gost_tex/rules/illustrations.py +96 -0
  24. lint_gost_tex-0.1.1/src/lint_gost_tex/rules/images.py +53 -0
  25. lint_gost_tex-0.1.1/src/lint_gost_tex/rules/lists.py +278 -0
  26. lint_gost_tex-0.1.1/src/lint_gost_tex/rules/refs.py +73 -0
  27. lint_gost_tex-0.1.1/src/lint_gost_tex/rules/spelling.py +234 -0
  28. lint_gost_tex-0.1.1/src/lint_gost_tex/rules/styles.py +43 -0
  29. lint_gost_tex-0.1.1/src/lint_gost_tex/rules/unicode_chars.py +48 -0
  30. lint_gost_tex-0.1.1/src/lint_gost_tex/tex.py +421 -0
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ ## [0.1.0] - 2026-02-02
6
+ ### Added
7
+ - Initial standalone release of lint-gost-tex.
@@ -0,0 +1,17 @@
1
+ # Code of Conduct
2
+
3
+ Проект lint-gost-tex придерживается принципов уважительного и инклюзивного общения.
4
+
5
+ ## Наши ожидания
6
+ - Уважайте участников и их время.
7
+ - Критикуйте идеи, а не людей.
8
+ - Избегайте оскорблений, дискриминации и харассмента.
9
+
10
+ ## Неприемлемое поведение
11
+ - Личные нападки и угрозы.
12
+ - Дискриминация по любым признакам.
13
+ - Сексуализированные высказывания или контент.
14
+
15
+ ## Сообщение о нарушениях
16
+ Сообщайте о нарушениях через issues (если это безопасно) или через приватные каналы
17
+ поддержки репозитория (например, GitHub Security Advisories).
@@ -0,0 +1,21 @@
1
+ # Contributing
2
+
3
+ Спасибо за интерес к lint-gost-tex!
4
+
5
+ ## Разработка
6
+ ```bash
7
+ poetry install
8
+ poetry run lint-gost-tex --root main.tex
9
+ ```
10
+
11
+ ## Что стоит учитывать
12
+ - Пожалуйста, сохраняйте текущий стиль кода и относительные импорты.
13
+ - Новые правила добавляйте в `src/lint_gost_tex/rules` и регистрируйте в `build_rules`.
14
+ - Для изменений в конфиге обновляйте `examples/lint-gost-tex.toml` и README.
15
+
16
+ ## PR-процесс
17
+ 1) Опишите проблему/идею и ожидаемое поведение.
18
+ 2) Добавьте минимальный воспроизводимый пример (кусок `.tex`).
19
+ 3) Убедитесь, что не сломали формат сообщений и сортировку ошибок.
20
+
21
+ Если у вас нет уверенности по правилам ГОСТ — откройте issue с обсуждением.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lint GOST TeX contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.1
2
+ Name: lint-gost-tex
3
+ Version: 0.1.1
4
+ Summary: LaTeX linter for GOST-styled documents.
5
+ License: MIT
6
+ Keywords: latex,gost,linter,tex
7
+ Author: Lint GOST TeX contributors
8
+ Requires-Python: >=3.11,<4.0
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Software Development :: Quality Assurance
16
+ Classifier: Topic :: Text Processing :: Markup :: LaTeX
17
+ Description-Content-Type: text/markdown
18
+
19
+ # lint-gost-tex
20
+
21
+ [![status-badge](https://woodpecker.dev.nachert.art/api/badges/9/status.svg)](https://woodpecker.dev.nachert.art/repos/9)
22
+
23
+ Линтер LaTeX‑документов под требования ГОСТ: проверяет оформление ссылок, списков,
24
+ иллюстраций, запрещённые сокращения, нестандартные символы и орфографию.
25
+
26
+ ## Возможности
27
+ - проверка `\includegraphics` на фиксированную ширину;
28
+ - пробелы перед `\ref/\eqref/\autoref/...` (неразрывный `~`);
29
+ - пунктуация вокруг ссылок;
30
+ - запрет подчеркиваний/курсива;
31
+ - правила для списков (вложенность, пунктуация, регистр);
32
+ - подписи к рисункам/таблицам;
33
+ - порядок иллюстраций относительно первого упоминания;
34
+ - орфография (RU/EN) и запрет «пиксель»;
35
+ - контроль не‑клавиатурных символов.
36
+
37
+ ## Установка
38
+ ```bash
39
+ pip install lint-gost-tex
40
+ ```
41
+
42
+ ## Быстрый старт
43
+ ```bash
44
+ lint-gost-tex --root main.tex
45
+ ```
46
+
47
+ или через модуль:
48
+ ```bash
49
+ python -m lint_gost_tex --root main.tex
50
+ ```
51
+
52
+ По умолчанию линтер ищет конфиг `lint-gost-tex.toml` в текущей директории.
53
+ Другой файл можно указать явно:
54
+ ```bash
55
+ lint-gost-tex --config path/to/config.toml
56
+ ```
57
+
58
+ ## Конфигурация
59
+ Пример конфига: `examples/lint-gost-tex.toml`.
60
+
61
+ 1) Скопируйте конфиг в корень проекта:
62
+ ```bash
63
+ cp examples/lint-gost-tex.toml ./lint-gost-tex.toml
64
+ ```
65
+
66
+ 2) Скопируйте шаблоны словарей:
67
+ ```bash
68
+ mkdir -p dictionaries
69
+ cp examples/dictionaries/*.txt ./dictionaries/
70
+ ```
71
+
72
+ ### Важные параметры
73
+ - `document.root` — корневой `.tex` файл.
74
+ - `document.exclude` — исключения (по имени файла или glob).
75
+ - `spellcheck.custom_dict` — пользовательский словарь.
76
+ - `spellcheck.extra_ru_dicts` — русские словари (обязательно для RU‑проверки).
77
+ - `spellcheck.extra_en_dicts` — дополнительные EN‑словари.
78
+
79
+ Если русских/английских словарей нет, линтер выдаст предупреждение `SPELL000`.
80
+
81
+ ## Ограничения
82
+ - `\include` и `\input` учитываются только из корневого файла (без рекурсии).
83
+ - Проверка орфографии требует явных словарей для русского языка.
84
+
85
+ ## Список правил
86
+ - `IMG001` — `\includegraphics` должен использовать заданную ширину.
87
+ - `REF001` — перед ссылками нужен ровно один `~`.
88
+ - `REF002` — ссылки должны стоять перед завершающей пунктуацией.
89
+ - `TXT001` — запрет курсивов/подчеркиваний.
90
+ - `LST001` — запрет кастомных окружений списков/лейблов.
91
+ - `LST002` — запрет вложенных списков.
92
+ - `LST003` — пунктуация элементов списка.
93
+ - `LST004` — в элементе списка только одно предложение.
94
+ - `LST005` — элементы списка не должны начинаться с заглавной буквы.
95
+ - `CAP001` — подписи не должны оканчиваться пунктуацией.
96
+ - `ILL001` — иллюстрация появляется раньше первого упоминания.
97
+ - `ILL002` — иллюстрация не имеет ссылок.
98
+ - `ABBR001` — запрещённые сокращения (ГОСТ).
99
+ - `UNIC001` — запрет не‑клавиатурных символов.
100
+ - `SPELL000` — нет словарей для проверки.
101
+ - `SPELL001` — неизвестное слово.
102
+ - `SPELL002` — запрещённое слово «пиксель».
103
+ - `SPELL003` — требуется «ё» вместо «е».
104
+
105
+ ## Формат вывода
106
+ ```
107
+ path:line:col [RULE_ID] message
108
+ | source line
109
+ | ^
110
+ ```
111
+
112
+ ## Коды выхода
113
+ - `0` — ошибок нет.
114
+ - `1` — найдены проблемы.
115
+
116
+ ## Разработка
117
+ ```bash
118
+ poetry install
119
+ poetry run lint-gost-tex --root main.tex
120
+ ```
121
+
122
+ ## Лицензия
123
+ MIT. См. `LICENSE`.
124
+
@@ -0,0 +1,105 @@
1
+ # lint-gost-tex
2
+
3
+ [![status-badge](https://woodpecker.dev.nachert.art/api/badges/9/status.svg)](https://woodpecker.dev.nachert.art/repos/9)
4
+
5
+ Линтер LaTeX‑документов под требования ГОСТ: проверяет оформление ссылок, списков,
6
+ иллюстраций, запрещённые сокращения, нестандартные символы и орфографию.
7
+
8
+ ## Возможности
9
+ - проверка `\includegraphics` на фиксированную ширину;
10
+ - пробелы перед `\ref/\eqref/\autoref/...` (неразрывный `~`);
11
+ - пунктуация вокруг ссылок;
12
+ - запрет подчеркиваний/курсива;
13
+ - правила для списков (вложенность, пунктуация, регистр);
14
+ - подписи к рисункам/таблицам;
15
+ - порядок иллюстраций относительно первого упоминания;
16
+ - орфография (RU/EN) и запрет «пиксель»;
17
+ - контроль не‑клавиатурных символов.
18
+
19
+ ## Установка
20
+ ```bash
21
+ pip install lint-gost-tex
22
+ ```
23
+
24
+ ## Быстрый старт
25
+ ```bash
26
+ lint-gost-tex --root main.tex
27
+ ```
28
+
29
+ или через модуль:
30
+ ```bash
31
+ python -m lint_gost_tex --root main.tex
32
+ ```
33
+
34
+ По умолчанию линтер ищет конфиг `lint-gost-tex.toml` в текущей директории.
35
+ Другой файл можно указать явно:
36
+ ```bash
37
+ lint-gost-tex --config path/to/config.toml
38
+ ```
39
+
40
+ ## Конфигурация
41
+ Пример конфига: `examples/lint-gost-tex.toml`.
42
+
43
+ 1) Скопируйте конфиг в корень проекта:
44
+ ```bash
45
+ cp examples/lint-gost-tex.toml ./lint-gost-tex.toml
46
+ ```
47
+
48
+ 2) Скопируйте шаблоны словарей:
49
+ ```bash
50
+ mkdir -p dictionaries
51
+ cp examples/dictionaries/*.txt ./dictionaries/
52
+ ```
53
+
54
+ ### Важные параметры
55
+ - `document.root` — корневой `.tex` файл.
56
+ - `document.exclude` — исключения (по имени файла или glob).
57
+ - `spellcheck.custom_dict` — пользовательский словарь.
58
+ - `spellcheck.extra_ru_dicts` — русские словари (обязательно для RU‑проверки).
59
+ - `spellcheck.extra_en_dicts` — дополнительные EN‑словари.
60
+
61
+ Если русских/английских словарей нет, линтер выдаст предупреждение `SPELL000`.
62
+
63
+ ## Ограничения
64
+ - `\include` и `\input` учитываются только из корневого файла (без рекурсии).
65
+ - Проверка орфографии требует явных словарей для русского языка.
66
+
67
+ ## Список правил
68
+ - `IMG001` — `\includegraphics` должен использовать заданную ширину.
69
+ - `REF001` — перед ссылками нужен ровно один `~`.
70
+ - `REF002` — ссылки должны стоять перед завершающей пунктуацией.
71
+ - `TXT001` — запрет курсивов/подчеркиваний.
72
+ - `LST001` — запрет кастомных окружений списков/лейблов.
73
+ - `LST002` — запрет вложенных списков.
74
+ - `LST003` — пунктуация элементов списка.
75
+ - `LST004` — в элементе списка только одно предложение.
76
+ - `LST005` — элементы списка не должны начинаться с заглавной буквы.
77
+ - `CAP001` — подписи не должны оканчиваться пунктуацией.
78
+ - `ILL001` — иллюстрация появляется раньше первого упоминания.
79
+ - `ILL002` — иллюстрация не имеет ссылок.
80
+ - `ABBR001` — запрещённые сокращения (ГОСТ).
81
+ - `UNIC001` — запрет не‑клавиатурных символов.
82
+ - `SPELL000` — нет словарей для проверки.
83
+ - `SPELL001` — неизвестное слово.
84
+ - `SPELL002` — запрещённое слово «пиксель».
85
+ - `SPELL003` — требуется «ё» вместо «е».
86
+
87
+ ## Формат вывода
88
+ ```
89
+ path:line:col [RULE_ID] message
90
+ | source line
91
+ | ^
92
+ ```
93
+
94
+ ## Коды выхода
95
+ - `0` — ошибок нет.
96
+ - `1` — найдены проблемы.
97
+
98
+ ## Разработка
99
+ ```bash
100
+ poetry install
101
+ poetry run lint-gost-tex --root main.tex
102
+ ```
103
+
104
+ ## Лицензия
105
+ MIT. См. `LICENSE`.
@@ -0,0 +1,7 @@
1
+ # Security Policy
2
+
3
+ Если вы нашли уязвимость, пожалуйста:
4
+ 1) Не публикуйте детали в публичных issues.
5
+ 2) Используйте приватный канал (GitHub Security Advisories) или другой приватный способ связи.
6
+
7
+ Мы постараемся ответить как можно быстрее.
@@ -0,0 +1 @@
1
+ # Add project-specific allowed words here, one per line.
@@ -0,0 +1 @@
1
+ # Add a Russian base wordlist here (one word per line).
@@ -0,0 +1,173 @@
1
+ [document]
2
+ root = "main.tex"
3
+ exclude = []
4
+
5
+ [rules.images]
6
+ required_width = "0.9\\textwidth"
7
+
8
+ [rules.refs]
9
+ commands = ["ref", "eqref", "autoref", "pageref", "cref", "Cref"]
10
+
11
+ [rules.links]
12
+ commands = [
13
+ "ref",
14
+ "eqref",
15
+ "autoref",
16
+ "pageref",
17
+ "cref",
18
+ "Cref",
19
+ "cite",
20
+ "citep",
21
+ "citet",
22
+ "citealp",
23
+ "citeauthor",
24
+ "citeyear",
25
+ "citeyearpar",
26
+ "url",
27
+ "href",
28
+ "hyperref",
29
+ ]
30
+
31
+ [rules.styles]
32
+ commands = ["underline", "uline", "ul", "textit", "textsl", "emph", "em", "itshape", "it"]
33
+
34
+ [rules.lists]
35
+ allowed_envs = ["itemize", "enumerate"]
36
+ list_envs = ["itemize", "enumerate", "description", "list"]
37
+ disallow_begin_optional = true
38
+ disallow_item_optional = true
39
+
40
+ [rules.captions]
41
+ commands = ["caption", "captionof"]
42
+ forbid_trailing = [".", ",", ";", ":", "!", "?"]
43
+
44
+ [rules.illustrations]
45
+ envs = ["figure", "table", "figure*", "table*"]
46
+ ref_commands = ["ref", "autoref", "cref", "Cref", "pageref", "eqref"]
47
+
48
+ [rules.abbrev]
49
+ banned_words = [
50
+ "\u0441\u043c",
51
+ "\u0440\u0438\u0441",
52
+ "\u0442\u0430\u0431\u043b",
53
+ "\u0441\u0442\u0440",
54
+ "\u0433\u043b",
55
+ "\u0440\u0430\u0437\u0434",
56
+ "\u043f\u0440\u0438\u043b",
57
+ ]
58
+ banned_patterns = [
59
+ "\\b\\u0442\\.\\s*\\u0434\\.",
60
+ "\\b\\u0442\\.\\s*\\u043f\\.",
61
+ "\\b\\u0438\\s+\\u0442\\.\\s*\\u0434\\.",
62
+ "\\b\\u0438\\s+\\u0442\\.\\s*\\u043f\\.",
63
+ "\\b\\u0442\\.\\s*\\u0435\\.",
64
+ "\\b\\u0442\\.\\s*\\u043a\\.",
65
+ "\\b\\u0442\\.\\s*\\u043e\\.",
66
+ "\\b\\u0438\\s+\\u0434\\u0440\\.",
67
+ ]
68
+ allow_words = []
69
+ skip_commands = [
70
+ "include",
71
+ "input",
72
+ "cite",
73
+ "citep",
74
+ "citet",
75
+ "citealp",
76
+ "citeauthor",
77
+ "citeyear",
78
+ "citeyearpar",
79
+ "ref",
80
+ "eqref",
81
+ "autoref",
82
+ "pageref",
83
+ "cref",
84
+ "Cref",
85
+ "label",
86
+ "url",
87
+ "href",
88
+ "hyperref",
89
+ "includegraphics",
90
+ "includepdf",
91
+ "graphicspath",
92
+ ]
93
+ two_arg_commands = ["href", "hyperref"]
94
+
95
+ [rules.unicode]
96
+ allowed_extra = ["\u2116", "\u00ab", "\u00bb"]
97
+
98
+ [rules.list_items]
99
+ skip_commands = [
100
+ "include",
101
+ "input",
102
+ "cite",
103
+ "citep",
104
+ "citet",
105
+ "citealp",
106
+ "citeauthor",
107
+ "citeyear",
108
+ "citeyearpar",
109
+ "ref",
110
+ "eqref",
111
+ "autoref",
112
+ "pageref",
113
+ "cref",
114
+ "Cref",
115
+ "label",
116
+ "url",
117
+ "href",
118
+ "hyperref",
119
+ "includegraphics",
120
+ "includepdf",
121
+ "graphicspath",
122
+ ]
123
+ two_arg_commands = ["href", "hyperref"]
124
+ sentence_endings = [".", "!", "?"]
125
+ last_end = "."
126
+ non_last_end = ";"
127
+
128
+ [spellcheck]
129
+ custom_dict = "dictionaries/custom.txt"
130
+ extra_ru_dicts = ["dictionaries/ru.txt"]
131
+ extra_en_dicts = []
132
+ ignore_envs = [
133
+ "lstlisting",
134
+ "verbatim",
135
+ "verbatim*",
136
+ "minted",
137
+ "tikzpicture",
138
+ "equation",
139
+ "equation*",
140
+ "align",
141
+ "align*",
142
+ "gather",
143
+ "gather*",
144
+ "multline",
145
+ "multline*",
146
+ ]
147
+ skip_commands = [
148
+ "include",
149
+ "input",
150
+ "cite",
151
+ "citep",
152
+ "citet",
153
+ "citealp",
154
+ "citeauthor",
155
+ "citeyear",
156
+ "citeyearpar",
157
+ "ref",
158
+ "eqref",
159
+ "autoref",
160
+ "pageref",
161
+ "cref",
162
+ "Cref",
163
+ "label",
164
+ "url",
165
+ "href",
166
+ "hyperref",
167
+ "includegraphics",
168
+ "includepdf",
169
+ "graphicspath",
170
+ ]
171
+ keep_commands = ["textbf", "textrm", "textsf", "texttt", "textsc"]
172
+ min_word_length = 2
173
+ ignore_uppercase_acronyms = true
@@ -0,0 +1,37 @@
1
+ [tool.poetry]
2
+ name = "lint-gost-tex"
3
+ version = "0.1.1"
4
+ description = "LaTeX linter for GOST-styled documents."
5
+ authors = ["Lint GOST TeX contributors"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ packages = [{ include = "lint_gost_tex", from = "src" }]
9
+ keywords = ["latex", "gost", "linter", "tex"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Intended Audience :: Developers",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.11",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Topic :: Text Processing :: Markup :: LaTeX",
18
+ "Topic :: Software Development :: Quality Assurance",
19
+ ]
20
+ include = [
21
+ "LICENSE",
22
+ "CHANGELOG.md",
23
+ "CODE_OF_CONDUCT.md",
24
+ "CONTRIBUTING.md",
25
+ "SECURITY.md",
26
+ "examples/**",
27
+ ]
28
+
29
+ [tool.poetry.dependencies]
30
+ python = ">=3.11,<4.0"
31
+
32
+ [tool.poetry.scripts]
33
+ lint-gost-tex = "lint_gost_tex.cli:main"
34
+
35
+ [build-system]
36
+ requires = ["poetry-core>=1.7.0"]
37
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,13 @@
1
+ """LaTeX linting package for GOST-styled documents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+
8
+ try:
9
+ __version__ = version("lint-gost-tex")
10
+ except PackageNotFoundError: # pragma: no cover - fallback for editable installs
11
+ __version__ = "0.0.0"
12
+
13
+ __all__ = ["__version__"]
@@ -0,0 +1,5 @@
1
+ from .cli import main
2
+
3
+
4
+ if __name__ == "__main__":
5
+ raise SystemExit(main())
@@ -0,0 +1,85 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import os
5
+ from pathlib import Path
6
+
7
+ from .config import DEFAULT_CONFIG_FILENAME, Config, DocumentConfig
8
+ from .context import LintContext
9
+ from .document import load_document
10
+ from .rules import build_rules
11
+
12
+
13
+ def main(argv: list[str] | None = None) -> int:
14
+ parser = argparse.ArgumentParser(description="Lint LaTeX sources.")
15
+ parser.add_argument(
16
+ "--config",
17
+ default=DEFAULT_CONFIG_FILENAME,
18
+ help="Path to lint-gost-tex config file.",
19
+ )
20
+ parser.add_argument("--root", help="Override root .tex file path.")
21
+ args = parser.parse_args(argv)
22
+
23
+ base_dir = Path.cwd()
24
+ config_path = Path(args.config) if args.config else None
25
+ config = Config.load(config_path, base_dir)
26
+ if args.root:
27
+ root_path = Path(args.root)
28
+ if not root_path.is_absolute():
29
+ root_path = base_dir / root_path
30
+ config = _override_root(config, root_path)
31
+
32
+ document = load_document(config.document, base_dir)
33
+ ctx = LintContext(document=document, config=config, base_dir=base_dir, config_path=config_path)
34
+ issues = []
35
+ for rule in build_rules(config):
36
+ issues.extend(rule.check(ctx))
37
+
38
+ path_index = document.path_index()
39
+ issues.sort(key=lambda item: (path_index.get(item.path, 9999), item.line, item.col, item.rule_id))
40
+
41
+ for issue in issues:
42
+ print(_format_issue(issue, base_dir))
43
+
44
+ if issues:
45
+ print(f"{len(issues)} issue(s) found.")
46
+ return 1
47
+ print("No issues found.")
48
+ return 0
49
+
50
+
51
+ def _override_root(config: Config, root: Path) -> Config:
52
+ document = DocumentConfig(root=root, exclude=config.document.exclude)
53
+ return Config(
54
+ document=document,
55
+ images=config.images,
56
+ refs=config.refs,
57
+ links=config.links,
58
+ styles=config.styles,
59
+ lists=config.lists,
60
+ captions=config.captions,
61
+ illustrations=config.illustrations,
62
+ abbrev=config.abbrev,
63
+ unicode=config.unicode,
64
+ list_items=config.list_items,
65
+ spellcheck=config.spellcheck,
66
+ )
67
+
68
+
69
+ def _format_issue(issue, base_dir: Path) -> str:
70
+ path = _rel_path(issue.path, base_dir)
71
+ location = f"{path}:{issue.line}:{issue.col}"
72
+ lines = [f"{location} [{issue.rule_id}] {issue.message}"]
73
+ if issue.snippet:
74
+ lines.append(f" | {issue.snippet}")
75
+ if issue.col > 0:
76
+ caret = " " * (issue.col - 1)
77
+ lines.append(f" | {caret}^")
78
+ return "\n".join(lines)
79
+
80
+
81
+ def _rel_path(path: Path, base_dir: Path) -> str:
82
+ try:
83
+ return os.path.relpath(path, base_dir)
84
+ except ValueError:
85
+ return str(path)