rb-sitemap-xml 0.3.4__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 (53) hide show
  1. rb_sitemap_xml-0.3.4/.gitignore +16 -0
  2. rb_sitemap_xml-0.3.4/.python-version +1 -0
  3. rb_sitemap_xml-0.3.4/LICENSE +21 -0
  4. rb_sitemap_xml-0.3.4/PKG-INFO +16 -0
  5. rb_sitemap_xml-0.3.4/README.md +184 -0
  6. rb_sitemap_xml-0.3.4/pyproject.toml +116 -0
  7. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/__init__.py +23 -0
  8. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/cli.py +89 -0
  9. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/commands/__init__.py +0 -0
  10. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/commands/auth.py +40 -0
  11. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/commands/build.py +74 -0
  12. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/commands/config.py +87 -0
  13. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/commands/doctor.py +57 -0
  14. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/commands/init.py +50 -0
  15. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/commands/parse.py +105 -0
  16. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/commands/skill.py +68 -0
  17. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/commands/status.py +43 -0
  18. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/core/__init__.py +0 -0
  19. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/core/build.py +90 -0
  20. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/core/client.py +260 -0
  21. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/core/errors.py +86 -0
  22. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/core/models.py +61 -0
  23. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/core/services.py +186 -0
  24. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/core/version.py +23 -0
  25. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/data/SKILL.md +103 -0
  26. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/data/__init__.py +0 -0
  27. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/output/__init__.py +175 -0
  28. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/output/human.py +29 -0
  29. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/output/json.py +9 -0
  30. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/providers/__init__.py +13 -0
  31. rb_sitemap_xml-0.3.4/src/rb_sitemap_xml/providers/sitemap.py +121 -0
  32. rb_sitemap_xml-0.3.4/tests/__init__.py +0 -0
  33. rb_sitemap_xml-0.3.4/tests/conftest.py +12 -0
  34. rb_sitemap_xml-0.3.4/tests/snapshots/help/auth-status.txt +21 -0
  35. rb_sitemap_xml-0.3.4/tests/snapshots/help/auth.txt +12 -0
  36. rb_sitemap_xml-0.3.4/tests/snapshots/help/build.txt +39 -0
  37. rb_sitemap_xml-0.3.4/tests/snapshots/help/config-get.txt +16 -0
  38. rb_sitemap_xml-0.3.4/tests/snapshots/help/config-list.txt +13 -0
  39. rb_sitemap_xml-0.3.4/tests/snapshots/help/config-set.txt +17 -0
  40. rb_sitemap_xml-0.3.4/tests/snapshots/help/config.txt +14 -0
  41. rb_sitemap_xml-0.3.4/tests/snapshots/help/doctor.txt +19 -0
  42. rb_sitemap_xml-0.3.4/tests/snapshots/help/init.txt +20 -0
  43. rb_sitemap_xml-0.3.4/tests/snapshots/help/parse.txt +48 -0
  44. rb_sitemap_xml-0.3.4/tests/snapshots/help/skill-install.txt +16 -0
  45. rb_sitemap_xml-0.3.4/tests/snapshots/help/skill.txt +12 -0
  46. rb_sitemap_xml-0.3.4/tests/snapshots/help/status.txt +14 -0
  47. rb_sitemap_xml-0.3.4/tests/test_auth.py +37 -0
  48. rb_sitemap_xml-0.3.4/tests/test_build.py +84 -0
  49. rb_sitemap_xml-0.3.4/tests/test_cli.py +314 -0
  50. rb_sitemap_xml-0.3.4/tests/test_client.py +205 -0
  51. rb_sitemap_xml-0.3.4/tests/test_errors.py +29 -0
  52. rb_sitemap_xml-0.3.4/tests/test_help.py +126 -0
  53. rb_sitemap_xml-0.3.4/tests/test_providers.py +130 -0
@@ -0,0 +1,16 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .env
8
+ .env.shared
9
+ .claude/settings.local.json
10
+ .pytest_cache/
11
+ .ruff_cache/
12
+ .coverage
13
+ .DS_Store
14
+ Thumbs.db
15
+ .pdm-build/
16
+ .cache/
@@ -0,0 +1 @@
1
+ 3.14
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Roman Bolandau
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,16 @@
1
+ Metadata-Version: 2.5
2
+ Name: rb-sitemap-xml
3
+ Version: 0.3.4
4
+ Summary: Parse and generate sitemap.xml: files, images, hreflang.
5
+ Project-URL: Repository, https://github.com/bolandeu/sitemap-xml
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: defusedxml>=0.7
9
+ Requires-Dist: httpx[socks]>=0.27
10
+ Requires-Dist: loguru>=0.7
11
+ Requires-Dist: packaging>=24.0
12
+ Requires-Dist: platformdirs>=4.2
13
+ Requires-Dist: pydantic>=2.0
14
+ Requires-Dist: rich>=13.7
15
+ Requires-Dist: tomli-w>=1.0
16
+ Requires-Dist: typer<0.29,>=0.27
@@ -0,0 +1,184 @@
1
+ # rb-sitemap-xml
2
+
3
+ Поиск и парсинг sitemap.xml сайта. Ищет через `Sitemap:` в robots.txt, при отсутствии — по стандартным путям (`/sitemap.xml`, `/sitemap_index.xml` и т.п.). Рекурсивно обходит вложенные sitemap-индексы, понимает gzip (`.xml.gz`).
4
+
5
+ Два режима использования: **библиотека** (`rb_sitemap_xml`) и **CLI** (`sitemap-xml`).
6
+
7
+ ---
8
+
9
+ ## Установка
10
+
11
+ ```bash
12
+ # Локальная разработка (editable — изменения в коде сразу видны)
13
+ uv sync
14
+ uv run sitemap-xml parse example.com
15
+
16
+ # Глобальный CLI в системе (editable — исходники обновляются без переустановки)
17
+ uv tool install --editable .
18
+ sitemap-xml parse example.com
19
+
20
+ # После изменения зависимостей/entry points — переустановить:
21
+ uv tool install --editable . --reinstall
22
+
23
+ # С любой другой машины — прямо из GitHub, без публикации в PyPI:
24
+ uv tool install "git+https://github.com/bolandeu/sitemap-xml.git"
25
+ # Конкретный релиз (версия берётся из git-тега):
26
+ uv tool install "git+https://github.com/bolandeu/sitemap-xml.git@v0.1.0"
27
+
28
+ # Зависимость другого нашего пакета — только по тегу:
29
+ # [tool.uv.sources] rb-sitemap-xml = { git = "https://github.com/bolandeu/sitemap-xml", tag = "vX.Y.Z" }
30
+ ```
31
+
32
+ Авторизация не нужна — только публичные HTTP-запросы. `sitemap-xml auth status --json`
33
+ отдаёт отчёт в общем для наших CLI формате с пустым списком `credentials` (выход 0).
34
+
35
+ ---
36
+
37
+ ## CLI
38
+
39
+ ### Основная команда: parse
40
+
41
+ ```bash
42
+ sitemap-xml parse example.com
43
+ sitemap-xml parse example.com --include '/blog/' --output blog-urls.csv
44
+ sitemap-xml parse example.com --format csv > urls.csv
45
+ sitemap-xml parse example.com --json | jq .
46
+ ```
47
+
48
+ | Параметр | Короткий | По умолчанию | Описание |
49
+ |---|---|---|---|
50
+ | `--format` | `-f` | `json` | `json` / `csv`. Если `-o` указан с расширением `.csv` — автоматически `csv`. Если проект инициализирован (`init`) — берётся из `config get output.format`. |
51
+ | `--output` | `-o` | — (печать в stdout) | Сохранить результат в файл вместо stdout. |
52
+ | `--include` | `-i` | — | Regex: оставить только URL, совпадающие с шаблоном. |
53
+ | `--exclude` | `-x` | — | Regex: исключить URL, совпадающие с шаблоном. |
54
+ | `--limit` | `-n` | — | Ограничить число URL в выводе. |
55
+ | `--timeout` | — | `15.0` | HTTP-таймаут, сек. Если не передан — берётся из конфига проекта, иначе `15.0`. |
56
+ | `--concurrency` | — | `8` | Параллельные запросы при обходе вложенных sitemap. Если не передан — из конфига проекта, иначе `8`. |
57
+ | `--user-agent` | — | — | Кастомный User-Agent. Если не передан — из конфига проекта. |
58
+ | `--max-sitemaps` | — | `500` | Лимит вложенных sitemap-файлов (защита от аномально больших/зацикленных индексов). |
59
+ | `--compact` | — | — | JSON в одну строку без отступов. |
60
+ | `--json` | — | — | Эквивалент `--format json`; при ошибке — вывод в JSON-конверте `{"ok": false, "error": {...}}` вместо цветного текста. |
61
+
62
+ `parse` не требует инициализированного проекта — работает как обычная команда с публичными HTTP-запросами. `init`/`config` нужны только если хочется задать значения по умолчанию, не повторяя флаги при каждом вызове.
63
+
64
+ `--timeout`/`--concurrency`/`--limit`/`--max-sitemaps` валидируются (должны быть положительными) — при некорректном значении команда завершается с exit-кодом `2` (`INVALID_ARGUMENTS`), а не зависает или падает трейсбэком.
65
+
66
+ Логи (`loguru`) идут в **stderr**, результат `parse` — в **stdout**, поэтому вывод можно пайпить напрямую: `sitemap-xml parse example.com 2>/dev/null | jq .`
67
+
68
+ Ошибки (sitemap не найден, некорректный regex и т.п.) — понятное сообщение и ненулевой exit code, без трейсбэка. Под `--json` — структурированный JSON `{"ok": false, "error": {"code": ..., "message": ..., "action": ...}}`.
69
+
70
+ ### Проект и конфигурация
71
+
72
+ ```bash
73
+ sitemap-xml init # создать .sitemap-xml/config.toml
74
+ sitemap-xml status --json # статус текущего проекта
75
+ sitemap-xml config set defaults.timeout 20 # изменить значение по умолчанию
76
+ sitemap-xml config set defaults.concurrency 4
77
+ sitemap-xml config set defaults.user_agent "my-bot/1.0"
78
+ sitemap-xml config set output.format csv
79
+ sitemap-xml config get defaults.timeout
80
+ sitemap-xml config list --json
81
+ ```
82
+
83
+ ### Диагностика и служебные команды
84
+
85
+ ```bash
86
+ sitemap-xml doctor --json # проверка окружения/версии/конфига проекта
87
+ sitemap-xml --version
88
+ sitemap-xml --ai # печатает встроенный SKILL.md для AI-агентов
89
+ sitemap-xml skill install --tool claude-code # установить skill для Claude Code
90
+ sitemap-xml skill install --tool claude-code --project # ...в текущий проект
91
+ ```
92
+
93
+ ### Глобальные опции
94
+
95
+ `--project PATH`, `--json`, `--quiet`, `--verbose`, `--version`, `--ai`, `--help` — доступны и до, и после имени подкоманды (`sitemap-xml --json status` и `sitemap-xml status --json` работают одинаково).
96
+
97
+ ### Коды завершения
98
+
99
+ ```
100
+ 0 Успех
101
+ 1 Общая ошибка (включая ошибку парсинга sitemap)
102
+ 2 Некорректные аргументы
103
+ 3 Ошибка аутентификации (не используется — авторизация не нужна)
104
+ 4 Проект не инициализирован
105
+ 5 Ошибка внешнего сервиса (сеть/таймаут/5xx/429 при загрузке sitemap)
106
+ 6 Установленный CLI старше cli.min_version проекта
107
+ ```
108
+
109
+ ---
110
+
111
+ ## Python-библиотека
112
+
113
+ ### Быстрый старт
114
+
115
+ ```python
116
+ from rb_sitemap_xml import parse_sitemap
117
+
118
+ urls = parse_sitemap("example.com", include=r"/blog/", limit=100)
119
+ for u in urls:
120
+ print(u.loc, u.lastmod)
121
+ ```
122
+
123
+ ### Класс SitemapClient
124
+
125
+ ```python
126
+ from rb_sitemap_xml import SitemapClient, filter_entries
127
+
128
+ client = SitemapClient(timeout=15.0, concurrency=8)
129
+
130
+ # sync
131
+ entries = client.parse_sync("example.com")
132
+
133
+ # async
134
+ import asyncio
135
+
136
+ entries = asyncio.run(client.parse("example.com"))
137
+
138
+ # только discovery, без парсинга
139
+ sitemap_urls = asyncio.run(client.discover("example.com"))
140
+
141
+ # фильтрация отдельно
142
+ blog_entries = filter_entries(entries, include=r"/blog/", exclude=r"/blog/tag/")
143
+ ```
144
+
145
+ ### SitemapEntry — поля результата
146
+
147
+ ```python
148
+ e.loc # str — URL страницы
149
+ e.lastmod # str | None — дата последнего изменения (как в sitemap, без парсинга формата)
150
+ e.changefreq # str | None
151
+ e.priority # float | None
152
+ ```
153
+
154
+ ---
155
+
156
+ ## Структура данных (JSON/CSV)
157
+
158
+ ```json
159
+ [
160
+ {
161
+ "loc": "https://example.com/blog/post-1",
162
+ "lastmod": "2026-01-01",
163
+ "changefreq": "weekly",
164
+ "priority": 0.8
165
+ }
166
+ ]
167
+ ```
168
+
169
+ ---
170
+
171
+ ## Разработка
172
+
173
+ ```bash
174
+ uv sync
175
+ uv run sitemap-xml doctor
176
+ ```
177
+
178
+ - **Версия** — только из git-тега `vX.Y.Z` (uv-dynamic-versioning); строки `version =` в `pyproject.toml` нет.
179
+ - **Справка команд** — докстринг команды и есть её `--help` (обязательная строка `Example:`, `help=` у каждого
180
+ параметра). Поменял поведение команды — обнови докстринг в том же коммите и `uv run pytest --snapshot-update`
181
+ (снапшоты в `tests/snapshots/help/`).
182
+ - **Релиз** — `antagor publish` (semver и changelog).
183
+
184
+ Гейт (lock, ruff, ty, pytest со снапшотами `--help`, сборка колеса, osv-scanner) — шаг `rb-release check` в `the gate check before a commit`.
@@ -0,0 +1,116 @@
1
+ [project]
2
+ name = "rb-sitemap-xml"
3
+ # Версия — из git-тега vX.Y.Z (uv-dynamic-versioning), никогда не добавлять `version =`.
4
+ dynamic = ["version"]
5
+ description = "Parse and generate sitemap.xml: files, images, hreflang."
6
+ requires-python = ">=3.11"
7
+ dependencies = [
8
+ "httpx[socks]>=0.27",
9
+ "pydantic>=2.0",
10
+ "loguru>=0.7",
11
+ "typer>=0.27,<0.29",
12
+ "rich>=13.7",
13
+ "platformdirs>=4.2",
14
+ "tomli-w>=1.0",
15
+ "packaging>=24.0",
16
+ "defusedxml>=0.7",
17
+ ]
18
+
19
+ [dependency-groups]
20
+ dev = [
21
+ "pytest>=8.0",
22
+ "pytest-asyncio>=0.23",
23
+ "pytest-cov>=5.0",
24
+ "ruff>=0.6",
25
+ "syrupy>=4.8",
26
+ "ty>=0.0.80",
27
+ ]
28
+
29
+ [project.scripts]
30
+ sitemap-xml = "rb_sitemap_xml.cli:main"
31
+
32
+ [project.urls]
33
+ Repository = "https://github.com/bolandeu/sitemap-xml"
34
+
35
+ [build-system]
36
+ requires = ["hatchling", "uv-dynamic-versioning"]
37
+ build-backend = "hatchling.build"
38
+
39
+ [tool.hatch.version]
40
+ source = "uv-dynamic-versioning"
41
+
42
+ [tool.uv-dynamic-versioning]
43
+ vcs = "git"
44
+ style = "pep440"
45
+ fallback-version = "0.0.0"
46
+
47
+ [tool.uv]
48
+ # Пересобирать editable-установку, когда двигается коммит или тег, — чтобы `--version` следовал за тегом.
49
+ cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }]
50
+
51
+ [tool.hatch.build.targets.sdist]
52
+ # What a release must not carry: the agent's own files, the forge configs and the dev tooling. The wheel is
53
+ # narrow already (`packages = ["src/<pkg>"]`); this is about the sdist, which is otherwise a copy of the repo.
54
+ exclude = [
55
+ "/.agents",
56
+ "/.claude",
57
+ "/.claude-plugin",
58
+ "/.gitea",
59
+ "/.github",
60
+ "/docs",
61
+ "/scripts",
62
+ "/uv.lock",
63
+ "/AGENTS.md",
64
+ "/CLAUDE.md",
65
+ "/CODING_STANDARDS.md",
66
+ "/CONTEXT.md",
67
+ "/.copier-answers.yml",
68
+ "^\\.gitignore$",
69
+ "/.gitleaks.toml",
70
+ ]
71
+
72
+ [tool.hatch.build.targets.wheel]
73
+ packages = ["src/rb_sitemap_xml"]
74
+
75
+ [tool.cli-generator]
76
+ # Where scripts/check_command_docstrings.py (проверка тикетов Antagor)
77
+ # looks for commands: a glob or a list of globs, relative to the repo root.
78
+ commands = ["src/rb_sitemap_xml/commands/*.py"]
79
+
80
+ [tool.pytest.ini_options]
81
+ addopts = "--cov --cov-report=term-missing:skip-covered"
82
+
83
+ [tool.coverage.run]
84
+ source = ["src"]
85
+ core = "ctrace"
86
+
87
+ [tool.coverage.report]
88
+ # Нынешний уровень покрытия проекта — не понижать, только повышать.
89
+ fail_under = 90
90
+ show_missing = true
91
+
92
+ [tool.ty.terminal]
93
+ # Only errors fail the gate; recent ty (>= 0.0.84) otherwise exits 1 on warnings too.
94
+ error-on-warning = false
95
+
96
+ [tool.ruff]
97
+ line-length = 120
98
+
99
+ [tool.ruff.lint]
100
+ select = ["E4", "E7", "E9", "F", "I", "UP", "B", "SIM", "RUF", "S"]
101
+ # Кодовая база и комментарии — на русском (см. CLAUDE.md); эти правила
102
+ # считают кириллицу "подозрительной похожестью" на латиницу — шум для
103
+ # каждой русской буквы a/c/e/o/p/x/у.
104
+ ignore = ["RUF001", "RUF002", "RUF003"]
105
+
106
+ [tool.ruff.lint.per-file-ignores]
107
+ "tests/*" = ["S101"] # assert — весь смысл теста
108
+ "scripts/*" = ["S603", "S607"] # subprocess с фиксированными argv (git, uv), без shell
109
+
110
+ [tool.ruff.lint.flake8-bugbear]
111
+ # Стиль Typer `param: T = typer.Option(...)` — вызов в default нарочно.
112
+ extend-immutable-calls = ["typer.Option", "typer.Argument"]
113
+
114
+ [tool.rb.install]
115
+ homeserver = ["rbtools"]
116
+ mac = true # инструмент запускается на Mac
@@ -0,0 +1,23 @@
1
+ """rb-sitemap-xml — парсинг sitemap.xml сайта: библиотека и CLI."""
2
+
3
+ from importlib.metadata import PackageNotFoundError
4
+ from importlib.metadata import version as _pkg_version
5
+
6
+ from .core.build import write_sitemaps
7
+ from .core.client import SitemapClient, SitemapError, filter_entries, parse_sitemap
8
+ from .core.models import SitemapEntry, SitemapFile
9
+
10
+ try:
11
+ __version__ = _pkg_version("rb-sitemap-xml")
12
+ except PackageNotFoundError:
13
+ __version__ = "0.0.0-dev"
14
+
15
+ __all__ = [
16
+ "SitemapClient",
17
+ "SitemapEntry",
18
+ "SitemapError",
19
+ "SitemapFile",
20
+ "filter_entries",
21
+ "parse_sitemap",
22
+ "write_sitemaps",
23
+ ]
@@ -0,0 +1,89 @@
1
+ """CLI-обёртка для rb-sitemap-xml."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib import resources
6
+
7
+ import typer
8
+
9
+ from . import output
10
+ from .commands import auth, build, doctor, init, parse, skill, status
11
+ from .commands import config as config_cmd
12
+ from .core.version import DEV_VERSION, installed_version
13
+
14
+ _PACKAGE_NAME = __name__.split(".")[0]
15
+
16
+ # Голый `<cli>` — точка входа для обнаружения (и человеком, и агентом):
17
+ # имя + версия + описание, затем каждая команда с первой строкой докстринга.
18
+ # no_args_is_help НЕ используем (Click выходит с кодом 2) — за это отвечает
19
+ # main_options() ниже через output.help_if_no_command, с чистым exit 0.
20
+ app = typer.Typer(
21
+ cls=output.RootGroup,
22
+ help=f"sitemap-xml {installed_version() or DEV_VERSION} — "
23
+ "поиск и парсинг sitemap.xml сайта (robots.txt + стандартные пути, вложенные индексы).",
24
+ add_completion=False,
25
+ )
26
+
27
+ app.command(name="parse")(parse.parse)
28
+ app.command(name="build")(build.build)
29
+ app.command(name="init")(init.init)
30
+ app.command(name="status")(status.status)
31
+ app.command(name="doctor")(doctor.doctor)
32
+ app.add_typer(config_cmd.app, name="config")
33
+ app.add_typer(auth.app, name="auth")
34
+ app.add_typer(skill.app, name="skill")
35
+
36
+
37
+ def _version_callback(value: bool) -> None:
38
+ if not value:
39
+ return
40
+ typer.echo(installed_version() or DEV_VERSION)
41
+ raise typer.Exit()
42
+
43
+
44
+ def _ai_callback(value: bool) -> None:
45
+ """Печатает встроенный SKILL.md в stdout.
46
+
47
+ Для агентов, которые могут выполнить этот CLI, но не имеют доступа к
48
+ файловой системе (например, изолированный шелл без доступа к
49
+ установленному SKILL.md).
50
+ """
51
+ if not value:
52
+ return
53
+ content = resources.files(f"{_PACKAGE_NAME}.data").joinpath("SKILL.md").read_text()
54
+ typer.echo(content)
55
+ raise typer.Exit()
56
+
57
+
58
+ @app.callback(invoke_without_command=True)
59
+ def main_options(
60
+ ctx: typer.Context,
61
+ project: str = typer.Option(None, "--project", help="Путь к корню проекта (без поиска вверх от cwd)."),
62
+ json_output: bool = typer.Option(False, "--json", help="Машиночитаемый вывод (JSON)."),
63
+ quiet: bool = typer.Option(False, "--quiet", help="Подавить второстепенный вывод."),
64
+ verbose: bool = typer.Option(False, "--verbose", help="Дополнительная диагностическая информация."),
65
+ version: bool = typer.Option(
66
+ False, "--version", callback=_version_callback, is_eager=True, help="Показать версию и выйти."
67
+ ),
68
+ ai: bool = typer.Option(
69
+ False,
70
+ "--ai",
71
+ callback=_ai_callback,
72
+ is_eager=True,
73
+ help="Напечатать документацию для AI-агентов (встроенный skill) и выйти.",
74
+ ),
75
+ ) -> None:
76
+ ctx.ensure_object(dict)
77
+ ctx.obj["project"] = project
78
+ ctx.obj["json"] = json_output
79
+ ctx.obj["quiet"] = quiet
80
+ ctx.obj["verbose"] = verbose
81
+ output.help_if_no_command(ctx)
82
+
83
+
84
+ def main() -> None:
85
+ app()
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
@@ -0,0 +1,40 @@
1
+ from __future__ import annotations
2
+
3
+ import typer
4
+
5
+ from .. import output
6
+ from ..core import services
7
+ from ..core.errors import InvalidArguments
8
+
9
+ app = output.group("Состояние доступов (у sitemap-xml их нет — только публичные HTTP-запросы).")
10
+
11
+
12
+ @app.command("status")
13
+ @output.guard
14
+ def auth_status(
15
+ ctx: typer.Context,
16
+ check: bool = typer.Option(
17
+ False, "--check", help="Проверить каждый доступ реальным запросом (здесь проверять нечего)."
18
+ ),
19
+ provider: str | None = typer.Option(
20
+ None, "--provider", help="Показать только этого провайдера (у sitemap-xml провайдеров с доступами нет)."
21
+ ),
22
+ json_output: bool = output.JsonOption,
23
+ quiet: bool = output.QuietOption,
24
+ ) -> None:
25
+ """Отчёт о доступах в общем для всех наших CLI формате; значения никогда не печатаются.
26
+
27
+ sitemap-xml не хранит секретов, поэтому `credentials` всегда пуст и код выхода 0
28
+ (с --check тоже). --provider с любым именем — выход 2 (неизвестный провайдер).
29
+ Форма --json — межинструментальный контракт: `tool`, `version`, `checked_at`,
30
+ `credentials[]`.
31
+
32
+ Example: {cli} auth status --check --json
33
+ """
34
+ if provider is not None:
35
+ raise InvalidArguments(f"Неизвестный провайдер '{provider}' (известные: нет).")
36
+ output.emit_success(
37
+ ctx,
38
+ services.auth_report(),
39
+ render_human=lambda _: output.human.echo("Нет провайдеров с доступами."),
40
+ )
@@ -0,0 +1,74 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import typer
9
+
10
+ from .. import output
11
+ from ..core.build import MAX_URLS, write_sitemaps
12
+ from ..core.errors import InvalidArguments
13
+ from ..core.models import SitemapEntry
14
+
15
+
16
+ def _read_entries(source: str) -> list[SitemapEntry]:
17
+ """Записи из файла (или stdin `-`): JSON-массив как у `parse --format json`, CSV с колонкой loc, или список URL."""
18
+ text = sys.stdin.read() if source == "-" else Path(source).read_text(encoding="utf-8")
19
+ stripped = text.lstrip()
20
+ try:
21
+ if stripped.startswith("["):
22
+ return [SitemapEntry.model_validate(item) for item in json.loads(stripped)]
23
+ first = stripped.splitlines()[0] if stripped else ""
24
+ if "loc" in [c.strip() for c in first.split(",")]:
25
+ rows = csv.DictReader(stripped.splitlines())
26
+ return [SitemapEntry(loc=r["loc"], lastmod=r.get("lastmod") or None, changefreq=r.get("changefreq") or None,
27
+ priority=float(r["priority"]) if r.get("priority") else None) for r in rows] # fmt: skip
28
+ except (ValueError, KeyError) as exc:
29
+ raise InvalidArguments(f"Не удалось прочитать записи из {source}: {exc}") from exc
30
+ return [
31
+ SitemapEntry(loc=line.strip()) for line in stripped.splitlines() if line.strip() and not line.startswith("#")
32
+ ]
33
+
34
+
35
+ @output.guard
36
+ def build(
37
+ ctx: typer.Context,
38
+ source: str = typer.Argument(
39
+ ..., help="Файл с URL (или - для stdin): JSON как у parse, CSV с колонкой loc, или URL построчно."
40
+ ),
41
+ out_dir: Path = typer.Option(..., "--out", "-o", help="Каталог, куда записать sitemap.xml (и sitemap-N.xml)."),
42
+ base_url: str = typer.Option(
43
+ None,
44
+ "--base-url",
45
+ help="Адрес каталога на сайте, например https://example.com — нужен индексу, если файлов больше одного.",
46
+ ),
47
+ max_urls: int = typer.Option(
48
+ MAX_URLS, "--max-urls", min=1, max=50_000, help="URL в одном файле (по умолчанию 49 999)."
49
+ ),
50
+ json_output: bool = output.JsonOption,
51
+ quiet: bool = output.QuietOption,
52
+ ) -> None:
53
+ """Сгенерировать sitemap.xml из списка URL.
54
+
55
+ Больше --max-urls записей — файлы sitemap-1.xml, sitemap-2.xml… и индекс sitemap.xml
56
+ со ссылками на них (адреса — от --base-url). Из JSON берутся lastmod, changefreq,
57
+ priority, картинки (images → Image Sitemap) и hreflang-альтернативы (alternates),
58
+ из CSV — lastmod, changefreq, priority.
59
+
60
+ \b
61
+ sitemap-xml build urls.txt -o public/
62
+ sitemap-xml parse example.com --format json | sitemap-xml build - -o out/ --base-url https://example.com
63
+
64
+ JSON: `{ok, files: [путь…], urls}`; индекс — первым. Нет --base-url при нескольких
65
+ файлах, нечитаемый вход — выход 2.
66
+
67
+ Example: {cli} build urls.txt -o public/
68
+ """
69
+ entries = _read_entries(source)
70
+ try:
71
+ files = write_sitemaps(entries, out_dir, base_url=base_url, max_urls=max_urls)
72
+ except ValueError as exc:
73
+ raise InvalidArguments(f"{exc}: укажите --base-url https://ваш-сайт") from exc
74
+ output.emit_success(ctx, {"files": [str(f) for f in files], "urls": len(entries)}, render_human=output.human.built)
@@ -0,0 +1,87 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import typer
6
+
7
+ from .. import output
8
+ from ..core import services
9
+ from ..core.errors import InvalidArguments
10
+ from ..core.models import ProjectConfig
11
+
12
+ app = output.group("Управление конфигурацией проекта.")
13
+
14
+
15
+ @app.command("list")
16
+ @output.guard
17
+ def list_config(
18
+ ctx: typer.Context,
19
+ json_output: bool = output.JsonOption,
20
+ quiet: bool = output.QuietOption,
21
+ ) -> None:
22
+ """Показать все значения конфигурации.
23
+
24
+ Example: {cli} config list
25
+ """
26
+ start = Path(ctx.obj.get("project") or Path.cwd())
27
+ root = services.require_project_root(start)
28
+ config = services.load_config(root)
29
+ data = config.model_dump()
30
+ output.emit_success(ctx, data, render_human=lambda d: output.human.key_values("Конфигурация", d))
31
+
32
+
33
+ @app.command("get")
34
+ @output.guard
35
+ def get_config(
36
+ ctx: typer.Context,
37
+ key: str = typer.Argument(..., help="Ключ через точку, например defaults.timeout"),
38
+ json_output: bool = output.JsonOption,
39
+ quiet: bool = output.QuietOption,
40
+ ) -> None:
41
+ """Получить одно значение конфигурации.
42
+
43
+ Example: {cli} config get defaults.timeout
44
+ """
45
+ start = Path(ctx.obj.get("project") or Path.cwd())
46
+ root = services.require_project_root(start)
47
+ value: object = services.load_config(root).model_dump()
48
+ for part in key.split("."):
49
+ if not isinstance(value, dict) or part not in value:
50
+ raise InvalidArguments(f"Неизвестный ключ конфигурации '{key}'.")
51
+ value = value[part]
52
+ output.emit_success(
53
+ ctx, {"key": key, "value": value}, render_human=lambda d: output.human.echo(f"{d['key']} = {d['value']}")
54
+ )
55
+
56
+
57
+ @app.command("set")
58
+ @output.guard
59
+ def set_config(
60
+ ctx: typer.Context,
61
+ key: str = typer.Argument(..., help="Ключ через точку, например defaults.timeout"),
62
+ value: str = typer.Argument(..., help="Новое значение (сохраняется как строка)."),
63
+ json_output: bool = output.JsonOption,
64
+ quiet: bool = output.QuietOption,
65
+ ) -> None:
66
+ """Установить одно несекретное значение конфигурации.
67
+
68
+ Example: {cli} config set defaults.concurrency 16
69
+ """
70
+ start = Path(ctx.obj.get("project") or Path.cwd())
71
+ root = services.require_project_root(start)
72
+ data = services.load_config(root).model_dump()
73
+ parts = key.split(".")
74
+ target = data
75
+ for part in parts[:-1]:
76
+ if not isinstance(target, dict) or part not in target:
77
+ raise InvalidArguments(f"Неизвестный ключ конфигурации '{key}'.")
78
+ target = target[part]
79
+ if not isinstance(target, dict) or parts[-1] not in target:
80
+ raise InvalidArguments(f"Неизвестный ключ конфигурации '{key}'.")
81
+ target[parts[-1]] = value
82
+ services.save_config(root, ProjectConfig.model_validate(data))
83
+ output.emit_success(
84
+ ctx,
85
+ {"key": key, "value": value},
86
+ render_human=lambda d: output.human.echo(f"Установлено {d['key']} = {d['value']}"),
87
+ )