8 Commits

Author SHA1 Message Date
Uber Veng
b395df590e added version number, fixed infinite update loop 2026-05-22 01:26:21 +07:00
Uber Veng
3fafc71cdd Added startup setup 2026-05-22 01:00:57 +07:00
Uber Veng
8fe8af2962 fixed bash script scrolling 2026-05-22 00:31:29 +07:00
Uber Veng
65e189c913 Fixed auto update 2026-05-22 00:24:19 +07:00
Uber Veng
cb85dfa039 v1.0.3 vim motions 2026-05-22 00:10:31 +07:00
Uber Veng
9600e49385 added vim motions 2026-05-22 00:06:30 +07:00
Uber Veng
149246b000 gitignore update 2026-05-21 23:14:07 +07:00
Uber Veng
f2349c9f15 added auto update & changed config path 2026-05-21 23:02:14 +07:00
10 changed files with 829 additions and 180 deletions

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
/target
*txt
.DS_Store
/dist

2
Cargo.lock generated
View File

@@ -1123,7 +1123,7 @@ dependencies = [
[[package]]
name = "ostiary"
version = "1.0.0"
version = "1.0.7"
dependencies = [
"anyhow",
"crossterm",

View File

@@ -1,6 +1,6 @@
[package]
name = "ostiary"
version = "1.0.0"
version = "1.0.7"
edition = "2024"
[dependencies]

272
README.md
View File

@@ -1,47 +1,99 @@
# Ostiary — удалённый запуск скриптов
Консольный клиент с текстовым интерфейсом (TUI) на Rust. Загружает иерархическое меню с сервера и позволяет запускать bash-скрипты, скачивать файлы и выполнять HTTP-запросы прямо из терминала. Все диалоги (выбор из списка, подтверждение, ввод текста) реализованы внутри интерфейса — никаких сырых `read -p` в терминале.
Консольный клиент с текстовым интерфейсом (TUI) на Rust. Загружает иерархическое меню с сервера и позволяет запускать bash-скрипты, скачивать файлы и выполнять HTTP-запросы прямо из терминале. Все диалоги (выбор из списка, подтверждение, ввод текста) реализованы внутри интерфейса — никаких сырых `read -p` в терминале.
---
## Навигация
### Главное меню
| Клавиша | Действие |
|---|---|
| `↑` / `↓` | Перемещение по списку |
| `Enter` | Войти в категорию / запустить действие |
| `Esc` | Выйти из категории / закрыть popup / отменить скрипт |
| `↑` / `↓` или `k` / `j` | Перемещение по списку |
| `Enter` или `l` | Войти в категорию / запустить действие |
| `Esc` или `h` | Выйти из категории |
| `q` | Выйти из приложения |
| `R` | Перезагрузить меню с сервера |
В попапе запущенного скрипта:
### Popup запущенного скрипта
| Клавиша | Действие |
|---|---|
| `↑` / `↓` | Прокрутка лога (если нет активного запроса) / навигация по селектору |
| `↑` / `↓` или `k` / `j` | Прокрутка лога / навигация по селектору |
| `PgUp` / `PgDn` | Прокрутка лога на 10 строк |
| `Y` / `N` | Быстрый ответ на подтверждение |
| `Esc` | Прервать скрипт и закрыть popup |
| `Y` / `N` или `l` / `h` | Ответ на подтверждение (без Enter) |
| `Enter` или `l` | Выбрать пункт селектора / подтвердить |
| `Esc` или `h` | Прервать скрипт и закрыть popup |
> Vim-motions (`j`/`k`/`l`/`h`) отключаются автоматически во время текстового ввода — символы идут в поле ввода как обычно.
---
## Конфигурация
При первом запуске создаётся файл `~/.config/tui-client/config.toml`:
При первом запуске клиент запрашивает URL сервера прямо в терминале — до входа в TUI:
```
╔══════════════════════════════════╗
║ Ostiary — первый запуск ║
╚══════════════════════════════════╝
Конфиг будет сохранён в:
/home/user/.config/ostiary/config.toml
URL сервера меню: https://your-server/api/menu
```
После ввода создаётся `~/.config/ostiary/config.toml`. Его можно редактировать вручную:
```toml
server_url = "http://your-server/api/menu"
server_url = "https://your-server/api/menu"
timeout_sec = 10
update_api = "https://git.example.com/api/v1/repos/user/ostiary"
[theme]
selected_bg = "blue"
```
| Параметр | Описание |
|---|---|
| `server_url` | URL эндпоинта `GET /api/menu` |
| `timeout_sec` | Таймаут HTTP-запросов в секундах |
| `update_api` | Базовый URL Gitea API для проверки обновлений (опционально) |
---
## Автообновление
Если задан `update_api`, при каждом запуске клиент в фоне проверяет наличие нового релиза в Gitea. Если найдена новая стабильная версия — показывает диалог:
```
Доступно обновление
1.0.0 → 1.1.0
Размер: 4.2 МБ
[Y / l] Обновить [N / h / Esc] Пропустить
```
При подтверждении скачивает бинарник, атомарно заменяет текущий исполняемый файл и перезапускает приложение через `execv` (процесс не пересоздаётся, PID остаётся тем же).
### Naming convention ассетов в Gitea
Файлы релиза должны называться по шаблону `{name}-{os}-{arch}`:
| Файл | Платформа |
|---|---|
| `ostiary-linux-x86_64` | Linux 64-bit |
| `ostiary-linux-aarch64` | Linux ARM64 |
| `ostiary-macos-aarch64` | macOS Apple Silicon |
| `ostiary-macos-x86_64` | macOS Intel |
---
## Формат меню (JSON)
Сервер должен отдавать `GET /api/menu` с `Content-Type: application/json`.
Сервер отдаёт `GET /api/menu` с `Content-Type: application/json`.
### Корневая структура
@@ -67,16 +119,9 @@ selected_bg = "blue"
}
```
| Поле | Обязательное | Описание |
|---|---|---|
| `id` | ✓ | Уникальный идентификатор |
| `title` | ✓ | Отображаемое название |
| `description` | — | Текст в нижней панели при выборе |
| `children` | ✓ | Вложенные категории и действия |
### Действие
Отображается с иконкой ``.
Отображается с иконкой ``.
```json
{
@@ -92,13 +137,6 @@ selected_bg = "blue"
}
```
| Поле | Обязательное | Описание |
|---|---|---|
| `id` | ✓ | Уникальный идентификатор |
| `title` | ✓ | Отображаемое название |
| `description` | — | Текст в нижней панели |
| `action` | ✓ | Объект действия |
#### `confirm` и `confirm_message`
Если `confirm: true`, перед запуском появится диалог подтверждения.
@@ -113,7 +151,7 @@ selected_bg = "blue"
"script": "...",
"interaction": "structured",
"confirm": true,
"confirm_message": "Внимание! База данных будет удалена без возможности восстановления. Продолжить?"
"confirm_message": "База данных будет удалена без возможности восстановления. Продолжить?"
}
}
```
@@ -136,13 +174,13 @@ selected_bg = "blue"
| Параметр | Значения | Описание |
|---|---|---|
| `script` | строка | Полный текст bash-скрипта включая shebang |
| `interaction` | `"structured"` / `"terminal"` | Режим взаимодействия (см. ниже) |
| `interaction` | `"structured"` / `"terminal"` | Режим взаимодействия |
| `confirm` | `true` / `false` | Запросить подтверждение перед запуском |
| `confirm_message` | строка | Кастомный текст диалога подтверждения |
**`interaction: "terminal"`** — скрипт запускается как дочерний процесс, вывод игнорируется клиентом. Подходит для простых неинтерактивных команд.
**`interaction: "terminal"`** — скрипт запускается дочерним процессом без захвата вывода.
**`interaction: "structured"`** — скрипт общается с клиентом через протокол команд (см. раздел ниже). Весь вывод отображается в прокручиваемом логе с поддержкой ANSI-цветов. Поддерживает интерактивные элементы: селекторы, поля ввода, подтверждения.
**`interaction: "structured"`** — весь вывод отображается в прокручиваемом логе с ANSI-цветами, скрипт может запрашивать ввод через протокол команд.
### `download` — скачивание файла
@@ -156,12 +194,6 @@ selected_bg = "blue"
}
```
| Параметр | Описание |
|---|---|
| `url` | Адрес файла |
| `filename` | Имя сохраняемого файла (по умолчанию — из URL) |
| `target_dir` | Директория сохранения (по умолчанию — текущая) |
### `download_and_run` — скачать и выполнить
```json
@@ -174,11 +206,6 @@ selected_bg = "blue"
}
```
| Параметр | Описание |
|---|---|
| `run_args` | Аргументы командной строки |
| `keep_file` | Оставить файл после выполнения (по умолчанию `false`) |
### `http_request` — HTTP-запрос
```json
@@ -186,10 +213,7 @@ selected_bg = "blue"
"type": "http_request",
"method": "POST",
"url": "https://api.example.com/deploy",
"headers": {
"Authorization": "Bearer token123",
"Content-Type": "application/json"
},
"headers": { "Authorization": "Bearer token123" },
"body": "{\"env\": \"production\"}",
"confirm": true
}
@@ -199,12 +223,10 @@ selected_bg = "blue"
## Интерактивные скрипты (structured)
При `interaction: "structured"` скрипт может запрашивать у пользователя данные через специальный протокол. Клиент показывает соответствующий элемент интерфейса ratatui и ждёт ответа.
При `interaction: "structured"` скрипт общается с клиентом через протокол команд. Команды отправляются в **stderr** (`>&2`), ответы приходят в **stdin**.
### Базовые хелперы
Добавьте эти функции в начало каждого интерактивного скрипта:
```bash
#!/bin/bash
@@ -215,21 +237,16 @@ ask() {
printf '%s' "$_response"
}
# Отправить уведомление (не ждёт ответа)
# Отправить уведомление (не ждёт ответа, не блокирует скрипт)
notify() {
printf 'CMD:%s\n' "$1" >&2
}
```
Команды отправляются в **stderr** (`>&2`), ответы приходят в **stdin** через `read`. Это позволяет использовать `$(ask '...')` для захвата результата.
---
### Ввод текста (`input`)
Показывает текстовое поле с заголовком. Поддерживает маскировку для паролей.
**Команда:**
```json
{"type":"input","prompt":"Введите имя пользователя:","default":"admin","secret":false}
```
@@ -240,20 +257,17 @@ notify() {
| `default` | Значение по умолчанию (опционально) |
| `secret` | Если `true` — символы заменяются на `•` |
**Пример:**
```bash
username=$(ask '{"type":"input","prompt":"Имя пользователя:","default":"admin"}')
password=$(ask '{"type":"input","prompt":"Пароль:","secret":true}')
echo "Логин: $username"
```
---
### Выбор из списка (`menu`)
Показывает список с навигацией `↑`/`↓` и выбором по `Enter`. Возвращает `id` выбранного пункта.
Список с навигацией `↑`/`↓`/`j`/`k`, выбор по `Enter`/`l`. Возвращает `id` выбранного пункта.
**Команда:**
```json
{
"type": "menu",
@@ -266,14 +280,6 @@ echo "Логин: $username"
}
```
| Поле | Описание |
|---|---|
| `prompt` | Заголовок списка |
| `options` | Массив объектов `{"id": "...", "label": "..."}` |
**Ответ:** строка `id` выбранного пункта.
**Пример:**
```bash
action=$(ask '{"type":"menu","prompt":"Выберите действие:","options":[
{"id":"dump","label":"Создать дамп"},
@@ -288,7 +294,7 @@ case $action in
esac
```
**Динамический список** (например, файлы на диске):
**Динамический список** (из массива bash):
```bash
files=($(ls *.sql 2>/dev/null))
@@ -302,31 +308,24 @@ options+=']'
idx=$(ask "{\"type\":\"menu\",\"prompt\":\"Выберите файл:\",\"options\":${options}}")
selected="${files[$idx]}"
echo "Выбран: $selected"
```
---
### Подтверждение (`confirm`)
Показывает вопрос с кнопками `[Y] Да` и `[N] Нет`. Нажатия `Y`/`N` обрабатываются без `Enter`.
Показывает вопрос с кнопками `[Y]`/`[N]`. Клавиши `Y`/`N`/`l`/`h` обрабатываются без Enter.
**Команда:**
```json
{"type":"confirm","prompt":"Данные будут перезаписаны. Продолжить?"}
```
**Ответ:** `"y"` или `"n"`.
Ответ: `"y"` или `"n"`.
**Пример:**
```bash
answer=$(ask '{"type":"confirm","prompt":"Удалить временные файлы?"}')
if [[ "$answer" =~ ^[Yy]$ ]]; then
rm -rf /tmp/myapp_*
echo "Файлы удалены"
else
echo "Отменено"
fi
```
@@ -334,79 +333,55 @@ fi
### Сообщение (`message`)
Показывает информационное сообщение с цветовым выделением. Скрипт продолжается после нажатия `Enter`.
Показывает сообщение с цветом. Скрипт продолжается после нажатия `Enter`.
**Команда:**
```json
{"type":"message","level":"info","text":"Операция завершена успешно!"}
```
| `level` | Цвет | Когда использовать |
|---|---|---|
| `"info"` | Зелёный | Успешное завершение, информация |
| `"warn"` | Жёлтый | Предупреждение, нестандартная ситуация |
| `"error"` | Красный | Ошибка, критическая проблема |
| `level` | Цвет |
|---|---|
| `"info"` | Зелёный |
| `"warn"` | Жёлтый |
| `"error"` | Красный |
**Пример:**
```bash
if ! command -v mysqldump &> /dev/null; then
ask '{"type":"message","level":"error","text":"mysqldump не найден. Установите пакет mysql-client."}' > /dev/null
ask '{"type":"message","level":"error","text":"mysqldump не найден."}' > /dev/null
exit 1
fi
ask '{"type":"message","level":"warn","text":"База данных занимает более 10 ГБ. Дамп может занять несколько минут."}' > /dev/null
echo "Начинаю создание дампа..."
```
> `> /dev/null` — сбрасывает пустой ответ клиента, чтобы он не попал в переменную.
> `> /dev/null` — сбрасывает пустой ответ клиента чтобы он не попал в переменную.
---
### Прогресс (`progress`)
Обновляет прогресс-бар без остановки скрипта. Скрипт продолжает выполнение немедленно.
Обновляет прогресс-бар не блокируя скрипт (используйте `notify`, не `ask`).
**Команда:**
```json
{"type":"progress","percent":45,"message":"Копирование файлов..."}
```
| Поле | Описание |
|---|---|
| `percent` | Число от 0 до 100 |
| `message` | Подпись под прогресс-баром (опционально) |
**Пример:**
```bash
notify '{"type":"progress","percent":0,"message":"Начало..."}'
mysqldump -h "$host" -u "$user" "$db" > backup.sql
notify '{"type":"progress","percent":60,"message":"Дамп создан, сжимаю..."}'
notify '{"type":"progress","percent":70,"message":"Сжимаю..."}'
gzip backup.sql
notify '{"type":"progress","percent":100,"message":"Готово!"}'
echo "Файл: backup.sql.gz ($(du -h backup.sql.gz | cut -f1))"
```
---
### Запуск внешнего приложения (`exec`)
Временно **передаёт терминал** внешней программе (mysql, vim, htop и т.д.). Клиент скрывает ratatui, программа работает на полном экране, после завершения TUI восстанавливается. Возвращает код завершения.
Временно **передаёт терминал** внешней программе (mysql, vim, htop и др.). Клиент скрывает TUI, программа работает на полном экране, после завершения TUI восстанавливается. Возвращает код завершения.
**Команда:**
```json
{"type":"exec","shell":"mysql -h localhost -u root mydb"}
```
| Поле | Описание |
|---|---|
| `shell` | Команда, которая будет выполнена через `bash -c` |
**Ответ:** код завершения программы (`"0"`, `"1"` и т.д.).
**Примеры:**
```bash
# Интерактивная сессия mysql
exit_code=$(ask "{\"type\":\"exec\",\"shell\":\"mysql -h \\\"$host\\\" -u \\\"$user\\\" -p\\\"$pass\\\" \\\"$db\\\"\"}")
@@ -414,7 +389,6 @@ echo "Сессия завершена (код: $exit_code)"
# Редактирование конфига
ask '{"type":"exec","shell":"vim /etc/nginx/nginx.conf"}' > /dev/null
notify '{"type":"progress","percent":0,"message":"Перезагружаю nginx..."}'
systemctl reload nginx
# Мониторинг ресурсов
@@ -428,25 +402,14 @@ ask '{"type":"exec","shell":"htop"}' > /dev/null
```bash
#!/bin/bash
ask() {
printf 'CMD:%s\n' "$1" >&2
read -r _response
printf '%s' "$_response"
}
ask() { printf 'CMD:%s\n' "$1" >&2; read -r _r; printf '%s' "$_r"; }
notify() { printf 'CMD:%s\n' "$1" >&2; }
notify() {
printf 'CMD:%s\n' "$1" >&2
}
# Запрос данных
host=$(ask '{"type":"input","prompt":"Хост базы данных:","default":"localhost"}')
db=$(ask '{"type":"input","prompt":"Имя базы данных:"}')
host=$(ask '{"type":"input","prompt":"Хост:","default":"localhost"}')
db=$(ask '{"type":"input","prompt":"База данных:"}')
user=$(ask '{"type":"input","prompt":"Пользователь:","default":"root"}')
pass=$(ask '{"type":"input","prompt":"Пароль:","secret":true}')
echo "Подключаюсь к $db на $host..."
# Выбор действия
action=$(ask "{\"type\":\"menu\",\"prompt\":\"Выберите действие:\",\"options\":[
{\"id\":\"dump\", \"label\":\"Создать дамп\"},
{\"id\":\"shell\", \"label\":\"Открыть mysql-консоль\"},
@@ -463,7 +426,7 @@ case $action in
if mysqldump -h "$host" -u "$user" -p"$pass" "$db" > "$backup"; then
notify '{"type":"progress","percent":100,"message":"Готово!"}'
echo "Дамп сохранён: $backup ($(du -h "$backup" | cut -f1))"
echo "Дамп: $backup ($(du -h "$backup" | cut -f1))"
else
ask '{"type":"message","level":"error","text":"Ошибка при создании дампа!"}' > /dev/null
exit 1
@@ -471,15 +434,11 @@ case $action in
;;
shell)
echo "Открываю mysql-консоль..."
code=$(ask "{\"type\":\"exec\",\"shell\":\"mysql -h \\\"$host\\\" -u \\\"$user\\\" -p\\\"$pass\\\" \\\"$db\\\"\"}")
echo "Сессия завершена с кодом $code"
;;
cancel)
echo "Отменено"
exit 0
;;
cancel) exit 0 ;;
esac
```
@@ -487,15 +446,14 @@ esac
## Структура сервера
Рекомендуемая организация серверной части:
```
server/
├── index.php # Собирает JSON из menu_structure.json + scripts/
├── index.php # Собирает JSON: menu_structure.json + scripts/
├── menu_structure.json # Иерархия меню (script_file вместо script)
└── scripts/
├── bitrix_db_manage.sh
├── bitrix_monitoring.sh
├── network_suspicious_connections.sh
└── wordpress_db_backup.sh
```
@@ -514,48 +472,66 @@ server/
}
```
`index.php` подставляет содержимое файла при каждом запросе — скрипты редактируются без изменения JSON.
`index.php` читает файл скрипта при каждом запросе — скрипты редактируются без изменения JSON.
### Добавление нового пункта меню
1. Создать скрипт `server/scripts/myapp_action.sh`
1. Создать `server/scripts/category_action.sh`
2. Добавить пункт в `menu_structure.json`:
```json
{
"id": "myapp_action",
"id": "my_action",
"title": "Название в меню",
"description": "Описание для нижней панели",
"action": {
"type": "bash",
"script_file": "myapp_action.sh",
"script_file": "category_action.sh",
"interaction": "structured",
"confirm": false
}
}
```
Именование файлов: `{категория}_{подкатегория}_{действие}.sh`
Соглашение по именованию файлов: `{категория}_{подкатегория}_{действие}.sh`
---
## Сборка
**Linux:**
Скрипт `release.sh` собирает бинарники для всех платформ сразу:
```bash
cd Ratatui
cargo build --release
# → target/release/tui-client
cd Ostiary
./release.sh
# → dist/ostiary-linux-x86_64
# → dist/ostiary-linux-aarch64
# → dist/ostiary-macos-aarch64
```
**Кросс-компиляция с macOS → Linux (musl, статический бинарный файл):**
**Вручную — Linux:**
```bash
cargo build --release
# → target/release/ostiary
```
**Вручную — кросс-компиляция macOS → Linux x86_64 (musl, статический):**
```bash
rustup target add x86_64-unknown-linux-musl
brew install FiloSottile/musl-cross/musl-cross
CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER=x86_64-linux-musl-gcc \
cargo build --release --target x86_64-unknown-linux-musl
# → target/x86_64-unknown-linux-musl/release/tui-client
# → target/x86_64-unknown-linux-musl/release/ostiary
```
Бинарный файл собирается статически и не требует никаких зависимостей на целевом сервере.
**Вручную — ARM64 Linux:**
```bash
rustup target add aarch64-unknown-linux-musl
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-musl-gcc \
cargo build --release --target aarch64-unknown-linux-musl
# → target/aarch64-unknown-linux-musl/release/ostiary
```
Бинарник собирается статически (musl) и не требует никаких зависимостей на целевом сервере.

55
release.sh Executable file
View File

@@ -0,0 +1,55 @@
#!/bin/bash
set -e
BINARY=$(cargo metadata --no-deps --format-version 1 | python3 -c "import sys,json; print(json.load(sys.stdin)['packages'][0]['name'])")
VERSION=$(cargo metadata --no-deps --format-version 1 | python3 -c "import sys,json; print(json.load(sys.stdin)['packages'][0]['version'])")
OUT_DIR="dist"
TARGETS=(
"x86_64-unknown-linux-musl:linux-x86_64"
"aarch64-unknown-linux-musl:linux-aarch64"
"aarch64-apple-darwin:macos-aarch64"
)
echo "Building $BINARY v$VERSION"
echo ""
# Ensure rustup targets are installed
rustup target add \
x86_64-unknown-linux-musl \
aarch64-unknown-linux-musl \
aarch64-apple-darwin 2>/dev/null
mkdir -p "$OUT_DIR"
# Clean previous release artifacts
rm -f "$OUT_DIR/$BINARY"-*
for entry in "${TARGETS[@]}"; do
RUST_TARGET="${entry%%:*}"
LABEL="${entry##*:}"
ARTIFACT="$OUT_DIR/${BINARY}-${LABEL}"
echo "── $LABEL ($RUST_TARGET)"
case "$RUST_TARGET" in
x86_64-unknown-linux-musl)
CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER=x86_64-linux-musl-gcc \
cargo build --release --target "$RUST_TARGET" --quiet
;;
aarch64-unknown-linux-musl)
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-musl-gcc \
cargo build --release --target "$RUST_TARGET" --quiet
;;
aarch64-apple-darwin)
cargo build --release --target "$RUST_TARGET" --quiet
;;
esac
cp "target/$RUST_TARGET/release/$BINARY" "$ARTIFACT"
SIZE=$(du -sh "$ARTIFACT" | cut -f1)
echo "$ARTIFACT ($SIZE)"
done
echo ""
echo "Done. Artifacts in $OUT_DIR/:"
ls -lh "$OUT_DIR/$BINARY"-*

View File

@@ -4,6 +4,7 @@ use crate::error::Result;
use crate::executor;
use crate::menu::{Action, InteractionMode, MenuItem, MenuItemKind, MenuRoot};
use crate::network;
use crate::updater;
use crossterm::event::{Event as CrosstermEvent, KeyCode, KeyEventKind};
use tokio::sync::mpsc::UnboundedSender;
@@ -16,6 +17,11 @@ pub enum Event {
StructuredCommand(executor::StructuredCommand),
StructuredOutput(String),
StructuredFinished(i32),
UpdateAvailable(updater::UpdateInfo),
UpdateProgress(u64),
/// Carries the exe path captured before the binary was replaced.
UpdateDone(std::path::PathBuf),
UpdateError(String),
}
/// A pending request to hand the terminal to an external interactive process.
@@ -35,6 +41,8 @@ pub struct App {
pub event_tx: UnboundedSender<Event>,
/// When set, main loop suspends ratatui, runs the command, then restores.
pub pending_exec: Option<PendingExec>,
/// Exe path to exec after update; captured before the binary was replaced.
pub pending_restart: Option<std::path::PathBuf>,
}
pub enum Popup {
@@ -62,6 +70,22 @@ pub enum Popup {
},
Downloading { progress: f32, message: String },
Message { text: String, level: MessageLevel },
UpdateConfirm {
info: updater::UpdateInfo,
},
Updating {
info: updater::UpdateInfo,
downloaded: u64,
status: UpdatingStatus,
},
}
#[derive(Debug, PartialEq)]
pub enum UpdatingStatus {
Downloading,
Applying,
Done,
Failed(String),
}
#[derive(Debug, Clone, Copy)]
@@ -82,9 +106,25 @@ impl App {
popup: None,
event_tx,
pending_exec: None,
pending_restart: None,
}
}
pub fn check_update(&mut self) {
let api_base = match &self.config.update_api {
Some(url) => url.clone(),
None => return,
};
let timeout = self.config.timeout_sec;
let tx = self.event_tx.clone();
tokio::spawn(async move {
if let Ok(Some(info)) = updater::check(&api_base, timeout).await {
let _ = tx.send(Event::UpdateAvailable(info));
}
});
}
pub async fn load_menu(&mut self) {
let server_url = self.config.server_url.clone();
let timeout = self.config.timeout_sec;
@@ -190,6 +230,32 @@ impl App {
// script), we silently discard the exit event.
Ok(false)
}
Event::UpdateAvailable(info) => {
// Only show if no popup is currently open (don't interrupt running scripts)
if self.popup.is_none() {
self.popup = Some(Popup::UpdateConfirm { info });
}
Ok(false)
}
Event::UpdateProgress(bytes) => {
if let Some(Popup::Updating { downloaded, .. }) = &mut self.popup {
*downloaded = bytes;
}
Ok(false)
}
Event::UpdateDone(exe_path) => {
if let Some(Popup::Updating { status, .. }) = &mut self.popup {
*status = UpdatingStatus::Done;
}
self.pending_restart = Some(exe_path);
Ok(false)
}
Event::UpdateError(msg) => {
if let Some(Popup::Updating { status, .. }) = &mut self.popup {
*status = UpdatingStatus::Failed(msg);
}
Ok(false)
}
}
}
@@ -233,6 +299,11 @@ impl App {
Some(executor::StructuredCommand::Confirm { .. })
);
let has_command = current_command.is_some();
// Vim motions are disabled only when free text input is active.
let is_text_input = matches!(
current_command,
Some(executor::StructuredCommand::Input { .. })
);
match key.code {
// ── Log scrolling (PageUp / PageDown always work) ─
@@ -288,7 +359,14 @@ impl App {
}
// ── Text input ────────────────────────────────────
KeyCode::Char(c) if !is_menu && !is_confirm => {
// Vim motion keys (j/k/l/h) are excluded here so they
// fall through to the vim-motion arms below.
KeyCode::Char(c)
if !is_menu
&& !is_confirm
&& (is_text_input
|| !matches!(c, 'j' | 'k' | 'l' | 'h')) =>
{
input_buffer.push(c);
}
KeyCode::Backspace if !is_menu => {
@@ -330,7 +408,66 @@ impl App {
let _ = current_command.take();
let _ = reply_tx.send("n".to_string());
} else {
// Kill the script if still running.
if let Some(kx) = kill_tx.take() {
let _ = kx.send(());
}
self.popup = None;
}
}
// ── Vim motions (off during text input) ───────────
KeyCode::Char('k') if !is_text_input => {
if is_menu {
if *menu_selected_index > 0 {
*menu_selected_index -= 1;
}
} else if !has_command {
*log_scroll_pos = log_scroll_pos.saturating_sub(1);
*log_follow_bottom = false;
}
}
KeyCode::Char('j') if !is_text_input => {
if is_menu {
if let Some(executor::StructuredCommand::Menu {
options, ..
}) = current_command
{
if *menu_selected_index + 1 < options.len() {
*menu_selected_index += 1;
}
}
} else if !has_command {
*log_scroll_pos = log_scroll_pos.saturating_add(1);
*log_follow_bottom =
*log_scroll_pos + 1 >= log_buffer.len();
}
}
KeyCode::Char('l') if !is_text_input => {
// Forward / confirm — same logic as Enter.
if let Some(cmd) = current_command.take() {
let response = match &cmd {
executor::StructuredCommand::Confirm { .. } => {
"y".to_string()
}
executor::StructuredCommand::Menu {
options, ..
} => options
.get(*menu_selected_index)
.map(|o| o.id.clone())
.unwrap_or_default(),
_ => String::new(),
};
let _ = reply_tx.send(response);
input_buffer.clear();
*menu_selected_index = 0;
}
}
KeyCode::Char('h') if !is_text_input => {
// Back / cancel — same logic as Esc.
if is_confirm {
let _ = current_command.take();
let _ = reply_tx.send("n".to_string());
} else {
if let Some(kx) = kill_tx.take() {
let _ = kx.send(());
}
@@ -347,6 +484,73 @@ impl App {
self.popup = None;
return Ok(false);
}
Popup::UpdateConfirm { info } => {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Char('l') => {
let info = info.clone();
self.popup = Some(Popup::Updating {
info: info.clone(),
downloaded: 0,
status: UpdatingStatus::Downloading,
});
let (progress_tx, mut progress_rx) =
tokio::sync::mpsc::unbounded_channel::<u64>();
let tx = self.event_tx.clone();
let info_clone = info.clone();
// Forward progress events
tokio::spawn(async move {
while let Some(bytes) = progress_rx.recv().await {
let _ = tx.send(Event::UpdateProgress(bytes));
}
});
// Download and apply
let tx2 = self.event_tx.clone();
tokio::spawn(async move {
match updater::download_and_apply(
&info_clone,
progress_tx,
)
.await
{
Ok(exe_path) => {
// Write expected version before exec so
// the next startup can detect a failed
// replacement (wrong asset, etc.).
updater::write_update_target(
&info_clone.new_version,
);
let _ = tx2.send(Event::UpdateDone(exe_path));
}
Err(e) => {
let _ =
tx2.send(Event::UpdateError(e.to_string()));
}
}
});
}
KeyCode::Char('n') | KeyCode::Char('N')
| KeyCode::Esc | KeyCode::Char('h') => {
self.popup = None;
}
_ => {}
}
return Ok(false);
}
Popup::Updating { status, .. } => {
if key.code == KeyCode::Esc {
if matches!(status, UpdatingStatus::Failed(_)) {
self.popup = None;
}
// Ignore Esc while downloading/applying
}
return Ok(false);
}
_ => {}
}
}
@@ -354,24 +558,24 @@ impl App {
// ── Main menu navigation ─────────────────────────────────────────
match key.code {
KeyCode::Char('q') => return Ok(true),
KeyCode::Up => {
KeyCode::Up | KeyCode::Char('k') => {
let len = self.current_items().len();
if len > 0 {
self.selected_index = (self.selected_index + len - 1) % len;
}
}
KeyCode::Down => {
KeyCode::Down | KeyCode::Char('j') => {
let len = self.current_items().len();
if len > 0 {
self.selected_index = (self.selected_index + 1) % len;
}
}
KeyCode::Enter => {
KeyCode::Enter | KeyCode::Char('l') => {
if let Some(item) = self.selected_item().cloned() {
self.activate_item(item).await?;
}
}
KeyCode::Esc => {
KeyCode::Esc | KeyCode::Char('h') => {
if !self.breadcrumbs.is_empty() {
self.breadcrumbs.pop();
self.selected_index = 0;

View File

@@ -9,6 +9,8 @@ pub struct Config {
pub timeout_sec: u64,
#[serde(default = "default_theme")]
pub theme: Theme,
#[serde(default)]
pub update_api: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
@@ -27,25 +29,42 @@ fn default_theme() -> Theme {
}
}
impl Config {
pub fn load() -> Result<Self> {
let config_path = dirs::config_dir()
pub fn config_path() -> PathBuf {
// Respect XDG_CONFIG_HOME; fall back to ~/.config on all platforms.
let base = std::env::var("XDG_CONFIG_HOME")
.map(PathBuf::from)
.unwrap_or_else(|_| {
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("tui-client")
.join("config.toml");
if !config_path.exists() {
let default = Config {
server_url: "http://localhost:8080/api/menu".to_string(),
timeout_sec: 10,
theme: default_theme(),
};
fs::create_dir_all(config_path.parent().unwrap())?;
fs::write(config_path, toml::to_string_pretty(&default)?)?;
return Ok(default);
.join(".config")
});
base.join(env!("CARGO_PKG_NAME")).join("config.toml")
}
let content = fs::read_to_string(config_path)?;
impl Config {
/// Returns true when a config file already exists.
pub fn exists() -> bool {
config_path().exists()
}
/// Load config from disk. Panics-safe: returns error if file is missing or malformed.
pub fn load() -> Result<Self> {
let path = config_path();
let content = fs::read_to_string(&path)?;
Ok(toml::from_str(&content)?)
}
/// Create and persist a new config with the given server URL.
pub fn create_with_url(server_url: &str) -> Result<Self> {
let path = config_path();
let config = Config {
server_url: server_url.to_string(),
timeout_sec: 10,
theme: default_theme(),
update_api: None,
};
fs::create_dir_all(path.parent().unwrap())?;
fs::write(&path, toml::to_string_pretty(&config)?)?;
Ok(config)
}
}

View File

@@ -6,6 +6,7 @@ mod executor;
mod menu;
mod network;
mod ui;
mod updater;
use std::io;
use anyhow::Result;
@@ -19,7 +20,12 @@ use tokio::sync::mpsc;
#[tokio::main]
async fn main() -> Result<()> {
let config = config::Config::load()?;
let config = if config::Config::exists() {
config::Config::load()?
} else {
let url = prompt_server_url()?;
config::Config::create_with_url(&url)?
};
enable_raw_mode()?;
let mut stdout = io::stdout();
@@ -29,7 +35,26 @@ async fn main() -> Result<()> {
let (event_tx, mut event_rx) = mpsc::unbounded_channel();
let mut app = app::App::new(config, event_tx.clone());
// Detect failed update: if the previous run wrote an expected version but
// the actual version didn't change, the replacement didn't work.
// Show an error and skip the update check to break any infinite loop.
let update_ok = match updater::take_update_target() {
Some(expected) if expected != env!("CARGO_PKG_VERSION") => {
app.error = Some(format!(
"Обновление не применилось: ожидалась v{expected}, \
запущена v{}. Проверьте, что в релизе загружен правильный бинарник.",
env!("CARGO_PKG_VERSION")
));
false
}
_ => true,
};
app.load_menu().await;
if update_ok {
app.check_update();
}
let res = run_app(&mut terminal, &mut app, &mut event_rx).await;
@@ -71,6 +96,21 @@ async fn run_app(
break;
}
// Check for pending restart (after update applied) — before pending_exec.
if let Some(exe_path) = app.pending_restart.take() {
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
#[cfg(unix)]
updater::exec_updated(&exe_path);
// fallback for non-unix or if exec failed
break;
}
// After handling events, check if a script requested an exec.
if let Some(exec) = app.pending_exec.take() {
run_exec(terminal, exec).await?;
@@ -126,6 +166,37 @@ async fn run_exec(
Ok(())
}
/// Runs before ratatui starts. Prompts for the server URL on first launch.
fn prompt_server_url() -> Result<String> {
use std::io::Write;
println!();
println!(" ╔══════════════════════════════════╗");
println!(" ║ Ostiary — первый запуск ║");
println!(" ╚══════════════════════════════════╝");
println!();
println!(" Конфиг будет сохранён в:");
println!(" {}", config::config_path().display());
println!();
loop {
print!(" URL сервера меню: ");
std::io::stdout().flush()?;
let mut url = String::new();
std::io::stdin().read_line(&mut url)?;
let url = url.trim().to_string();
if url.is_empty() {
println!(" URL не может быть пустым. Попробуйте ещё раз.\n");
continue;
}
println!();
return Ok(url);
}
}
async fn read_crossterm_event() -> Result<Option<crossterm::event::Event>> {
if crossterm::event::poll(std::time::Duration::from_millis(100))? {
Ok(Some(crossterm::event::read()?))

126
src/ui.rs
View File

@@ -1,6 +1,6 @@
use crate::ansi;
use crate::executor;
use crate::app::{App, MessageLevel, Popup};
use crate::app::{App, MessageLevel, Popup, UpdatingStatus};
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Color, Modifier, Style},
@@ -48,7 +48,18 @@ fn render_menu(f: &mut Frame, app: &App, area: Rect) {
.collect();
let list = List::new(list_items)
.block(Block::default().borders(Borders::ALL).title("Меню"))
.block(
Block::default()
.borders(Borders::ALL)
.title(" Меню ")
.title(
Line::from(Span::styled(
format!(" v{} ", env!("CARGO_PKG_VERSION")),
Style::default().fg(Color::DarkGray),
))
.alignment(Alignment::Right),
),
)
.highlight_style(Style::default().add_modifier(Modifier::BOLD));
f.render_widget(list, area);
}
@@ -69,7 +80,12 @@ fn render_description(f: &mut Frame, app: &App, area: Rect) {
fn render_popup(f: &mut Frame, popup: &mut Popup) {
let area = f.area();
let popup_area = centered_rect(80, 90, area);
// Use a smaller area for update-related popups
let popup_area = match popup {
Popup::UpdateConfirm { .. } | Popup::Updating { .. } => centered_rect(50, 40, area),
_ => centered_rect(80, 90, area),
};
f.render_widget(Clear, popup_area);
@@ -235,6 +251,110 @@ fn render_popup(f: &mut Frame, popup: &mut Popup) {
f.render_widget(paragraph, popup_area);
}
Popup::UpdateConfirm { info } => {
let mut lines = vec![
Line::from(""),
Line::from(Span::raw(format!(
" {}{}",
info.current_version, info.new_version
))),
];
if info.size > 0 {
let mb = info.size as f64 / 1_048_576.0;
lines.push(Line::from(Span::raw(format!(" Размер: {:.1} МБ", mb))));
}
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(
" [Y] Обновить [N / Esc] Пропустить",
Style::default().fg(Color::Yellow),
)));
let block = Block::default()
.borders(Borders::ALL)
.title(" Доступно обновление ")
.border_style(Style::default().fg(Color::Cyan));
let paragraph = Paragraph::new(lines)
.block(block)
.wrap(Wrap { trim: true });
f.render_widget(paragraph, popup_area);
}
Popup::Updating {
info,
downloaded,
status,
} => {
let (title, border_color) = match status {
UpdatingStatus::Downloading => (" Загрузка обновления… ", Color::Cyan),
UpdatingStatus::Applying => (" Применение обновления… ", Color::Yellow),
UpdatingStatus::Done => (" Обновление завершено ", Color::Green),
UpdatingStatus::Failed(_) => (" Ошибка обновления ", Color::Red),
};
let bar_width = popup_area.width.saturating_sub(4) as usize;
let progress_line = if info.size > 0 {
let percent = ((*downloaded as f64 / info.size as f64) * 100.0)
.min(100.0) as usize;
let filled = (percent * bar_width) / 100;
format!(
"[{}{}] {}%",
"".repeat(filled),
"".repeat(bar_width.saturating_sub(filled)),
percent
)
} else {
// Indeterminate: animate based on downloaded bytes
let pos = ((*downloaded / 4096) as usize) % bar_width.max(1);
let thumb = 4.min(bar_width);
let mut bar = vec!['░'; bar_width];
for i in pos..((pos + thumb).min(bar_width)) {
bar[i] = '█';
}
format!("[{}]", bar.iter().collect::<String>())
};
let status_text = match status {
UpdatingStatus::Downloading => {
if info.size > 0 {
let mb_done = *downloaded as f64 / 1_048_576.0;
let mb_total = info.size as f64 / 1_048_576.0;
format!(" {:.1} / {:.1} МБ", mb_done, mb_total)
} else {
let kb = *downloaded / 1024;
format!(" {} КБ загружено", kb)
}
}
UpdatingStatus::Applying => " Применяется…".to_string(),
UpdatingStatus::Done => " Обновление успешно установлено. Перезапуск…".to_string(),
UpdatingStatus::Failed(msg) => format!(" Ошибка: {}", msg),
};
let mut lines = vec![
Line::from(""),
Line::from(Span::raw(progress_line)),
Line::from(""),
Line::from(Span::raw(status_text)),
];
if matches!(status, UpdatingStatus::Failed(_)) {
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(
" [Esc] Закрыть",
Style::default().fg(Color::Yellow),
)));
}
let block = Block::default()
.borders(Borders::ALL)
.title(title)
.border_style(Style::default().fg(border_color));
let paragraph = Paragraph::new(lines)
.block(block)
.wrap(Wrap { trim: true });
f.render_widget(paragraph, popup_area);
}
_ => {}
}
}

203
src/updater.rs Normal file
View File

@@ -0,0 +1,203 @@
// src/updater.rs
use anyhow::{Context, Result};
use futures::StreamExt;
use serde::Deserialize;
use tokio::io::AsyncWriteExt;
use tokio::sync::mpsc::UnboundedSender;
#[derive(Debug, Clone)]
pub struct UpdateInfo {
pub current_version: String,
pub new_version: String,
pub download_url: String,
pub size: u64,
}
#[derive(Deserialize)]
struct Release {
tag_name: String,
prerelease: bool,
assets: Vec<ReleaseAsset>,
}
#[derive(Deserialize)]
struct ReleaseAsset {
name: String,
browser_download_url: String,
size: u64,
}
/// Checks Gitea releases API for latest stable (non-prerelease) release.
/// Returns Ok(None) if already up to date or no matching asset found.
pub async fn check(api_base: &str, timeout_sec: u64) -> Result<Option<UpdateInfo>> {
let url = format!("{}/releases?limit=10&page=1", api_base);
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(timeout_sec))
.build()
.context("failed to build HTTP client")?;
let releases: Vec<Release> = client
.get(&url)
.send()
.await
.context("failed to fetch releases")?
.json()
.await
.context("failed to parse releases JSON")?;
let current_version = env!("CARGO_PKG_VERSION").to_string();
// Find the latest non-prerelease release
let latest = releases.into_iter().find(|r| !r.prerelease);
let release = match latest {
Some(r) => r,
None => return Ok(None),
};
// Strip "v" prefix and anything after "@" (e.g. "v1.0.0@master" → "1.0.0")
let tag = release.tag_name.as_str();
let tag = tag.strip_prefix('v').unwrap_or(tag);
let tag = tag.split('@').next().unwrap_or(tag).trim();
let new_version = tag.to_string();
// Already up to date
if new_version == current_version {
return Ok(None);
}
// Find a matching asset
let asset_prefix = format!(
"{}-{}-{}",
env!("CARGO_PKG_NAME"),
std::env::consts::OS,
std::env::consts::ARCH
);
let asset = release
.assets
.into_iter()
.find(|a| a.name.starts_with(&asset_prefix));
let asset = match asset {
Some(a) => a,
None => return Ok(None),
};
Ok(Some(UpdateInfo {
current_version,
new_version,
download_url: asset.browser_download_url,
size: asset.size,
}))
}
/// Downloads binary to temp file with streaming progress, atomically replaces
/// current exe, sets chmod 755.
/// Returns the path of the replaced executable (captured before rename so it
/// remains valid even after the old inode is marked "(deleted)" by the kernel).
pub async fn download_and_apply(
info: &UpdateInfo,
progress_tx: UnboundedSender<u64>,
) -> Result<std::path::PathBuf> {
let client = reqwest::Client::new();
let response = client
.get(&info.download_url)
.send()
.await
.context("failed to start download")?
.error_for_status()
.context("download request failed with error status")?;
// Write to a temp file next to the current exe so rename is atomic
let current_exe = std::env::current_exe().context("failed to get current exe path")?;
let exe_dir = current_exe
.parent()
.context("current exe has no parent directory")?;
let tmp_path = exe_dir.join(format!(".{}.tmp", env!("CARGO_PKG_NAME")));
let mut file = tokio::fs::File::create(&tmp_path)
.await
.context("failed to create temp file")?;
let mut stream = response.bytes_stream();
let mut downloaded: u64 = 0;
while let Some(chunk) = stream.next().await {
let chunk = chunk.context("error reading download chunk")?;
downloaded += chunk.len() as u64;
file.write_all(&chunk)
.await
.context("failed to write to temp file")?;
let _ = progress_tx.send(downloaded);
}
// Flush and close
drop(file);
// chmod 755
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let perms = std::fs::Permissions::from_mode(0o755);
std::fs::set_permissions(&tmp_path, perms).context("failed to set permissions")?;
}
// Atomically replace current exe.
// current_exe is captured BEFORE this rename — after rename, /proc/self/exe
// on Linux returns the path with " (deleted)" appended, but the PathBuf we
// hold still refers to the correct filesystem path of the new binary.
std::fs::rename(&tmp_path, &current_exe).context("failed to replace current exe")?;
Ok(current_exe)
}
// ── Update-target file ───────────────────────────────────────────────────────
// Written just before exec. On next startup we compare the expected version
// with CARGO_PKG_VERSION. A mismatch means the replacement didn't work
// (wrong asset, failed rename, etc.) and we show an error instead of looping.
fn update_target_path() -> std::path::PathBuf {
crate::config::config_path()
.parent()
.expect("config dir has parent")
.join(".update_target")
}
/// Write the expected version to disk before exec'ing the new binary.
pub fn write_update_target(new_version: &str) {
let _ = std::fs::write(update_target_path(), new_version);
}
/// Read and delete the update-target file.
/// Returns `Some(expected_version)` if a previous run attempted an update.
/// The caller should compare it with `env!("CARGO_PKG_VERSION")` and show
/// an error if they differ.
pub fn take_update_target() -> Option<String> {
let path = update_target_path();
if !path.exists() {
return None;
}
let version = std::fs::read_to_string(&path).ok()?;
let _ = std::fs::remove_file(&path);
Some(version.trim().to_string())
}
/// Replaces current process via execv (Unix). Never returns on success.
/// `exe_path` must be the path captured *before* the binary was replaced —
/// do NOT call std::env::current_exe() here, it returns "(deleted)" on Linux.
#[cfg(unix)]
pub fn exec_updated(exe_path: &std::path::Path) -> ! {
use std::os::unix::process::CommandExt;
let args: Vec<String> = std::env::args().collect();
let err = std::process::Command::new(exe_path)
.args(&args[1..])
.exec();
eprintln!("Failed to exec updated binary: {}", err);
std::process::exit(1);
}