rb-sitemap-xml 0.3.4__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.
@@ -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
+ ]
rb_sitemap_xml/cli.py ADDED
@@ -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()
File without changes
@@ -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
+ )
@@ -0,0 +1,57 @@
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 CliTooOld
10
+ from ..core.models import ProjectConfig
11
+ from ..core.version import DEV_VERSION, installed_version
12
+
13
+
14
+ @output.guard
15
+ def doctor(
16
+ ctx: typer.Context,
17
+ json_output: bool = output.JsonOption,
18
+ quiet: bool = output.QuietOption,
19
+ verbose: bool = output.VerboseOption,
20
+ ) -> None:
21
+ """Запустить диагностику окружения и конфигурации.
22
+
23
+ Проверяет Python, версию CLI, наличие/валидность проектного конфига и
24
+ (если проект найден) совместимость установленного CLI с его
25
+ `cli.min_version` — несовпадение репортится как отдельная проверка,
26
+ а не как ошибка команды.
27
+
28
+ Example: {cli} doctor --json
29
+ """
30
+ checks: list[dict] = [{"name": "python", "ok": True}]
31
+ checks.append({"name": "cli_version", "ok": True, "detail": installed_version() or DEV_VERSION})
32
+
33
+ start = Path(ctx.obj.get("project") or Path.cwd())
34
+ output.vecho(ctx, f"Поиск корня проекта начиная с: {start}")
35
+ root = services.find_project_root(start)
36
+ checks.append({"name": "project", "ok": root is not None, "detail": str(root) if root else None})
37
+
38
+ config: ProjectConfig | None = None
39
+ if root is not None:
40
+ try:
41
+ config = services.load_config(root, check_compat=False)
42
+ checks.append({"name": "config", "ok": True})
43
+ except Exception as exc:
44
+ checks.append({"name": "config", "ok": False, "detail": str(exc)})
45
+ if config is not None:
46
+ try:
47
+ services.check_cli_compat(config)
48
+ checks.append({"name": "cli_compat", "ok": True, "detail": f"проект требует >= {config.cli.min_version}"})
49
+ except CliTooOld as exc:
50
+ checks.append({"name": "cli_compat", "ok": False, "detail": exc.message})
51
+
52
+ all_ok = all(check["ok"] for check in checks)
53
+ output.emit_success(
54
+ ctx,
55
+ {"healthy": all_ok, "checks": checks},
56
+ render_human=lambda data: output.human.render_doctor(data["checks"]),
57
+ )
@@ -0,0 +1,50 @@
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
+
10
+
11
+ @output.guard
12
+ def init(
13
+ ctx: typer.Context,
14
+ name: str = typer.Option(None, "--name", help="Имя проекта (по умолчанию — имя каталога)."),
15
+ force: bool = typer.Option(False, "--force", help="Перезаписать уже существующий config.toml."),
16
+ json_output: bool = output.JsonOption,
17
+ quiet: bool = output.QuietOption,
18
+ verbose: bool = output.VerboseOption,
19
+ ) -> None:
20
+ """Инициализировать проект: создаёт .sitemap-xml/config.toml в целевом каталоге.
21
+
22
+ Для `parse` инициализация не обязательна — она нужна только если вы
23
+ хотите задать значения по умолчанию (timeout/concurrency/user-agent/
24
+ формат вывода) через `config set`, а не передавать их каждый раз флагами.
25
+
26
+ Example: {cli} init
27
+ """
28
+ target = Path(ctx.obj.get("project") or Path.cwd()).resolve()
29
+
30
+ if not force and services.find_project_root(target) == target:
31
+ output.vecho(ctx, f"Найден существующий конфиг: {services.config_path(target)}")
32
+ config = services.load_config(target)
33
+ output.emit_success(
34
+ ctx,
35
+ {"project": config.name, "path": str(target), "already_initialized": True},
36
+ render_human=lambda data: output.human.echo(
37
+ f"Уже инициализирован в {data['path']} (используйте --force для сброса)."
38
+ ),
39
+ )
40
+ return
41
+
42
+ project_name = name or target.name
43
+ config = services.init_project(target, project_name)
44
+ output.emit_success(
45
+ ctx,
46
+ {"project": config.name, "path": str(target), "already_initialized": False},
47
+ render_human=lambda data: output.human.key_values(
48
+ f"Проект инициализирован в {data['path']}", {"name": data["project"]}
49
+ ),
50
+ )
@@ -0,0 +1,105 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import typer
7
+
8
+ from .. import output
9
+ from ..core import services
10
+ from ..core.errors import InvalidArguments
11
+ from ..core.models import PARSE_FIELDS
12
+
13
+
14
+ @output.guard
15
+ def parse(
16
+ ctx: typer.Context,
17
+ domain: str = typer.Argument(..., help="Домен сайта, например example.com."),
18
+ fmt: str = typer.Option(
19
+ None,
20
+ "--format",
21
+ "-f",
22
+ help="Формат вывода данных: json или csv. По умолчанию — json "
23
+ "(или csv, если -o указан с расширением .csv, или конфиг проекта).",
24
+ ),
25
+ output_path: str = typer.Option(None, "--output", "-o", help="Сохранить результат в файл вместо печати в stdout."),
26
+ include: str = typer.Option(None, "--include", "-i", help="Regex: оставить только URL, совпадающие с шаблоном."),
27
+ exclude: str = typer.Option(None, "--exclude", "-x", help="Regex: исключить URL, совпадающие с шаблоном."),
28
+ limit: int = typer.Option(None, "--limit", "-n", help="Ограничить число URL в выводе."),
29
+ timeout: float = typer.Option(None, "--timeout", help="HTTP-таймаут, сек. (по умолчанию 15, либо из конфига)."),
30
+ concurrency: int = typer.Option(
31
+ None, "--concurrency", help="Параллельные запросы при обходе вложенных sitemap (по умолчанию 8)."
32
+ ),
33
+ user_agent: str = typer.Option(None, "--user-agent", help="Кастомный User-Agent."),
34
+ max_sitemaps: int = typer.Option(
35
+ 500, "--max-sitemaps", help="Лимит вложенных sitemap-файлов (защита от зацикленных индексов)."
36
+ ),
37
+ compact: bool = typer.Option(False, "--compact", help="JSON в одну строку без отступов."),
38
+ json_output: bool = output.JsonOption,
39
+ quiet: bool = output.QuietOption,
40
+ verbose: bool = output.VerboseOption,
41
+ ) -> None:
42
+ """Спарсить sitemap.xml сайта DOMAIN.
43
+
44
+ Не требует инициализированного проекта — работает как обычная команда
45
+ с публичными HTTP-запросами. Если рядом есть `.sitemap-xml/config.toml`
46
+ (см. `init`/`config set`), его значения используются как значения по
47
+ умолчанию для timeout/concurrency/user-agent/формата вывода, если
48
+ соответствующий флаг не передан явно.
49
+
50
+ Данные результата (JSON-массив или CSV) печатаются как есть, без
51
+ обёртки `{"ok": ...}` — так вывод остаётся пригодным для пайпов
52
+ (`| jq`, `> file.csv`), как и раньше. `--json`/глобальный `--json`
53
+ равносилен `--format json` для данных, а ошибки при этом всегда
54
+ выводятся в стандартном JSON-конверте `{"ok": false, "error": {...}}`.
55
+
56
+ \b
57
+ sitemap-xml parse example.com
58
+ sitemap-xml parse example.com -i '/blog/' -o blog-urls.csv
59
+ sitemap-xml parse example.com --format csv > urls.csv
60
+
61
+ Example: {cli} parse example.com --include '/blog/' -o blog.csv
62
+ """
63
+ if json_output and fmt not in (None, "json"):
64
+ raise InvalidArguments(f"--json конфликтует с --format {fmt!r} (--json подразумевает JSON-данные).")
65
+ if json_output and fmt is None:
66
+ fmt = "json"
67
+
68
+ services.validate_regex(include, "--include")
69
+ services.validate_regex(exclude, "--exclude")
70
+
71
+ start = Path(ctx.obj.get("project") or Path.cwd())
72
+ project_config = services.find_config_for_parse(start)
73
+ defaults = project_config.defaults if project_config else None
74
+ config_output_format = project_config.output.format if project_config else "json"
75
+
76
+ resolved_timeout = timeout if timeout is not None else (defaults.timeout if defaults else 15.0)
77
+ resolved_concurrency = concurrency if concurrency is not None else (defaults.concurrency if defaults else 8)
78
+ resolved_user_agent = user_agent or (defaults.user_agent if defaults else None)
79
+
80
+ services.validate_parse_params(
81
+ timeout=resolved_timeout, concurrency=resolved_concurrency, limit=limit, max_sitemaps=max_sitemaps
82
+ )
83
+
84
+ entries = services.run_parse(
85
+ domain,
86
+ timeout=resolved_timeout,
87
+ concurrency=resolved_concurrency,
88
+ user_agent=resolved_user_agent,
89
+ include=include,
90
+ exclude=exclude,
91
+ limit=limit,
92
+ max_sitemaps=max_sitemaps,
93
+ )
94
+ rows = [e.model_dump(include=set(PARSE_FIELDS)) for e in entries]
95
+
96
+ resolved_fmt = services.resolve_format(fmt, output_path, config_output_format)
97
+
98
+ if output_path:
99
+ newline = "" if resolved_fmt == "csv" else None
100
+ with open(output_path, "w", newline=newline, encoding="utf-8") as f:
101
+ services.render_rows(rows, resolved_fmt, compact=compact, stream=f)
102
+ if not quiet:
103
+ typer.echo(f"Сохранено {len(rows)} URL в {output_path}", err=True)
104
+ else:
105
+ services.render_rows(rows, resolved_fmt, compact=compact, stream=sys.stdout)
@@ -0,0 +1,68 @@
1
+ from __future__ import annotations
2
+
3
+ from importlib import resources
4
+ from pathlib import Path
5
+
6
+ import typer
7
+
8
+ from .. import output
9
+
10
+ app = output.group("Установить агентский skill этого CLI для AI-инструментов.")
11
+
12
+ _PACKAGE_NAME = __name__.split(".")[0]
13
+ # Публичное имя инструмента — под ним живут каталоги skill'ов, а не под
14
+ # именем Python-пакета.
15
+ _SKILL_NAME = "sitemap-xml"
16
+
17
+ # Где каждый AI-инструмент ищет личные (уровня пользователя) и проектные skill'ы.
18
+ _TOOL_TARGETS = {
19
+ "claude-code": {
20
+ "user": Path.home() / ".claude" / "skills" / _SKILL_NAME,
21
+ "project": Path(".claude") / "skills" / _SKILL_NAME,
22
+ },
23
+ "agents": {
24
+ "user": Path.home() / ".agents" / "skills" / _SKILL_NAME,
25
+ "project": Path(".agents") / "skills" / _SKILL_NAME,
26
+ },
27
+ }
28
+
29
+
30
+ def _skill_content() -> str:
31
+ return resources.files(f"{_PACKAGE_NAME}.data").joinpath("SKILL.md").read_text()
32
+
33
+
34
+ @app.command("install")
35
+ @output.guard
36
+ def install(
37
+ ctx: typer.Context,
38
+ tool: str = typer.Option(
39
+ "claude-code",
40
+ "--tool",
41
+ help=f"Целевой AI-инструмент: один из {', '.join(_TOOL_TARGETS)}.",
42
+ ),
43
+ project: bool = typer.Option(
44
+ False, "--project", help="Установить в текущий проект вместо каталога уровня пользователя."
45
+ ),
46
+ json_output: bool = output.JsonOption,
47
+ quiet: bool = output.QuietOption,
48
+ ) -> None:
49
+ """Скопировать встроенный SKILL.md в каталог skill'ов AI-инструмента.
50
+
51
+ Example: {cli} skill install
52
+ """
53
+ from ..core.errors import InvalidArguments
54
+
55
+ if tool not in _TOOL_TARGETS:
56
+ raise InvalidArguments(f"Неизвестный --tool '{tool}'. Доступные значения: {', '.join(_TOOL_TARGETS)}.")
57
+
58
+ scope = "project" if project else "user"
59
+ target_dir = _TOOL_TARGETS[tool][scope]
60
+ target_dir.mkdir(parents=True, exist_ok=True)
61
+ target_path = target_dir / "SKILL.md"
62
+ target_path.write_text(_skill_content())
63
+
64
+ output.emit_success(
65
+ ctx,
66
+ {"tool": tool, "scope": scope, "path": str(target_path)},
67
+ render_human=lambda d: output.human.echo(f"Skill для '{d['tool']}' ({d['scope']}) установлен в {d['path']}"),
68
+ )
@@ -0,0 +1,43 @@
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
+
10
+
11
+ @output.guard
12
+ def status(
13
+ ctx: typer.Context,
14
+ json_output: bool = output.JsonOption,
15
+ quiet: bool = output.QuietOption,
16
+ verbose: bool = output.VerboseOption,
17
+ ) -> None:
18
+ """Показать статус текущего проекта.
19
+
20
+ Example: {cli} status --json
21
+ """
22
+ start = Path(ctx.obj.get("project") or Path.cwd())
23
+ root = services.require_project_root(start)
24
+ output.vecho(ctx, f"Найден корень проекта: {root}")
25
+ config = services.load_config(root)
26
+ output.emit_success(
27
+ ctx,
28
+ {
29
+ "project": config.name,
30
+ "path": str(root),
31
+ "defaults": config.defaults.model_dump(),
32
+ "output_format": config.output.format,
33
+ },
34
+ render_human=lambda data: output.human.key_values(
35
+ "Статус",
36
+ {
37
+ "project": data["project"],
38
+ "path": data["path"],
39
+ "defaults": data["defaults"],
40
+ "output_format": data["output_format"],
41
+ },
42
+ ),
43
+ )
File without changes