Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90974d064e |
145
Cargo.lock
generated
145
Cargo.lock
generated
@@ -50,12 +50,6 @@ version = "0.22.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "base64ct"
|
|
||||||
version = "1.8.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bit-set"
|
name = "bit-set"
|
||||||
version = "0.5.3"
|
version = "0.5.3"
|
||||||
@@ -155,12 +149,6 @@ dependencies = [
|
|||||||
"static_assertions",
|
"static_assertions",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "const-oid"
|
|
||||||
version = "0.9.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "convert_case"
|
name = "convert_case"
|
||||||
version = "0.10.0"
|
version = "0.10.0"
|
||||||
@@ -189,7 +177,6 @@ dependencies = [
|
|||||||
"crossterm_winapi",
|
"crossterm_winapi",
|
||||||
"derive_more",
|
"derive_more",
|
||||||
"document-features",
|
"document-features",
|
||||||
"filedescriptor",
|
|
||||||
"mio",
|
"mio",
|
||||||
"parking_lot",
|
"parking_lot",
|
||||||
"rustix",
|
"rustix",
|
||||||
@@ -227,33 +214,6 @@ dependencies = [
|
|||||||
"phf",
|
"phf",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "curve25519-dalek"
|
|
||||||
version = "4.1.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"cpufeatures",
|
|
||||||
"curve25519-dalek-derive",
|
|
||||||
"digest",
|
|
||||||
"fiat-crypto",
|
|
||||||
"rustc_version",
|
|
||||||
"subtle",
|
|
||||||
"zeroize",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "curve25519-dalek-derive"
|
|
||||||
version = "0.1.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.117",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "darling"
|
name = "darling"
|
||||||
version = "0.23.0"
|
version = "0.23.0"
|
||||||
@@ -294,16 +254,6 @@ version = "0.3.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5729f5117e208430e437df2f4843f5e5952997175992d1414f94c57d61e270b4"
|
checksum = "5729f5117e208430e437df2f4843f5e5952997175992d1414f94c57d61e270b4"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "der"
|
|
||||||
version = "0.7.10"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
|
||||||
dependencies = [
|
|
||||||
"const-oid",
|
|
||||||
"zeroize",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "deranged"
|
name = "deranged"
|
||||||
version = "0.5.8"
|
version = "0.5.8"
|
||||||
@@ -386,31 +336,6 @@ dependencies = [
|
|||||||
"litrs",
|
"litrs",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "ed25519"
|
|
||||||
version = "2.2.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
|
|
||||||
dependencies = [
|
|
||||||
"pkcs8",
|
|
||||||
"signature",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "ed25519-dalek"
|
|
||||||
version = "2.2.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
|
|
||||||
dependencies = [
|
|
||||||
"curve25519-dalek",
|
|
||||||
"ed25519",
|
|
||||||
"rand_core 0.6.4",
|
|
||||||
"serde",
|
|
||||||
"sha2",
|
|
||||||
"subtle",
|
|
||||||
"zeroize",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "either"
|
name = "either"
|
||||||
version = "1.15.0"
|
version = "1.15.0"
|
||||||
@@ -452,12 +377,6 @@ dependencies = [
|
|||||||
"regex",
|
"regex",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "fiat-crypto"
|
|
||||||
version = "0.2.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "filedescriptor"
|
name = "filedescriptor"
|
||||||
version = "0.8.3"
|
version = "0.8.3"
|
||||||
@@ -1204,16 +1123,13 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostiary"
|
name = "ostiary"
|
||||||
version = "1.1.6"
|
version = "1.0.8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64",
|
|
||||||
"crossterm",
|
"crossterm",
|
||||||
"dirs",
|
"dirs",
|
||||||
"ed25519-dalek",
|
|
||||||
"futures",
|
"futures",
|
||||||
"libc",
|
"libc",
|
||||||
"rand 0.8.5",
|
|
||||||
"ratatui",
|
"ratatui",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -1223,7 +1139,6 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
"toml",
|
"toml",
|
||||||
"unicode-width 0.1.14",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1362,16 +1277,6 @@ version = "0.1.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
|
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "pkcs8"
|
|
||||||
version = "0.10.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
|
|
||||||
dependencies = [
|
|
||||||
"der",
|
|
||||||
"spki",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "portable-atomic"
|
name = "portable-atomic"
|
||||||
version = "1.13.1"
|
version = "1.13.1"
|
||||||
@@ -1503,8 +1408,6 @@ version = "0.8.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
|
||||||
"rand_chacha 0.3.1",
|
|
||||||
"rand_core 0.6.4",
|
"rand_core 0.6.4",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1514,20 +1417,10 @@ version = "0.9.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
|
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"rand_chacha 0.9.0",
|
"rand_chacha",
|
||||||
"rand_core 0.9.5",
|
"rand_core 0.9.5",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rand_chacha"
|
|
||||||
version = "0.3.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
|
||||||
dependencies = [
|
|
||||||
"ppv-lite86",
|
|
||||||
"rand_core 0.6.4",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rand_chacha"
|
name = "rand_chacha"
|
||||||
version = "0.9.0"
|
version = "0.9.0"
|
||||||
@@ -1543,9 +1436,6 @@ name = "rand_core"
|
|||||||
version = "0.6.4"
|
version = "0.6.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||||
dependencies = [
|
|
||||||
"getrandom 0.2.17",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rand_core"
|
name = "rand_core"
|
||||||
@@ -1587,7 +1477,7 @@ dependencies = [
|
|||||||
"thiserror 2.0.18",
|
"thiserror 2.0.18",
|
||||||
"unicode-segmentation",
|
"unicode-segmentation",
|
||||||
"unicode-truncate",
|
"unicode-truncate",
|
||||||
"unicode-width 0.2.2",
|
"unicode-width",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1638,7 +1528,7 @@ dependencies = [
|
|||||||
"strum",
|
"strum",
|
||||||
"time",
|
"time",
|
||||||
"unicode-segmentation",
|
"unicode-segmentation",
|
||||||
"unicode-width 0.2.2",
|
"unicode-width",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1955,15 +1845,6 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "signature"
|
|
||||||
version = "2.2.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
|
||||||
dependencies = [
|
|
||||||
"rand_core 0.6.4",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "siphasher"
|
name = "siphasher"
|
||||||
version = "1.0.2"
|
version = "1.0.2"
|
||||||
@@ -1992,16 +1873,6 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "spki"
|
|
||||||
version = "0.7.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
|
|
||||||
dependencies = [
|
|
||||||
"base64ct",
|
|
||||||
"der",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "stable_deref_trait"
|
name = "stable_deref_trait"
|
||||||
version = "1.2.1"
|
version = "1.2.1"
|
||||||
@@ -2432,15 +2303,9 @@ checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"itertools",
|
"itertools",
|
||||||
"unicode-segmentation",
|
"unicode-segmentation",
|
||||||
"unicode-width 0.2.2",
|
"unicode-width",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "unicode-width"
|
|
||||||
version = "0.1.14"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-width"
|
name = "unicode-width"
|
||||||
version = "0.2.2"
|
version = "0.2.2"
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "ostiary"
|
name = "ostiary"
|
||||||
version = "1.1.6"
|
version = "1.0.9"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
crossterm = { version = "0.29", features = ["use-dev-tty"] }
|
crossterm = "0.29"
|
||||||
ratatui = "0.30"
|
ratatui = "0.30"
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
reqwest = { version = "0.12", features = ["json", "stream", "rustls-tls"], default-features = false }
|
reqwest = { version = "0.12", features = ["json", "stream", "rustls-tls"], default-features = false }
|
||||||
@@ -18,7 +18,3 @@ tokio-util = "0.7"
|
|||||||
toml = "0.8"
|
toml = "0.8"
|
||||||
serde_path_to_error = "0.1"
|
serde_path_to_error = "0.1"
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
|
||||||
rand = "0.8"
|
|
||||||
base64 = "0.22"
|
|
||||||
unicode-width = "0.1"
|
|
||||||
|
|||||||
61
README.md
61
README.md
@@ -9,7 +9,7 @@
|
|||||||
### Быстрая установка (Linux / macOS)
|
### Быстрая установка (Linux / macOS)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -fsSL https://vainend.com/ostiary | bash
|
curl -fsSL https://git.vainend.com/admin/ostiary/raw/branch/master/install.sh | bash
|
||||||
```
|
```
|
||||||
|
|
||||||
Скрипт определяет ОС и архитектуру, скачивает последний стабильный релиз и устанавливает бинарник в `~/.local/bin/ostiary`. Если этого пути нет в `$PATH` — автоматически добавляет строку в `~/.bashrc` (или `~/.bash_profile` / `~/.profile`). Не требует `sudo`.
|
Скрипт определяет ОС и архитектуру, скачивает последний стабильный релиз и устанавливает бинарник в `~/.local/bin/ostiary`. Если этого пути нет в `$PATH` — автоматически добавляет строку в `~/.bashrc` (или `~/.bash_profile` / `~/.profile`). Не требует `sudo`.
|
||||||
@@ -38,7 +38,7 @@ source ~/.bashrc
|
|||||||
### Удаление
|
### Удаление
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -fsSL https://vainend.com/ostiary-remove | bash
|
curl -fsSL https://git.vainend.com/admin/ostiary/raw/branch/master/uninstall.sh | bash
|
||||||
```
|
```
|
||||||
|
|
||||||
Или вручную:
|
Или вручную:
|
||||||
@@ -75,14 +75,13 @@ INSTALL_DIR=~/.local/bin bash install.sh
|
|||||||
|
|
||||||
### Popup запущенного скрипта
|
### Popup запущенного скрипта
|
||||||
|
|
||||||
| Клавиша | Контекст | Действие |
|
| Клавиша | Действие |
|
||||||
|---|---|---|
|
|---|---|
|
||||||
| `↑` / `↓` или `k` / `j` | Лог / селектор / форма | Прокрутка лога или навигация между элементами |
|
| `↑` / `↓` или `k` / `j` | Прокрутка лога / навигация по селектору |
|
||||||
| `PgUp` / `PgDn` | Лог | Прокрутка на 10 строк |
|
| `PgUp` / `PgDn` | Прокрутка лога на 10 строк |
|
||||||
| `Space` | Форма | Переключить чекбокс / выбрать радиокнопку |
|
| `Y` / `N` или `l` / `h` | Ответ на подтверждение (без Enter) |
|
||||||
| `Y` / `N` или `l` / `h` | Подтверждение | Ответ без Enter |
|
| `Enter` или `l` | Выбрать пункт селектора / подтвердить |
|
||||||
| `Enter` или `l` | Любой ввод | Отправить / выбрать / применить форму |
|
| `Esc` или `h` | Прервать скрипт и закрыть popup |
|
||||||
| `Esc` или `h` | — | Прервать скрипт и закрыть popup |
|
|
||||||
|
|
||||||
> Vim-motions (`j`/`k`/`l`/`h`) отключаются автоматически во время текстового ввода — символы идут в поле ввода как обычно.
|
> Vim-motions (`j`/`k`/`l`/`h`) отключаются автоматически во время текстового ввода — символы идут в поле ввода как обычно.
|
||||||
|
|
||||||
@@ -432,48 +431,6 @@ notify '{"type":"progress","percent":100,"message":"Готово!"}'
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Форма с чекбоксами и радиокнопками (`form`)
|
|
||||||
|
|
||||||
Отображает список полей с возможностью навигации и переключения. Возвращает строку с ID всех включённых/выбранных полей через пробел.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"type": "form",
|
|
||||||
"prompt": "Параметры поиска:",
|
|
||||||
"fields": [
|
|
||||||
{"id": "verbose", "label": "Подробный вывод", "field_type": "checkbox", "default": false},
|
|
||||||
{"id": "php", "label": "PHP файлы (*.php)", "field_type": "radio", "group": "ftype", "default": true},
|
|
||||||
{"id": "js", "label": "JS файлы (*.js)", "field_type": "radio", "group": "ftype", "default": false}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
| Поле | Описание |
|
|
||||||
|---|---|
|
|
||||||
| `id` | Идентификатор, возвращается если поле включено |
|
|
||||||
| `label` | Отображаемый текст |
|
|
||||||
| `field_type` | `"checkbox"` или `"radio"` |
|
|
||||||
| `default` | Начальное состояние |
|
|
||||||
| `group` | Группа радиокнопок — одновременно активна только одна в группе |
|
|
||||||
|
|
||||||
**Ответ:** строка с ID активных полей через пробел: `"verbose php"`
|
|
||||||
|
|
||||||
**Клавиши внутри формы:** `↑`/`↓`/`j`/`k` — навигация, `Space` — переключить, `Enter`/`l` — применить, `Esc` — отмена.
|
|
||||||
|
|
||||||
**Важно:** весь JSON должен быть на **одной строке** — протокол читает строки, не блоки.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
result=$(ask '{"type":"form","prompt":"Параметры:","fields":[{"id":"verbose","label":"Подробный вывод","field_type":"checkbox","default":false},{"id":"php","label":"PHP файлы","field_type":"radio","group":"t","default":true},{"id":"js","label":"JS файлы","field_type":"radio","group":"t","default":false}]}')
|
|
||||||
|
|
||||||
is_on() { [[ " $result " == *" $1 "* ]]; }
|
|
||||||
|
|
||||||
is_on "verbose" && FLAGS+=("-v")
|
|
||||||
is_on "php" && INCLUDE="--include=*.php"
|
|
||||||
is_on "js" && INCLUDE="--include=*.js"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Запуск внешнего приложения (`exec`)
|
### Запуск внешнего приложения (`exec`)
|
||||||
|
|
||||||
Временно **передаёт терминал** внешней программе (mysql, vim, htop и др.). Клиент скрывает TUI, программа работает на полном экране, после завершения TUI восстанавливается. Возвращает код завершения.
|
Временно **передаёт терминал** внешней программе (mysql, vim, htop и др.). Клиент скрывает TUI, программа работает на полном экране, после завершения TUI восстанавливается. Возвращает код завершения.
|
||||||
|
|||||||
22
install.sh
22
install.sh
@@ -84,32 +84,34 @@ ok "Installed → $INSTALL_DIR/$BINARY"
|
|||||||
|
|
||||||
# ── Add ~/.local/bin to PATH if missing ──────────────────────────────────────
|
# ── Add ~/.local/bin to PATH if missing ──────────────────────────────────────
|
||||||
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
|
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
|
||||||
export PATH="$INSTALL_DIR:$PATH"
|
warn "$INSTALL_DIR is not in PATH — adding it now..."
|
||||||
|
|
||||||
EXPORT_LINE="export PATH=\"\$HOME/.local/bin:\$PATH\""
|
EXPORT_LINE="export PATH=\"\$HOME/.local/bin:\$PATH\""
|
||||||
|
|
||||||
if [ -f "$HOME/.zshrc" ]; then
|
# Determine which profile file to update
|
||||||
PROFILE="$HOME/.zshrc"
|
if [ -f "$HOME/.bashrc" ]; then
|
||||||
elif [ -f "$HOME/.bashrc" ]; then
|
|
||||||
PROFILE="$HOME/.bashrc"
|
PROFILE="$HOME/.bashrc"
|
||||||
elif [ -f "$HOME/.bash_profile" ]; then
|
elif [ -f "$HOME/.bash_profile" ]; then
|
||||||
PROFILE="$HOME/.bash_profile"
|
PROFILE="$HOME/.bash_profile"
|
||||||
elif [ -f "$HOME/.profile" ]; then
|
elif [ -f "$HOME/.profile" ]; then
|
||||||
PROFILE="$HOME/.profile"
|
PROFILE="$HOME/.profile"
|
||||||
else
|
else
|
||||||
|
# Create .bashrc if nothing exists
|
||||||
PROFILE="$HOME/.bashrc"
|
PROFILE="$HOME/.bashrc"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Avoid duplicate entries
|
||||||
if ! grep -qF "$INSTALL_DIR" "$PROFILE" 2>/dev/null; then
|
if ! grep -qF "$INSTALL_DIR" "$PROFILE" 2>/dev/null; then
|
||||||
printf '\n# Added by ostiary installer\n%s\n' "$EXPORT_LINE" >> "$PROFILE"
|
printf '\n# Added by ostiary installer\n%s\n' "$EXPORT_LINE" >> "$PROFILE"
|
||||||
ok "Added PATH entry to $PROFILE"
|
ok "Added PATH entry to $PROFILE"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
warn "Run the following to use ostiary in this session:"
|
||||||
|
warn " export PATH=\"\$HOME/.local/bin:\$PATH\""
|
||||||
|
warn "New shells will pick it up automatically."
|
||||||
|
else
|
||||||
|
ok "$INSTALL_DIR is already in PATH"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
ok "Launching ${BINARY}..."
|
ok "Done! Run: $BINARY"
|
||||||
if { true </dev/tty; } 2>/dev/null; then
|
|
||||||
"$INSTALL_DIR/$BINARY"
|
|
||||||
else
|
|
||||||
ok "Run: $BINARY"
|
|
||||||
fi
|
|
||||||
|
|||||||
729
src/app.rs
729
src/app.rs
File diff suppressed because it is too large
Load Diff
123
src/config.rs
123
src/config.rs
@@ -3,39 +3,9 @@ use anyhow::Result;
|
|||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
|
||||||
pub struct Endpoint {
|
|
||||||
pub name: String,
|
|
||||||
pub url: String,
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub private_key: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Endpoint {
|
|
||||||
/// Creates a new endpoint with a freshly generated Ed25519 key pair.
|
|
||||||
pub fn new(name: String, url: String) -> Self {
|
|
||||||
Self {
|
|
||||||
name,
|
|
||||||
url,
|
|
||||||
private_key: Some(crate::identity::Identity::generate().to_b64()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn identity(&self) -> Option<crate::identity::Identity> {
|
|
||||||
self.private_key.as_deref()
|
|
||||||
.and_then(|k| crate::identity::Identity::from_b64(k).ok())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
// Legacy field — present only in old configs; migrated to endpoints on load.
|
pub server_url: String,
|
||||||
#[serde(default, skip_serializing)]
|
|
||||||
server_url: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
pub endpoints: Vec<Endpoint>,
|
|
||||||
#[serde(default)]
|
|
||||||
pub active_endpoint: String,
|
|
||||||
pub timeout_sec: u64,
|
pub timeout_sec: u64,
|
||||||
#[serde(default = "default_theme")]
|
#[serde(default = "default_theme")]
|
||||||
pub theme: Theme,
|
pub theme: Theme,
|
||||||
@@ -54,10 +24,13 @@ fn default_selected_bg() -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn default_theme() -> Theme {
|
fn default_theme() -> Theme {
|
||||||
Theme { selected_bg: default_selected_bg() }
|
Theme {
|
||||||
|
selected_bg: default_selected_bg(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn config_path() -> PathBuf {
|
pub fn config_path() -> PathBuf {
|
||||||
|
// Respect XDG_CONFIG_HOME; fall back to ~/.config on all platforms.
|
||||||
let base = std::env::var("XDG_CONFIG_HOME")
|
let base = std::env::var("XDG_CONFIG_HOME")
|
||||||
.map(PathBuf::from)
|
.map(PathBuf::from)
|
||||||
.unwrap_or_else(|_| {
|
.unwrap_or_else(|_| {
|
||||||
@@ -69,89 +42,41 @@ pub fn config_path() -> PathBuf {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
|
/// Returns true when a config file already exists.
|
||||||
pub fn exists() -> bool {
|
pub fn exists() -> bool {
|
||||||
config_path().exists()
|
config_path().exists()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn active_url(&self) -> &str {
|
/// Load config from disk. Panics-safe: returns error if file is missing or malformed.
|
||||||
&self.active_endpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the identity for the currently active endpoint, if any.
|
|
||||||
pub fn active_identity(&self) -> Option<crate::identity::Identity> {
|
|
||||||
self.endpoints.iter()
|
|
||||||
.find(|ep| ep.url == self.active_endpoint)
|
|
||||||
.and_then(|ep| ep.identity())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn load() -> Result<Self> {
|
pub fn load() -> Result<Self> {
|
||||||
let path = config_path();
|
let path = config_path();
|
||||||
let content = fs::read_to_string(&path)?;
|
let content = fs::read_to_string(&path)?;
|
||||||
let mut cfg: Config = toml::from_str(&content)?;
|
Ok(toml::from_str(&content)?)
|
||||||
// Migrate old single server_url format to endpoints list.
|
|
||||||
if cfg.endpoints.is_empty() {
|
|
||||||
if let Some(url) = cfg.server_url.take() {
|
|
||||||
cfg.active_endpoint = url.clone();
|
|
||||||
cfg.endpoints.push(Endpoint { name: "Default".to_string(), url, private_key: None });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if cfg.active_endpoint.is_empty() {
|
|
||||||
if let Some(ep) = cfg.endpoints.first() {
|
|
||||||
cfg.active_endpoint = ep.url.clone();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(cfg)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_with_endpoint(url: &str, name: &str) -> Result<Self> {
|
/// 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 path = config_path();
|
||||||
let config = Config {
|
let config = Config {
|
||||||
server_url: None,
|
server_url: server_url.to_string(),
|
||||||
endpoints: vec![Endpoint::new(name.to_string(), url.to_string())],
|
|
||||||
active_endpoint: url.to_string(),
|
|
||||||
timeout_sec: 10,
|
timeout_sec: 10,
|
||||||
theme: default_theme(),
|
theme: default_theme(),
|
||||||
update_api: Some("https://git.vainend.com/api/v1/repos/admin/ostiary".to_string()),
|
update_api: Some("https://git.vainend.com/api/v1/repos/admin/ostiary".to_string()),
|
||||||
};
|
};
|
||||||
|
let contents = format!(
|
||||||
|
r#"server_url = "{}"
|
||||||
|
timeout_sec = {}
|
||||||
|
update_api = "https://git.vainend.com/api/v1/repos/admin/ostiary"
|
||||||
|
|
||||||
|
[theme]
|
||||||
|
selected_bg = "{}"
|
||||||
|
"#,
|
||||||
|
config.server_url,
|
||||||
|
config.timeout_sec,
|
||||||
|
config.theme.selected_bg,
|
||||||
|
);
|
||||||
fs::create_dir_all(path.parent().unwrap())?;
|
fs::create_dir_all(path.parent().unwrap())?;
|
||||||
fs::write(&path, config.to_toml())?;
|
fs::write(&path, contents)?;
|
||||||
Ok(config)
|
Ok(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn save(&self) -> Result<()> {
|
|
||||||
let path = config_path();
|
|
||||||
fs::create_dir_all(path.parent().unwrap())?;
|
|
||||||
fs::write(&path, self.to_toml())?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_toml(&self) -> String {
|
|
||||||
let mut s = format!(
|
|
||||||
"active_endpoint = \"{}\"\ntimeout_sec = {}\n",
|
|
||||||
escape_toml(&self.active_endpoint),
|
|
||||||
self.timeout_sec,
|
|
||||||
);
|
|
||||||
if let Some(api) = &self.update_api {
|
|
||||||
s.push_str(&format!("update_api = \"{}\"\n", escape_toml(api)));
|
|
||||||
}
|
|
||||||
s.push_str(&format!(
|
|
||||||
"\n[theme]\nselected_bg = \"{}\"\n",
|
|
||||||
escape_toml(&self.theme.selected_bg),
|
|
||||||
));
|
|
||||||
for ep in &self.endpoints {
|
|
||||||
s.push_str(&format!(
|
|
||||||
"\n[[endpoints]]\nname = \"{}\"\nurl = \"{}\"\n",
|
|
||||||
escape_toml(&ep.name),
|
|
||||||
escape_toml(&ep.url),
|
|
||||||
));
|
|
||||||
if let Some(key) = &ep.private_key {
|
|
||||||
s.push_str(&format!("private_key = \"{}\"\n", escape_toml(key)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
s
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn escape_toml(s: &str) -> String {
|
|
||||||
s.replace('\\', "\\\\").replace('"', "\\\"")
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,8 +14,6 @@ pub enum AppError {
|
|||||||
Child(String),
|
Child(String),
|
||||||
#[error("Protocol error: {0}")]
|
#[error("Protocol error: {0}")]
|
||||||
Protocol(String),
|
Protocol(String),
|
||||||
#[error("Access denied by server")]
|
|
||||||
AccessDenied,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type Result<T> = std::result::Result<T, AppError>;
|
pub type Result<T> = std::result::Result<T, AppError>;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
pub mod structured;
|
pub mod structured;
|
||||||
pub use structured::{StructuredCommand, MessageLevel, FormFieldType};
|
pub use structured::{StructuredCommand, MessageLevel};
|
||||||
|
|
||||||
// Здесь могут быть функции для download, http и т.д.
|
// Здесь могут быть функции для download, http и т.д.
|
||||||
|
|||||||
@@ -28,39 +28,18 @@ pub enum StructuredCommand {
|
|||||||
text: String,
|
text: String,
|
||||||
},
|
},
|
||||||
Progress {
|
Progress {
|
||||||
/// Some(n) = deterministic bar (0-100).
|
percent: u8,
|
||||||
/// None = indeterminate spinner (percent omitted from JSON).
|
|
||||||
percent: Option<u8>,
|
|
||||||
message: Option<String>,
|
message: Option<String>,
|
||||||
},
|
},
|
||||||
/// A list of checkboxes and radio buttons.
|
|
||||||
/// Response: space-separated IDs of all checked/selected fields.
|
|
||||||
Form {
|
|
||||||
prompt: String,
|
|
||||||
fields: Vec<FormField>,
|
|
||||||
},
|
|
||||||
/// Run an interactive program that needs the real terminal.
|
/// Run an interactive program that needs the real terminal.
|
||||||
|
/// The client suspends ratatui, inherits stdin/stdout/stderr, waits for
|
||||||
|
/// the process to exit, then restores the TUI.
|
||||||
|
/// The script receives the exit code as the response.
|
||||||
Exec {
|
Exec {
|
||||||
shell: String,
|
shell: String,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub enum FormFieldType {
|
|
||||||
Checkbox,
|
|
||||||
Radio,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct FormField {
|
|
||||||
pub id: String,
|
|
||||||
pub label: String,
|
|
||||||
pub field_type: FormFieldType,
|
|
||||||
pub default: bool,
|
|
||||||
/// Radio buttons with the same group are mutually exclusive.
|
|
||||||
pub group: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct MenuOption {
|
pub struct MenuOption {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
@@ -220,30 +199,10 @@ fn parse_command(json_str: &str, cmd_tx: UnboundedSender<StructuredCommand>) ->
|
|||||||
StructuredCommand::Message { level, text }
|
StructuredCommand::Message { level, text }
|
||||||
}
|
}
|
||||||
"progress" => {
|
"progress" => {
|
||||||
// percent absent or null → None (indeterminate spinner)
|
let percent = v["percent"].as_u64().unwrap_or(0) as u8;
|
||||||
let percent = v["percent"].as_u64().map(|n| n.min(100) as u8);
|
|
||||||
let message = v["message"].as_str().map(String::from);
|
let message = v["message"].as_str().map(String::from);
|
||||||
StructuredCommand::Progress { percent, message }
|
StructuredCommand::Progress { percent, message }
|
||||||
}
|
}
|
||||||
"form" => {
|
|
||||||
let prompt = v["prompt"].as_str().unwrap_or("").to_string();
|
|
||||||
let fields = v["fields"].as_array()
|
|
||||||
.map(|arr| {
|
|
||||||
arr.iter().filter_map(|f| {
|
|
||||||
let id = f["id"].as_str()?.to_string();
|
|
||||||
let label = f["label"].as_str()?.to_string();
|
|
||||||
let field_type = match f["field_type"].as_str().unwrap_or("checkbox") {
|
|
||||||
"radio" => FormFieldType::Radio,
|
|
||||||
_ => FormFieldType::Checkbox,
|
|
||||||
};
|
|
||||||
let default = f["default"].as_bool().unwrap_or(false);
|
|
||||||
let group = f["group"].as_str().map(String::from);
|
|
||||||
Some(FormField { id, label, field_type, default, group })
|
|
||||||
}).collect()
|
|
||||||
})
|
|
||||||
.unwrap_or_default();
|
|
||||||
StructuredCommand::Form { prompt, fields }
|
|
||||||
}
|
|
||||||
"exec" => {
|
"exec" => {
|
||||||
let shell = v["shell"].as_str().unwrap_or("").to_string();
|
let shell = v["shell"].as_str().unwrap_or("").to_string();
|
||||||
StructuredCommand::Exec { shell }
|
StructuredCommand::Exec { shell }
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
use anyhow::{anyhow, Result};
|
|
||||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64, Engine};
|
|
||||||
use ed25519_dalek::{Signer, SigningKey};
|
|
||||||
use rand::rngs::OsRng;
|
|
||||||
|
|
||||||
pub struct Identity {
|
|
||||||
key: SigningKey,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Identity {
|
|
||||||
pub fn generate() -> Self {
|
|
||||||
Self { key: SigningKey::generate(&mut OsRng) }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn from_b64(s: &str) -> Result<Self> {
|
|
||||||
let bytes = B64.decode(s)?;
|
|
||||||
let arr: [u8; 32] = bytes.try_into().map_err(|_| anyhow!("invalid key length"))?;
|
|
||||||
Ok(Self { key: SigningKey::from_bytes(&arr) })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn to_b64(&self) -> String {
|
|
||||||
B64.encode(self.key.to_bytes())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn public_key_b64(&self) -> String {
|
|
||||||
B64.encode(self.key.verifying_key().to_bytes())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Signs `"METHOD\nPATH\nTIMESTAMP"` and returns base64url signature.
|
|
||||||
pub fn sign(&self, method: &str, path: &str, timestamp: u64) -> String {
|
|
||||||
let msg = format!("{}\n{}\n{}", method, path, timestamp);
|
|
||||||
B64.encode(self.key.sign(msg.as_bytes()).to_bytes())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn current_hostname() -> String {
|
|
||||||
let mut buf = vec![0u8; 256];
|
|
||||||
unsafe {
|
|
||||||
if libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) == 0 {
|
|
||||||
let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
|
|
||||||
String::from_utf8_lossy(&buf[..len]).into_owned()
|
|
||||||
} else {
|
|
||||||
"unknown".to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
78
src/main.rs
78
src/main.rs
@@ -3,10 +3,8 @@ mod app;
|
|||||||
mod config;
|
mod config;
|
||||||
mod error;
|
mod error;
|
||||||
mod executor;
|
mod executor;
|
||||||
mod identity;
|
|
||||||
mod menu;
|
mod menu;
|
||||||
mod network;
|
mod network;
|
||||||
mod text_input;
|
|
||||||
mod ui;
|
mod ui;
|
||||||
mod updater;
|
mod updater;
|
||||||
|
|
||||||
@@ -25,8 +23,8 @@ async fn main() -> Result<()> {
|
|||||||
let config = if config::Config::exists() {
|
let config = if config::Config::exists() {
|
||||||
config::Config::load()?
|
config::Config::load()?
|
||||||
} else {
|
} else {
|
||||||
let (url, name) = prompt_first_endpoint()?;
|
let url = prompt_server_url()?;
|
||||||
config::Config::create_with_endpoint(&url, &name)?
|
config::Config::create_with_url(&url)?
|
||||||
};
|
};
|
||||||
|
|
||||||
enable_raw_mode()?;
|
enable_raw_mode()?;
|
||||||
@@ -109,7 +107,7 @@ async fn run_app(
|
|||||||
terminal.show_cursor()?;
|
terminal.show_cursor()?;
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
updater::exec_updated(&exe_path);
|
updater::exec_updated(&exe_path);
|
||||||
#[cfg(not(unix))]
|
// fallback for non-unix or if exec failed
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,61 +166,35 @@ async fn run_exec(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs before ratatui starts. Prompts for endpoint URL and name on first launch.
|
/// Runs before ratatui starts. Prompts for the server URL on first launch.
|
||||||
fn prompt_first_endpoint() -> Result<(String, String)> {
|
fn prompt_server_url() -> Result<String> {
|
||||||
use std::io::{BufRead, BufReader, Write};
|
use std::io::Write;
|
||||||
|
|
||||||
// Open /dev/tty read-only for keyboard input so the wizard works even when
|
println!();
|
||||||
// stdin is a pipe (e.g. `curl | bash`). Writing goes through stdout so we
|
println!(" ╔══════════════════════════════════╗");
|
||||||
// don't touch the terminal's write-side state before crossterm takes over.
|
println!(" ║ Ostiary — первый запуск ║");
|
||||||
let tty_in = std::fs::File::open("/dev/tty")
|
println!(" ╚══════════════════════════════════╝");
|
||||||
.map_err(|e| anyhow::anyhow!(
|
println!();
|
||||||
"Не удалось открыть терминал ({e}). Запустите ostiary напрямую."
|
println!(" Конфиг будет сохранён в:");
|
||||||
))?;
|
println!(" {}", config::config_path().display());
|
||||||
let mut reader = BufReader::new(tty_in);
|
println!();
|
||||||
let mut out = std::io::stdout();
|
|
||||||
|
|
||||||
writeln!(out)?;
|
loop {
|
||||||
writeln!(out, " ╔══════════════════════════════════╗")?;
|
print!(" URL сервера меню: ");
|
||||||
writeln!(out, " ║ Ostiary — первый запуск ║")?;
|
std::io::stdout().flush()?;
|
||||||
writeln!(out, " ╚══════════════════════════════════╝")?;
|
|
||||||
writeln!(out)?;
|
|
||||||
writeln!(out, " Конфиг будет сохранён в:")?;
|
|
||||||
writeln!(out, " {}", config::config_path().display())?;
|
|
||||||
writeln!(out)?;
|
|
||||||
|
|
||||||
let name = loop {
|
let mut url = String::new();
|
||||||
write!(out, " Название эндпоинта: ")?;
|
std::io::stdin().read_line(&mut url)?;
|
||||||
out.flush()?;
|
let url = url.trim().to_string();
|
||||||
let mut buf = String::new();
|
|
||||||
if reader.read_line(&mut buf)? == 0 {
|
if url.is_empty() {
|
||||||
anyhow::bail!("Неожиданный конец ввода.");
|
println!(" URL не может быть пустым. Попробуйте ещё раз.\n");
|
||||||
}
|
|
||||||
let val = buf.trim().to_string();
|
|
||||||
if val.is_empty() {
|
|
||||||
writeln!(out, " Название не может быть пустым. Попробуйте ещё раз.\n")?;
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
break val;
|
|
||||||
};
|
|
||||||
|
|
||||||
let url = loop {
|
println!();
|
||||||
write!(out, " URL эндпоинта: ")?;
|
return Ok(url);
|
||||||
out.flush()?;
|
|
||||||
let mut buf = String::new();
|
|
||||||
if reader.read_line(&mut buf)? == 0 {
|
|
||||||
anyhow::bail!("Неожиданный конец ввода.");
|
|
||||||
}
|
}
|
||||||
let val = buf.trim().to_string();
|
|
||||||
if val.is_empty() {
|
|
||||||
writeln!(out, " URL не может быть пустым. Попробуйте ещё раз.\n")?;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
break val;
|
|
||||||
};
|
|
||||||
|
|
||||||
writeln!(out)?;
|
|
||||||
Ok((url, name))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn read_crossterm_event() -> Result<Option<crossterm::event::Event>> {
|
async fn read_crossterm_event() -> Result<Option<crossterm::event::Event>> {
|
||||||
|
|||||||
141
src/network.rs
141
src/network.rs
@@ -1,138 +1,29 @@
|
|||||||
use crate::error::{AppError, Result};
|
use crate::error::Result;
|
||||||
use crate::identity::Identity;
|
|
||||||
use crate::menu::{MenuItem, MenuRoot};
|
use crate::menu::{MenuItem, MenuRoot};
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_path_to_error as path_to_error;
|
use serde_path_to_error as path_to_error;
|
||||||
|
|
||||||
pub async fn fetch_menu(server_url: &str, timeout_sec: u64, identity: Option<&Identity>) -> Result<MenuRoot> {
|
pub async fn fetch_menu(server_url: &str, timeout_sec: u64) -> Result<MenuRoot> {
|
||||||
let client = Client::builder()
|
let client = Client::builder()
|
||||||
.timeout(std::time::Duration::from_secs(timeout_sec))
|
.timeout(std::time::Duration::from_secs(timeout_sec))
|
||||||
.build()?;
|
.build()?;
|
||||||
|
|
||||||
let mut req = client.get(server_url);
|
let resp = client.get(server_url).send().await?;
|
||||||
|
|
||||||
if let Some(id) = identity {
|
|
||||||
let timestamp = unix_now();
|
|
||||||
let path = url_path(server_url);
|
|
||||||
req = req
|
|
||||||
.header("X-Public-Key", id.public_key_b64())
|
|
||||||
.header("X-Timestamp", timestamp.to_string())
|
|
||||||
.header("X-Signature", id.sign("GET", &path, timestamp));
|
|
||||||
}
|
|
||||||
|
|
||||||
let resp = req.send().await?;
|
|
||||||
|
|
||||||
if resp.status() == reqwest::StatusCode::FORBIDDEN {
|
|
||||||
return Err(parse_access_denied(resp).await);
|
|
||||||
}
|
|
||||||
|
|
||||||
let text = resp.text().await?;
|
let text = resp.text().await?;
|
||||||
parse_menu_body(&text)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sends an enrollment request to `{server_url}/access-request`.
|
let mut deserializer = serde_json::Deserializer::from_str(&text);
|
||||||
/// The server stores the public key + source IP for admin approval.
|
match path_to_error::deserialize(&mut deserializer) {
|
||||||
/// Returns a human-readable status string on success.
|
|
||||||
pub async fn request_access(server_url: &str, timeout_sec: u64, identity: &Identity) -> Result<String> {
|
|
||||||
let access_url = enrollment_url(server_url);
|
|
||||||
|
|
||||||
let client = Client::builder()
|
|
||||||
.timeout(std::time::Duration::from_secs(timeout_sec))
|
|
||||||
.build()?;
|
|
||||||
|
|
||||||
let resp = client
|
|
||||||
.post(&access_url)
|
|
||||||
.json(&serde_json::json!({
|
|
||||||
"public_key": identity.public_key_b64(),
|
|
||||||
"hostname": crate::identity::current_hostname(),
|
|
||||||
}))
|
|
||||||
.send()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let status = resp.status();
|
|
||||||
let body = resp.text().await.unwrap_or_default();
|
|
||||||
|
|
||||||
let json_status = serde_json::from_str::<serde_json::Value>(&body)
|
|
||||||
.ok()
|
|
||||||
.and_then(|v| v["status"].as_str().map(|s| s.to_string()));
|
|
||||||
|
|
||||||
if status == reqwest::StatusCode::FORBIDDEN {
|
|
||||||
let msg = match json_status.as_deref() {
|
|
||||||
Some("banned") => "Ваш IP заблокирован администратором.".to_string(),
|
|
||||||
_ => format!("Сервер вернул {}: {}", status, body),
|
|
||||||
};
|
|
||||||
return Ok(msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
if !status.is_success() {
|
|
||||||
return Err(AppError::Config(format!("Сервер вернул {}: {}", status, body)));
|
|
||||||
}
|
|
||||||
|
|
||||||
let msg = match json_status.as_deref() {
|
|
||||||
Some("pending") => "Запрос отправлен. Ожидайте одобрения администратора.".to_string(),
|
|
||||||
Some("already_pending") => "Запрос уже был отправлен ранее. Ожидайте одобрения.".to_string(),
|
|
||||||
Some("already_authorized") => "Ключ уже авторизован. Нажмите R для обновления меню.".to_string(),
|
|
||||||
_ => format!("Ответ сервера: {}", body),
|
|
||||||
};
|
|
||||||
Ok(msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
fn unix_now() -> u64 {
|
|
||||||
std::time::SystemTime::now()
|
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
|
||||||
.unwrap_or_default()
|
|
||||||
.as_secs()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Builds the enrollment URL: `access-request.php` in the same directory as the menu URL.
|
|
||||||
/// `https://host/api/menu/index.php` → `https://host/api/menu/access-request.php`
|
|
||||||
/// `https://host/api/menu/` → `https://host/api/menu/access-request.php`
|
|
||||||
fn enrollment_url(server_url: &str) -> String {
|
|
||||||
reqwest::Url::parse(server_url)
|
|
||||||
.map(|mut u| {
|
|
||||||
let path = u.path().to_string();
|
|
||||||
let trimmed = path.trim_end_matches('/');
|
|
||||||
// If the last path segment looks like a file (contains '.'), use its parent dir.
|
|
||||||
let dir = match trimmed.rfind('/') {
|
|
||||||
Some(pos) if trimmed[pos + 1..].contains('.') => &trimmed[..pos],
|
|
||||||
_ => trimmed,
|
|
||||||
};
|
|
||||||
u.set_path(&format!("{}/access-request.php", dir));
|
|
||||||
u.set_query(None);
|
|
||||||
u.to_string()
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|_| format!("{}/access-request.php", server_url.trim_end_matches('/')))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extracts just the path component from a URL string.
|
|
||||||
fn url_path(url: &str) -> String {
|
|
||||||
reqwest::Url::parse(url)
|
|
||||||
.map(|u| u.path().to_string())
|
|
||||||
.unwrap_or_else(|_| "/".to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns `AppError::AccessDenied` when the 403 body contains `{"error":"access_denied"}`,
|
|
||||||
/// otherwise a generic config error.
|
|
||||||
async fn parse_access_denied(resp: reqwest::Response) -> AppError {
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
struct ErrBody { error: String }
|
|
||||||
if let Ok(body) = resp.json::<ErrBody>().await {
|
|
||||||
if body.error == "access_denied" {
|
|
||||||
return AppError::AccessDenied;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
AppError::Config("Сервер вернул 403 Forbidden".to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_menu_body(text: &str) -> Result<MenuRoot> {
|
|
||||||
let mut de = serde_json::Deserializer::from_str(text);
|
|
||||||
match path_to_error::deserialize(&mut de) {
|
|
||||||
Ok(root) => Ok(root),
|
Ok(root) => Ok(root),
|
||||||
Err(e) => match serde_json::from_str::<Vec<MenuItem>>(text) {
|
Err(e) => {
|
||||||
Ok(items) => Ok(MenuRoot { version: "1.0".to_string(), menu: items }),
|
// Если не удалось распарсить как объект с полем "menu",
|
||||||
Err(_) => Err(AppError::Json(e.into_inner())),
|
// пробуем интерпретировать ответ как прямой массив пунктов меню.
|
||||||
},
|
match serde_json::from_str::<Vec<MenuItem>>(&text) {
|
||||||
|
Ok(items) => Ok(MenuRoot {
|
||||||
|
version: "1.0".to_string(),
|
||||||
|
menu: items,
|
||||||
|
}),
|
||||||
|
Err(_) => Err(crate::error::AppError::Json(e.into_inner())),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
|
||||||
|
|
||||||
pub struct TextInput {
|
|
||||||
pub buf: String,
|
|
||||||
pub cursor: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TextInput {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self { buf: String::new(), cursor: 0 }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_text(text: impl Into<String>) -> Self {
|
|
||||||
let buf = text.into();
|
|
||||||
let cursor = buf.chars().count();
|
|
||||||
Self { buf, cursor }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn value(&self) -> &str {
|
|
||||||
&self.buf
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn clear(&mut self) {
|
|
||||||
self.buf.clear();
|
|
||||||
self.cursor = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn move_left(&mut self) {
|
|
||||||
self.cursor = self.cursor.saturating_sub(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn move_right(&mut self) {
|
|
||||||
self.cursor = (self.cursor + 1).min(self.buf.chars().count());
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn word_back(&mut self) {
|
|
||||||
let chars: Vec<char> = self.buf.chars().collect();
|
|
||||||
let mut pos = self.cursor;
|
|
||||||
while pos > 0 && !is_word(chars[pos - 1]) { pos -= 1; }
|
|
||||||
while pos > 0 && is_word(chars[pos - 1]) { pos -= 1; }
|
|
||||||
self.cursor = pos;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn word_fwd(&mut self) {
|
|
||||||
let chars: Vec<char> = self.buf.chars().collect();
|
|
||||||
let len = chars.len();
|
|
||||||
let mut pos = self.cursor;
|
|
||||||
while pos < len && !is_word(chars[pos]) { pos += 1; }
|
|
||||||
while pos < len && is_word(chars[pos]) { pos += 1; }
|
|
||||||
self.cursor = pos;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn insert(&mut self, c: char) {
|
|
||||||
let byte_idx = self.buf.char_indices().nth(self.cursor).map(|(b, _)| b).unwrap_or(self.buf.len());
|
|
||||||
self.buf.insert(byte_idx, c);
|
|
||||||
self.cursor += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn backspace(&mut self) {
|
|
||||||
if self.cursor == 0 { return; }
|
|
||||||
let byte_idx = self.buf.char_indices().nth(self.cursor - 1).map(|(b, _)| b).unwrap_or(0);
|
|
||||||
self.buf.remove(byte_idx);
|
|
||||||
self.cursor -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn word_delete_back(&mut self) {
|
|
||||||
let chars: Vec<char> = self.buf.chars().collect();
|
|
||||||
let mut new_cursor = self.cursor;
|
|
||||||
while new_cursor > 0 && !is_word(chars[new_cursor - 1]) { new_cursor -= 1; }
|
|
||||||
while new_cursor > 0 && is_word(chars[new_cursor - 1]) { new_cursor -= 1; }
|
|
||||||
if new_cursor == self.cursor { return; }
|
|
||||||
let start_byte = self.buf.char_indices().nth(new_cursor).map(|(b, _)| b).unwrap_or(0);
|
|
||||||
let end_byte = self.buf.char_indices().nth(self.cursor).map(|(b, _)| b).unwrap_or(self.buf.len());
|
|
||||||
self.buf.drain(start_byte..end_byte);
|
|
||||||
self.cursor = new_cursor;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns true if the key was consumed.
|
|
||||||
pub fn handle_key(&mut self, key: &KeyEvent) -> bool {
|
|
||||||
let alt = key.modifiers.intersects(KeyModifiers::ALT | KeyModifiers::SUPER);
|
|
||||||
match key.code {
|
|
||||||
KeyCode::Left if alt => { self.word_back(); true }
|
|
||||||
KeyCode::Right if alt => { self.word_fwd(); true }
|
|
||||||
KeyCode::Char('b') if alt => { self.word_back(); true }
|
|
||||||
KeyCode::Char('f') if alt => { self.word_fwd(); true }
|
|
||||||
KeyCode::Left => { self.move_left(); true }
|
|
||||||
KeyCode::Right => { self.move_right(); true }
|
|
||||||
KeyCode::Backspace if alt => { self.word_delete_back(); true }
|
|
||||||
KeyCode::Backspace => { self.backspace(); true }
|
|
||||||
KeyCode::Char(c) => { self.insert(c); true }
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_word(c: char) -> bool {
|
|
||||||
c.is_alphanumeric() || c == '_'
|
|
||||||
}
|
|
||||||
748
src/ui.rs
748
src/ui.rs
@@ -1,9 +1,6 @@
|
|||||||
use crate::ansi;
|
use crate::ansi;
|
||||||
use crate::config::Config;
|
|
||||||
use crate::executor;
|
use crate::executor;
|
||||||
use crate::app::{App, MessageLevel, Popup, UpdatingStatus};
|
use crate::app::{App, MessageLevel, Popup, UpdatingStatus};
|
||||||
use crate::text_input::TextInput;
|
|
||||||
use unicode_width::UnicodeWidthChar;
|
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
layout::{Alignment, Constraint, Direction, Layout, Rect},
|
||||||
style::{Color, Modifier, Style},
|
style::{Color, Modifier, Style},
|
||||||
@@ -27,92 +24,34 @@ pub fn render(f: &mut Frame, app: &mut App) {
|
|||||||
render_description(f, app, chunks[1]);
|
render_description(f, app, chunks[1]);
|
||||||
|
|
||||||
if let Some(popup) = &mut app.popup {
|
if let Some(popup) = &mut app.popup {
|
||||||
render_popup(f, popup, &app.config);
|
render_popup(f, popup);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_menu(f: &mut Frame, app: &mut App, area: Rect) {
|
fn render_menu(f: &mut Frame, app: &App, area: Rect) {
|
||||||
const SCROLLOFF: usize = 1;
|
|
||||||
|
|
||||||
let items = app.current_items();
|
let items = app.current_items();
|
||||||
let total = items.len();
|
let list_items: Vec<ListItem> = items
|
||||||
let inner_w = area.width.saturating_sub(2) as usize;
|
.iter()
|
||||||
let inner_h = area.height.saturating_sub(2) as usize;
|
.enumerate()
|
||||||
let sel = if total > 0 { app.selected_index.min(total - 1) } else { 0 };
|
.map(|(i, item)| {
|
||||||
|
|
||||||
let item_lines: Vec<Vec<String>> = items.iter().map(|item| {
|
|
||||||
let prefix = match &item.kind {
|
let prefix = match &item.kind {
|
||||||
crate::menu::MenuItemKind::Category { .. } => "📁 ",
|
crate::menu::MenuItemKind::Category { .. } => "📁 ",
|
||||||
crate::menu::MenuItemKind::Action { .. } => "⚡ ",
|
crate::menu::MenuItemKind::Action { .. } => "⚡ ",
|
||||||
};
|
};
|
||||||
wrap_to_lines(&format!("{}{}", prefix, item.title), inner_w)
|
let content = Line::from(Span::raw(format!("{}{}", prefix, item.title)));
|
||||||
}).collect();
|
if i == app.selected_index {
|
||||||
|
ListItem::new(content).style(Style::default().bg(Color::Blue))
|
||||||
let vis_from = |off: usize| -> usize {
|
|
||||||
let mut rows = 0usize;
|
|
||||||
let mut n = 0usize;
|
|
||||||
for lines in item_lines.get(off..).unwrap_or(&[]) {
|
|
||||||
let h = lines.len().max(1);
|
|
||||||
if rows + h > inner_h { break; }
|
|
||||||
rows += h;
|
|
||||||
n += 1;
|
|
||||||
}
|
|
||||||
n
|
|
||||||
};
|
|
||||||
|
|
||||||
let offset = &mut app.menu_scroll_offset;
|
|
||||||
if total == 0 {
|
|
||||||
*offset = 0;
|
|
||||||
} else {
|
} else {
|
||||||
if *offset > sel { *offset = sel; }
|
ListItem::new(content)
|
||||||
if sel < offset.saturating_add(SCROLLOFF) && *offset > 0 {
|
|
||||||
*offset = sel.saturating_sub(SCROLLOFF);
|
|
||||||
}
|
|
||||||
loop {
|
|
||||||
let vis = vis_from(*offset);
|
|
||||||
if vis == 0 { break; }
|
|
||||||
let trigger = offset.saturating_add(vis).saturating_sub(SCROLLOFF);
|
|
||||||
if sel >= trigger && *offset + vis < total {
|
|
||||||
*offset += 1;
|
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let max_off = total.saturating_sub(1);
|
|
||||||
*offset = (*offset).min(max_off);
|
|
||||||
}
|
|
||||||
|
|
||||||
let start = *offset;
|
|
||||||
let vis = vis_from(start);
|
|
||||||
let end = (start + vis).min(total);
|
|
||||||
|
|
||||||
let list_items: Vec<ListItem> = item_lines[start..end]
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(i, lines)| {
|
|
||||||
let abs = start + i;
|
|
||||||
let text: Vec<Line> = lines.iter().map(|l| Line::from(l.clone())).collect();
|
|
||||||
let li = ListItem::new(ratatui::text::Text::from(text));
|
|
||||||
if abs == sel {
|
|
||||||
li.style(Style::default().bg(Color::Blue).add_modifier(Modifier::BOLD))
|
|
||||||
} else {
|
|
||||||
li
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let endpoint_title = app.config.endpoints.iter()
|
let list = List::new(list_items)
|
||||||
.find(|ep| ep.url == app.config.active_endpoint)
|
.block(
|
||||||
.map(|ep| Line::from(vec![
|
|
||||||
Span::raw(format!(" {} ", ep.name)),
|
|
||||||
Span::styled(" — [↹] Изменить ", Style::default().fg(Color::DarkGray)),
|
|
||||||
]))
|
|
||||||
.unwrap_or_else(|| Line::from(" Меню "));
|
|
||||||
|
|
||||||
let list = List::new(list_items).block(
|
|
||||||
Block::default()
|
Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.title(endpoint_title)
|
.title(" Меню ")
|
||||||
.title(
|
.title(
|
||||||
Line::from(Span::styled(
|
Line::from(Span::styled(
|
||||||
format!(" v{} ", env!("CARGO_PKG_VERSION")),
|
format!(" v{} ", env!("CARGO_PKG_VERSION")),
|
||||||
@@ -120,25 +59,9 @@ fn render_menu(f: &mut Frame, app: &mut App, area: Rect) {
|
|||||||
))
|
))
|
||||||
.alignment(Alignment::Right),
|
.alignment(Alignment::Right),
|
||||||
),
|
),
|
||||||
);
|
)
|
||||||
|
.highlight_style(Style::default().add_modifier(Modifier::BOLD));
|
||||||
f.render_widget(list, area);
|
f.render_widget(list, area);
|
||||||
|
|
||||||
if total > vis {
|
|
||||||
let max_off = total.saturating_sub(vis);
|
|
||||||
let scrollbar = Scrollbar::default()
|
|
||||||
.orientation(ScrollbarOrientation::VerticalRight)
|
|
||||||
.begin_symbol(Some("▲"))
|
|
||||||
.end_symbol(Some("▼"))
|
|
||||||
.thumb_symbol("█");
|
|
||||||
let mut sb_state = ScrollbarState::new(max_off).position(start);
|
|
||||||
let sb_area = Rect {
|
|
||||||
x: area.x + area.width.saturating_sub(1),
|
|
||||||
y: area.y + 1,
|
|
||||||
width: 1,
|
|
||||||
height: area.height.saturating_sub(2),
|
|
||||||
};
|
|
||||||
f.render_stateful_widget(scrollbar, sb_area, &mut sb_state);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_description(f: &mut Frame, app: &App, area: Rect) {
|
fn render_description(f: &mut Frame, app: &App, area: Rect) {
|
||||||
@@ -155,9 +78,10 @@ fn render_description(f: &mut Frame, app: &App, area: Rect) {
|
|||||||
f.render_widget(paragraph, area);
|
f.render_widget(paragraph, area);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
fn render_popup(f: &mut Frame, popup: &mut Popup) {
|
||||||
let area = f.area();
|
let area = f.area();
|
||||||
|
|
||||||
|
// Use a smaller area for update-related popups
|
||||||
let popup_area = match popup {
|
let popup_area = match popup {
|
||||||
Popup::UpdateConfirm { .. } | Popup::Updating { .. } => centered_rect(50, 40, area),
|
Popup::UpdateConfirm { .. } | Popup::Updating { .. } => centered_rect(50, 40, area),
|
||||||
_ => centered_rect(80, 90, area),
|
_ => centered_rect(80, 90, area),
|
||||||
@@ -166,7 +90,11 @@ fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
|||||||
f.render_widget(Clear, popup_area);
|
f.render_widget(Clear, popup_area);
|
||||||
|
|
||||||
match popup {
|
match popup {
|
||||||
Popup::Confirming { action: _, item_title, confirm_message } => {
|
Popup::Confirming {
|
||||||
|
action: _,
|
||||||
|
item_title,
|
||||||
|
confirm_message,
|
||||||
|
} => {
|
||||||
let block = Block::default()
|
let block = Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.title("Подтверждение")
|
.title("Подтверждение")
|
||||||
@@ -190,10 +118,11 @@ fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
|||||||
)),
|
)),
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
f.render_widget(
|
let paragraph = Paragraph::new(text)
|
||||||
Paragraph::new(text).block(block).alignment(Alignment::Center).wrap(Wrap { trim: true }),
|
.block(block)
|
||||||
popup_area,
|
.alignment(Alignment::Center)
|
||||||
);
|
.wrap(Wrap { trim: true });
|
||||||
|
f.render_widget(paragraph, popup_area);
|
||||||
}
|
}
|
||||||
|
|
||||||
Popup::ExecutingStructured {
|
Popup::ExecutingStructured {
|
||||||
@@ -201,18 +130,16 @@ fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
|||||||
kill_tx: _,
|
kill_tx: _,
|
||||||
log_buffer,
|
log_buffer,
|
||||||
current_command,
|
current_command,
|
||||||
input,
|
input_buffer,
|
||||||
menu_selected_index,
|
menu_selected_index,
|
||||||
form_cursor,
|
|
||||||
form_values,
|
|
||||||
log_scroll_pos,
|
log_scroll_pos,
|
||||||
log_scroll_x,
|
|
||||||
log_follow_bottom,
|
log_follow_bottom,
|
||||||
finished,
|
finished,
|
||||||
} => {
|
} => {
|
||||||
let cmd_height: u16 = match current_command {
|
let cmd_height: u16 = match current_command {
|
||||||
Some(executor::StructuredCommand::Menu { options, .. }) => (options.len() as u16 + 2).min(14),
|
Some(executor::StructuredCommand::Menu { options, .. }) => {
|
||||||
Some(executor::StructuredCommand::Form { fields, .. }) => (fields.len() as u16 + 2).min(16),
|
(options.len() as u16 + 2).min(14)
|
||||||
|
}
|
||||||
Some(_) => 5,
|
Some(_) => 5,
|
||||||
None => 0,
|
None => 0,
|
||||||
};
|
};
|
||||||
@@ -223,9 +150,11 @@ fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
|||||||
.constraints([Constraint::Min(3), Constraint::Length(cmd_height)].as_ref())
|
.constraints([Constraint::Min(3), Constraint::Length(cmd_height)].as_ref())
|
||||||
.split(popup_area);
|
.split(popup_area);
|
||||||
|
|
||||||
|
// ── Scrollable log ──────────────────────────────────────────────
|
||||||
let visible = chunks[0].height.saturating_sub(2) as usize;
|
let visible = chunks[0].height.saturating_sub(2) as usize;
|
||||||
let total = log_buffer.len();
|
let total = log_buffer.len();
|
||||||
|
|
||||||
|
// Clamp pos so we never show empty lines past the end.
|
||||||
let max_pos = total.saturating_sub(visible);
|
let max_pos = total.saturating_sub(visible);
|
||||||
if *log_follow_bottom {
|
if *log_follow_bottom {
|
||||||
*log_scroll_pos = max_pos;
|
*log_scroll_pos = max_pos;
|
||||||
@@ -236,20 +165,13 @@ fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
|||||||
let start = pos;
|
let start = pos;
|
||||||
let end = (start + visible).min(total);
|
let end = (start + visible).min(total);
|
||||||
|
|
||||||
let viewport_w = chunks[0].width.saturating_sub(2) as usize;
|
|
||||||
let max_content_w: usize = log_buffer
|
|
||||||
.iter()
|
|
||||||
.map(|l| ansi::parse_line(l).iter().map(|(_, s)| s.chars().count()).sum::<usize>())
|
|
||||||
.max()
|
|
||||||
.unwrap_or(0);
|
|
||||||
let max_scroll_x = max_content_w.saturating_sub(viewport_w);
|
|
||||||
*log_scroll_x = (*log_scroll_x).min(max_scroll_x);
|
|
||||||
let scroll_x = *log_scroll_x;
|
|
||||||
|
|
||||||
let log_items: Vec<ListItem> = log_buffer[start..end]
|
let log_items: Vec<ListItem> = log_buffer[start..end]
|
||||||
.iter()
|
.iter()
|
||||||
.map(|line| {
|
.map(|line| {
|
||||||
let spans: Vec<Span> = h_scroll(ansi::parse_line(line), scroll_x);
|
let spans: Vec<Span> = ansi::parse_line(line)
|
||||||
|
.into_iter()
|
||||||
|
.map(|(style, text)| Span::styled(text, style))
|
||||||
|
.collect();
|
||||||
ListItem::new(Line::from(spans))
|
ListItem::new(Line::from(spans))
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -257,32 +179,37 @@ fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
|||||||
let at_bottom = pos >= max_pos;
|
let at_bottom = pos >= max_pos;
|
||||||
let at_top = pos == 0;
|
let at_top = pos == 0;
|
||||||
|
|
||||||
let scroll_hint = if total <= visible {
|
|
||||||
String::new()
|
|
||||||
} else if at_top && at_bottom {
|
|
||||||
String::new()
|
|
||||||
} else if at_top {
|
|
||||||
format!(" │ PgDn/↓ вниз ({}/{})", end, total)
|
|
||||||
} else if at_bottom {
|
|
||||||
format!(" │ PgUp/↑ вверх ({}/{})", end, total)
|
|
||||||
} else {
|
|
||||||
format!(" │ PgUp ↑ PgDn ↓ ({}/{})", end, total)
|
|
||||||
};
|
|
||||||
|
|
||||||
let (title, border_color): (String, Color) = match finished {
|
let (title, border_color): (String, Color) = match finished {
|
||||||
Some(0) => (format!(" ✓ Завершено — Esc закрыть{} ", scroll_hint), Color::Green),
|
Some(0) => (
|
||||||
Some(code) => (format!(" ✗ Ошибка (код {}) — Esc закрыть{} ", code, scroll_hint), Color::Red),
|
" ✓ Завершено — Esc закрыть │ PgUp/↑↓ скролл ".to_string(),
|
||||||
None if at_top && at_bottom => (" Выполняется… ".to_string(), Color::DarkGray),
|
Color::Green,
|
||||||
None if at_bottom => (" Выполняется… │ PgUp/↑ прокрутить вверх ".to_string(), Color::DarkGray),
|
),
|
||||||
None => (format!(" Выполняется… │ {}/{} │ PgDn/↓ вниз ", pos + 1, total), Color::Yellow),
|
Some(code) => (
|
||||||
|
format!(" ✗ Ошибка (код {}) — Esc закрыть │ PgUp/↑↓ скролл ", code),
|
||||||
|
Color::Red,
|
||||||
|
),
|
||||||
|
None if at_top && at_bottom => (
|
||||||
|
" Выполняется… ".to_string(),
|
||||||
|
Color::DarkGray,
|
||||||
|
),
|
||||||
|
None if at_bottom => (
|
||||||
|
" Выполняется… │ PgUp/↑ прокрутить вверх ".to_string(),
|
||||||
|
Color::DarkGray,
|
||||||
|
),
|
||||||
|
None => (
|
||||||
|
format!(" Выполняется… │ {}/{} │ PgDn/↓ вниз ", pos + 1, total),
|
||||||
|
Color::Yellow,
|
||||||
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
let log_block = Block::default()
|
let log_block = Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.title(title.as_str())
|
.title(title.as_str())
|
||||||
.border_style(Style::default().fg(border_color));
|
.border_style(Style::default().fg(border_color));
|
||||||
|
|
||||||
f.render_widget(List::new(log_items).block(log_block), chunks[0]);
|
f.render_widget(List::new(log_items).block(log_block), chunks[0]);
|
||||||
|
|
||||||
|
// ── Scrollbar ───────────────────────────────────────────────────
|
||||||
if total > visible {
|
if total > visible {
|
||||||
let scrollbar = Scrollbar::default()
|
let scrollbar = Scrollbar::default()
|
||||||
.orientation(ScrollbarOrientation::VerticalRight)
|
.orientation(ScrollbarOrientation::VerticalRight)
|
||||||
@@ -299,53 +226,38 @@ fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
|||||||
f.render_stateful_widget(scrollbar, sb_area, &mut sb_state);
|
f.render_stateful_widget(scrollbar, sb_area, &mut sb_state);
|
||||||
}
|
}
|
||||||
|
|
||||||
if max_content_w > viewport_w {
|
// ── Interactive command area ─────────────────────────────────────
|
||||||
let mut h_state = ScrollbarState::new(max_scroll_x).position(scroll_x);
|
|
||||||
let hscroll_area = Rect {
|
|
||||||
x: chunks[0].x + 1,
|
|
||||||
y: chunks[0].y + chunks[0].height.saturating_sub(1),
|
|
||||||
width: chunks[0].width.saturating_sub(2),
|
|
||||||
height: 1,
|
|
||||||
};
|
|
||||||
f.render_stateful_widget(
|
|
||||||
Scrollbar::new(ScrollbarOrientation::HorizontalBottom)
|
|
||||||
.begin_symbol(Some("◄"))
|
|
||||||
.end_symbol(Some("►"))
|
|
||||||
.thumb_symbol("▄")
|
|
||||||
.track_symbol(Some("─")),
|
|
||||||
hscroll_area,
|
|
||||||
&mut h_state,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if cmd_height > 0 {
|
if cmd_height > 0 {
|
||||||
if let Some(cmd) = current_command {
|
if let Some(cmd) = current_command {
|
||||||
render_command(f, cmd, input, *menu_selected_index, *form_cursor, form_values, chunks[1]);
|
render_command(f, cmd, input_buffer, *menu_selected_index, chunks[1]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Popup::Message { text, level, .. } => {
|
Popup::Message { text, level } => {
|
||||||
let color = match level {
|
let color = match level {
|
||||||
MessageLevel::Info => Color::Green,
|
MessageLevel::Info => Color::Green,
|
||||||
MessageLevel::Warn => Color::Yellow,
|
MessageLevel::Warn => Color::Yellow,
|
||||||
MessageLevel::Error => Color::Red,
|
MessageLevel::Error => Color::Red,
|
||||||
};
|
};
|
||||||
let content = format!("{}\n\n[любая клавиша] Закрыть", text);
|
|
||||||
let block = Block::default()
|
let block = Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.title("Сообщение")
|
.title("Сообщение")
|
||||||
.border_style(Style::default().fg(color));
|
.border_style(Style::default().fg(color));
|
||||||
f.render_widget(
|
let paragraph = Paragraph::new(text.as_str())
|
||||||
Paragraph::new(content.as_str()).block(block).alignment(Alignment::Center).wrap(Wrap { trim: true }),
|
.block(block)
|
||||||
popup_area,
|
.alignment(Alignment::Center)
|
||||||
);
|
.wrap(Wrap { trim: true });
|
||||||
|
f.render_widget(paragraph, popup_area);
|
||||||
}
|
}
|
||||||
|
|
||||||
Popup::UpdateConfirm { info } => {
|
Popup::UpdateConfirm { info } => {
|
||||||
let mut lines = vec![
|
let mut lines = vec![
|
||||||
Line::from(""),
|
Line::from(""),
|
||||||
Line::from(Span::raw(format!(" {} → {}", info.current_version, info.new_version))),
|
Line::from(Span::raw(format!(
|
||||||
|
" {} → {}",
|
||||||
|
info.current_version, info.new_version
|
||||||
|
))),
|
||||||
];
|
];
|
||||||
if info.size > 0 {
|
if info.size > 0 {
|
||||||
let mb = info.size as f64 / 1_048_576.0;
|
let mb = info.size as f64 / 1_048_576.0;
|
||||||
@@ -361,10 +273,17 @@ fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
|||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.title(" Доступно обновление ")
|
.title(" Доступно обновление ")
|
||||||
.border_style(Style::default().fg(Color::Cyan));
|
.border_style(Style::default().fg(Color::Cyan));
|
||||||
f.render_widget(Paragraph::new(lines).block(block).wrap(Wrap { trim: true }), popup_area);
|
let paragraph = Paragraph::new(lines)
|
||||||
|
.block(block)
|
||||||
|
.wrap(Wrap { trim: true });
|
||||||
|
f.render_widget(paragraph, popup_area);
|
||||||
}
|
}
|
||||||
|
|
||||||
Popup::Updating { info, downloaded, status } => {
|
Popup::Updating {
|
||||||
|
info,
|
||||||
|
downloaded,
|
||||||
|
status,
|
||||||
|
} => {
|
||||||
let (title, border_color) = match status {
|
let (title, border_color) = match status {
|
||||||
UpdatingStatus::Downloading => (" Загрузка обновления… ", Color::Cyan),
|
UpdatingStatus::Downloading => (" Загрузка обновления… ", Color::Cyan),
|
||||||
UpdatingStatus::Applying => (" Применение обновления… ", Color::Yellow),
|
UpdatingStatus::Applying => (" Применение обновления… ", Color::Yellow),
|
||||||
@@ -375,14 +294,23 @@ fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
|||||||
let bar_width = popup_area.width.saturating_sub(4) as usize;
|
let bar_width = popup_area.width.saturating_sub(4) as usize;
|
||||||
|
|
||||||
let progress_line = if info.size > 0 {
|
let progress_line = if info.size > 0 {
|
||||||
let percent = ((*downloaded as f64 / info.size as f64) * 100.0).min(100.0) as usize;
|
let percent = ((*downloaded as f64 / info.size as f64) * 100.0)
|
||||||
|
.min(100.0) as usize;
|
||||||
let filled = (percent * bar_width) / 100;
|
let filled = (percent * bar_width) / 100;
|
||||||
format!("[{}{}] {}%", "█".repeat(filled), "░".repeat(bar_width.saturating_sub(filled)), percent)
|
format!(
|
||||||
|
"[{}{}] {}%",
|
||||||
|
"█".repeat(filled),
|
||||||
|
"░".repeat(bar_width.saturating_sub(filled)),
|
||||||
|
percent
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
|
// Indeterminate: animate based on downloaded bytes
|
||||||
let pos = ((*downloaded / 4096) as usize) % bar_width.max(1);
|
let pos = ((*downloaded / 4096) as usize) % bar_width.max(1);
|
||||||
let thumb = 4.min(bar_width);
|
let thumb = 4.min(bar_width);
|
||||||
let mut bar = vec!['░'; bar_width];
|
let mut bar = vec!['░'; bar_width];
|
||||||
for i in pos..((pos + thumb).min(bar_width)) { bar[i] = '█'; }
|
for i in pos..((pos + thumb).min(bar_width)) {
|
||||||
|
bar[i] = '█';
|
||||||
|
}
|
||||||
format!("[{}]", bar.iter().collect::<String>())
|
format!("[{}]", bar.iter().collect::<String>())
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -393,7 +321,8 @@ fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
|||||||
let mb_total = info.size as f64 / 1_048_576.0;
|
let mb_total = info.size as f64 / 1_048_576.0;
|
||||||
format!(" {:.1} / {:.1} МБ", mb_done, mb_total)
|
format!(" {:.1} / {:.1} МБ", mb_done, mb_total)
|
||||||
} else {
|
} else {
|
||||||
format!(" {} КБ загружено", *downloaded / 1024)
|
let kb = *downloaded / 1024;
|
||||||
|
format!(" {} КБ загружено", kb)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
UpdatingStatus::Applying => " Применяется…".to_string(),
|
UpdatingStatus::Applying => " Применяется…".to_string(),
|
||||||
@@ -410,258 +339,49 @@ fn render_popup(f: &mut Frame, popup: &mut Popup, config: &Config) {
|
|||||||
|
|
||||||
if matches!(status, UpdatingStatus::Failed(_)) {
|
if matches!(status, UpdatingStatus::Failed(_)) {
|
||||||
lines.push(Line::from(""));
|
lines.push(Line::from(""));
|
||||||
lines.push(Line::from(Span::styled(" [Esc] Закрыть", Style::default().fg(Color::Yellow))));
|
lines.push(Line::from(Span::styled(
|
||||||
|
" [Esc] Закрыть",
|
||||||
|
Style::default().fg(Color::Yellow),
|
||||||
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
let block = Block::default()
|
let block = Block::default()
|
||||||
.borders(Borders::ALL)
|
.borders(Borders::ALL)
|
||||||
.title(title)
|
.title(title)
|
||||||
.border_style(Style::default().fg(border_color));
|
.border_style(Style::default().fg(border_color));
|
||||||
f.render_widget(Paragraph::new(lines).block(block).wrap(Wrap { trim: true }), popup_area);
|
let paragraph = Paragraph::new(lines)
|
||||||
}
|
.block(block)
|
||||||
|
.wrap(Wrap { trim: true });
|
||||||
Popup::EndpointSelector { selected, scroll_offset } => {
|
f.render_widget(paragraph, popup_area);
|
||||||
let popup_area = centered_rect(70, 60, area);
|
|
||||||
f.render_widget(Clear, popup_area);
|
|
||||||
|
|
||||||
let endpoints = &config.endpoints;
|
|
||||||
let total = endpoints.len();
|
|
||||||
let inner_h = popup_area.height.saturating_sub(2) as usize;
|
|
||||||
|
|
||||||
let name_col_w = endpoints.iter()
|
|
||||||
.map(|ep| ep.name.chars().count())
|
|
||||||
.max()
|
|
||||||
.unwrap_or(8)
|
|
||||||
.max(8);
|
|
||||||
|
|
||||||
if *selected < *scroll_offset {
|
|
||||||
*scroll_offset = *selected;
|
|
||||||
} else if inner_h > 0 && *selected >= *scroll_offset + inner_h {
|
|
||||||
*scroll_offset = selected.saturating_sub(inner_h - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
let start = *scroll_offset;
|
|
||||||
let end = (start + inner_h).min(total);
|
|
||||||
|
|
||||||
let items: Vec<ListItem> = endpoints.get(start..end).unwrap_or(&[])
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(i, ep)| {
|
|
||||||
let abs = start + i;
|
|
||||||
let is_selected = abs == *selected;
|
|
||||||
let is_active = ep.url == config.active_endpoint;
|
|
||||||
|
|
||||||
let prefix = if is_selected { "▶ " } else { " " };
|
|
||||||
let n = ep.name.chars().count();
|
|
||||||
let pad = if n < name_col_w { " ".repeat(name_col_w - n) } else { String::new() };
|
|
||||||
|
|
||||||
let (bg, name_fg, url_fg) = if is_selected {
|
|
||||||
(Color::Blue, Color::White, Color::Gray)
|
|
||||||
} else {
|
|
||||||
(Color::Reset, Color::White, Color::DarkGray)
|
|
||||||
};
|
|
||||||
|
|
||||||
let name_style = if is_active {
|
|
||||||
Style::default().fg(name_fg).bg(bg).add_modifier(Modifier::BOLD)
|
|
||||||
} else {
|
|
||||||
Style::default().fg(name_fg).bg(bg)
|
|
||||||
};
|
|
||||||
|
|
||||||
ListItem::new(Line::from(vec![
|
|
||||||
Span::styled(prefix, Style::default().bg(bg)),
|
|
||||||
Span::styled(format!("{}{}", ep.name, pad), name_style),
|
|
||||||
Span::styled(" ", Style::default().bg(bg)),
|
|
||||||
Span::styled(ep.url.clone(), Style::default().fg(url_fg).bg(bg)),
|
|
||||||
]))
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
let active_name = config.endpoints.iter()
|
|
||||||
.find(|ep| ep.url == config.active_endpoint)
|
|
||||||
.map(|ep| ep.name.as_str())
|
|
||||||
.unwrap_or("—");
|
|
||||||
|
|
||||||
let block = Block::default()
|
|
||||||
.borders(Borders::ALL)
|
|
||||||
.title(format!(" Эндпоинты [активен: {}] ", active_name))
|
|
||||||
.title(
|
|
||||||
Line::from(Span::styled(" [Esc] ", Style::default().fg(Color::DarkGray)))
|
|
||||||
.alignment(Alignment::Right),
|
|
||||||
)
|
|
||||||
.title_bottom(
|
|
||||||
Line::from(Span::styled(
|
|
||||||
" [N] добавить [E] редактировать [D] удалить ",
|
|
||||||
Style::default().fg(Color::DarkGray),
|
|
||||||
))
|
|
||||||
.alignment(Alignment::Right),
|
|
||||||
)
|
|
||||||
.border_style(Style::default().fg(Color::Cyan));
|
|
||||||
|
|
||||||
f.render_widget(List::new(items).block(block), popup_area);
|
|
||||||
|
|
||||||
if total > inner_h {
|
|
||||||
let max_off = total.saturating_sub(inner_h);
|
|
||||||
let scrollbar = Scrollbar::default()
|
|
||||||
.orientation(ScrollbarOrientation::VerticalRight)
|
|
||||||
.begin_symbol(Some("▲"))
|
|
||||||
.end_symbol(Some("▼"))
|
|
||||||
.thumb_symbol("█");
|
|
||||||
let mut sb_state = ScrollbarState::new(max_off).position(start);
|
|
||||||
let sb_area = Rect {
|
|
||||||
x: popup_area.x + popup_area.width.saturating_sub(1),
|
|
||||||
y: popup_area.y + 1,
|
|
||||||
width: 1,
|
|
||||||
height: popup_area.height.saturating_sub(2),
|
|
||||||
};
|
|
||||||
f.render_stateful_widget(scrollbar, sb_area, &mut sb_state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Popup::UpsertEndpoint { edit_index, fields, active_field, error, .. } => {
|
|
||||||
let popup_area = centered_rect(60, 50, area);
|
|
||||||
f.render_widget(Clear, popup_area);
|
|
||||||
|
|
||||||
let chunks = Layout::default()
|
|
||||||
.direction(Direction::Vertical)
|
|
||||||
.margin(1)
|
|
||||||
.constraints([
|
|
||||||
Constraint::Length(3),
|
|
||||||
Constraint::Length(3),
|
|
||||||
Constraint::Length(2),
|
|
||||||
Constraint::Min(0),
|
|
||||||
])
|
|
||||||
.split(popup_area);
|
|
||||||
|
|
||||||
render_text_field(f, " Название ", &fields[0], *active_field == 0, chunks[0]);
|
|
||||||
render_text_field(f, " URL ", &fields[1], *active_field == 1, chunks[1]);
|
|
||||||
|
|
||||||
if let Some(err) = error {
|
|
||||||
f.render_widget(
|
|
||||||
Paragraph::new(err.as_str())
|
|
||||||
.style(Style::default().fg(Color::Red))
|
|
||||||
.wrap(Wrap { trim: true }),
|
|
||||||
chunks[2],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Real terminal cursor in the active field
|
|
||||||
let af = *active_field;
|
|
||||||
let cx = (chunks[af].x + 1 + display_cols(&fields[af].buf, fields[af].cursor))
|
|
||||||
.min(chunks[af].x + chunks[af].width.saturating_sub(2));
|
|
||||||
f.set_cursor_position((cx, chunks[af].y + 1));
|
|
||||||
|
|
||||||
|
|
||||||
let (title, hint) = if edit_index.is_some() {
|
|
||||||
(" Редактировать эндпоинт ", " Enter — далее / сохранить ")
|
|
||||||
} else {
|
|
||||||
(" Добавить эндпоинт ", " Enter — далее / добавить ")
|
|
||||||
};
|
|
||||||
|
|
||||||
f.render_widget(
|
|
||||||
Block::default()
|
|
||||||
.borders(Borders::ALL)
|
|
||||||
.title(title)
|
|
||||||
.title(
|
|
||||||
Line::from(Span::styled(" [Esc] ", Style::default().fg(Color::DarkGray)))
|
|
||||||
.alignment(Alignment::Right),
|
|
||||||
)
|
|
||||||
.title_bottom(
|
|
||||||
Line::from(Span::styled(hint, Style::default().fg(Color::DarkGray)))
|
|
||||||
.alignment(Alignment::Right),
|
|
||||||
)
|
|
||||||
.border_style(Style::default().fg(Color::Cyan)),
|
|
||||||
popup_area,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Popup::AccessDenied { endpoint_url } => {
|
|
||||||
let popup_area = centered_rect(55, 30, area);
|
|
||||||
f.render_widget(Clear, popup_area);
|
|
||||||
|
|
||||||
let name = config.endpoints.iter()
|
|
||||||
.find(|ep| &ep.url == endpoint_url)
|
|
||||||
.map(|ep| ep.name.as_str())
|
|
||||||
.unwrap_or(endpoint_url.as_str());
|
|
||||||
|
|
||||||
let text = vec![
|
|
||||||
Line::from(""),
|
|
||||||
Line::from(Span::raw(format!(" Сервер «{}» запретил доступ.", name))),
|
|
||||||
Line::from(""),
|
|
||||||
Line::from(Span::styled(
|
|
||||||
" [Y] Запросить доступ [N / Esc] Отмена",
|
|
||||||
Style::default().fg(Color::Yellow),
|
|
||||||
)),
|
|
||||||
];
|
|
||||||
f.render_widget(
|
|
||||||
Paragraph::new(text)
|
|
||||||
.block(Block::default().borders(Borders::ALL).title(" Доступ запрещён ")
|
|
||||||
.border_style(Style::default().fg(Color::Red)))
|
|
||||||
.wrap(Wrap { trim: true }),
|
|
||||||
popup_area,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Popup::ConfirmDeleteEndpoint { index, .. } => {
|
|
||||||
let popup_area = centered_rect(50, 30, area);
|
|
||||||
f.render_widget(Clear, popup_area);
|
|
||||||
|
|
||||||
let name = config.endpoints.get(*index).map(|ep| ep.name.as_str()).unwrap_or("?");
|
|
||||||
let text = vec![
|
|
||||||
Line::from(""),
|
|
||||||
Line::from(Span::raw(format!(" Удалить эндпоинт «{}»?", name))),
|
|
||||||
Line::from(""),
|
|
||||||
Line::from(Span::styled(" [Y] Да [N / Esc] Нет", Style::default().fg(Color::Yellow))),
|
|
||||||
];
|
|
||||||
f.render_widget(
|
|
||||||
Paragraph::new(text)
|
|
||||||
.block(Block::default().borders(Borders::ALL).title(" Подтверждение ")
|
|
||||||
.border_style(Style::default().fg(Color::Yellow)))
|
|
||||||
.wrap(Wrap { trim: true }),
|
|
||||||
popup_area,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Renders a labelled text field with colored border for active/inactive state.
|
|
||||||
fn render_text_field(f: &mut Frame, label: &str, input: &TextInput, is_active: bool, area: Rect) {
|
|
||||||
let color = if is_active { Color::Cyan } else { Color::DarkGray };
|
|
||||||
f.render_widget(
|
|
||||||
Paragraph::new(input.buf.as_str()).block(
|
|
||||||
Block::default().borders(Borders::ALL).title(label)
|
|
||||||
.border_style(Style::default().fg(color)),
|
|
||||||
),
|
|
||||||
area,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_command(
|
fn render_command(
|
||||||
f: &mut Frame,
|
f: &mut Frame,
|
||||||
cmd: &executor::StructuredCommand,
|
cmd: &executor::StructuredCommand,
|
||||||
input: &TextInput,
|
input_buffer: &str,
|
||||||
menu_selected_index: usize,
|
menu_selected_index: usize,
|
||||||
form_cursor: usize,
|
|
||||||
form_values: &[bool],
|
|
||||||
area: Rect,
|
area: Rect,
|
||||||
) {
|
) {
|
||||||
match cmd {
|
match cmd {
|
||||||
executor::StructuredCommand::Input { prompt, secret, .. } => {
|
executor::StructuredCommand::Input { prompt, secret, .. } => {
|
||||||
let display = if *secret {
|
let display = if *secret {
|
||||||
"•".repeat(input.buf.chars().count())
|
"•".repeat(input_buffer.chars().count())
|
||||||
} else {
|
} else {
|
||||||
input.buf.clone()
|
input_buffer.to_string()
|
||||||
};
|
};
|
||||||
f.render_widget(
|
let paragraph = Paragraph::new(display.as_str()).block(
|
||||||
Paragraph::new(display.as_str()).block(
|
Block::default()
|
||||||
Block::default().borders(Borders::ALL).title(format!(" {} ", prompt))
|
.borders(Borders::ALL)
|
||||||
|
.title(format!(" {} ", prompt))
|
||||||
.border_style(Style::default().fg(Color::Cyan)),
|
.border_style(Style::default().fg(Color::Cyan)),
|
||||||
),
|
|
||||||
area,
|
|
||||||
);
|
);
|
||||||
let col = if *secret { input.cursor as u16 } else { display_cols(&input.buf, input.cursor) };
|
f.render_widget(paragraph, area);
|
||||||
let cursor_x = (area.x + 1 + col).min(area.x + area.width.saturating_sub(2));
|
let cursor_x = (area.x + 1 + input_buffer.chars().count() as u16)
|
||||||
|
.min(area.x + area.width.saturating_sub(2));
|
||||||
f.set_cursor_position((cursor_x, area.y + 1));
|
f.set_cursor_position((cursor_x, area.y + 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -673,7 +393,12 @@ fn render_command(
|
|||||||
if i == menu_selected_index {
|
if i == menu_selected_index {
|
||||||
ListItem::new(Line::from(vec![
|
ListItem::new(Line::from(vec![
|
||||||
Span::styled(" ▶ ", Style::default().fg(Color::Cyan)),
|
Span::styled(" ▶ ", Style::default().fg(Color::Cyan)),
|
||||||
Span::styled(opt.label.as_str(), Style::default().bg(Color::Blue).add_modifier(Modifier::BOLD)),
|
Span::styled(
|
||||||
|
opt.label.as_str(),
|
||||||
|
Style::default()
|
||||||
|
.bg(Color::Blue)
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
),
|
||||||
]))
|
]))
|
||||||
} else {
|
} else {
|
||||||
ListItem::new(Line::from(vec![
|
ListItem::new(Line::from(vec![
|
||||||
@@ -687,32 +412,40 @@ fn render_command(
|
|||||||
let mut state = ListState::default();
|
let mut state = ListState::default();
|
||||||
state.select(Some(menu_selected_index));
|
state.select(Some(menu_selected_index));
|
||||||
|
|
||||||
f.render_stateful_widget(
|
let list = List::new(items).block(
|
||||||
List::new(items).block(
|
Block::default()
|
||||||
Block::default().borders(Borders::ALL).title(format!(" {} ", prompt))
|
.borders(Borders::ALL)
|
||||||
|
.title(format!(" {} ", prompt))
|
||||||
.title_bottom(
|
.title_bottom(
|
||||||
Line::from(Span::styled(" ↑↓ навигация Enter выбор ", Style::default().fg(Color::DarkGray)))
|
Line::from(Span::styled(
|
||||||
|
" ↑↓ навигация Enter выбор ",
|
||||||
|
Style::default().fg(Color::DarkGray),
|
||||||
|
))
|
||||||
.alignment(Alignment::Right),
|
.alignment(Alignment::Right),
|
||||||
)
|
)
|
||||||
.border_style(Style::default().fg(Color::Cyan)),
|
.border_style(Style::default().fg(Color::Cyan)),
|
||||||
),
|
|
||||||
area,
|
|
||||||
&mut state,
|
|
||||||
);
|
);
|
||||||
|
f.render_stateful_widget(list, area, &mut state);
|
||||||
}
|
}
|
||||||
|
|
||||||
executor::StructuredCommand::Confirm { prompt } => {
|
executor::StructuredCommand::Confirm { prompt } => {
|
||||||
f.render_widget(
|
let text = vec![
|
||||||
Paragraph::new(vec![
|
|
||||||
Line::from(Span::raw(prompt.as_str())),
|
Line::from(Span::raw(prompt.as_str())),
|
||||||
Line::from(""),
|
Line::from(""),
|
||||||
Line::from(Span::styled(" [Y] Да [N / Esc] Нет", Style::default().fg(Color::Yellow))),
|
Line::from(Span::styled(
|
||||||
])
|
" [Y] Да [N / Esc] Нет",
|
||||||
.block(Block::default().borders(Borders::ALL).title(" Подтверждение ")
|
Style::default().fg(Color::Yellow),
|
||||||
.border_style(Style::default().fg(Color::Yellow)))
|
)),
|
||||||
.wrap(Wrap { trim: true }),
|
];
|
||||||
area,
|
let paragraph = Paragraph::new(text)
|
||||||
);
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.title(" Подтверждение ")
|
||||||
|
.border_style(Style::default().fg(Color::Yellow)),
|
||||||
|
)
|
||||||
|
.wrap(Wrap { trim: true });
|
||||||
|
f.render_widget(paragraph, area);
|
||||||
}
|
}
|
||||||
|
|
||||||
executor::StructuredCommand::Message { level, text } => {
|
executor::StructuredCommand::Message { level, text } => {
|
||||||
@@ -721,190 +454,81 @@ fn render_command(
|
|||||||
executor::MessageLevel::Warn => Color::Yellow,
|
executor::MessageLevel::Warn => Color::Yellow,
|
||||||
executor::MessageLevel::Error => Color::Red,
|
executor::MessageLevel::Error => Color::Red,
|
||||||
};
|
};
|
||||||
f.render_widget(
|
let lines = vec![
|
||||||
Paragraph::new(vec![
|
|
||||||
Line::from(Span::styled(text.as_str(), Style::default().fg(color))),
|
Line::from(Span::styled(text.as_str(), Style::default().fg(color))),
|
||||||
Line::from(""),
|
Line::from(""),
|
||||||
Line::from(Span::styled(" Нажмите Enter для продолжения", Style::default().fg(Color::DarkGray))),
|
Line::from(Span::styled(
|
||||||
])
|
" Нажмите Enter для продолжения",
|
||||||
.block(Block::default().borders(Borders::ALL).title(" Сообщение ")
|
Style::default().fg(Color::DarkGray),
|
||||||
.border_style(Style::default().fg(color)))
|
)),
|
||||||
.wrap(Wrap { trim: true }),
|
];
|
||||||
area,
|
let paragraph = Paragraph::new(lines)
|
||||||
);
|
.block(
|
||||||
|
Block::default()
|
||||||
|
.borders(Borders::ALL)
|
||||||
|
.title(" Сообщение ")
|
||||||
|
.border_style(Style::default().fg(color)),
|
||||||
|
)
|
||||||
|
.wrap(Wrap { trim: true });
|
||||||
|
f.render_widget(paragraph, area);
|
||||||
}
|
}
|
||||||
|
|
||||||
executor::StructuredCommand::Progress { percent, message } => {
|
executor::StructuredCommand::Progress { percent, message } => {
|
||||||
let msg = message.as_deref().unwrap_or("");
|
|
||||||
match percent {
|
|
||||||
Some(pct) => {
|
|
||||||
let bar_width = area.width.saturating_sub(4) as usize;
|
let bar_width = area.width.saturating_sub(4) as usize;
|
||||||
let filled = (*pct as usize * bar_width) / 100;
|
let filled = (*percent as usize * bar_width) / 100;
|
||||||
let bar = format!(
|
let bar = format!(
|
||||||
"[{}{}] {}%",
|
"[{}{}] {}%",
|
||||||
"█".repeat(filled),
|
"█".repeat(filled),
|
||||||
"░".repeat(bar_width.saturating_sub(filled)),
|
"░".repeat(bar_width.saturating_sub(filled)),
|
||||||
pct
|
percent
|
||||||
);
|
);
|
||||||
f.render_widget(
|
let msg = message.as_deref().unwrap_or("");
|
||||||
Paragraph::new(vec![Line::from(bar), Line::from(msg)])
|
let paragraph = Paragraph::new(vec![Line::from(bar), Line::from(msg)]).block(
|
||||||
.block(Block::default().borders(Borders::ALL).title(" Прогресс ")
|
Block::default()
|
||||||
.border_style(Style::default().fg(Color::Cyan))),
|
.borders(Borders::ALL)
|
||||||
area,
|
.title(" Прогресс ")
|
||||||
);
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
const SPINNER: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
||||||
let frame = (std::time::SystemTime::now()
|
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
|
||||||
.unwrap_or_default()
|
|
||||||
.as_millis() / 120) as usize;
|
|
||||||
let spinner = SPINNER[frame % SPINNER.len()];
|
|
||||||
f.render_widget(
|
|
||||||
Paragraph::new(format!("{} {}", spinner, msg))
|
|
||||||
.block(Block::default().borders(Borders::ALL).title(" Прогресс ")
|
|
||||||
.border_style(Style::default().fg(Color::Cyan))),
|
|
||||||
area,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
executor::StructuredCommand::Form { prompt, fields } => {
|
|
||||||
let items: Vec<ListItem> = fields.iter().enumerate().map(|(i, field)| {
|
|
||||||
let checked = form_values.get(i).copied().unwrap_or(false);
|
|
||||||
let icon = match field.field_type {
|
|
||||||
executor::FormFieldType::Checkbox => if checked { "[✓]" } else { "[ ]" },
|
|
||||||
executor::FormFieldType::Radio => if checked { "(●)" } else { "( )" },
|
|
||||||
};
|
|
||||||
let is_cursor = i == form_cursor;
|
|
||||||
let prefix = if is_cursor { "▶ " } else { " " };
|
|
||||||
let style = if is_cursor {
|
|
||||||
Style::default().bg(Color::Blue).add_modifier(Modifier::BOLD)
|
|
||||||
} else {
|
|
||||||
Style::default()
|
|
||||||
};
|
|
||||||
ListItem::new(Line::from(vec![
|
|
||||||
Span::raw(format!("{}{} {}", prefix, icon, field.label)),
|
|
||||||
])).style(style)
|
|
||||||
}).collect();
|
|
||||||
|
|
||||||
let mut state = ListState::default();
|
|
||||||
state.select(Some(form_cursor));
|
|
||||||
|
|
||||||
f.render_stateful_widget(
|
|
||||||
List::new(items).block(
|
|
||||||
Block::default().borders(Borders::ALL).title(format!(" {} ", prompt))
|
|
||||||
.title_bottom(
|
|
||||||
Line::from(Span::styled(
|
|
||||||
" Space — переключить Enter/l — применить Esc — отмена ",
|
|
||||||
Style::default().fg(Color::DarkGray),
|
|
||||||
)).alignment(Alignment::Right),
|
|
||||||
)
|
|
||||||
.border_style(Style::default().fg(Color::Cyan)),
|
.border_style(Style::default().fg(Color::Cyan)),
|
||||||
),
|
|
||||||
area,
|
|
||||||
&mut state,
|
|
||||||
);
|
);
|
||||||
|
f.render_widget(paragraph, area);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Exec is handled by the main loop before rendering; this arm is
|
||||||
|
// never reached in practice but satisfies the exhaustiveness check.
|
||||||
executor::StructuredCommand::Exec { shell } => {
|
executor::StructuredCommand::Exec { shell } => {
|
||||||
f.render_widget(
|
let paragraph = Paragraph::new(format!("Запуск: {}", shell))
|
||||||
Paragraph::new(format!("Запуск: {}", shell))
|
.block(
|
||||||
.block(Block::default().borders(Borders::ALL).title(" Внешнее приложение ")
|
Block::default()
|
||||||
.border_style(Style::default().fg(Color::Magenta)))
|
.borders(Borders::ALL)
|
||||||
.wrap(Wrap { trim: true }),
|
.title(" Внешнее приложение ")
|
||||||
area,
|
.border_style(Style::default().fg(Color::Magenta)),
|
||||||
);
|
)
|
||||||
|
.wrap(Wrap { trim: true });
|
||||||
|
f.render_widget(paragraph, area);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Display-column width of `buf` up to char index `cursor`.
|
|
||||||
/// Accounts for wide characters (emoji, CJK) that occupy 2 terminal columns.
|
|
||||||
fn display_cols(buf: &str, cursor: usize) -> u16 {
|
|
||||||
buf.chars()
|
|
||||||
.take(cursor)
|
|
||||||
.map(|c| UnicodeWidthChar::width(c).unwrap_or(0))
|
|
||||||
.sum::<usize>() as u16
|
|
||||||
}
|
|
||||||
|
|
||||||
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
|
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
|
||||||
let popup_layout = Layout::default()
|
let popup_layout = Layout::default()
|
||||||
.direction(Direction::Vertical)
|
.direction(Direction::Vertical)
|
||||||
.constraints([
|
.constraints(
|
||||||
|
[
|
||||||
Constraint::Percentage((100 - percent_y) / 2),
|
Constraint::Percentage((100 - percent_y) / 2),
|
||||||
Constraint::Percentage(percent_y),
|
Constraint::Percentage(percent_y),
|
||||||
Constraint::Percentage((100 - percent_y) / 2),
|
Constraint::Percentage((100 - percent_y) / 2),
|
||||||
].as_ref())
|
]
|
||||||
|
.as_ref(),
|
||||||
|
)
|
||||||
.split(r);
|
.split(r);
|
||||||
Layout::default()
|
Layout::default()
|
||||||
.direction(Direction::Horizontal)
|
.direction(Direction::Horizontal)
|
||||||
.constraints([
|
.constraints(
|
||||||
|
[
|
||||||
Constraint::Percentage((100 - percent_x) / 2),
|
Constraint::Percentage((100 - percent_x) / 2),
|
||||||
Constraint::Percentage(percent_x),
|
Constraint::Percentage(percent_x),
|
||||||
Constraint::Percentage((100 - percent_x) / 2),
|
Constraint::Percentage((100 - percent_x) / 2),
|
||||||
].as_ref())
|
]
|
||||||
|
.as_ref(),
|
||||||
|
)
|
||||||
.split(popup_layout[1])[1]
|
.split(popup_layout[1])[1]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn wrap_to_lines(text: &str, max_width: usize) -> Vec<String> {
|
|
||||||
if max_width == 0 || text.is_empty() {
|
|
||||||
return vec![text.to_string()];
|
|
||||||
}
|
|
||||||
let mut lines: Vec<String> = Vec::new();
|
|
||||||
let mut current = String::new();
|
|
||||||
for word in text.split_whitespace() {
|
|
||||||
let wlen = word.chars().count();
|
|
||||||
if current.is_empty() {
|
|
||||||
if wlen > max_width {
|
|
||||||
let chars: Vec<char> = word.chars().collect();
|
|
||||||
for chunk in chars.chunks(max_width) {
|
|
||||||
let s: String = chunk.iter().collect();
|
|
||||||
if s.chars().count() == max_width {
|
|
||||||
lines.push(s);
|
|
||||||
} else {
|
|
||||||
current = s;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
current = word.to_string();
|
|
||||||
}
|
|
||||||
} else if current.chars().count() + 1 + wlen <= max_width {
|
|
||||||
current.push(' ');
|
|
||||||
current.push_str(word);
|
|
||||||
} else {
|
|
||||||
lines.push(std::mem::take(&mut current));
|
|
||||||
current = word.to_string();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !current.is_empty() {
|
|
||||||
lines.push(current);
|
|
||||||
}
|
|
||||||
if lines.is_empty() {
|
|
||||||
lines.push(String::new());
|
|
||||||
}
|
|
||||||
lines
|
|
||||||
}
|
|
||||||
|
|
||||||
fn h_scroll(parsed: Vec<(ratatui::style::Style, String)>, offset: usize) -> Vec<Span<'static>> {
|
|
||||||
let mut skip = offset;
|
|
||||||
let mut result = Vec::new();
|
|
||||||
for (style, text) in parsed {
|
|
||||||
if skip == 0 {
|
|
||||||
result.push(Span::styled(text, style));
|
|
||||||
} else {
|
|
||||||
let len = text.chars().count();
|
|
||||||
if skip >= len {
|
|
||||||
skip -= len;
|
|
||||||
} else {
|
|
||||||
let trimmed: String = text.chars().skip(skip).collect();
|
|
||||||
skip = 0;
|
|
||||||
if !trimmed.is_empty() {
|
|
||||||
result.push(Span::styled(trimmed, style));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -61,8 +61,8 @@ pub async fn check(api_base: &str, timeout_sec: u64) -> Result<Option<UpdateInfo
|
|||||||
let tag = tag.split('@').next().unwrap_or(tag).trim();
|
let tag = tag.split('@').next().unwrap_or(tag).trim();
|
||||||
let new_version = tag.to_string();
|
let new_version = tag.to_string();
|
||||||
|
|
||||||
// Only offer update if the remote version is strictly newer
|
// Already up to date
|
||||||
if !is_newer(&new_version, ¤t_version) {
|
if new_version == current_version {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,16 +185,6 @@ pub fn take_update_target() -> Option<String> {
|
|||||||
Some(version.trim().to_string())
|
Some(version.trim().to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns true if `candidate` is strictly greater than `current` by semver rules.
|
|
||||||
/// Parses `MAJOR.MINOR.PATCH`; any unparseable component is treated as 0.
|
|
||||||
fn is_newer(candidate: &str, current: &str) -> bool {
|
|
||||||
fn parse(v: &str) -> (u64, u64, u64) {
|
|
||||||
let mut parts = v.splitn(3, '.').map(|s| s.parse::<u64>().unwrap_or(0));
|
|
||||||
(parts.next().unwrap_or(0), parts.next().unwrap_or(0), parts.next().unwrap_or(0))
|
|
||||||
}
|
|
||||||
parse(candidate) > parse(current)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Replaces current process via execv (Unix). Never returns on success.
|
/// Replaces current process via execv (Unix). Never returns on success.
|
||||||
/// `exe_path` must be the path captured *before* the binary was replaced —
|
/// `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.
|
/// do NOT call std::env::current_exe() here, it returns "(deleted)" on Linux.
|
||||||
|
|||||||
48
uninstall.sh
48
uninstall.sh
@@ -1,4 +1,5 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
BINARY="ostiary"
|
BINARY="ostiary"
|
||||||
INSTALL_DIR="$HOME/.local/bin"
|
INSTALL_DIR="$HOME/.local/bin"
|
||||||
@@ -11,54 +12,49 @@ info() { echo -e "${CYAN}[ostiary]${NC} $*"; }
|
|||||||
ok() { echo -e "${GREEN}[ostiary]${NC} $*"; }
|
ok() { echo -e "${GREEN}[ostiary]${NC} $*"; }
|
||||||
warn() { echo -e "${YELLOW}[ostiary]${NC} $*"; }
|
warn() { echo -e "${YELLOW}[ostiary]${NC} $*"; }
|
||||||
|
|
||||||
# Read from /dev/tty so the script works when piped through bash
|
|
||||||
# (e.g. curl ... | bash), where stdin is the pipe, not the terminal.
|
|
||||||
ask() {
|
|
||||||
local answer
|
|
||||||
read -rp "$1 [y/N] " answer </dev/tty
|
|
||||||
[[ "$answer" =~ ^[Yy]$ ]]
|
|
||||||
}
|
|
||||||
|
|
||||||
# ── Remove binary ────────────────────────────────────────────────────────────
|
# ── Remove binary ────────────────────────────────────────────────────────────
|
||||||
BINARY_PATH="$INSTALL_DIR/$BINARY"
|
BINARY_PATH="$INSTALL_DIR/$BINARY"
|
||||||
|
|
||||||
if [ -f "$BINARY_PATH" ]; then
|
if [ -f "$BINARY_PATH" ]; then
|
||||||
info "Найден бинарник: $BINARY_PATH"
|
info "Found binary: $BINARY_PATH"
|
||||||
if ask " Удалить?"; then
|
read -rp " Remove it? [y/N] " answer
|
||||||
|
if [[ "$answer" =~ ^[Yy]$ ]]; then
|
||||||
rm "$BINARY_PATH"
|
rm "$BINARY_PATH"
|
||||||
ok "Бинарник удалён"
|
ok "Binary removed"
|
||||||
else
|
|
||||||
ok "Бинарник оставлен"
|
|
||||||
fi
|
fi
|
||||||
else
|
else
|
||||||
warn "Бинарник не найден в $BINARY_PATH"
|
warn "Binary not found at $BINARY_PATH"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ── Remove config ────────────────────────────────────────────────────────────
|
# ── Remove config ────────────────────────────────────────────────────────────
|
||||||
echo ""
|
|
||||||
if [ -d "$CONFIG_DIR" ]; then
|
if [ -d "$CONFIG_DIR" ]; then
|
||||||
info "Найден конфиг: $CONFIG_DIR"
|
echo ""
|
||||||
if ask " Удалить конфиг и настройки?"; then
|
info "Config directory: $CONFIG_DIR"
|
||||||
|
read -rp " Remove config and saved settings? [y/N] " answer
|
||||||
|
if [[ "$answer" =~ ^[Yy]$ ]]; then
|
||||||
rm -rf "$CONFIG_DIR"
|
rm -rf "$CONFIG_DIR"
|
||||||
ok "Конфиг удалён"
|
ok "Config removed"
|
||||||
else
|
else
|
||||||
ok "Конфиг оставлен: $CONFIG_DIR"
|
ok "Config kept at $CONFIG_DIR"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ── Remove PATH entry from shell profile ─────────────────────────────────────
|
# ── Remove PATH entry from shell profile ─────────────────────────────────────
|
||||||
for PROFILE in "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
|
for PROFILE in "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do
|
||||||
if [ -f "$PROFILE" ] && grep -qF "# Added by ostiary installer" "$PROFILE"; then
|
if [ -f "$PROFILE" ] && grep -qF ".local/bin" "$PROFILE"; then
|
||||||
echo ""
|
echo ""
|
||||||
info "Найдена запись PATH в $PROFILE"
|
info "Found PATH entry in $PROFILE"
|
||||||
if ask " Удалить строку PATH, добавленную установщиком?"; then
|
read -rp " Remove the PATH line added by ostiary installer? [y/N] " answer
|
||||||
sed -i '/# Added by ostiary installer/d' "$PROFILE"
|
if [[ "$answer" =~ ^[Yy]$ ]]; then
|
||||||
sed -i '/\.local\/bin.*PATH/d' "$PROFILE"
|
# Remove the comment and the export line added by install.sh
|
||||||
ok "Запись PATH удалена из $PROFILE"
|
sed -i.bak '/# Added by ostiary installer/d' "$PROFILE"
|
||||||
|
sed -i.bak '/\.local\/bin.*PATH/d' "$PROFILE"
|
||||||
|
rm -f "${PROFILE}.bak"
|
||||||
|
ok "PATH entry removed from $PROFILE"
|
||||||
fi
|
fi
|
||||||
break
|
break
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
ok "Готово"
|
ok "Done"
|
||||||
|
|||||||
Reference in New Issue
Block a user