rb-google-search-console 0.5.5__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.
- rb_google_search_console-0.5.5/.gitignore +21 -0
- rb_google_search_console-0.5.5/LICENSE +21 -0
- rb_google_search_console-0.5.5/PKG-INFO +203 -0
- rb_google_search_console-0.5.5/README.md +184 -0
- rb_google_search_console-0.5.5/pyproject.toml +166 -0
- rb_google_search_console-0.5.5/src/gsc/__init__.py +99 -0
- rb_google_search_console-0.5.5/src/gsc/_distribution.py +24 -0
- rb_google_search_console-0.5.5/src/gsc/cli.py +87 -0
- rb_google_search_console-0.5.5/src/gsc/commands/__init__.py +1 -0
- rb_google_search_console-0.5.5/src/gsc/commands/_common.py +21 -0
- rb_google_search_console-0.5.5/src/gsc/commands/analytics.py +120 -0
- rb_google_search_console-0.5.5/src/gsc/commands/auth.py +41 -0
- rb_google_search_console-0.5.5/src/gsc/commands/config.py +87 -0
- rb_google_search_console-0.5.5/src/gsc/commands/crux.py +135 -0
- rb_google_search_console-0.5.5/src/gsc/commands/describe.py +34 -0
- rb_google_search_console-0.5.5/src/gsc/commands/doctor.py +72 -0
- rb_google_search_console-0.5.5/src/gsc/commands/init.py +51 -0
- rb_google_search_console-0.5.5/src/gsc/commands/inspect.py +91 -0
- rb_google_search_console-0.5.5/src/gsc/commands/pagespeed.py +133 -0
- rb_google_search_console-0.5.5/src/gsc/commands/project.py +55 -0
- rb_google_search_console-0.5.5/src/gsc/commands/sitemaps.py +120 -0
- rb_google_search_console-0.5.5/src/gsc/commands/sites.py +83 -0
- rb_google_search_console-0.5.5/src/gsc/commands/skill.py +138 -0
- rb_google_search_console-0.5.5/src/gsc/commands/status.py +35 -0
- rb_google_search_console-0.5.5/src/gsc/core/__init__.py +1 -0
- rb_google_search_console-0.5.5/src/gsc/core/auth.py +113 -0
- rb_google_search_console-0.5.5/src/gsc/core/crux.py +149 -0
- rb_google_search_console-0.5.5/src/gsc/core/data_files.py +20 -0
- rb_google_search_console-0.5.5/src/gsc/core/deps.py +165 -0
- rb_google_search_console-0.5.5/src/gsc/core/errors.py +197 -0
- rb_google_search_console-0.5.5/src/gsc/core/models.py +292 -0
- rb_google_search_console-0.5.5/src/gsc/core/opencli.py +285 -0
- rb_google_search_console-0.5.5/src/gsc/core/pagespeed.py +234 -0
- rb_google_search_console-0.5.5/src/gsc/core/quota.py +95 -0
- rb_google_search_console-0.5.5/src/gsc/core/search_console.py +388 -0
- rb_google_search_console-0.5.5/src/gsc/core/services.py +134 -0
- rb_google_search_console-0.5.5/src/gsc/core/skills.py +64 -0
- rb_google_search_console-0.5.5/src/gsc/core/version.py +92 -0
- rb_google_search_console-0.5.5/src/gsc/credentials/__init__.py +1 -0
- rb_google_search_console-0.5.5/src/gsc/credentials/manager.py +17 -0
- rb_google_search_console-0.5.5/src/gsc/data/SKILL.md +92 -0
- rb_google_search_console-0.5.5/src/gsc/data/__init__.py +1 -0
- rb_google_search_console-0.5.5/src/gsc/output/__init__.py +282 -0
- rb_google_search_console-0.5.5/src/gsc/output/human.py +29 -0
- rb_google_search_console-0.5.5/src/gsc/output/json.py +11 -0
- rb_google_search_console-0.5.5/src/gsc/providers/__init__.py +14 -0
- rb_google_search_console-0.5.5/src/gsc/providers/google.py +260 -0
- rb_google_search_console-0.5.5/src/gsc/providers/http.py +142 -0
- rb_google_search_console-0.5.5/src/gsc/testing.py +219 -0
- rb_google_search_console-0.5.5/tests/__init__.py +1 -0
- rb_google_search_console-0.5.5/tests/conftest.py +101 -0
- rb_google_search_console-0.5.5/tests/contracts/fixtures.yaml +11 -0
- rb_google_search_console-0.5.5/tests/contracts/schema.json +89 -0
- rb_google_search_console-0.5.5/tests/contracts/tools-catalog/gsc.yaml +20 -0
- rb_google_search_console-0.5.5/tests/data/contracts/windmill-serp.yaml +106 -0
- rb_google_search_console-0.5.5/tests/data/opencli.schema.json +350 -0
- rb_google_search_console-0.5.5/tests/fixtures/psi_ost_term_mobile.json +5470 -0
- rb_google_search_console-0.5.5/tests/help_allowlist.txt +3 -0
- rb_google_search_console-0.5.5/tests/snapshots/describe.json +2084 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/analytics.txt +52 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/auth-login.txt +35 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/auth-logout.txt +18 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/auth-status.txt +24 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/auth.txt +16 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/config-get.txt +17 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/config-list.txt +13 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/config-set.txt +18 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/config.txt +14 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/crux.txt +37 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/describe.txt +18 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/doctor.txt +20 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/init.txt +18 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/inspect.txt +35 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/pagespeed.txt +45 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/site.txt +19 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/sitemap.txt +22 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/sitemaps.txt +19 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/sites.txt +25 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/skill-install.txt +19 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/skill-list.txt +13 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/skill.txt +13 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/status.txt +14 -0
- rb_google_search_console-0.5.5/tests/snapshots/help/submit-sitemap.txt +28 -0
- rb_google_search_console-0.5.5/tests/test_auth.py +310 -0
- rb_google_search_console-0.5.5/tests/test_cli.py +413 -0
- rb_google_search_console-0.5.5/tests/test_commands.py +330 -0
- rb_google_search_console-0.5.5/tests/test_contract_runner.py +257 -0
- rb_google_search_console-0.5.5/tests/test_contracts.py +397 -0
- rb_google_search_console-0.5.5/tests/test_crux.py +160 -0
- rb_google_search_console-0.5.5/tests/test_deps.py +150 -0
- rb_google_search_console-0.5.5/tests/test_describe.py +181 -0
- rb_google_search_console-0.5.5/tests/test_detach.py +161 -0
- rb_google_search_console-0.5.5/tests/test_help.py +495 -0
- rb_google_search_console-0.5.5/tests/test_pagespeed.py +254 -0
- rb_google_search_console-0.5.5/tests/test_project.py +123 -0
- rb_google_search_console-0.5.5/tests/test_providers.py +84 -0
- rb_google_search_console-0.5.5/tests/test_scripts.py +54 -0
- rb_google_search_console-0.5.5/tests/test_search_console.py +395 -0
- rb_google_search_console-0.5.5/tests/test_services.py +64 -0
- rb_google_search_console-0.5.5/tests/test_skills.py +179 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
__pycache__/
|
|
2
|
+
*.py[cod]
|
|
3
|
+
.venv/
|
|
4
|
+
.pytest_cache/
|
|
5
|
+
.ruff_cache/
|
|
6
|
+
dist/
|
|
7
|
+
*.egg-info/
|
|
8
|
+
.python-version
|
|
9
|
+
.coverage
|
|
10
|
+
htmlcov/
|
|
11
|
+
.claude/settings.local.json
|
|
12
|
+
# mutmut's working copy and results (uv run --group mutation mutmut run)
|
|
13
|
+
mutants/
|
|
14
|
+
# Local env files hold keys: keys never go into the repo (the gate's secret scan)
|
|
15
|
+
.env
|
|
16
|
+
.env.*
|
|
17
|
+
# The root lines Antagor adds
|
|
18
|
+
.DS_Store
|
|
19
|
+
Thumbs.db
|
|
20
|
+
.pdm-build/
|
|
21
|
+
.cache/
|
|
@@ -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,203 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: rb-google-search-console
|
|
3
|
+
Version: 0.5.5
|
|
4
|
+
Summary: Google Search Console and PageSpeed Insights: properties, search analytics, URL inspection, sitemaps, page speed.
|
|
5
|
+
Project-URL: Repository, https://homeserver.tailee01ab.ts.net:3000/bolandeu/google-search-console
|
|
6
|
+
Author: bolandeu
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Python: >=3.14
|
|
10
|
+
Requires-Dist: httpx>=0.27
|
|
11
|
+
Requires-Dist: packaging>=24.0
|
|
12
|
+
Requires-Dist: platformdirs>=4.2
|
|
13
|
+
Requires-Dist: pydantic>=2.6
|
|
14
|
+
Requires-Dist: rb-google-oauth<0.4,>=0.2
|
|
15
|
+
Requires-Dist: rich>=13.7
|
|
16
|
+
Requires-Dist: tomli-w>=1.0
|
|
17
|
+
Requires-Dist: typer<0.29,>=0.27
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# gsc — Google Search Console, PageSpeed Insights и CrUX
|
|
21
|
+
|
|
22
|
+
Данные [Search Console](https://search.google.com/search-console) (ресурсы, поисковая
|
|
23
|
+
аналитика, инспекция URL, карты сайта), [PageSpeed Insights](https://pagespeed.web.dev/)
|
|
24
|
+
(Lighthouse, CrUX, все аудиты) и [Chrome UX Report API](https://developer.chrome.com/docs/crux/api)
|
|
25
|
+
(реальные посетители Chrome, история по неделям). Работает как CLI (`gsc analytics …`) и как Python-библиотека
|
|
26
|
+
(`import gsc`). Пакет, импорт и команда — `gsc`. Поддерживаются macOS и Linux.
|
|
27
|
+
|
|
28
|
+
## Установка
|
|
29
|
+
|
|
30
|
+
Из реестра Gitea (пакет выпускается туда):
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Или из git-тега, на любой другой машине:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
uv tool install "rb-google-search-console @ git+https://homeserver.tailee01ab.ts.net:3000/bolandeu/google-search-console.git@vX.Y.Z"
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`vX.Y.Z` — последний тег релиза (ставить из тега, не из ветки). Обновление — `uv tool upgrade rb-google-search-console`.
|
|
42
|
+
Дистрибутив называется `rb-google-search-console` (`gsc` на PyPI — чужой пакет), команда и импорт — `gsc`.
|
|
43
|
+
Стоит старая установка под именем `gsc` — сначала `uv tool uninstall gsc`, иначе два
|
|
44
|
+
инструмента делят одну команду.
|
|
45
|
+
|
|
46
|
+
Как зависимость другого проекта (библиотека): `"rb-google-search-console>=0.5,<0.6"` в `dependencies` и
|
|
47
|
+
`rb-google-search-console = { index = "gitea" }` в `[tool.uv.sources]` (с индексом `gitea` из `[[tool.uv.index]]`).
|
|
48
|
+
|
|
49
|
+
## Доступы
|
|
50
|
+
|
|
51
|
+
Секреты живут только в связке ключей ОС (Keychain) и переменных окружения; `.env` не читается.
|
|
52
|
+
|
|
53
|
+
**Search Console — сервисный аккаунт Google.**
|
|
54
|
+
|
|
55
|
+
1. [Google Cloud Console](https://console.cloud.google.com/iam-admin/serviceaccounts) →
|
|
56
|
+
создать сервисный аккаунт → *Keys → Add key → JSON*; включить *Google Search Console API*.
|
|
57
|
+
2. `gsc auth login --file ~/Downloads/key.json` — JSON ключа кладётся в Keychain, в общий слот
|
|
58
|
+
всех Google-инструментов (`google-oauth:service_account`, пакет
|
|
59
|
+
[google-oauth](https://homeserver.tailee01ab.ts.net:3000/bolandeu/google-oauth)); файл после этого можно удалить.
|
|
60
|
+
3. Email аккаунта (выводится командой) добавить в Search Console → *Настройки → Пользователи
|
|
61
|
+
и разрешения* каждого нужного ресурса. Для `submit-sitemap` — с полными правами.
|
|
62
|
+
|
|
63
|
+
Порядок поиска ключа: `GSC_GOOGLE_SERVICE_ACCOUNT_JSON` → `GOOGLE_SERVICE_ACCOUNT_JSON` →
|
|
64
|
+
`GOOGLE_OAUTH_SERVICE_ACCOUNT_JSON` → `GOOGLE_SERVICE_ACCOUNT_FILE` / `GOOGLE_OAUTH_SERVICE_ACCOUNT_FILE`
|
|
65
|
+
(путь к файлу) → Keychain. Вход общий: ключ, положенный другим Google-инструментом, gsc тоже видит,
|
|
66
|
+
а `gsc auth logout` удаляет его для всех.
|
|
67
|
+
|
|
68
|
+
**PageSpeed Insights — API-ключ** (без ключа квота Google нулевая).
|
|
69
|
+
|
|
70
|
+
1. Cloud Console → *APIs & Services → Library* → включить *PageSpeed Insights API*.
|
|
71
|
+
2. *Credentials → Create credentials → API key*; желательно ограничить ключ этим API.
|
|
72
|
+
3. `gsc auth login --provider pagespeed` (спросит скрытым вводом; Keychain `google-oauth:api_key`)
|
|
73
|
+
или env `GSC_PAGESPEED_API_KEY` (а также `GOOGLE_PAGESPEED_API_KEY`, `GOOGLE_OAUTH_PAGESPEED_API_KEY`).
|
|
74
|
+
4. Для `gsc crux` тот же ключ: включить **Chrome UX Report API** и добавить его в ограничения ключа
|
|
75
|
+
(в списке ограничений видны только уже включённые API). Изменения доходят за 1–5 минут.
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
gsc auth status # что найдено; --check — ещё и спросить у Google, принят ли ключ
|
|
79
|
+
gsc doctor # общая диагностика
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## CLI
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
gsc # версия + список команд
|
|
86
|
+
gsc analytics --help # опции и формат --json
|
|
87
|
+
gsc --ai # памятка для AI-агентов
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
gsc sites # ресурсы аккаунта
|
|
92
|
+
gsc sites --for https://blog.example.com/post # какой ресурс покрывает URL
|
|
93
|
+
gsc analytics -s sc-domain:example.com -d page,query --limit 100
|
|
94
|
+
gsc analytics -s sc-domain:example.com -d page,query --by-day --limit 0 --json > full.json # без предела 50 000
|
|
95
|
+
gsc analytics -s sc-domain:example.com -d query -f page:contains:/blog/ --aggregation byPage
|
|
96
|
+
gsc inspect -s sc-domain:example.com https://example.com/a https://example.com/b
|
|
97
|
+
gsc sitemaps -s sc-domain:example.com
|
|
98
|
+
gsc submit-sitemap -s sc-domain:example.com https://example.com/sitemap.xml --dry-run
|
|
99
|
+
gsc pagespeed https://example.com --strategy desktop --audits # все 4 категории
|
|
100
|
+
gsc crux --origin https://example.com --form-factor phone # реальные посетители, 28 дней
|
|
101
|
+
gsc crux --origin https://example.com --history --periods 40 # тренд по неделям
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`--json` у каждой команды; коды выхода: 0 успех, 2 неверные аргументы / нет доступа к
|
|
105
|
+
ресурсу, 3 нужны доступы, 5 сбой API Google (в т. ч. квота), 6 CLI устарел.
|
|
106
|
+
|
|
107
|
+
В папке проекта ресурс можно закрепить: `gsc init --site sc-domain:example.com` — тогда
|
|
108
|
+
`-s` не нужен (`.gsc/config.toml`, секретов там нет).
|
|
109
|
+
|
|
110
|
+
## Библиотека
|
|
111
|
+
|
|
112
|
+
Публичный API — всё из `gsc.__all__`; меняется только по SemVer. Импорт не лезет в сеть,
|
|
113
|
+
keychain и CLI; ключ читается при первом запросе. Всё синхронное.
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
import gsc
|
|
117
|
+
|
|
118
|
+
sc = gsc.SearchConsole()
|
|
119
|
+
site = sc.property_for("https://example.com/") # доменный ресурс важнее URL-prefix
|
|
120
|
+
start, end = gsc.default_range() # 28 дней с задержкой данных 3 дня
|
|
121
|
+
|
|
122
|
+
rows = sc.iter_search_analytics(
|
|
123
|
+
site,
|
|
124
|
+
start,
|
|
125
|
+
end,
|
|
126
|
+
dimensions=["page", "query"],
|
|
127
|
+
filters=[{"dimension": "page", "operator": "contains", "expression": "/blog/"}],
|
|
128
|
+
aggregation_type="byPage", # byPage / byProperty считают клики и показы по-разному
|
|
129
|
+
by_day=True, # по запросу на день: обходит предел ~50 000 строк на запрос
|
|
130
|
+
)
|
|
131
|
+
for row in rows: # постранично по 25 000
|
|
132
|
+
row.keys["page"], row.keys["date"], row.clicks, row.impressions, row.ctr, row.position
|
|
133
|
+
rows.first_incomplete_date # при data_state="all": с какой даты данные неполные
|
|
134
|
+
|
|
135
|
+
for item in sc.inspect_many(urls, site, limit=500): # темп 600/мин, стоп на дневной квоте
|
|
136
|
+
if isinstance(item, gsc.InspectionError):
|
|
137
|
+
...
|
|
138
|
+
else:
|
|
139
|
+
item.coverage_state, item.google_canonical, item.rich_results
|
|
140
|
+
|
|
141
|
+
ps = gsc.PageSpeed()
|
|
142
|
+
r = ps.analyze("https://example.com/", "mobile") # все 4 категории за одну единицу квоты
|
|
143
|
+
r.scores, r.lab.lcp_ms, r.crux_origin.lcp.good, r.crux_origin_fallback
|
|
144
|
+
a = r.audit("render-blocking-insight")
|
|
145
|
+
a.description, a.categories, a.details, a.metric_savings # категория, вес, группа; советы
|
|
146
|
+
r.stack_packs, r.entities, r.run_warnings, r.runtime_error # платформа, сторонние сервисы, сбои замера
|
|
147
|
+
for res in ps.analyze_many(urls, "mobile", concurrency=4):
|
|
148
|
+
...
|
|
149
|
+
|
|
150
|
+
crux = gsc.CrUX() # тот же ключ; нет данных у Google → None
|
|
151
|
+
crux.record(origin="https://example.com", form_factor="PHONE").metrics["largest_contentful_paint"]
|
|
152
|
+
crux.history("https://example.com/", periods=40).metrics["largest_contentful_paint"].p75 # по неделям
|
|
153
|
+
|
|
154
|
+
gsc.auth_status() # AuthStatus(google="ok"|"missing"|"expired", pagespeed_key=bool, account=…)
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
| Ошибка | Когда | Что делать |
|
|
158
|
+
| --- | --- | --- |
|
|
159
|
+
| `gsc.NotAuthorized` | нет ключа / Google его отверг | `.action` — команда `gsc auth login …` |
|
|
160
|
+
| `gsc.PropertyNotFound` | ресурса нет или нет доступа | добавить email аккаунта в Search Console |
|
|
161
|
+
| `gsc.QuotaExceeded` | квота API; `.daily`, `.retry_after` (с) | ждать `retry_after` |
|
|
162
|
+
| `gsc.ApiError` | сеть, 5xx, прочие 4xx после повторов; `.status` | повторить позже |
|
|
163
|
+
|
|
164
|
+
Все они — подклассы `gsc.CliError` (`.code`, `.message`, `.action`). Ошибки по отдельным URL в
|
|
165
|
+
`inspect_many` / `analyze_many` не прерывают обход — приходят как `InspectionError` /
|
|
166
|
+
`PageSpeedError`.
|
|
167
|
+
|
|
168
|
+
**Тесты без сети:** `gsc.testing.FakeSearchConsole` / `FakePageSpeed` / `FakeCrUX` — те же методы, данные
|
|
169
|
+
задаются моделями (`gsc.Row`, `gsc.Inspection`, `gsc.PageSpeedResult`), исключение в словаре —
|
|
170
|
+
ошибка по этому URL. Разобрать записанный ответ API: `gsc.parse_inspection`, `gsc.parse_pagespeed`,
|
|
171
|
+
`gsc.parse_crux_record`, `gsc.parse_crux_history`.
|
|
172
|
+
|
|
173
|
+
**Чего нет ни в одном API** (только интерфейс Search Console): сводный отчёт об индексировании,
|
|
174
|
+
отчёт Core Web Vitals, ссылки, ручные меры, безопасность, статистика сканирования. Полные данные
|
|
175
|
+
поиска без предела строк — только [выгрузка в BigQuery](https://support.google.com/webmasters/answer/12918484)
|
|
176
|
+
(настраивается в интерфейсе GSC).
|
|
177
|
+
|
|
178
|
+
**Квота URL Inspection** учитывается локально (файл в папке состояния пользователя, общий для
|
|
179
|
+
процессов на машине): `sc.quota_remaining(site)`. Запросы с других машин он не видит — это оценка;
|
|
180
|
+
точный стоп даёт ответ Google 429.
|
|
181
|
+
|
|
182
|
+
## Разработка
|
|
183
|
+
|
|
184
|
+
```bash
|
|
185
|
+
uv sync
|
|
186
|
+
uv run gsc --help
|
|
187
|
+
uv run pytest --snapshot-update # после изменения справки команды — снапшоты tests/snapshots/help/
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Гейт — шаг `gate check` в `.gitea/workflows/ci.yml`: его команду запускают перед каждым коммитом.
|
|
191
|
+
Версия — git-тег (`vX.Y.Z`); работа и релизы идут через Antagor. Архитектура — шаблон
|
|
192
|
+
[cli-generator](https://homeserver.tailee01ab.ts.net:3000/bolandeu/cli-generator); правила для
|
|
193
|
+
агентов-разработчиков — [AGENTS.md](AGENTS.md).
|
|
194
|
+
|
|
195
|
+
### Выбор решений
|
|
196
|
+
|
|
197
|
+
- **HTTP к Google — `httpx` через общий `HttpProvider`**, токен сервисного аккаунта —
|
|
198
|
+
`google-auth`. `google-api-python-client` убран: тяжёлый (discovery, httplib2), свои
|
|
199
|
+
повторы и исключения, хуже тестируется; нужные эндпоинты (webmasters/v3, urlInspection v1,
|
|
200
|
+
PSI v5) — пять REST-вызовов.
|
|
201
|
+
- **Сервисный аккаунт, а не OAuth пользователя** — работает неинтерактивно везде (CI, spider);
|
|
202
|
+
цена — добавлять email аккаунта в каждый ресурс.
|
|
203
|
+
- **MCP-сервер удалён** — агенты вызывают CLI с `--json` по памятке `gsc --ai`.
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# gsc — Google Search Console, PageSpeed Insights и CrUX
|
|
2
|
+
|
|
3
|
+
Данные [Search Console](https://search.google.com/search-console) (ресурсы, поисковая
|
|
4
|
+
аналитика, инспекция URL, карты сайта), [PageSpeed Insights](https://pagespeed.web.dev/)
|
|
5
|
+
(Lighthouse, CrUX, все аудиты) и [Chrome UX Report API](https://developer.chrome.com/docs/crux/api)
|
|
6
|
+
(реальные посетители Chrome, история по неделям). Работает как CLI (`gsc analytics …`) и как Python-библиотека
|
|
7
|
+
(`import gsc`). Пакет, импорт и команда — `gsc`. Поддерживаются macOS и Linux.
|
|
8
|
+
|
|
9
|
+
## Установка
|
|
10
|
+
|
|
11
|
+
Из реестра Gitea (пакет выпускается туда):
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Или из git-тега, на любой другой машине:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
uv tool install "rb-google-search-console @ git+https://homeserver.tailee01ab.ts.net:3000/bolandeu/google-search-console.git@vX.Y.Z"
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`vX.Y.Z` — последний тег релиза (ставить из тега, не из ветки). Обновление — `uv tool upgrade rb-google-search-console`.
|
|
23
|
+
Дистрибутив называется `rb-google-search-console` (`gsc` на PyPI — чужой пакет), команда и импорт — `gsc`.
|
|
24
|
+
Стоит старая установка под именем `gsc` — сначала `uv tool uninstall gsc`, иначе два
|
|
25
|
+
инструмента делят одну команду.
|
|
26
|
+
|
|
27
|
+
Как зависимость другого проекта (библиотека): `"rb-google-search-console>=0.5,<0.6"` в `dependencies` и
|
|
28
|
+
`rb-google-search-console = { index = "gitea" }` в `[tool.uv.sources]` (с индексом `gitea` из `[[tool.uv.index]]`).
|
|
29
|
+
|
|
30
|
+
## Доступы
|
|
31
|
+
|
|
32
|
+
Секреты живут только в связке ключей ОС (Keychain) и переменных окружения; `.env` не читается.
|
|
33
|
+
|
|
34
|
+
**Search Console — сервисный аккаунт Google.**
|
|
35
|
+
|
|
36
|
+
1. [Google Cloud Console](https://console.cloud.google.com/iam-admin/serviceaccounts) →
|
|
37
|
+
создать сервисный аккаунт → *Keys → Add key → JSON*; включить *Google Search Console API*.
|
|
38
|
+
2. `gsc auth login --file ~/Downloads/key.json` — JSON ключа кладётся в Keychain, в общий слот
|
|
39
|
+
всех Google-инструментов (`google-oauth:service_account`, пакет
|
|
40
|
+
[google-oauth](https://homeserver.tailee01ab.ts.net:3000/bolandeu/google-oauth)); файл после этого можно удалить.
|
|
41
|
+
3. Email аккаунта (выводится командой) добавить в Search Console → *Настройки → Пользователи
|
|
42
|
+
и разрешения* каждого нужного ресурса. Для `submit-sitemap` — с полными правами.
|
|
43
|
+
|
|
44
|
+
Порядок поиска ключа: `GSC_GOOGLE_SERVICE_ACCOUNT_JSON` → `GOOGLE_SERVICE_ACCOUNT_JSON` →
|
|
45
|
+
`GOOGLE_OAUTH_SERVICE_ACCOUNT_JSON` → `GOOGLE_SERVICE_ACCOUNT_FILE` / `GOOGLE_OAUTH_SERVICE_ACCOUNT_FILE`
|
|
46
|
+
(путь к файлу) → Keychain. Вход общий: ключ, положенный другим Google-инструментом, gsc тоже видит,
|
|
47
|
+
а `gsc auth logout` удаляет его для всех.
|
|
48
|
+
|
|
49
|
+
**PageSpeed Insights — API-ключ** (без ключа квота Google нулевая).
|
|
50
|
+
|
|
51
|
+
1. Cloud Console → *APIs & Services → Library* → включить *PageSpeed Insights API*.
|
|
52
|
+
2. *Credentials → Create credentials → API key*; желательно ограничить ключ этим API.
|
|
53
|
+
3. `gsc auth login --provider pagespeed` (спросит скрытым вводом; Keychain `google-oauth:api_key`)
|
|
54
|
+
или env `GSC_PAGESPEED_API_KEY` (а также `GOOGLE_PAGESPEED_API_KEY`, `GOOGLE_OAUTH_PAGESPEED_API_KEY`).
|
|
55
|
+
4. Для `gsc crux` тот же ключ: включить **Chrome UX Report API** и добавить его в ограничения ключа
|
|
56
|
+
(в списке ограничений видны только уже включённые API). Изменения доходят за 1–5 минут.
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
gsc auth status # что найдено; --check — ещё и спросить у Google, принят ли ключ
|
|
60
|
+
gsc doctor # общая диагностика
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## CLI
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
gsc # версия + список команд
|
|
67
|
+
gsc analytics --help # опции и формат --json
|
|
68
|
+
gsc --ai # памятка для AI-агентов
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
gsc sites # ресурсы аккаунта
|
|
73
|
+
gsc sites --for https://blog.example.com/post # какой ресурс покрывает URL
|
|
74
|
+
gsc analytics -s sc-domain:example.com -d page,query --limit 100
|
|
75
|
+
gsc analytics -s sc-domain:example.com -d page,query --by-day --limit 0 --json > full.json # без предела 50 000
|
|
76
|
+
gsc analytics -s sc-domain:example.com -d query -f page:contains:/blog/ --aggregation byPage
|
|
77
|
+
gsc inspect -s sc-domain:example.com https://example.com/a https://example.com/b
|
|
78
|
+
gsc sitemaps -s sc-domain:example.com
|
|
79
|
+
gsc submit-sitemap -s sc-domain:example.com https://example.com/sitemap.xml --dry-run
|
|
80
|
+
gsc pagespeed https://example.com --strategy desktop --audits # все 4 категории
|
|
81
|
+
gsc crux --origin https://example.com --form-factor phone # реальные посетители, 28 дней
|
|
82
|
+
gsc crux --origin https://example.com --history --periods 40 # тренд по неделям
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`--json` у каждой команды; коды выхода: 0 успех, 2 неверные аргументы / нет доступа к
|
|
86
|
+
ресурсу, 3 нужны доступы, 5 сбой API Google (в т. ч. квота), 6 CLI устарел.
|
|
87
|
+
|
|
88
|
+
В папке проекта ресурс можно закрепить: `gsc init --site sc-domain:example.com` — тогда
|
|
89
|
+
`-s` не нужен (`.gsc/config.toml`, секретов там нет).
|
|
90
|
+
|
|
91
|
+
## Библиотека
|
|
92
|
+
|
|
93
|
+
Публичный API — всё из `gsc.__all__`; меняется только по SemVer. Импорт не лезет в сеть,
|
|
94
|
+
keychain и CLI; ключ читается при первом запросе. Всё синхронное.
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
import gsc
|
|
98
|
+
|
|
99
|
+
sc = gsc.SearchConsole()
|
|
100
|
+
site = sc.property_for("https://example.com/") # доменный ресурс важнее URL-prefix
|
|
101
|
+
start, end = gsc.default_range() # 28 дней с задержкой данных 3 дня
|
|
102
|
+
|
|
103
|
+
rows = sc.iter_search_analytics(
|
|
104
|
+
site,
|
|
105
|
+
start,
|
|
106
|
+
end,
|
|
107
|
+
dimensions=["page", "query"],
|
|
108
|
+
filters=[{"dimension": "page", "operator": "contains", "expression": "/blog/"}],
|
|
109
|
+
aggregation_type="byPage", # byPage / byProperty считают клики и показы по-разному
|
|
110
|
+
by_day=True, # по запросу на день: обходит предел ~50 000 строк на запрос
|
|
111
|
+
)
|
|
112
|
+
for row in rows: # постранично по 25 000
|
|
113
|
+
row.keys["page"], row.keys["date"], row.clicks, row.impressions, row.ctr, row.position
|
|
114
|
+
rows.first_incomplete_date # при data_state="all": с какой даты данные неполные
|
|
115
|
+
|
|
116
|
+
for item in sc.inspect_many(urls, site, limit=500): # темп 600/мин, стоп на дневной квоте
|
|
117
|
+
if isinstance(item, gsc.InspectionError):
|
|
118
|
+
...
|
|
119
|
+
else:
|
|
120
|
+
item.coverage_state, item.google_canonical, item.rich_results
|
|
121
|
+
|
|
122
|
+
ps = gsc.PageSpeed()
|
|
123
|
+
r = ps.analyze("https://example.com/", "mobile") # все 4 категории за одну единицу квоты
|
|
124
|
+
r.scores, r.lab.lcp_ms, r.crux_origin.lcp.good, r.crux_origin_fallback
|
|
125
|
+
a = r.audit("render-blocking-insight")
|
|
126
|
+
a.description, a.categories, a.details, a.metric_savings # категория, вес, группа; советы
|
|
127
|
+
r.stack_packs, r.entities, r.run_warnings, r.runtime_error # платформа, сторонние сервисы, сбои замера
|
|
128
|
+
for res in ps.analyze_many(urls, "mobile", concurrency=4):
|
|
129
|
+
...
|
|
130
|
+
|
|
131
|
+
crux = gsc.CrUX() # тот же ключ; нет данных у Google → None
|
|
132
|
+
crux.record(origin="https://example.com", form_factor="PHONE").metrics["largest_contentful_paint"]
|
|
133
|
+
crux.history("https://example.com/", periods=40).metrics["largest_contentful_paint"].p75 # по неделям
|
|
134
|
+
|
|
135
|
+
gsc.auth_status() # AuthStatus(google="ok"|"missing"|"expired", pagespeed_key=bool, account=…)
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
| Ошибка | Когда | Что делать |
|
|
139
|
+
| --- | --- | --- |
|
|
140
|
+
| `gsc.NotAuthorized` | нет ключа / Google его отверг | `.action` — команда `gsc auth login …` |
|
|
141
|
+
| `gsc.PropertyNotFound` | ресурса нет или нет доступа | добавить email аккаунта в Search Console |
|
|
142
|
+
| `gsc.QuotaExceeded` | квота API; `.daily`, `.retry_after` (с) | ждать `retry_after` |
|
|
143
|
+
| `gsc.ApiError` | сеть, 5xx, прочие 4xx после повторов; `.status` | повторить позже |
|
|
144
|
+
|
|
145
|
+
Все они — подклассы `gsc.CliError` (`.code`, `.message`, `.action`). Ошибки по отдельным URL в
|
|
146
|
+
`inspect_many` / `analyze_many` не прерывают обход — приходят как `InspectionError` /
|
|
147
|
+
`PageSpeedError`.
|
|
148
|
+
|
|
149
|
+
**Тесты без сети:** `gsc.testing.FakeSearchConsole` / `FakePageSpeed` / `FakeCrUX` — те же методы, данные
|
|
150
|
+
задаются моделями (`gsc.Row`, `gsc.Inspection`, `gsc.PageSpeedResult`), исключение в словаре —
|
|
151
|
+
ошибка по этому URL. Разобрать записанный ответ API: `gsc.parse_inspection`, `gsc.parse_pagespeed`,
|
|
152
|
+
`gsc.parse_crux_record`, `gsc.parse_crux_history`.
|
|
153
|
+
|
|
154
|
+
**Чего нет ни в одном API** (только интерфейс Search Console): сводный отчёт об индексировании,
|
|
155
|
+
отчёт Core Web Vitals, ссылки, ручные меры, безопасность, статистика сканирования. Полные данные
|
|
156
|
+
поиска без предела строк — только [выгрузка в BigQuery](https://support.google.com/webmasters/answer/12918484)
|
|
157
|
+
(настраивается в интерфейсе GSC).
|
|
158
|
+
|
|
159
|
+
**Квота URL Inspection** учитывается локально (файл в папке состояния пользователя, общий для
|
|
160
|
+
процессов на машине): `sc.quota_remaining(site)`. Запросы с других машин он не видит — это оценка;
|
|
161
|
+
точный стоп даёт ответ Google 429.
|
|
162
|
+
|
|
163
|
+
## Разработка
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
uv sync
|
|
167
|
+
uv run gsc --help
|
|
168
|
+
uv run pytest --snapshot-update # после изменения справки команды — снапшоты tests/snapshots/help/
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Гейт — шаг `gate check` в `.gitea/workflows/ci.yml`: его команду запускают перед каждым коммитом.
|
|
172
|
+
Версия — git-тег (`vX.Y.Z`); работа и релизы идут через Antagor. Архитектура — шаблон
|
|
173
|
+
[cli-generator](https://homeserver.tailee01ab.ts.net:3000/bolandeu/cli-generator); правила для
|
|
174
|
+
агентов-разработчиков — [AGENTS.md](AGENTS.md).
|
|
175
|
+
|
|
176
|
+
### Выбор решений
|
|
177
|
+
|
|
178
|
+
- **HTTP к Google — `httpx` через общий `HttpProvider`**, токен сервисного аккаунта —
|
|
179
|
+
`google-auth`. `google-api-python-client` убран: тяжёлый (discovery, httplib2), свои
|
|
180
|
+
повторы и исключения, хуже тестируется; нужные эндпоинты (webmasters/v3, urlInspection v1,
|
|
181
|
+
PSI v5) — пять REST-вызовов.
|
|
182
|
+
- **Сервисный аккаунт, а не OAuth пользователя** — работает неинтерактивно везде (CI, spider);
|
|
183
|
+
цена — добавлять email аккаунта в каждый ресурс.
|
|
184
|
+
- **MCP-сервер удалён** — агенты вызывают CLI с `--json` по памятке `gsc --ai`.
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "rb-google-search-console" # стандарт §10 (`gsc` на PyPI занят); команда `gsc` и пакет `gsc` — прежние
|
|
3
|
+
# Версия — из git-тега vX.Y.Z (uv-dynamic-versioning); строку `version =` не добавлять.
|
|
4
|
+
dynamic = ["version"]
|
|
5
|
+
description = "Google Search Console and PageSpeed Insights: properties, search analytics, URL inspection, sitemaps, page speed."
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [{ name = "bolandeu" }]
|
|
10
|
+
requires-python = ">=3.14"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"typer>=0.27,<0.29",
|
|
13
|
+
"rich>=13.7",
|
|
14
|
+
"pydantic>=2.6",
|
|
15
|
+
"tomli-w>=1.0",
|
|
16
|
+
"platformdirs>=4.2",
|
|
17
|
+
"httpx>=0.27",
|
|
18
|
+
"packaging>=24.0",
|
|
19
|
+
"rb-google-oauth>=0.2,<0.4", # на 0.x минорная версия ломающая; локально резолвится с диска (path)
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.scripts]
|
|
23
|
+
gsc = "gsc.cli:main"
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Repository = "https://homeserver.tailee01ab.ts.net:3000/bolandeu/google-search-console"
|
|
27
|
+
|
|
28
|
+
[build-system]
|
|
29
|
+
requires = ["hatchling", "uv-dynamic-versioning"]
|
|
30
|
+
build-backend = "hatchling.build"
|
|
31
|
+
|
|
32
|
+
[tool.hatch.version]
|
|
33
|
+
source = "uv-dynamic-versioning"
|
|
34
|
+
|
|
35
|
+
[tool.uv-dynamic-versioning]
|
|
36
|
+
vcs = "git"
|
|
37
|
+
style = "pep440"
|
|
38
|
+
fallback-version = "0.0.0"
|
|
39
|
+
|
|
40
|
+
[tool.uv]
|
|
41
|
+
# Rebuild the editable install when a commit or tag moves, so `--version` follows the tag.
|
|
42
|
+
cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }]
|
|
43
|
+
|
|
44
|
+
# rb-google-oauth — общая авторизация Google для всех инструментов (ключи в общем слоте keychain).
|
|
45
|
+
[tool.hatch.build.targets.sdist]
|
|
46
|
+
# What a release must not carry: the agent's own files, the forge configs and the dev tooling. The wheel is
|
|
47
|
+
# narrow already (`packages = ["src/<pkg>"]`); this is about the sdist, which is otherwise a copy of the repo.
|
|
48
|
+
exclude = [
|
|
49
|
+
"/.agents",
|
|
50
|
+
"/.claude",
|
|
51
|
+
"/.claude-plugin",
|
|
52
|
+
"/.gitea",
|
|
53
|
+
"/.github",
|
|
54
|
+
"/docs",
|
|
55
|
+
"/scripts",
|
|
56
|
+
"/uv.lock",
|
|
57
|
+
"/AGENTS.md",
|
|
58
|
+
"/CLAUDE.md",
|
|
59
|
+
"/CODING_STANDARDS.md",
|
|
60
|
+
"/CONTEXT.md",
|
|
61
|
+
"/.copier-answers.yml",
|
|
62
|
+
"^\\.gitignore$",
|
|
63
|
+
"/.gitleaks.toml",
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
# Siblings resolve from disk: a version range in `dependencies` plus a `path` source, never an index.
|
|
67
|
+
[tool.uv.sources]
|
|
68
|
+
rb-google-oauth = { path = "../rb-google-oauth", editable = true }
|
|
69
|
+
|
|
70
|
+
[tool.hatch.build.targets.wheel]
|
|
71
|
+
packages = ["src/gsc"]
|
|
72
|
+
|
|
73
|
+
[dependency-groups]
|
|
74
|
+
# Mutation testing, run now and then and before big releases — not in the gate:
|
|
75
|
+
# `uv run --group mutation mutmut run`, then `mutmut results` / `mutmut browse`.
|
|
76
|
+
# Needs fork(): macOS/Linux (WSL on Windows). Settings: [tool.mutmut] below.
|
|
77
|
+
mutation = ["mutmut>=3.3"]
|
|
78
|
+
dev = [
|
|
79
|
+
"jsonschema>=4.23",
|
|
80
|
+
"pytest>=8.0",
|
|
81
|
+
"pyyaml>=6.0", # .copier-answers.yml, the CI workflow, tests/contracts/*.yaml
|
|
82
|
+
"pytest-cov>=5.0",
|
|
83
|
+
"ruff>=0.6",
|
|
84
|
+
"syrupy>=4.8",
|
|
85
|
+
"ty>=0.0.80",
|
|
86
|
+
]
|
|
87
|
+
|
|
88
|
+
# External (non-Python) dependencies — every CLI this tool runs (require_cli,
|
|
89
|
+
# shutil.which, subprocess with a literal program, npx). The gate checks this
|
|
90
|
+
# list against the code both ways; doctor and require_cli read it at runtime;
|
|
91
|
+
# the tools catalog reads it (the Standard, Technology).
|
|
92
|
+
# [[tool.rb.external]]
|
|
93
|
+
# name = "ffmpeg"
|
|
94
|
+
# required = true # false: the tool works without it (doctor stays healthy)
|
|
95
|
+
# min_version = "6.0" # optional
|
|
96
|
+
# check = "ffmpeg -version" # prints the version; default "<name> --version"
|
|
97
|
+
# why = "transcodes the downloaded videos"
|
|
98
|
+
# detect = false # run via an injected runner / absolute path the gate can't see
|
|
99
|
+
# dist = "rb-serp" # for one of our CLIs: its distribution (default rb-<name>)
|
|
100
|
+
# url = "https://github.com/bolandeu/serp" # its repo: DEPENDENCY_TOO_OLD then prints a pinned install
|
|
101
|
+
|
|
102
|
+
# Where sysadmin's tool-updater installs this tool after its first tag. The
|
|
103
|
+
# installation is sysadmin's; this section only says where. homeserver: users
|
|
104
|
+
# to install for (empty = build and publish only); mac: install on the Mac.
|
|
105
|
+
# extras (optional): the extras to install with, e.g. extras = ["browser"].
|
|
106
|
+
[tool.rb.install]
|
|
107
|
+
homeserver = ["rbtools"]
|
|
108
|
+
mac = true
|
|
109
|
+
|
|
110
|
+
[tool.cli-generator]
|
|
111
|
+
# Where scripts/check_command_docstrings.py (called by the project's checks)
|
|
112
|
+
# looks for commands: a glob or a list of globs, relative to the repo root.
|
|
113
|
+
commands = ["src/gsc/commands/*.py"]
|
|
114
|
+
# gate check (the gate): extras to install before ruff/ty/pytest.
|
|
115
|
+
# gate_extras = ["browser"]
|
|
116
|
+
|
|
117
|
+
[tool.pytest.ini_options]
|
|
118
|
+
# Only tests/: mutmut leaves a copy of the tree in mutants/.
|
|
119
|
+
testpaths = ["tests"]
|
|
120
|
+
addopts = "--cov --cov-report=term-missing:skip-covered"
|
|
121
|
+
# tests/test_help.py keeps help snapshots at tests/snapshots/help/<command>.txt
|
|
122
|
+
# (the Standard, Commands), not in syrupy's own `__snapshots__/<test file>/` layout, so
|
|
123
|
+
# syrupy warns it "can not relate" each file to its test. It can — by name.
|
|
124
|
+
filterwarnings = ["ignore:(?s).*Can not relate snapshot:UserWarning"]
|
|
125
|
+
|
|
126
|
+
[tool.mutmut]
|
|
127
|
+
source_paths = ["src/gsc"]
|
|
128
|
+
also_copy = ["scripts/", "pyproject.toml"] # tests read them (test_scripts.py, the distribution checks)
|
|
129
|
+
pytest_add_cli_args = ["--no-cov"] # fail_under would kill every mutant
|
|
130
|
+
# only_mutate = ["*/core/normalize.py"] # one module at a time on a big tool
|
|
131
|
+
|
|
132
|
+
[tool.coverage.run]
|
|
133
|
+
source = ["src"]
|
|
134
|
+
# sysmon (default on 3.14) keeps a record per recompiled code object; Typer recompiles annotations on every invoke, so memory grows.
|
|
135
|
+
core = "ctrace"
|
|
136
|
+
|
|
137
|
+
[tool.coverage.report]
|
|
138
|
+
# Сейчас ~97%; планку не опускать — новая команда без тестов должна падать здесь.
|
|
139
|
+
fail_under = 95
|
|
140
|
+
show_missing = true
|
|
141
|
+
|
|
142
|
+
[tool.ty.terminal]
|
|
143
|
+
# Only errors fail the gate; recent ty (>= 0.0.84) otherwise exits 1 on warnings too.
|
|
144
|
+
# Legacy code that can't be fixed yet: downgrade specific rules instead of
|
|
145
|
+
# ignoring them, e.g. [tool.ty.rules] possibly-unbound-attribute = "warn".
|
|
146
|
+
error-on-warning = false
|
|
147
|
+
|
|
148
|
+
[tool.ruff]
|
|
149
|
+
line-length = 120
|
|
150
|
+
|
|
151
|
+
[tool.ruff.lint]
|
|
152
|
+
select = ["E4", "E7", "E9", "F", "I", "UP", "B", "SIM", "RUF", "S", "T20", "TID251"]
|
|
153
|
+
# Тексты и комментарии на русском: кириллица — не «похожие символы».
|
|
154
|
+
ignore = ["RUF001", "RUF002", "RUF003"]
|
|
155
|
+
|
|
156
|
+
[tool.ruff.lint.per-file-ignores]
|
|
157
|
+
"tests/*" = ["S101", "T201", "TID251"] # assert is the point of a test; print in code strings; httpx for mocks
|
|
158
|
+
"scripts/*" = ["S603", "S607", "T201"] # subprocess with fixed argv lists (git, uv), no shell; scripts print to the console
|
|
159
|
+
"src/*/providers/*" = ["TID251"] # external APIs live here
|
|
160
|
+
|
|
161
|
+
[tool.ruff.lint.flake8-tidy-imports.banned-api]
|
|
162
|
+
"httpx".msg = "Call external APIs through providers/ (subclass providers.HttpProvider)."
|
|
163
|
+
|
|
164
|
+
[tool.ruff.lint.flake8-bugbear]
|
|
165
|
+
# Typer's `param: T = typer.Option(...)` style is a call in a default on purpose.
|
|
166
|
+
extend-immutable-calls = ["typer.Option", "typer.Argument"]
|