rb-hostme 0.6.18__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 (111) hide show
  1. rb_hostme-0.6.18/.gitignore +26 -0
  2. rb_hostme-0.6.18/.python-version +1 -0
  3. rb_hostme-0.6.18/LICENSE +21 -0
  4. rb_hostme-0.6.18/PKG-INFO +115 -0
  5. rb_hostme-0.6.18/README.md +97 -0
  6. rb_hostme-0.6.18/pyproject.toml +187 -0
  7. rb_hostme-0.6.18/src/rb_hostme/__init__.py +1 -0
  8. rb_hostme-0.6.18/src/rb_hostme/_distribution.py +24 -0
  9. rb_hostme-0.6.18/src/rb_hostme/cli.py +180 -0
  10. rb_hostme-0.6.18/src/rb_hostme/commands/__init__.py +9 -0
  11. rb_hostme-0.6.18/src/rb_hostme/commands/auth.py +70 -0
  12. rb_hostme-0.6.18/src/rb_hostme/commands/describe.py +34 -0
  13. rb_hostme-0.6.18/src/rb_hostme/commands/doctor.py +42 -0
  14. rb_hostme-0.6.18/src/rb_hostme/commands/domain.py +85 -0
  15. rb_hostme-0.6.18/src/rb_hostme/commands/help.py +141 -0
  16. rb_hostme-0.6.18/src/rb_hostme/commands/server.py +104 -0
  17. rb_hostme-0.6.18/src/rb_hostme/commands/site.py +310 -0
  18. rb_hostme-0.6.18/src/rb_hostme/commands/skill.py +138 -0
  19. rb_hostme-0.6.18/src/rb_hostme/commands/target.py +98 -0
  20. rb_hostme-0.6.18/src/rb_hostme/config.py +470 -0
  21. rb_hostme-0.6.18/src/rb_hostme/core/__init__.py +1 -0
  22. rb_hostme-0.6.18/src/rb_hostme/core/data_files.py +20 -0
  23. rb_hostme-0.6.18/src/rb_hostme/core/deps.py +165 -0
  24. rb_hostme-0.6.18/src/rb_hostme/core/doctor.py +141 -0
  25. rb_hostme-0.6.18/src/rb_hostme/core/errors.py +234 -0
  26. rb_hostme-0.6.18/src/rb_hostme/core/opencli.py +285 -0
  27. rb_hostme-0.6.18/src/rb_hostme/core/services.py +798 -0
  28. rb_hostme-0.6.18/src/rb_hostme/core/skills.py +64 -0
  29. rb_hostme-0.6.18/src/rb_hostme/core/version.py +89 -0
  30. rb_hostme-0.6.18/src/rb_hostme/credentials/__init__.py +1 -0
  31. rb_hostme-0.6.18/src/rb_hostme/credentials/health.py +109 -0
  32. rb_hostme-0.6.18/src/rb_hostme/credentials/manager.py +93 -0
  33. rb_hostme-0.6.18/src/rb_hostme/data/SKILL.md +222 -0
  34. rb_hostme-0.6.18/src/rb_hostme/data/__init__.py +9 -0
  35. rb_hostme-0.6.18/src/rb_hostme/data/nginx-defaults.conf +64 -0
  36. rb_hostme-0.6.18/src/rb_hostme/output/__init__.py +354 -0
  37. rb_hostme-0.6.18/src/rb_hostme/output/human.py +34 -0
  38. rb_hostme-0.6.18/src/rb_hostme/output/json.py +14 -0
  39. rb_hostme-0.6.18/src/rb_hostme/providers/__init__.py +9 -0
  40. rb_hostme-0.6.18/src/rb_hostme/providers/ftp.py +178 -0
  41. rb_hostme-0.6.18/src/rb_hostme/providers/http.py +23 -0
  42. rb_hostme-0.6.18/src/rb_hostme/providers/ssh.py +338 -0
  43. rb_hostme-0.6.18/src/rb_hostme/providers/webinoly.py +598 -0
  44. rb_hostme-0.6.18/src/rb_hostme/templates/maintenance/index.html +31 -0
  45. rb_hostme-0.6.18/tests/__init__.py +1 -0
  46. rb_hostme-0.6.18/tests/conftest.py +130 -0
  47. rb_hostme-0.6.18/tests/contracts/fixtures.yaml +11 -0
  48. rb_hostme-0.6.18/tests/contracts/schema.json +89 -0
  49. rb_hostme-0.6.18/tests/contracts/tools-catalog/hostme.yaml +20 -0
  50. rb_hostme-0.6.18/tests/data/contracts/windmill-serp.yaml +106 -0
  51. rb_hostme-0.6.18/tests/data/opencli.schema.json +350 -0
  52. rb_hostme-0.6.18/tests/e2e/conftest.py +119 -0
  53. rb_hostme-0.6.18/tests/e2e/test_from_zero.py +55 -0
  54. rb_hostme-0.6.18/tests/e2e/test_php_site.py +44 -0
  55. rb_hostme-0.6.18/tests/e2e/test_ssh_layer.py +43 -0
  56. rb_hostme-0.6.18/tests/e2e/test_webinoly_adapter.py +63 -0
  57. rb_hostme-0.6.18/tests/e2e/test_webinoly_smoke.py +58 -0
  58. rb_hostme-0.6.18/tests/help_allowlist.txt +3 -0
  59. rb_hostme-0.6.18/tests/snapshots/describe.json +1834 -0
  60. rb_hostme-0.6.18/tests/snapshots/help/_deploy.txt +31 -0
  61. rb_hostme-0.6.18/tests/snapshots/help/auth-status.txt +24 -0
  62. rb_hostme-0.6.18/tests/snapshots/help/auth.txt +13 -0
  63. rb_hostme-0.6.18/tests/snapshots/help/config.txt +34 -0
  64. rb_hostme-0.6.18/tests/snapshots/help/debug.txt +16 -0
  65. rb_hostme-0.6.18/tests/snapshots/help/describe.txt +18 -0
  66. rb_hostme-0.6.18/tests/snapshots/help/doctor.txt +21 -0
  67. rb_hostme-0.6.18/tests/snapshots/help/domain-add.txt +19 -0
  68. rb_hostme-0.6.18/tests/snapshots/help/domain-default.txt +14 -0
  69. rb_hostme-0.6.18/tests/snapshots/help/domain-list.txt +11 -0
  70. rb_hostme-0.6.18/tests/snapshots/help/domain-remove.txt +14 -0
  71. rb_hostme-0.6.18/tests/snapshots/help/domain.txt +16 -0
  72. rb_hostme-0.6.18/tests/snapshots/help/help.txt +11 -0
  73. rb_hostme-0.6.18/tests/snapshots/help/http-auth.txt +18 -0
  74. rb_hostme-0.6.18/tests/snapshots/help/list.txt +11 -0
  75. rb_hostme-0.6.18/tests/snapshots/help/maintenance.txt +20 -0
  76. rb_hostme-0.6.18/tests/snapshots/help/open.txt +14 -0
  77. rb_hostme-0.6.18/tests/snapshots/help/revs.txt +14 -0
  78. rb_hostme-0.6.18/tests/snapshots/help/rollback.txt +21 -0
  79. rb_hostme-0.6.18/tests/snapshots/help/rollfore.txt +15 -0
  80. rb_hostme-0.6.18/tests/snapshots/help/server-add.txt +20 -0
  81. rb_hostme-0.6.18/tests/snapshots/help/server-init.txt +17 -0
  82. rb_hostme-0.6.18/tests/snapshots/help/server-list.txt +11 -0
  83. rb_hostme-0.6.18/tests/snapshots/help/server-remove.txt +18 -0
  84. rb_hostme-0.6.18/tests/snapshots/help/server-update.txt +17 -0
  85. rb_hostme-0.6.18/tests/snapshots/help/server.txt +17 -0
  86. rb_hostme-0.6.18/tests/snapshots/help/skill-install.txt +18 -0
  87. rb_hostme-0.6.18/tests/snapshots/help/skill-list.txt +13 -0
  88. rb_hostme-0.6.18/tests/snapshots/help/skill.txt +13 -0
  89. rb_hostme-0.6.18/tests/snapshots/help/target-add.txt +28 -0
  90. rb_hostme-0.6.18/tests/snapshots/help/target-list.txt +11 -0
  91. rb_hostme-0.6.18/tests/snapshots/help/target-remove.txt +18 -0
  92. rb_hostme-0.6.18/tests/snapshots/help/target.txt +16 -0
  93. rb_hostme-0.6.18/tests/snapshots/help/teardown.txt +19 -0
  94. rb_hostme-0.6.18/tests/test_cli.py +31 -0
  95. rb_hostme-0.6.18/tests/test_contract_runner.py +257 -0
  96. rb_hostme-0.6.18/tests/test_contracts.py +397 -0
  97. rb_hostme-0.6.18/tests/test_describe.py +181 -0
  98. rb_hostme-0.6.18/tests/test_detach.py +161 -0
  99. rb_hostme-0.6.18/tests/test_help.py +502 -0
  100. rb_hostme-0.6.18/tests/test_skills.py +179 -0
  101. rb_hostme-0.6.18/tests/unit/test_auth.py +163 -0
  102. rb_hostme-0.6.18/tests/unit/test_cli.py +173 -0
  103. rb_hostme-0.6.18/tests/unit/test_config.py +340 -0
  104. rb_hostme-0.6.18/tests/unit/test_data_dirs.py +167 -0
  105. rb_hostme-0.6.18/tests/unit/test_doctor.py +70 -0
  106. rb_hostme-0.6.18/tests/unit/test_errors.py +48 -0
  107. rb_hostme-0.6.18/tests/unit/test_ftp.py +245 -0
  108. rb_hostme-0.6.18/tests/unit/test_output.py +232 -0
  109. rb_hostme-0.6.18/tests/unit/test_services.py +388 -0
  110. rb_hostme-0.6.18/tests/unit/test_ssh.py +346 -0
  111. rb_hostme-0.6.18/tests/unit/test_webinoly.py +590 -0
@@ -0,0 +1,26 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .DS_Store
5
+ .pytest_cache/
6
+ .coverage
7
+ *.egg-info/
8
+ dist/
9
+ build/
10
+
11
+ # Черновики с учётными данными (см. AGENTS.md) — никогда не коммитить
12
+ vps.txt
13
+ *.env
14
+ .env*
15
+ .ruff_cache/
16
+ htmlcov/
17
+ # mutmut's working copy and results (uv run --group mutation mutmut run)
18
+ mutants/
19
+ # Local env files hold keys: keys never go into the repo (the gate's secret scan)
20
+ .env
21
+ .env.*
22
+ # The root lines Antagor adds
23
+ .DS_Store
24
+ Thumbs.db
25
+ .pdm-build/
26
+ .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,115 @@
1
+ Metadata-Version: 2.5
2
+ Name: rb-hostme
3
+ Version: 0.6.18
4
+ Summary: Deploy static sites and PHP to your own VPS: a personal surge.sh alike.
5
+ Project-URL: Repository, https://homeserver.tailee01ab.ts.net:3000/bolandeu/hostme
6
+ Author-email: Roman Bolandau <r.bolandau@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.14
10
+ Requires-Dist: keyring>=25.0.0
11
+ Requires-Dist: packaging>=24.0
12
+ Requires-Dist: platformdirs>=4.4
13
+ Requires-Dist: rb-credentials<1,>=0.7.1
14
+ Requires-Dist: rich>=15.0.0
15
+ Requires-Dist: ruamel-yaml>=0.19.1
16
+ Requires-Dist: typer<0.28,>=0.27.2
17
+ Description-Content-Type: text/markdown
18
+
19
+ # hostme
20
+
21
+ Личный аналог [surge.sh](https://surge.sh/): CLI на Python/uv, который одной командой деплоит статические сайты и простые PHP-скрипты на собственные VPS (через [Webinoly](https://webinoly.com/)), с поддержкой нескольких серверов и доменов.
22
+
23
+ Документация по продукту — **[docs/usage/](docs/usage/)**: что такое hostme и чего он не делает, серверы и домены, настройки и реестр, контракт для агента, безопасность. Решения и их причины — **[docs/adr/](docs/adr/)**. Для AI-агентов, работающих в этом репозитории — **[AGENTS.md](AGENTS.md)**.
24
+
25
+ ## Установка
26
+
27
+ Из Gitea-реестра (пакет релизится туда):
28
+
29
+ ```
30
+ ```
31
+
32
+ Или из git-тега, на любой машине:
33
+
34
+ ```
35
+ uv tool install "rb-hostme @ git+https://homeserver.tailee01ab.ts.net:3000/bolandeu/rb_hostme.git@vX.Y.Z"
36
+ ```
37
+
38
+ `vX.Y.Z` — последний тег релиза (только из тега, не из ветки). Дистрибутив
39
+ называется `rb-hostme`, команда — `hostme`; обновление — `uv tool upgrade rb-hostme`.
40
+
41
+ При разработке самого `hostme` (в этом репозитории) — editable-режим, чтобы
42
+ изменения в коде подхватывались без переустановки:
43
+
44
+ ```
45
+ uv tool install --editable .
46
+ ```
47
+
48
+ **После изменения `[project.scripts]` в `pyproject.toml`** editable-режим
49
+ не перегенерирует уже установленный launcher-скрипт сам — обязательно
50
+ `uv tool install --editable . --force`, иначе `hostme` из PATH продолжит
51
+ звать старый entry point (см. AGENTS.md).
52
+
53
+ После любого из вариантов `hostme` доступен как обычная команда в PATH из
54
+ любой директории.
55
+
56
+ ## Требования к серверу перед `server add`/`server init`
57
+
58
+ - Чистый Ubuntu Server 24.04/26.04 LTS (arm64 или x86_64), минимум 512MB RAM — `hostme server init` сам ставит Webinoly (nginx+php-fpm), но ОС должна быть готова заранее
59
+ - Открытые порты (входящие как минимум): `22/TCP` (SSH), `80/TCP` и `443/TCP+UDP` (HTTP/HTTPS/HTTP3). Подробный список (включая исходящие для почты/GPG) — [docs/usage/webinoly.md](docs/usage/webinoly.md), раздел «Установка стека»
60
+ - SSH-пользователь (обычно `root`) должен пускать по ключу (`ssh_key` в `hostme server add`) и иметь **passwordless sudo** — `hostme`/Webinoly не умеют отвечать на запрос пароля sudo
61
+ - Перед первым `server init`: `sudo apt update && sudo apt -y upgrade` (и по-хорошему `reboot`) — руками, `hostme` этого не делает
62
+
63
+ ## Деплой
64
+
65
+ ```
66
+ hostme <path> [domain] [--server NAME]
67
+ ```
68
+
69
+ Заливка файлов идёт через `rsync --delete`: webroot на сервере становится точным зеркалом локальной папки на момент деплоя. Если файл убрать из `path` и задеплоить снова — на сервере он тоже исчезнет. Это сделано намеренно, чтобы повторный деплой был идемпотентным и не копил старые файлы — но по той же причине деплой не той (пустой/неверной) папки снесёт существующий контент сайта на сервере.
70
+
71
+ ## Где лежат настройки и данные
72
+
73
+ - Настройки — `~/.config/hostme/`: `servers.yaml` (серверы и target'ы), `settings.yaml`.
74
+ - Данные (пишет сам hostme) — `platformdirs.user_data_dir("hostme")` (macOS
75
+ `~/Library/Application Support/hostme`, Linux `~/.local/share/hostme`):
76
+ `sites.yaml` + `sites.d/`, `target-backups/<target>/<ts>/` — снепшоты target-сайта перед деплоем.
77
+ До v0.4.0 всё лежало в `~/.config/hostme` — переносится само при первом запуске.
78
+ - Хранение бэкапов (`settings.yaml`, по умолчанию `keep: 5` без срока; самый свежий не удаляется):
79
+
80
+ ```yaml
81
+ target_backups:
82
+ keep: 5 # последние N на target
83
+ max_age_days: 30 # и/или удалять старше X дней
84
+ ```
85
+
86
+ - `hostme doctor` показывает путь, размер и политику бэкапов.
87
+
88
+ ## Для агентов
89
+
90
+ `hostme --ai` печатает встроенный SKILL.md (конвенции: `--json`, exit-коды,
91
+ `--dry-run`/`--confirm`, правила для `--target`); `hostme skill install`
92
+ кладёт его в `~/.claude/skills/hostme/`. Список команд — голый `hostme`,
93
+ полный справочник с примерами — `hostme help` (`--json` для агентов).
94
+
95
+ ## Разработка
96
+
97
+ Архитектура — по [cli-builder](https://homeserver.tailee01ab.ts.net:3000/bolandeu/cli-generator):
98
+ `commands/` (только разбор аргументов) → `core/` (сервисы, ошибки) →
99
+ `providers/` (ssh/rsync/lftp/Webinoly — всё, что выходит за пределы процесса),
100
+ `output/` (human/json, guard), `credentials/` (пароли target'ов: env
101
+ `HOSTME_DEPLOY_<TARGET>_PASSWORD`, иначе OS keychain `hostme:<target>`; `auth status`).
102
+
103
+ Проверка — один гейт: `gate check` на этой машине, команда —
104
+ `[publish] gate_command` в `.agents/antagor/antagor.toml`. Из корня пакета:
105
+
106
+ ```
107
+ gate check
108
+ ```
109
+
110
+ (lock, ruff, ty, pytest с порогом покрытия и снапшотами `--help`, сверка
111
+ `[[tool.rb.external]]` с кодом, сборка+установка колеса, правила Standard,
112
+ gitleaks и osv-scanner, если установлены). Работа и релизы — через Antagor
113
+ (`antagor publish` пишет CHANGELOG.md и ставит тег). Версия только из
114
+ git-тега, `version =` в pyproject нет. План и прогресс — в Antagor: `antagor board`
115
+ показывает задачи и их статусы, идеи — `antagor idea list`; файла-бэклога в репозитории нет.
@@ -0,0 +1,97 @@
1
+ # hostme
2
+
3
+ Личный аналог [surge.sh](https://surge.sh/): CLI на Python/uv, который одной командой деплоит статические сайты и простые PHP-скрипты на собственные VPS (через [Webinoly](https://webinoly.com/)), с поддержкой нескольких серверов и доменов.
4
+
5
+ Документация по продукту — **[docs/usage/](docs/usage/)**: что такое hostme и чего он не делает, серверы и домены, настройки и реестр, контракт для агента, безопасность. Решения и их причины — **[docs/adr/](docs/adr/)**. Для AI-агентов, работающих в этом репозитории — **[AGENTS.md](AGENTS.md)**.
6
+
7
+ ## Установка
8
+
9
+ Из Gitea-реестра (пакет релизится туда):
10
+
11
+ ```
12
+ ```
13
+
14
+ Или из git-тега, на любой машине:
15
+
16
+ ```
17
+ uv tool install "rb-hostme @ git+https://homeserver.tailee01ab.ts.net:3000/bolandeu/rb_hostme.git@vX.Y.Z"
18
+ ```
19
+
20
+ `vX.Y.Z` — последний тег релиза (только из тега, не из ветки). Дистрибутив
21
+ называется `rb-hostme`, команда — `hostme`; обновление — `uv tool upgrade rb-hostme`.
22
+
23
+ При разработке самого `hostme` (в этом репозитории) — editable-режим, чтобы
24
+ изменения в коде подхватывались без переустановки:
25
+
26
+ ```
27
+ uv tool install --editable .
28
+ ```
29
+
30
+ **После изменения `[project.scripts]` в `pyproject.toml`** editable-режим
31
+ не перегенерирует уже установленный launcher-скрипт сам — обязательно
32
+ `uv tool install --editable . --force`, иначе `hostme` из PATH продолжит
33
+ звать старый entry point (см. AGENTS.md).
34
+
35
+ После любого из вариантов `hostme` доступен как обычная команда в PATH из
36
+ любой директории.
37
+
38
+ ## Требования к серверу перед `server add`/`server init`
39
+
40
+ - Чистый Ubuntu Server 24.04/26.04 LTS (arm64 или x86_64), минимум 512MB RAM — `hostme server init` сам ставит Webinoly (nginx+php-fpm), но ОС должна быть готова заранее
41
+ - Открытые порты (входящие как минимум): `22/TCP` (SSH), `80/TCP` и `443/TCP+UDP` (HTTP/HTTPS/HTTP3). Подробный список (включая исходящие для почты/GPG) — [docs/usage/webinoly.md](docs/usage/webinoly.md), раздел «Установка стека»
42
+ - SSH-пользователь (обычно `root`) должен пускать по ключу (`ssh_key` в `hostme server add`) и иметь **passwordless sudo** — `hostme`/Webinoly не умеют отвечать на запрос пароля sudo
43
+ - Перед первым `server init`: `sudo apt update && sudo apt -y upgrade` (и по-хорошему `reboot`) — руками, `hostme` этого не делает
44
+
45
+ ## Деплой
46
+
47
+ ```
48
+ hostme <path> [domain] [--server NAME]
49
+ ```
50
+
51
+ Заливка файлов идёт через `rsync --delete`: webroot на сервере становится точным зеркалом локальной папки на момент деплоя. Если файл убрать из `path` и задеплоить снова — на сервере он тоже исчезнет. Это сделано намеренно, чтобы повторный деплой был идемпотентным и не копил старые файлы — но по той же причине деплой не той (пустой/неверной) папки снесёт существующий контент сайта на сервере.
52
+
53
+ ## Где лежат настройки и данные
54
+
55
+ - Настройки — `~/.config/hostme/`: `servers.yaml` (серверы и target'ы), `settings.yaml`.
56
+ - Данные (пишет сам hostme) — `platformdirs.user_data_dir("hostme")` (macOS
57
+ `~/Library/Application Support/hostme`, Linux `~/.local/share/hostme`):
58
+ `sites.yaml` + `sites.d/`, `target-backups/<target>/<ts>/` — снепшоты target-сайта перед деплоем.
59
+ До v0.4.0 всё лежало в `~/.config/hostme` — переносится само при первом запуске.
60
+ - Хранение бэкапов (`settings.yaml`, по умолчанию `keep: 5` без срока; самый свежий не удаляется):
61
+
62
+ ```yaml
63
+ target_backups:
64
+ keep: 5 # последние N на target
65
+ max_age_days: 30 # и/или удалять старше X дней
66
+ ```
67
+
68
+ - `hostme doctor` показывает путь, размер и политику бэкапов.
69
+
70
+ ## Для агентов
71
+
72
+ `hostme --ai` печатает встроенный SKILL.md (конвенции: `--json`, exit-коды,
73
+ `--dry-run`/`--confirm`, правила для `--target`); `hostme skill install`
74
+ кладёт его в `~/.claude/skills/hostme/`. Список команд — голый `hostme`,
75
+ полный справочник с примерами — `hostme help` (`--json` для агентов).
76
+
77
+ ## Разработка
78
+
79
+ Архитектура — по [cli-builder](https://homeserver.tailee01ab.ts.net:3000/bolandeu/cli-generator):
80
+ `commands/` (только разбор аргументов) → `core/` (сервисы, ошибки) →
81
+ `providers/` (ssh/rsync/lftp/Webinoly — всё, что выходит за пределы процесса),
82
+ `output/` (human/json, guard), `credentials/` (пароли target'ов: env
83
+ `HOSTME_DEPLOY_<TARGET>_PASSWORD`, иначе OS keychain `hostme:<target>`; `auth status`).
84
+
85
+ Проверка — один гейт: `gate check` на этой машине, команда —
86
+ `[publish] gate_command` в `.agents/antagor/antagor.toml`. Из корня пакета:
87
+
88
+ ```
89
+ gate check
90
+ ```
91
+
92
+ (lock, ruff, ty, pytest с порогом покрытия и снапшотами `--help`, сверка
93
+ `[[tool.rb.external]]` с кодом, сборка+установка колеса, правила Standard,
94
+ gitleaks и osv-scanner, если установлены). Работа и релизы — через Antagor
95
+ (`antagor publish` пишет CHANGELOG.md и ставит тег). Версия только из
96
+ git-тега, `version =` в pyproject нет. План и прогресс — в Antagor: `antagor board`
97
+ показывает задачи и их статусы, идеи — `antagor idea list`; файла-бэклога в репозитории нет.
@@ -0,0 +1,187 @@
1
+ [project]
2
+ name = "rb-hostme"
3
+ # Version comes from the git tag vX.Y.Z (uv-dynamic-versioning) — never add `version =`.
4
+ dynamic = ["version"]
5
+ description = "Deploy static sites and PHP to your own VPS: a personal surge.sh alike."
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Roman Bolandau", email = "r.bolandau@gmail.com" }]
10
+ requires-python = ">=3.14"
11
+ dependencies = [
12
+ "rb-credentials>=0.7.1,<1",
13
+ "keyring>=25.0.0",
14
+ "packaging>=24.0",
15
+ "platformdirs>=4.4",
16
+ "rich>=15.0.0",
17
+ "ruamel-yaml>=0.19.1",
18
+ "typer>=0.27.2,<0.28",
19
+ ]
20
+
21
+ [project.scripts]
22
+ hostme = "rb_hostme.cli:main"
23
+
24
+ [project.urls]
25
+ Repository = "https://homeserver.tailee01ab.ts.net:3000/bolandeu/hostme"
26
+
27
+ [build-system]
28
+ requires = ["hatchling", "uv-dynamic-versioning"]
29
+ build-backend = "hatchling.build"
30
+
31
+ [tool.hatch.version]
32
+ source = "uv-dynamic-versioning"
33
+
34
+ [tool.uv-dynamic-versioning]
35
+ vcs = "git"
36
+ style = "pep440"
37
+ fallback-version = "0.0.0"
38
+
39
+ [tool.uv]
40
+ # Rebuild the editable install when a commit or tag moves, so `--version` follows the tag.
41
+ cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }]
42
+
43
+ [tool.hatch.build.targets.sdist]
44
+ # What a release must not carry: the agent's own files, the forge configs and the dev tooling. The wheel is
45
+ # narrow already (`packages = ["src/<pkg>"]`); this is about the sdist, which is otherwise a copy of the repo.
46
+ exclude = [
47
+ "/.agents",
48
+ "/.claude",
49
+ "/.claude-plugin",
50
+ "/.gitea",
51
+ "/.github",
52
+ "/docs",
53
+ "/scripts",
54
+ "/uv.lock",
55
+ "/AGENTS.md",
56
+ "/CLAUDE.md",
57
+ "/CODING_STANDARDS.md",
58
+ "/CONTEXT.md",
59
+ "/.copier-answers.yml",
60
+ "^\\.gitignore$",
61
+ "/.gitleaks.toml",
62
+ ]
63
+
64
+ [tool.hatch.build.targets.wheel]
65
+ packages = ["src/rb_hostme"]
66
+
67
+ [tool.hatch.build.targets.wheel.force-include]
68
+ # Установленный CLI читает [[tool.rb.external]] отсюда (стандарт §12).
69
+ "pyproject.toml" = "hostme/_pyproject.toml"
70
+
71
+ [dependency-groups]
72
+ # Mutation testing, run now and then and before big releases — not in the gate:
73
+ # `uv run --group mutation mutmut run`, then `mutmut results` / `mutmut browse`.
74
+ # Needs fork(): macOS/Linux (WSL on Windows). Settings: [tool.mutmut] below.
75
+ mutation = ["mutmut>=3.3"]
76
+ dev = [
77
+ "jsonschema>=4.23",
78
+ "pytest>=9.1.1",
79
+ "pyyaml>=6.0", # .copier-answers.yml, the CI workflow, tests/contracts/*.yaml
80
+ "pytest-cov>=7.1.0",
81
+ "ruff>=0.16.6",
82
+ "syrupy>=4.8",
83
+ "ty>=0.0.80",
84
+ ]
85
+
86
+ # External (non-Python) dependencies — every CLI this tool runs (require_cli,
87
+ # shutil.which, subprocess with a literal program, npx). The gate checks this
88
+ # list against the code both ways; doctor and require_cli read it at runtime;
89
+ # the tools catalog reads it (the Standard, Technology).
90
+ [[tool.rb.external]]
91
+ name = "ssh"
92
+ required = true
93
+ check = "ssh -V"
94
+ why = "команды Webinoly на своих серверах, проверка доступа в auth status --check"
95
+
96
+ [[tool.rb.external]]
97
+ name = "rsync"
98
+ required = true
99
+ why = "заливка сайтов на свои серверы и на ssh-target'ы, бэкап target'а перед деплоем"
100
+
101
+ [[tool.rb.external]]
102
+ name = "lftp"
103
+ required = false
104
+ why = "заливка на ftp/sftp-target'ы (нужен, только если такие target'ы зарегистрированы)"
105
+
106
+ [[tool.rb.external]]
107
+ name = "sshpass"
108
+ required = false
109
+ check = "sshpass -V"
110
+ why = "ssh-target'ы с паролем вместо ключа (пароль через SSHPASS, не в argv)"
111
+
112
+ # Where sysadmin's tool-updater installs this tool after its first tag. The
113
+ # installation is sysadmin's; this section only says where. homeserver: users
114
+ # to install for (empty = build and publish only); mac: install on the Mac.
115
+ # extras (optional): the extras to install with, e.g. extras = ["browser"].
116
+ [tool.rb.install]
117
+ homeserver = ["rbtools"]
118
+ mac = true
119
+
120
+ [tool.cli-generator]
121
+ # Where scripts/check_command_docstrings.py (called by the project's checks)
122
+ # looks for commands: a glob or a list of globs, relative to the repo root.
123
+ commands = ["src/rb_hostme/commands/*.py"]
124
+ # gate check (the gate): extras to install before ruff/ty/pytest.
125
+ # gate_extras = ["browser"]
126
+
127
+ [tool.pytest.ini_options]
128
+ # Only tests/: mutmut leaves a copy of the tree in mutants/.
129
+ testpaths = ["tests"]
130
+ addopts = "--cov --cov-report=term-missing:skip-covered"
131
+ # tests/test_help.py keeps help snapshots at tests/snapshots/help/<command>.txt
132
+ # (the Standard, Commands), not in syrupy's own `__snapshots__/<test file>/` layout, so
133
+ # syrupy warns it "can not relate" each file to its test. It can — by name.
134
+ filterwarnings = ["ignore:(?s).*Can not relate snapshot:UserWarning"]
135
+ markers = [
136
+ "e2e: реальный сервер по SSH (HOSTME_E2E_HOST), по умолчанию пропускается",
137
+ ]
138
+
139
+ [tool.mutmut]
140
+ source_paths = ["src/rb_hostme"]
141
+ also_copy = ["scripts/", "pyproject.toml"] # tests read them (test_scripts.py, the distribution checks)
142
+ pytest_add_cli_args = ["--no-cov"] # fail_under would kill every mutant
143
+ # only_mutate = ["*/core/normalize.py"] # one module at a time on a big tool
144
+
145
+ [tool.coverage.run]
146
+ source = ["src"]
147
+ # sysmon (default on 3.14) keeps a record per recompiled code object; Typer recompiles annotations on every invoke, so memory grows.
148
+ core = "ctrace"
149
+
150
+ [tool.coverage.report]
151
+ # Порог — по факту на момент рефакторинга на cli-builder-архитектуру.
152
+ # Поднимать по мере добавления тестов, никогда не опускать (новая команда
153
+ # без тестов должна падать именно здесь — это осознанный «пинок»).
154
+ fail_under = 65
155
+ show_missing = true
156
+
157
+ [tool.ruff]
158
+ line-length = 120
159
+
160
+ [tool.ruff.lint]
161
+ select = ["E4", "E7", "E9", "F", "I", "UP", "B", "SIM", "RUF", "S", "BLE", "T20", "TID251"]
162
+ # RUF001-003 («похожие на латиницу» символы) — весь текст проекта на русском.
163
+ ignore = ["RUF001", "RUF002", "RUF003"]
164
+
165
+ [tool.ruff.lint.per-file-ignores]
166
+ # assert — суть теста; тестовые пароли/subprocess в e2e — тоже намеренно; print в строках кода; httpx для моков
167
+ "tests/*" = ["S101", "S105", "S106", "S108", "S603", "S607", "T201", "TID251", "BLE001"]
168
+ "scripts/*" = ["S603", "S607", "T201"] # subprocess with fixed argv lists (git, uv), no shell; scripts print to the console
169
+ # providers/ — весь смысл слоя в запуске ssh/rsync/lftp: argv-списком, без shell;
170
+ # бинарь ищется в PATH намеренно (уважаем окружение пользователя, кроссплатформенно)
171
+ "src/*/providers/*" = ["S603", "S607", "TID251"]
172
+
173
+ [tool.ruff.lint.flake8-tidy-imports.banned-api]
174
+ "httpx".msg = "Call external APIs through providers/ (subclass providers.HttpProvider)."
175
+
176
+ [tool.ruff.lint.flake8-bugbear]
177
+ # Typer's `param: T = typer.Option(...)` style is a call in a default on purpose.
178
+ extend-immutable-calls = ["typer.Option", "typer.Argument"]
179
+
180
+ [tool.ty.terminal]
181
+ # Only errors fail the gate; recent ty (>= 0.0.84) otherwise exits 1 on warnings too.
182
+ error-on-warning = false
183
+
184
+
185
+ # Siblings resolve from disk: a version range in `dependencies` plus a `path` source, never an index.
186
+ [tool.uv.sources]
187
+ rb-credentials = { path = "../rb-credentials", editable = true }
@@ -0,0 +1 @@
1
+ """The package: its modules are the CLI (`cli`), its commands, the output and the core they share."""
@@ -0,0 +1,24 @@
1
+ """The distribution name and the tool namespace copier writes from its answers, because an editable install cannot map
2
+ this import package to its distribution at runtime.
3
+ """
4
+
5
+ # Rendered by copier from the `dist_name` answer: the [project] name in
6
+ # pyproject.toml (`rb-<slug>`, the Standard, Technology), which may differ from this
7
+ # import package's name. importlib.metadata finds this package's version,
8
+ # summary and console script by it; an editable install (`uv sync`) can't be
9
+ # mapped from package to distribution at runtime, so it is written down here.
10
+ # tests/test_cli.py fails if it drifts from pyproject.toml.
11
+ DIST_NAME = "rb-hostme"
12
+ # The previous distribution name during a rename: an install made
13
+ # under it (not yet reinstalled) still finds its own version. Drop it once
14
+ # every machine has the new name.
15
+ DIST_NAME_LEGACY: str | None = "hostme"
16
+ # The command name (`cli_name`) as an identifier: the namespace of this tool's
17
+ # shared-database names (core/db.py) — table prefix `<TOOL>_`, env var
18
+ # `<TOOL>_DATABASE_URL`, Alembic table `alembic_version_<TOOL>`. Written down,
19
+ # not derived at runtime: a bare source run falls back to the package name,
20
+ # and a table name must never depend on how the tool was started.
21
+ TOOL = "hostme"
22
+ # The cli-generator release this project was generated or last updated from
23
+ # (copier's `_commit`), for `describe --json`; None for a project not made by copier.
24
+ TEMPLATE_VERSION: str | None = "v1.27.3"
@@ -0,0 +1,180 @@
1
+ """The root Typer app: global options, the command groups and the optional commands a generated package has, wired
2
+ together, and the console-script entry point.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import sys
8
+ from typing import Annotated
9
+
10
+ import typer
11
+ from rich.markup import escape as rich_escape
12
+
13
+ from . import config, output
14
+ from .commands import auth, doctor, domain, server, site, target
15
+ from .commands import help as help_cmd
16
+ from .core.errors import CliError
17
+ from .core.version import DEV_VERSION, installed_version, optional_module, package_summary
18
+
19
+ _PACKAGE_NAME = __name__.split(".")[0]
20
+ # Optional parts (copier questions, dropped by _exclude): each one ships a module that registers its
21
+ # commands and global options. Probed at runtime, so this file needs no template logic.
22
+ PARTS = ("project", "skill", "describe", "db")
23
+
24
+ # Форма команд копирует surge.sh (AGENTS.md): `hostme <path> [domain]` для деплоя,
25
+ # `hostme <domain> <subcommand>` для управления — без промежуточных слов вроде "deploy".
26
+ # Typer/Click умеет только статическое дерево подкоманд, поэтому реальный argv
27
+ # переписывается в explicit-подкоманды (_translate_argv) до того, как его увидит Typer.
28
+ _TOP_LEVEL_COMMANDS = {
29
+ "auth",
30
+ "server",
31
+ "domain",
32
+ "target",
33
+ "skill",
34
+ "describe",
35
+ "list",
36
+ "open",
37
+ "doctor",
38
+ "help",
39
+ "--ai",
40
+ "--version",
41
+ "--help",
42
+ "-h",
43
+ }
44
+ _DOMAIN_SUBCOMMANDS = {"teardown", "config", "auth", "ssl", "debug", "revs", "rollback", "rollfore", "maintenance"}
45
+ # `auth` занят дважды: `hostme auth status` — отчёт о доступах (стандарт §8, одинаковый
46
+ # у всех tools), `hostme <domain> auth` — HTTP Basic Auth сайта. Доменная форма
47
+ # уходит во внутреннее имя команды.
48
+ _DOMAIN_SUBCOMMAND_TARGETS = {"auth": "http-auth"}
49
+ # Глобальные флаги — только на уровне root-callback (Typer не даёт их объявить
50
+ # и там, и на каждой команде одновременно без дублирования на 15+ функций), но
51
+ # агент не обязан помнить, что они идут именно ДО команды — conventions.md
52
+ # (cli-builder) требует, чтобы `<cli> <command> --json` работало наравне с
53
+ # `<cli> --json <command>`. Раз argv и так целиком переписывается под
54
+ # surge-грамматику ниже, тут же вынимаем эти флаги из ЛЮБОЙ позиции и
55
+ # перекладываем в префикс — не только с начала, как раньше.
56
+ _GLOBAL_PREFIX_FLAGS = {"--json", "--non-interactive", "--dry-run", "--quiet", "--verbose"}
57
+
58
+
59
+ def _translate_argv(argv: list[str]) -> list[str]:
60
+ prefix: list[str] = [a for a in argv if a in _GLOBAL_PREFIX_FLAGS]
61
+ args = [a for a in argv if a not in _GLOBAL_PREFIX_FLAGS]
62
+
63
+ if not args or args[0] in _TOP_LEVEL_COMMANDS:
64
+ return prefix + args
65
+
66
+ if len(args) >= 2 and args[1] in _DOMAIN_SUBCOMMANDS:
67
+ domain, subcmd, *rest = args
68
+ return [*prefix, _DOMAIN_SUBCOMMAND_TARGETS.get(subcmd, subcmd), domain, *rest]
69
+
70
+ # `hostme teardown --help` — просьба о справке по teardown, а не деплой папки
71
+ # с именем "teardown" (иначе показывалась бы справка деплоя, сбивая с толку).
72
+ if args[0] in _DOMAIN_SUBCOMMANDS and (len(args) == 1 or args[1] in ("-h", "--help")):
73
+ return prefix + args
74
+
75
+ return [*prefix, "_deploy", *args]
76
+
77
+
78
+ # Голый `hostme` — точка входа для человека и агента: имя + версия + описание,
79
+ # затем команды с первой строкой docstring. Без no_args_is_help (он выходит с
80
+ # кодом 2) — main_options() ниже печатает справку и выходит с 0 (conventions.md).
81
+ app = typer.Typer(
82
+ cls=output.RootGroup, # a usage error under --json is the error envelope
83
+ name="hostme",
84
+ help=f"hostme {installed_version() or DEV_VERSION} — {package_summary() or 'деплой сайтов на свои VPS.'}",
85
+ epilog=rich_escape(help_cmd.GRAMMAR_NOTE),
86
+ invoke_without_command=True,
87
+ context_settings={"help_option_names": ["-h", "--help"]},
88
+ )
89
+
90
+ app.add_typer(server.app, name="server")
91
+ app.add_typer(domain.app, name="domain")
92
+ app.add_typer(target.app, name="target")
93
+ app.add_typer(auth.app, name="auth")
94
+
95
+ app.command("_deploy", hidden=True)(site.deploy)
96
+ app.command("list")(site.list_)
97
+ app.command("open")(site.open_)
98
+ app.command("revs")(site.revs)
99
+ app.command("rollback")(site.rollback)
100
+ app.command("rollfore")(site.rollfore)
101
+ app.command("maintenance")(site.maintenance)
102
+ app.command("teardown")(site.teardown)
103
+ app.command("http-auth")(site.auth)
104
+ app.command("config")(site.site_config)
105
+ app.command("debug")(site.debug)
106
+ app.command("doctor")(doctor.doctor)
107
+ app.command("help")(help_cmd.help_cmd)
108
+ for part in PARTS:
109
+ if module := optional_module(f"{_PACKAGE_NAME}.commands.{part}"):
110
+ module.register(app)
111
+
112
+
113
+ def _version_callback(value: bool) -> None:
114
+ if not value:
115
+ return
116
+ typer.echo(installed_version() or DEV_VERSION)
117
+ raise typer.Exit()
118
+
119
+
120
+ @app.callback(invoke_without_command=True)
121
+ def main_options(
122
+ ctx: typer.Context,
123
+ json_output: Annotated[bool, typer.Option("--json", help="Машиночитаемый вывод (для агентов).")] = False,
124
+ quiet: Annotated[bool, typer.Option("--quiet", help="Не печатать необязательный человеческий вывод.")] = False,
125
+ verbose: Annotated[
126
+ bool, typer.Option("--verbose", help="Диагностика в stderr: какие ssh/rsync/lftp-команды реально запускаются.")
127
+ ] = False,
128
+ non_interactive: Annotated[
129
+ bool, typer.Option("--non-interactive", help="Никогда не спрашивать подтверждение интерактивно.")
130
+ ] = False,
131
+ dry_run: Annotated[
132
+ bool, typer.Option("--dry-run", help="Показать, что сделала бы деструктивная команда, ничего не меняя.")
133
+ ] = False,
134
+ version: Annotated[
135
+ bool, typer.Option("--version", callback=_version_callback, is_eager=True, help="Показать версию и выйти.")
136
+ ] = False,
137
+ ) -> None:
138
+ ctx.ensure_object(dict) # a part's global option (--project) may have put its value here already
139
+ ctx.obj["json"] = json_output
140
+ ctx.obj["quiet"] = quiet
141
+ ctx.obj["verbose"] = verbose
142
+ ctx.obj["non_interactive"] = non_interactive
143
+ ctx.obj["dry_run"] = dry_run
144
+ output.configure_logging(verbose)
145
+ _migrate_legacy_data()
146
+ output.help_if_no_command(ctx)
147
+
148
+
149
+ def _migrate_legacy_data() -> None:
150
+ """До v0.4.0 состояние (sites.yaml, target-backups) лежало в ~/.config/hostme;
151
+ переносим один раз и сообщаем в stderr (stdout занят --json)."""
152
+ moved = config.migrate_legacy_data()
153
+ for line in moved:
154
+ output.human.err_console.print(f"hostme: данные перенесены (стандарт §13): {rich_escape(line)}")
155
+
156
+
157
+ def main() -> None:
158
+ output.force_utf8_streams()
159
+ # Команды уже под output.guard; это страховка для ошибок в самом
160
+ # root-callback (например, не перенеслись данные в _migrate_legacy_data).
161
+ # Здесь мы уже вне Typer — typer.Exit никто не поймает, поэтому sys.exit.
162
+ argv = _translate_argv(sys.argv[1:])
163
+ json_mode = "--json" in argv
164
+ try:
165
+ app(args=argv)
166
+ except CliError as exc:
167
+ output.render_error(exc, json_mode=json_mode)
168
+ sys.exit(exc.exit_code)
169
+ except Exception as exc: # noqa: BLE001 — не даём агенту голый трейсбек
170
+ error = CliError(
171
+ "UNEXPECTED",
172
+ f"{type(exc).__name__}: {exc}",
173
+ action="Повтори с --verbose, чтобы увидеть трейсбек; если повторяется — сообщи вместе с ним.",
174
+ )
175
+ output.render_error(error, json_mode=json_mode)
176
+ sys.exit(error.exit_code)
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()