cli/src/presentation.rs

652 lines
37 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Human-facing presentation; machine-readable keys are never translated.
use std::env;
pub fn russian() -> bool {
["LC_ALL", "LC_MESSAGES", "LANG"].iter()
.filter_map(|key| env::var(key).ok())
.find(|value| !value.is_empty())
.is_some_and(|value| value == "ru" || value.starts_with("ru_") || value.starts_with("ru."))
}
fn t(ru: bool, a: &'static str, b: &'static str) -> &'static str {
if ru { a } else { b }
}
/// Handle an explicit help request before daemon routing or argument parsing.
/// `Ok(text)` must be printed to stdout. `Err(text)` is an unknown command or
/// an unknown help topic and belongs on stderr with a usage exit code.
pub fn help_request(args: &[String]) -> Option<Result<String, String>> {
if args.is_empty() {
return Some(Ok(full_help(russian())));
}
if args[0] == "help" {
if args.len() == 1 {
return Some(Ok(full_help(russian())));
}
let tokens: Vec<&str> = args[1..].iter().map(String::as_str)
.filter(|a| !a.starts_with('-')).collect();
if tokens.is_empty() { return Some(Ok(full_help(russian()))); }
return Some(command_help(&tokens).ok_or_else(|| unknown_topic(&tokens)));
}
if !args.iter().any(|a| a == "--help" || a == "-h") {
return None;
}
let mut tokens = Vec::new();
let mut skip = false;
for arg in args {
if skip {
skip = false;
continue;
}
if matches!(arg.as_str(), "--request-id" | "--file" | "--plan" | "--reason" | "--purpose") {
skip = true;
continue;
}
if !arg.starts_with('-') {
tokens.push(arg.as_str());
}
}
if tokens.is_empty() {
return Some(Ok(full_help(russian())));
}
Some(command_help(&tokens).ok_or_else(|| unknown_topic(&tokens)))
}
fn unknown_topic(tokens: &[&str]) -> String {
let command = tokens.first().copied().unwrap_or("");
if russian() {
format!("Нет справки для «{command}». Общая справка: archipelago --help")
} else {
format!("No help for \"{command}\". General help: archipelago --help")
}
}
pub fn full_help(ru: bool) -> String {
let mut text = if ru {
format!("\
Archipelago — управление системой
Использование:
archipelago КОМАНДА [АРГУМЕНТЫ...]
archipelago help КОМАНДА
archipelago --version
Система:
status Загруженный и pending deployment, состояние обновлений
self-check Проверка владельца и целостности установленных файлов
update check | diff | plan Проверить обновления, показать изменения или подготовить план
update apply --plan SHA256 Применить проверенный план; последний шаг собирает недостижимые объекты OSTree
update download --plan SHA256 Загрузить и проверить без staging
extension status Состояние Host Extensions
extension add ПАКЕТ|ФАЙЛ... Добавить пакеты snapshot и/или локальные .pkg.tar.*
extension add --file ФАЙЛ Явный локальный архив
extension remove ПАКЕТ... Убрать явные запросы (пересборка без удаления данных)
extension enable | disable Включить или выключить слой Host Extensions
extension history История поколений
extension restore ID Восстановить точный набор из истории
extension import ФАЙЛ Импортировать локальный архив без плана
extension add-local INPUT_ID Добавить ранее импортированный вход
extension reset-override ИМЯ Снять явный override
extension override ID --replaces ИМЯ --reason ТЕКСТ
Заменить managed-пакет из репозитория явным решением
extension override-local ID --replaces ИМЯ --reason ТЕКСТ
Заменить managed-пакет локальным архивом
overlay status Состояние управляемых overlays
overlay list [ЗАПРОС] [CURSOR] Каталог доступных overlays
overlay add ID COMMIT Добавить overlay по точному commit
overlay remove ID Убрать overlay из выбора
overlay order ID... Задать полный порядок выбранных overlays
overlay clear Очистить выбор
kargs Параметры ядра следующей загрузки
kargs --append=ПАРАМЕТР Добавить параметр
kargs --append-if-missing=ПАРАМЕТР Добавить, если отсутствует
kargs --delete=ПАРАМЕТР Удалить (ошибка, если отсутствует)
kargs --delete-if-present=ПАРАМЕТР Удалить, если присутствует
kargs --replace=ИМЯ=ЗНАЧЕНИЕ Заменить; при неоднозначности ИМЯ=СТАРОЕ=НОВОЕ
transaction list [CURSOR] Операции daemon
transaction status ID Снимок операции
transaction log ID [CURSOR] Авторизованный журнал операции
transaction wait ID Дождаться операции
transaction cancel ID Запросить отмену
cleanup plan [--json] Отчёт о deployments, refs и размере OSTree
cleanup apply Собрать недостижимые OSTree-объекты
power hibernate-setup Спящий режим на диск (Desktop)
desktop reconcile Сверить desktop onboarding
desktop seed-flatpaks Подготовить базовые Flatpak-приложения
desktop refresh-updates Обновить состояние обновлений в desktop-интеграции
boot-sync Синхронизировать загрузочные записи
logs [--full] Последний локальный журнал CLI
service status | capabilities Состояние и возможности системной службы
Установка:
install /dev/ДИСК --erase Стереть выбранный диск и установить систему
firstboot Завершить создание основного пользователя
Сборка, registry и инфраструктура:
build iso [--purpose gnome|kde|container-runner] КАТАЛОГ BOOTSTRAP.tar.zst
layer validate МАНИФЕСТ
registry init|verify РЕПОЗИТОРИЙ
pipeline status
pipeline logs latest|ID
pipeline run --reason ТЕКСТ
release plan|publish CANDIDATES.json --reason ТЕКСТ
Диагностика и флаги:
logs [--full] Последний локальный журнал CLI
service host КОМАНДА Внутренний транспортный клиент; те же host-команды
--json JSON-результат installed-host, update и cleanup
--debug Технические события installed-host; для build — сырые строки
--verbose Строки дочерней операции build/install
--interactive Разрешить интерактивную авторизацию (installed-host)
--non-interactive Запретить интерактивную авторизацию (installed-host)
--offline Только проверенный кэш (installed-host update/extension)
--request-id UUID Явный токен запроса (installed-host)
--plan SHA256 План для update apply|download
--file ПУТЬ Локальный архив для extension add
--reason ТЕКСТ Причина release/pipeline
--purpose gnome|kde|container-runner Вариант build iso
--erase Разрешить стирание диска для install
--full Полный журнал для logs
-h, --help, help КОМАНДА Справка; help с командой показывает детали
Вывод: обычный — для человека; --json — один машинный документ; --debug —
технические события и авторизованные логи без анимации. --debug --json:
результат в stdout, диагностика в stderr.
Команды изменения установленной системы выполняются через archipelagod и Polkit.
Если служба недоступна, операция не выполняется; CLI не переключается на прямую
запись. Подготовленные изменения активируются только после явной перезагрузки.
Коды выхода: 0 — успех; 2 — неверные аргументы; 4 — авторизация/доверие;
5 — устаревшее состояние/конфликт; 6 — занято; 7 — сеть/недоступность/место;
8 — операция не выполнена или прервана.")
} else {
format!("\
Archipelago — system management
Usage:
archipelago COMMAND [ARGS...]
archipelago help COMMAND
archipelago --version
System:
status Booted and pending deployments, update state
self-check Verify package ownership and installed file integrity
update check | diff | plan Check updates, show changes, or prepare a plan
update apply --plan SHA256 Apply a checked plan; the last step collects unreachable OSTree objects
update download --plan SHA256 Download and verify without staging
extension status Host Extension state
extension add PACKAGE|FILE... Add snapshot packages and/or local .pkg.tar.* archives
extension add --file FILE Explicit local archive
extension remove PACKAGE... Remove explicit requests (rebuild without deleting data)
extension enable | disable Enable or disable the Host Extension layer
extension history Generation history
extension restore ID Restore an exact retained generation
extension import FILE Import a local archive without a plan
extension add-local INPUT_ID Add a previously imported input
extension reset-override NAME Remove an explicit override
extension override ID --replaces NAME --reason TEXT
Replace a managed repository package explicitly
extension override-local ID --replaces NAME --reason TEXT
Replace a managed package with a local archive
overlay status Managed overlay state
overlay list [QUERY] [CURSOR] Available overlay catalog
overlay add ID COMMIT Add an overlay by exact commit
overlay remove ID Remove an overlay from the selection
overlay order ID... Set the complete order of selected overlays
overlay clear Clear the selection
kargs Kernel arguments for the next boot
kargs --append=ARG Append
kargs --append-if-missing=ARG Append only if absent
kargs --delete=ARG Delete (error if absent)
kargs --delete-if-present=ARG Delete if present
kargs --replace=KEY=VALUE Replace; KEY=OLD=NEW when ambiguous
transaction list [CURSOR] Daemon operations
transaction status ID Operation snapshot
transaction log ID [CURSOR] Authorized operation log
transaction wait ID Wait for an operation
transaction cancel ID Request cancellation
cleanup plan [--json] Inventory deployments, refs and OSTree size
cleanup apply Collect unreachable OSTree objects
power hibernate-setup Enable sleep-to-disk (Desktop)
desktop reconcile Reconcile desktop onboarding
desktop seed-flatpaks Seed default Flatpak applications
desktop refresh-updates Refresh the desktop update state
boot-sync Synchronize boot entries
logs [--full] Latest local CLI transaction log
service status | capabilities System service state and capabilities
Kernel arguments:
kargs Show arguments for the next boot.
kargs --append=ARG Append.
kargs --append-if-missing=ARG Append only if absent.
kargs --delete=ARG Delete if present (error if absent).
kargs --delete-if-present=ARG Delete if present.
kargs --replace=KEY=VALUE Replace; if ambiguous use KEY=OLD=NEW.
Edits may be repeated. Activation requires an explicit reboot.
Installation:
install /dev/DISK --erase Erase the selected disk and install
firstboot Complete primary-user onboarding
Build, registry and infrastructure:
build iso [--purpose gnome|kde|container-runner] WORKDIR BOOTSTRAP.tar.zst
layer validate MANIFEST
registry init|verify REPOSITORY
pipeline status
pipeline logs latest|ID
pipeline run --reason TEXT
release plan|publish CANDIDATES.json --reason TEXT
Diagnostics and output:
logs [--full] Latest local CLI transaction log
service host COMMAND Internal transport diagnostic; same installed-host commands
--json JSON result for installed-host, update and cleanup
--debug Installed-host technical events; raw lines for build
--verbose Child-operation lines for build/install
--interactive Allow interactive Polkit authorization (installed-host)
--non-interactive Disallow interactive authorization (installed-host)
--offline Only verified cached inputs (installed-host update/extension)
--request-id UUID Explicit request token (installed-host)
--plan SHA256 Plan for update apply|download
--file PATH Local archive for extension add
--reason TEXT Reason for release/pipeline
--purpose gnome|kde|container-runner build iso variant
--erase Permit disk erasure for install
--full Full log for logs
-h, --help, help COMMAND Help; `help COMMAND` shows details
Installed-host output: human by default; --json emits one JSON document;
--debug emits technical events and authorized logs without animation.
--debug --json: JSON result on stdout, diagnostics on stderr.
Mutating installed-host commands run through archipelagod and Polkit. If the
service is unavailable, the command fails and does not switch to a direct write.
Prepared changes activate after an explicit reboot.
Exit codes: 0 — success; 2 — invalid arguments; 4 — authorization/trust;
5 — stale state/conflict; 6 — busy; 7 — network/unavailable/space;
8 — operation failed or interrupted.")
};
if cfg!(feature = "lab-fixtures") {
text.push_str(if ru {
"\nЛабораторные (сборка с lab-fixtures):\n overlay apply test-marker Тестовый overlay для приёмочных проверок\n"
} else {
"\nLab (lab-fixtures build only):\n overlay apply test-marker Acceptance-test overlay\n"
});
}
text
}
/// Detailed help for a command family. `tokens` are non-option words before
/// `--help`, or the words after `help`. The first word selects the family.
pub fn command_help(tokens: &[&str]) -> Option<String> {
let ru = russian();
match tokens.first().copied()? {
"status" => Some(t(ru, "\
Использование: archipelago status [--json]
Показывает загруженный и pending deployment, доступность обновления и состояние
Host Extensions. Не изменяет систему. --json выводит один документ.", "\
Usage: archipelago status [--json]
Shows booted and pending deployments, update availability and Host Extension state.
Read-only. --json emits one document.").to_string()),
"self-check" => Some(t(ru, "\
Использование: archipelago self-check
Проверяет владельца и целостность файлов пакета archipelago. Обычно запускается
при сборке, после установки и после активации расширений.", "\
Usage: archipelago self-check
Verifies ownership and installed-file integrity of the archipelago package. It is
normally run during image builds, after installation and after activating extensions.").to_string()),
"update" => Some(t(ru, "\
Использование:
archipelago update check [--json]
archipelago update diff [--json]
archipelago update plan [--json]
archipelago update apply --plan SHA256
archipelago update download --plan SHA256
check — проверить подписанный track и доступное обновление.
diff — показать изменения пакетов для проверенного target.
plan — сохранить immutable-план; применение требует --plan.
apply — загрузить, проверить, подготовить новый deployment и собрать старые
недостижимые OSTree-объекты. Активация — только явной перезагрузкой.
download — загрузить и проверить без staging.
--offline разрешает только уже проверенный кэш. --interactive разрешает Polkit
в текущем сеансе; --non-interactive запрещает. Без --json ошибки выводятся
по-человечески, технический журнал остаётся по ID операции.", "\
Usage:
archipelago update check [--json]
archipelago update diff [--json]
archipelago update plan [--json]
archipelago update apply --plan SHA256
archipelago update download --plan SHA256
check — verify the signed track and the available update.
diff — show package changes for the verified target.
plan — persist an immutable plan; applying requires --plan.
apply — download, verify, prepare a new deployment and collect superseded
unreachable OSTree objects. Activation requires an explicit reboot.
download — download and verify without staging.
--offline permits only verified cached inputs. --interactive permits Polkit in
the current session; --non-interactive forbids it. Without --json, errors are
rendered for humans; the technical log remains available by operation ID.").to_string()),
"extension" => Some(t(ru, "\
Использование:
archipelago extension status [--json]
archipelago extension add ПАКЕТ|ФАЙЛ... [--file ФАЙЛ]
archipelago extension remove ПАКЕТ...
archipelago extension enable | disable
archipelago extension history
archipelago extension restore ID
archipelago extension import ФАЙЛ
archipelago extension add-local INPUT_ID
archipelago extension reset-override ИМЯ
archipelago extension override ID --replaces ИМЯ --reason ТЕКСТ
archipelago extension override-local ID --replaces ИМЯ --reason ТЕКСТ
add принимает имена пакетов snapshot и локальные архивы. Путь распознаётся по
./, ../, /, ~/ или суффиксу .pkg.tar.*; имя без пути всегда означает пакет
snapshot и не ищется на диске. Несколько имён и архивов образуют один план и
один Stage. Локальный архив передаётся через защищённый FD, сохраняется как
source=local и оставляет композицию unsupported. Импорт сам по себе deployment
не меняет. remove пересобирает набор без удаления пользовательских данных.
После Stage изменения ждут явной перезагрузки; повторный add уже запрошенного
пакета является no-op. --json выводит один документ; --debug показывает
технические события. Ошибки указывают операцию и журнал для продолжения.", "\
Usage:
archipelago extension status [--json]
archipelago extension add PACKAGE|FILE... [--file FILE]
archipelago extension remove PACKAGE...
archipelago extension enable | disable
archipelago extension history
archipelago extension restore ID
archipelago extension import FILE
archipelago extension add-local INPUT_ID
archipelago extension reset-override NAME
archipelago extension override ID --replaces NAME --reason TEXT
archipelago extension override-local ID --replaces NAME --reason TEXT
add accepts snapshot package names and local archives. A path is recognized by
./, ../, /, ~/ or a .pkg.tar.* suffix; a bare name always means a snapshot
package and is never resolved from disk. Several names and archives form one plan
and one Stage. A local archive is passed through a protected FD, retained as
source=local and leaves the composition unsupported. Import alone changes no
deployment. remove rebuilds the remaining set without deleting user data.
After Stage, changes wait for an explicit reboot; adding an already requested
package is a no-op. --json emits one document; --debug shows technical events.
Errors name the operation and its log so the next step is clear.").to_string()),
"overlay" => Some(t(ru, "\
Использование:
archipelago overlay status
archipelago overlay list [ЗАПРОС] [CURSOR]
archipelago overlay add ID COMMIT
archipelago overlay remove ID
archipelago overlay order ID...
archipelago overlay clear
Overlay выбирается по точному commit из подписанного каталога. order задаёт
полный порядок и должен перечислять каждый выбранный overlay ровно один раз.
Подготовленный набор активируется только явной перезагрузкой.", "\
Usage:
archipelago overlay status
archipelago overlay list [QUERY] [CURSOR]
archipelago overlay add ID COMMIT
archipelago overlay remove ID
archipelago overlay order ID...
archipelago overlay clear
An overlay is selected by exact commit from the signed catalog. order sets the
complete order and must name every selected overlay exactly once. A prepared set
activates only after an explicit reboot.").to_string()),
"kargs" => Some(t(ru, "\
Использование:
archipelago kargs
archipelago kargs --append=ПАРАМЕТР
archipelago kargs --append-if-missing=ПАРАМЕТР
archipelago kargs --delete=ПАРАМЕТР
archipelago kargs --delete-if-present=ПАРАМЕТР
archipelago kargs --replace=ИМЯ=ЗНАЧЕНИЕ
archipelago kargs --replace=ИМЯ=СТАРОЕ=НОВОЕ
Операции можно повторять. --delete завершается ошибкой, если параметра нет;
--delete-if-present идемпотентен. Для replace при нескольких совпадениях нужно
указать старое значение. Изменения применяются к следующей загрузке после
явной перезагрузки; текущий deployment не меняется.", "\
Usage:
archipelago kargs
archipelago kargs --append=ARG
archipelago kargs --append-if-missing=ARG
archipelago kargs --delete=ARG
archipelago kargs --delete-if-present=ARG
archipelago kargs --replace=KEY=VALUE
archipelago kargs --replace=KEY=OLD=NEW
Edits may be repeated. --delete fails when the argument is absent;
--delete-if-present is idempotent. For replace with multiple matches, provide the
old value. Changes apply to the next boot after an explicit reboot; the current
deployment is unchanged.").to_string()),
"transaction" => Some(t(ru, "\
Использование:
archipelago transaction list [CURSOR]
archipelago transaction status ID
archipelago transaction log ID [CURSOR]
archipelago transaction wait ID
archipelago transaction cancel ID
ID — идентификатор операции (diagnostic_id). list и log используют курсор для
постраничного чтения. log требует авторизации чтения журнала. wait возвращает
итог операции; cancel только запрашивает отмену.", "\
Usage:
archipelago transaction list [CURSOR]
archipelago transaction status ID
archipelago transaction log ID [CURSOR]
archipelago transaction wait ID
archipelago transaction cancel ID
ID is an operation identifier (diagnostic_id). list and log paginate by cursor.
log requires authorization to read the journal. wait returns the operation result;
cancel only requests cancellation.").to_string()),
"cleanup" => Some(t(ru, "\
Использование: archipelago cleanup plan [--json] | apply
plan только читает deployment-корни, overlay/extension intent, keep/service refs
и размер OSTree. apply под общим host lock создаёт keep-refs, истекает свои
устаревшие refs и запускает только ostree prune --refs-only. Deployments и
stable/* не удаляются. apply отказывается работать при pending deployment;
во время успешного Stage та же очистка выполняется автоматически.", "\
Usage: archipelago cleanup plan [--json] | apply
plan is read-only: deployment roots, overlay/extension intent, keep/service refs
and OSTree size. apply takes the shared host lock, creates keep refs, expires its
own stale refs and runs only ostree prune --refs-only. Deployments and stable/*
are not removed. apply refuses a pending deployment; a successful Stage runs the
same collection automatically.").to_string()),
"logs" => Some(t(ru, "\
Использование: archipelago logs [--full]
Показывает путь к последнему локальному журналу CLI и его хвост; --full печатает
журнал целиком. Это журнал клиента, не журнал операции daemon: для конкретной
операции используйте archipelago transaction log ID.", "\
Usage: archipelago logs [--full]
Prints the latest local CLI log path and tail; --full prints the whole log. This
is the client log, not a daemon operation journal: for one operation use
archipelago transaction log ID.").to_string()),
"service" => Some(t(ru, "\
Использование:
archipelago service status
archipelago service capabilities
archipelago service host КОМАНДА [АРГУМЕНТЫ...]
status и capabilities только читают D-Bus API. service host — внутренний
транспортный клиент для установленных хостов; он принимает те же команды, что и
обычный CLI, но не выполняет локальный fallback. Ошибки сервиса выводятся
по-человечески; --debug показывает технические детали.", "\
Usage:
archipelago service status
archipelago service capabilities
archipelago service host COMMAND [ARGS...]
status and capabilities are read-only D-Bus queries. service host is an internal
transport client for installed hosts; it accepts the same commands as the normal
CLI and never performs a local fallback. Service errors are rendered for humans;
--debug shows technical details.").to_string()),
"build" => Some(t(ru, "\
Использование:
archipelago build iso КАТАЛОГ BOOTSTRAP.tar.zst
archipelago build iso --purpose gnome|kde|container-runner КАТАЛОГ BOOTSTRAP.tar.zst
Сборка выполняется в изолированном Arch/nspawn на build host. КАТАЛОГ должен быть
новым; BOOTSTRAP проверяется по закреплённому SHA-256. Для Purpose-вариантов
используется Core этого же прогона. Это инфраструктурная команда, не команда
установленной системы.", "\
Usage:
archipelago build iso WORKDIR BOOTSTRAP.tar.zst
archipelago build iso --purpose gnome|kde|container-runner WORKDIR BOOTSTRAP.tar.zst
Builds in an isolated Arch/nspawn on a build host. WORKDIR must be fresh;
BOOTSTRAP is checked against the pinned SHA-256. Purpose variants reuse the
cycle's Core. This is an infrastructure command, not an installed-host command.").to_string()),
"layer" => Some(t(ru, "\
Использование: archipelago layer validate МАНИФЕСТ
Проверяет синтаксис, схему и source-local инварианты Layer v1. Resolution и
build checks этим не выполняются.", "\
Usage: archipelago layer validate MANIFEST
Checks Layer v1 syntax, schema and source-local invariants. Resolution and build
checks are not performed.").to_string()),
"registry" => Some(t(ru, "\
Использование: archipelago registry init|verify РЕПОЗИТОРИЙ
init создаёт registry, verify проверяет его содержимое и идентичности. Команда
относится к инфраструктуре/разработке, не к установленной системе.", "\
Usage: archipelago registry init|verify REPOSITORY
init creates a registry; verify checks its content and identities. This is an
infrastructure/development command, not an installed-host command.").to_string()),
"pipeline" => Some(t(ru, "\
Использование:
archipelago pipeline status
archipelago pipeline logs latest|ID
archipelago pipeline run --reason ТЕКСТ
Доступно только при настроенном infrastructure.json на координаторе. status и
logs читают состояние; run запускает настроенный pipeline. Причина обязательна,
непустая и однострочная.", "\
Usage:
archipelago pipeline status
archipelago pipeline logs latest|ID
archipelago pipeline run --reason TEXT
Available only with infrastructure.json on the coordinator. status and logs read
state; run starts the configured pipeline. A nonempty single-line reason is
required.").to_string()),
"release" => Some(t(ru, "\
Использование:
archipelago release plan CANDIDATES.json --reason ТЕКСТ
archipelago release publish CANDIDATES.json --reason ТЕКСТ
plan проверяет кандидатов без публикации; publish запускает настроенную
публикацию. Путь кандидата должен находиться в разрешённом private-каталоге.
Причина обязательна. Это инфраструктурная команда координатора.", "\
Usage:
archipelago release plan CANDIDATES.json --reason TEXT
archipelago release publish CANDIDATES.json --reason TEXT
plan verifies candidates without publishing; publish starts the configured
publication. The candidate must be inside the allowed private artifact root.
A reason is required. This is a coordinator infrastructure command.").to_string()),
"install" => Some(t(ru, "\
Использование: archipelago install /dev/ДИСК --erase
Устанавливает систему на выбранный диск. --erase обязателен и разрешает стирание;
без него команда не должна угадывать намерение. Это команда live/installer, не
команда установленной системы.", "\
Usage: archipelago install /dev/DISK --erase
Installs onto the selected disk. --erase is mandatory and authorizes erasure;
the command does not guess intent. This is a live/installer command, not an
installed-host command.").to_string()),
"firstboot" => Some(t(ru, "\
Использование: archipelago firstboot
Завершает onboarding основного пользователя в установленном deployment. Обычно
запускается сервисом первой загрузки, а не вручную.", "\
Usage: archipelago firstboot
Completes primary-user onboarding in the installed deployment. It is normally run
by the first-boot service rather than manually.").to_string()),
"power" => Some(t(ru, "\
Использование: archipelago power hibernate-setup
Настраивает swap-файл и resume-параметры для спящего режима на диск. Требует
Desktop Purpose с resume initramfs hook и достаточно места в /var; команда
явная, потому что файл размером с RAM.", "\
Usage: archipelago power hibernate-setup
Configures the swap file and resume arguments for sleep-to-disk. Requires a
Desktop Purpose with the resume initramfs hook and enough /var space; it is
explicit because the file is as large as RAM.").to_string()),
"desktop" => Some(t(ru, "\
Использование:
archipelago desktop reconcile
archipelago desktop seed-flatpaks
archipelago desktop refresh-updates
reconcile проверяет аккаунты, сеанс и onboarding; seed-flatpaks готовит базовые
Flatpak-приложения; refresh-updates обновляет состояние обновлений в desktop-
интеграции. Это команды Desktop Purpose.", "\
Usage:
archipelago desktop reconcile
archipelago desktop seed-flatpaks
archipelago desktop refresh-updates
reconcile checks accounts, session and onboarding; seed-flatpaks prepares default
Flatpak applications; refresh-updates refreshes the desktop update state. These
are Desktop Purpose commands.").to_string()),
"boot-sync" => Some(t(ru, "\
Использование: archipelago boot-sync
Синхронизирует загрузочные записи с текущими deployments. Обычно вызывается
системной интеграцией; ручной запуск нужен для диагностики.", "\
Usage: archipelago boot-sync
Synchronizes boot entries with current deployments. It is normally invoked by
system integration; manual use is diagnostic.").to_string()),
"help" => Some(full_help(ru)),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn full_help_lists_every_supported_family_and_global_flag() {
let text = full_help(false);
for command in ["status", "self-check", "update", "extension", "overlay",
"kargs", "transaction", "cleanup", "power", "desktop",
"logs", "service", "build", "layer", "registry",
"pipeline", "release", "install", "firstboot"] {
assert!(text.contains(command), "missing {command}");
}
for flag in ["--json", "--debug", "--verbose", "--interactive",
"--non-interactive", "--offline", "--request-id", "--plan",
"--file", "--reason", "--purpose", "--erase", "--full",
"--help", "--version"] {
assert!(text.contains(flag), "missing {flag}");
}
assert!(text.contains("does not switch to a direct write"));
assert!(!text.contains("no direct fallback writes are permitted"));
}
#[test]
fn command_help_is_available_for_nested_families() {
assert!(command_help(&["extension", "add"]).unwrap().contains("--file"));
assert!(command_help(&["update", "apply"]).unwrap().contains("--plan"));
assert!(command_help(&["kargs"]).unwrap().contains("--append-if-missing"));
assert!(command_help(&["transaction", "log"]).unwrap().contains("CURSOR"));
assert!(command_help(&["unknown"]).is_none());
}
#[test]
fn help_request_handles_both_forms() {
let a = vec!["--help".to_owned()];
assert!(help_request(&a).unwrap().unwrap().contains("Usage:"));
let b = vec!["extension".to_owned(), "add".to_owned(), "--help".to_owned()];
assert!(help_request(&b).unwrap().unwrap().contains("--file"));
let c = vec!["help".to_owned(), "update".to_owned()];
assert!(help_request(&c).unwrap().unwrap().contains("update apply"));
assert!(help_request(&["unknown".to_owned(), "--help".to_owned()]).unwrap().is_err());
}
}