diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index 064c5e8..dfd4fb4 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,13 +1 @@ -# These are supported funding model platforms - -github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry custom: ["https://www.paypal.me/mastercruelty"] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 899ce25..40eee06 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,31 +4,36 @@ on: branches: [main, dev] pull_request: +permissions: + contents: read + jobs: shellcheck: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Install shellcheck run: sudo apt-get update && sudo apt-get install -y shellcheck - name: Lint (errors) run: | shopt -s globstar nullglob shellcheck -S error \ - setup.sh uninstall.sh update.sh \ - src/emerger.sh src/lib/*.sh - - name: Lint (warnings, non-blocking) + install.sh uninstall.sh \ + src/emerger.sh src/lib/**/*.sh share/plugins/*.sh share/profiles/*.sh completions/up.bash + - name: Lint (warnings) run: | shopt -s globstar nullglob shellcheck -S warning \ - setup.sh uninstall.sh update.sh \ - src/emerger.sh src/lib/*.sh || true + install.sh uninstall.sh \ + src/emerger.sh src/lib/**/*.sh share/plugins/*.sh share/profiles/*.sh completions/up.bash tests: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Install bats - run: sudo apt-get update && sudo apt-get install -y bats - - name: Run bats + run: sudo apt-get update && sudo apt-get install -y bats zsh fish shellcheck + - name: Require pwsh (tests/ps_*.bats skip without it) + run: command -v pwsh && pwsh -NoProfile -Command '$PSVersionTable.PSVersion.ToString()' + - name: Run bats (pwsh is preinstalled on the runner, so tests/ps_*.bats run) run: bats tests/ diff --git a/.gitignore b/.gitignore index 7297e23..9f8967d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,6 @@ -.log -src/utils/.cache -src/utils/.md5 -.hist +# LaTeX build output beside doc/documentation.tex *.aux *.log +*.out +*.toc *.synctex.gz -.idea \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0c95530..eed2135 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,52 +1,21 @@ # Contributing -First of all, thanks for being here! Contributions are very appreciated, but we ask you to follow a few simple rules so everyone can enjoy the ride. +Every contribution is licensed under the project's [MIT licence](LICENSE). -## 1. Comment your code (just a little) +## Pull requests -You don't need to explain every single line. But if your change spans multiple files, or it takes more than basic knowledge to understand, please leave a few small comments or share your stream of consciousness in the pull request. Future us (and you) will be grateful. +- Link an issue or describe the change in a few lines. +- Comment code that spans several files or needs more than basic knowledge to follow. +- Follow the indentation of the surrounding code. +- Run `bats tests/` and the lint command in [README.md](README.md#development) before opening the request. +- A change to a flag, variable or output field updates the bash and PowerShell halves, the help texts, [man/up.1](man/up.1), [doc/documentation.tex](doc/documentation.tex), the completions and the README together. -## 2. Write meaningful pull requests +## Rejected contributions -When opening a PR, link to an issue or describe what you did in a few words. Think of it as an extension of rule 1. +- Links or references to servers the project does not own. +- Code that exposes users to vulnerabilities or bypasses privileges. +- Code that discriminates against people or serves a crime. -## 3. About rules 1 and 2 +## Code under another licence -Skipping them won't get your contribution rejected, but it will slow things down, since we'll have to ask questions before merging. - -## 4. No shady code, no crimes - -We will not accept contributions containing *shady code* or any form of *crime*. - -Examples of *shady code* (not limited to): - -- References and links to servers we don't own or that are not certified -- Exposing users to external or internal vulnerabilities -- Code tricks to bypass privileges or access reserved memory areas - -Examples of *crimes* (not limited to): - -- Discrimination based on ethnicity, sex, religion, physical aspect, sexual orientation, or any other individual right protected by Human Rights or by simple logic and maturity -- Cybercrimes - -## 5. Mind the indentation - -Not mandatory, but please try to match the existing code style. It keeps the codebase tidy. - -## 6. Memes are welcome - -We believe in a friendly environment, so memes in comments are totally fine. Just don't overdo it, and always respect rule 4. - -## 7. Licensed code - -You can contribute with your licensed code, but we'll have to check a few things first: - -1. You are the real author. -2. The contribution respects rule 4. -3. If you propose someone else's code, the integration must respect the author's needs and license. - -## 8. Don't be afraid - -No one on this planet is born knowing everything. If you follow all the rules above but your PR gets rejected because of the nature of your code, your effort won't be in vain: your work may give someone else ideas, or the chance to refactor it into something even better. That's the beauty of open source. - -And remember, even us, the creators, started out knowing almost nothing. So really, don't be afraid of being judged. Just jump in. +Code you did not write is accepted only if its licence permits inclusion in an MIT project. State its author and licence in the pull request and in [reference/third-party.md](reference/third-party.md). diff --git a/LICENSE b/LICENSE index 87245fd..2ee9ce7 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2021-2026 eMerger contributors (https://github.com/MasterCruelty/eMerger/graphs/contributors) +Copyright (c) 2021-2026 Roberto Antoniello, Edoardo Ferrari and eMerger contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index c6b22c0..14e93e2 100644 --- a/README.md +++ b/README.md @@ -6,1509 +6,242 @@ [![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=MasterCruelty_eMerger&metric=ncloc)](https://sonarcloud.io/dashboard?id=MasterCruelty_eMerger)

- eMerger logo + eMerger logo

-**One command - `up` - refreshes, upgrades and cleans your whole system.** -Works on **Linux**, **macOS** and **Windows**. Auto-detects every package -manager you have, runs them in the right order, gives you one clean summary -at the end. No YAML, no daemons. +One command, `up`, refreshes, upgrades and cleans every package manager on your Linux, macOS or Windows machine. -> New to package managers? Read the [Why eMerger?](#why-emerger) section -> first. In a hurry? Jump to [Quickstart](#quickstart). +`up` finds the managers you have (`apt`, `dnf`, `pacman`, `brew`, `winget`, `flatpak`, `snap` and more), asks for `sudo` or a UAC prompt once if one of them needs it, runs each in turn and prints one summary. It runs on bash on Linux and macOS and on PowerShell on Windows. Nothing else is installed. ---- +Every configuration and environment variable, the JSON fields and the plugin API are in [the documentation](doc/documentation.pdf) and the man page [man/up.1](man/up.1), which `install.sh` installs (`man up`). -## Table of contents +## Quick start -1. [Why eMerger?](#why-emerger) -2. [Platforms at a glance](#platforms-at-a-glance) -3. [Quickstart](#quickstart) -4. [What `up` actually does](#what-up-actually-does) -5. [Requirements](#requirements) -6. [Installation](#installation) - - [Linux](#install-linux) - - [macOS](#install-macos) - - [Windows](#install-windows) -7. [Uninstallation](#uninstallation) -8. [Update / self-update](#update--self-update) -9. [User manual](#user-manual) - - [Running](#running) - - [Flags, quick reference](#flags-quick-reference) - - [Combining flags](#combining-flags) - - [Interactive mode](#interactive-mode) - - [Dry-run & verbose](#dry-run--verbose) - - [Quiet levels](#quiet-levels) - - [Security-only updates](#security-only-updates) - - [Dev toolchains](#dev-toolchains) - - [Firmware (Linux)](#firmware-linux) - - [Parallel mode](#parallel-mode) - - [Snapshots (Linux)](#snapshots-linux) - - [Mirrors refresh (Linux)](#mirrors-refresh-linux) - - [Reboot handling](#reboot-handling) - - [Resume after interruption](#resume-after-interruption) - - [Package diff & changelog](#package-diff--changelog) - - [Reports](#reports) - - [History & errors](#history--errors) - - [Doctor](#doctor) -10. [Configuration](#configuration) - - [config file](#config-file) - - [All config variables](#all-config-variables) - - [Profiles](#profiles) - - [Hooks](#hooks) - - [Ignore list (Linux)](#ignore-list-linux) - - [Quiet hours](#quiet-hours) - - [Manager plugins](#manager-plugins) -11. [Integration](#integration) - - [JSON output](#json-output) - - [Prometheus metrics](#prometheus-metrics) - - [Reboot exit code](#reboot-exit-code) - - [Download-only / offline](#download-only--offline) - - [Manager filtering](#manager-filtering) - - [Rollback](#rollback) - - [Short flag bundling](#short-flag-bundling) -12. [Auto-update (unattended)](#auto-update-unattended) -13. [Cookbook / Recipes](#cookbook--recipes) -14. [Safety & security](#safety--security) -15. [Files & paths](#files--paths) -16. [Supported package managers](#supported-package-managers) -17. [Exit codes](#exit-codes) -18. [Troubleshooting](#troubleshooting) -19. [FAQ](#faq) -20. [Glossary](#glossary) -21. [Development](#development) -22. [License](#license) - -๐Ÿ“„ **For a printable, all-in-one reference see -[doc/documentation.pdf](./doc/documentation.pdf).** - ---- - -## Why eMerger? - -A modern machine gets its software from many different places at once: -the distro's own package manager (`apt`, `dnf`, `pacman`, `zypper`, -`softwareupdate`, `winget`...), an app-store layer (`flatpak`, `snap`, -`brew --cask`, `choco`, `scoop`), a user-level store (`brew`, `mas`), -language ecosystems (`npm`, `pip`, `cargo`, `gem`, `pnpm`...) and, on -Linux, firmware via `fwupdmgr`. Each has its own syntax, its own cache, -its own notion of "security update" and its own definition of "clean". - -Keeping all of them up to date by hand is tedious and error-prone. -Writing a personal wrapper that works on three operating systems is a -weekend project most people never finish. - -**eMerger is that wrapper, generalised.** Type `up` and it will: - -1. detect every package manager installed on the host -2. ask for `sudo` (or trigger UAC) only if something actually needs it -3. take an optional snapshot so you can audit the run afterwards -4. run refresh / upgrade / clean, in the right order, with retries -5. wipe user caches and the trash, optionally -6. print one summary with per-manager result, disk freed, run duration - and a reboot advisory -7. export the same summary as JSON, Markdown or a Prometheus file - -It does this with no daemon, no YAML, no Python/Ruby runtime. Just Bash -on Unix, PowerShell on Windows. - -**What eMerger is NOT:** - -- Not a package manager itself. It drives the ones you already have. -- Not a configuration management system. No desired state, no manifest. - If you want that, use Ansible, Salt or NixOS. -- Not a service. It can install a weekly timer, but it does not run in - the background. - ---- - -## Platforms at a glance - -| | Linux | macOS | Windows | -|---|---|---|---| -| Entry point | `src/emerger.sh` | `src/emerger.sh` | `src/emerger.ps1` | -| Shell | bash 3.2+ | bash 3.2+ (system default) | PowerShell 5.1+ | -| Setup | `./setup.sh` | `./setup.sh` | `.\setup.ps1` | -| Uninstall | `./uninstall.sh` | `./uninstall.sh` | `.\uninstall.ps1` | -| Auto-update | systemd user timer / cron | launchd-compat cron | Task Scheduler | -| Elevation | `sudo` | `sudo` | UAC relaunch | -| TUI menu | yes (`-i`) | yes (`-i`) | no | -| Parallel mode | yes | yes | no (always serial) | -| Snapshots | snapper/timeshift/btrfs | no | no (System Restore is manual) | -| Config dir | `~/.config/emerger/` | `~/.config/emerger/` | `%APPDATA%\emerger\` | -| State dir | `~/.local/state/emerger/` | `~/.local/state/emerger/` | `%LOCALAPPDATA%\emerger\state\` | - -Feature parity is kept for the core flow (detect โ†’ upgrade โ†’ clean โ†’ summary). -Platform-specific features are documented below and clearly labelled. - ---- - -## Quickstart - -No commitment. Nothing gets upgraded until you say so. - -**Linux / macOS** -```sh -git clone https://github.com/MasterCruelty/eMerger -cd eMerger -./setup.sh -# open a new shell (or: source ~/.bashrc) -up --help -up -n # preview: shows what would run -up # real run -``` - -**Windows** (PowerShell) -```powershell -git clone https://github.com/MasterCruelty/eMerger -cd eMerger -.\setup.ps1 -# open a new PowerShell window (or: . $PROFILE) -up --help -up -n # preview -up # real run -``` - -### What you'll see on the first real run - -On a Debian/Ubuntu desktop with Flatpak installed, expect something like: +1. Clone the repository: `git clone https://github.com/MasterCruelty/eMerger && cd eMerger`. +2. Run `./install.sh` (Linux, macOS) or `.\install.ps1` (Windows PowerShell). +3. Open a new terminal. +4. Run `up -n` to see what would run. Nothing changes. +5. Run `up` to update. ```text - _____ __ __ -| ___| | \/ | eMerger v2.0.0 -| |__ | |\/| | one command for the whole system -|____| |_| |_| -Ubuntu 24.04 o x86_64 o 2026-04-16 10:12 -eMerger v2.0.0 o github.com/MasterCruelty/eMerger -[1/3] apt OK (38 upgraded, 0 removed, 0 new) -[2/3] flatpak OK (5 refreshed) -[3/3] fwupd SKIP (--firmware not set) -+---------------------------------------------+ -| eMerger - summary | -| duration 42s | -| freed 15 MiB | -| reboot not required | -| errors 0 | -+---------------------------------------------+ -``` - -> **Do not run `sudo up`.** eMerger will ask for `sudo` itself, only for -> the managers that need it. Running `sudo up` would install user-level -> packages (e.g. `pip --user`, Homebrew, `npm -g`) into root's home. - ---- - -## What `up` actually does - -Each full run performs, in order: - -1. Load `config.sh` (or `config.ps1`) and any `--profile`. -2. Parse CLI flags. CLI always wins over config and profile defaults. -3. Acquire a global exclusive lock (`/tmp/emerger.lock` on Unix). -4. Print logo, OS info line and timestamp (skippable with `-nl`/`-ni`). -5. Warn on low battery and on low free disk space. -6. Cache `sudo` credentials (Unix) or relaunch elevated (Windows) if any - detected manager needs it. -7. Snapshot installed packages (for the post-run diff). -8. Run `pre.d` hooks. -9. For each detected manager: **refresh โ†’ upgrade โ†’ clean**. -10. Optionally clean user cache / `%TEMP%` and trash / Recycle Bin. -11. Run `post.d` hooks. -12. Compute the installed-packages diff. -13. Print boxed summary + reboot advisory. -14. Emit desktop notification if the session has a display (or if - BurntToast is installed on Windows). -15. Exit 0 on success, 3 if any manager failed, 4 if a reboot is pending - and `--reboot-exit` was passed. - ---- - -## Requirements - -**Linux** -- bash โ‰ฅ 3.2, coreutils, git, sudo. -- Optional: `gum`/`whiptail`, `notify-send`, `curl`, `flock`, `reflector`, - `netselect-apt`, `snapper`/`timeshift`/`btrfs-progs`, `fwupdmgr`. - -**macOS** -- bash โ‰ฅ 3.2 (the system `/bin/bash` works out of the box; no Homebrew bash needed). -- Xcode Command Line Tools (for git). -- Optional: Homebrew, `mas` (`brew install mas`). - -**Windows** -- PowerShell 5.1 (built-in on Win10+) or 7+. -- Git for Windows (for `up --self-update`). -- Optional: `winget`, `scoop`, `choco`, `PSWindowsUpdate` - (`Install-Module PSWindowsUpdate -Scope CurrentUser`), `BurntToast` - (`Install-Module BurntToast`) for toast notifications. - -eMerger never installs these for you - it only uses what's there. - ---- - -## Installation - -### Install (Linux) - -```sh -git clone https://github.com/MasterCruelty/eMerger -cd eMerger -./setup.sh -``` - -`setup.sh` does exactly this: - -1. Adds `alias up='bash /path/to/eMerger/src/emerger.sh'` to your shell rc - (bash, zsh, fish - whichever you use). -2. Makes `src/emerger.sh` executable. -3. Installs shell completions under: - - `~/.local/share/bash-completion/completions/up` - - `~/.zsh/completions/_up` - - `~/.config/fish/completions/up.fish` -4. Creates `~/.config/emerger/{config.sh,ignore.list,hooks/,profiles.d/}`. - -After install, **open a new shell** (or `source ~/.bashrc`). - -### Install (macOS) - -Identical script, same flow: - -```sh -git clone https://github.com/MasterCruelty/eMerger -cd eMerger -./setup.sh -``` - -macOS specifics handled automatically: -- The alias is written to `~/.zshrc` first (zsh is the default shell since Catalina). -- If Homebrew is installed, completions go to - `$(brew --prefix)/etc/bash_completion.d/` and - `$(brew --prefix)/share/zsh/site-functions/`. -- `softwareupdate` (native macOS updater) is auto-detected alongside `brew`, - `brew --cask`, and `mas`. - -### Install (Windows) - -```powershell -git clone https://github.com/MasterCruelty/eMerger -cd eMerger -.\setup.ps1 -``` - -`setup.ps1` does: +$ up + โ—† Debian GNU/Linux 13 ยท x86_64 ยท 2026-10-16 10:12 ยท eMerger v3.0.0 -1. Sets `ExecutionPolicy` to `RemoteSigned` for `CurrentUser` if it was - `Restricted` or `Undefined`. No admin needed for this. -2. Adds a `function up { & "โ€ฆ\emerger.ps1" @args }` block to your - `$PROFILE.CurrentUserAllHosts` (so `up` works from any host: cmd-hosted - PS, ISE, Terminalโ€ฆ). -3. Scaffolds `%APPDATA%\emerger\{config.ps1,hooks\,profiles.d\}`. + ๐ŸŒ€ apt ~40s โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ–ฐโ–ฑ 1/2 + โœ” update ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท 6.8s + โ ‰ full-upgrade .:::. 0:14 Unpacking libssl3 ... -After install, **open a new PowerShell window** (or `. $PROFILE`). + ๐Ÿ“ฆ flatpak โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ–ฐโ–ฐ 2/2 + โœ” update ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท 12.4s 5 refreshed -> **Important**: `setup.ps1` does **not** require admin. Package manager -> runs that need admin will trigger a UAC prompt via automatic elevation. - -### Manual install - -All three platforms: just point an alias/function at the entry point. - -```sh -# bash/zsh/fish - macOS or Linux -alias up='bash /absolute/path/to/eMerger/src/emerger.sh' -``` - -```powershell -# PowerShell - Windows -function up { & "C:\path\to\eMerger\src\emerger.ps1" @args } -``` - ---- - -## Uninstallation - -```sh -# Linux / macOS -./uninstall.sh -``` - -```powershell -# Windows -.\uninstall.ps1 + โ•ญโ”€ eMerger summary โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ + โ”‚ managers โœ” apt โœ” flatpak โ”‚ + โ”‚ time 0m42s โ”‚ + โ”‚ freed 812.0MB โ”‚ + โ”‚ status โœ” all good โ”‚ + โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ ``` -Removes the shell alias / `up` function, any cronjob, systemd user timer or -scheduled task. **Keeps** your config and state directories so you don't -lose history or hooks. Delete those paths manually if you want a clean -wipe: - -```sh -rm -rf ~/.config/emerger ~/.cache/emerger ~/.local/state/emerger -``` - -The repo itself is not removed - `rm -rf` or `Remove-Item` the directory -when you're done. - ---- - -## Update / self-update - -Three equivalent ways: - -```sh -up -up # flag form -``` -or -```sh -up --self-update -``` -or -```sh -./update.sh # Linux / macOS -.\update.ps1 # Windows -``` +Do not run `sudo up`: under `sudo`, user-level packages (`pip --user`, Homebrew, `npm -g`) land in root's home. `up` asks for `sudo` itself. -This does a `git pull --ff-only` inside the repo and shows the commit range. -Refuses non-fast-forward pulls so local changes never silently vanish. +## What you need -For automatic updates of eMerger itself, put it in `post.d` hook (see -[Hooks](#hooks)). - ---- - -## User manual - -### Running - -```sh -up # Linux / macOS -``` -```powershell -up # Windows -``` - -Full list of flags: `up --help`. - -### Flags, quick reference - -Authoritative list: `up --help`. Highlights: - -| Flag | Meaning | Platforms | +| platform | required | optional | |---|---|---| -| `-n`, `--dry-run` | Preview, don't run | all | -| `-v`, `--verbose` | Stream output live | all | -| `-q` / `-qq` / `-qqq` | Quieter | all | -| `-y`, `--yes` | Assume yes | all | -| `-i`, `--interactive` | Menu UI | Linux/macOS | -| `--security` | Security-only | all (where supported) | -| `--dev` | Include dev toolchains | all | -| `--firmware` | `fwupdmgr` | Linux | -| `--parallel` | Run user-space concurrently | Linux/macOS | -| `--profile NAME` | Load a profile | all | -| `--snapshot` | snapper/timeshift/btrfs | Linux | -| `--refresh-mirrors` | re-rank mirrors | Linux | -| `--resume` | Skip completed managers | Linux/macOS | -| `--reboot` | Reboot if required | all | -| `--changed` | Package diff | Linux/macOS | -| `--changelog PKG` | Upstream changelog | Linux/macOS | -| `--report FILE` | Export Markdown | Linux/macOS | -| `--doctor` | Health check | all | -| `--history` | Recent runs | all | -| `--errors` / `-err` | Log tail | all | -| `--no-emoji` | ASCII only | all | -| `--json` | Machine-readable summary | all | -| `--reboot-exit` | Exit 4 if reboot is required | all | -| `--rollback` | Revert last snapshot | Linux | -| `--download-only` / `--offline` | Prefetch, don't install | Linux/macOS (apt/dnf/pacman/zypper) | -| `--only LIST` | Keep only these managers | all | -| `--except LIST` | Skip these managers | all | -| `--metrics FILE` | Prometheus textfile export | all | -| `-up` | Self-update | all | -| `-au` | Install auto-update | all | - -### Combining flags +| Linux | bash 4.4 or later, coreutils, git, sudo | `curl` (`-w`, `--doctor`), `flock`, `timeout`, `pkill` (stops `--parallel` managers on Ctrl-C), `notify-send`, `fwupdmgr`, `snapper` or `timeshift` or `btrfs-progs`, `reflector` or `netselect-apt` | +| macOS | bash 4.4 or later first in `PATH` (`/bin/bash` 3.2 is too old: `brew install bash`), Xcode Command Line Tools | Homebrew, `mas` | +| Windows | PowerShell 5.1 or 7, Git for Windows | `winget`, `scoop`, `choco`, the `PSWindowsUpdate` and `BurntToast` modules | -Flags are independent tokens - mix and match as many as you need, in any -order. Short bundling `-nv` โ†’ `-n -v` is supported for the letters -`{h V n v q y i w}`. Compound short flags (`-nl`, `-ni`, `-qq`, `-up`, -`-err`, ...) and long flags pass through unchanged. +`up` installs none of these. It uses what it finds. -```sh -up -n -v # dry-run + live stream (preview a full run) -up -y -q --security # unattended security-only, minimal output -up --dev --parallel -v # dev toolchains + user-space concurrency, verbose -up --snapshot --reboot -y # snapshot first, reboot at the end if needed -up --profile server --resume # resume an interrupted headless run -up -n --dev --firmware # preview a full dev + firmware run, no side effects -up -qq -y -nl -ni --security # exactly what the scheduled timer does -up --refresh-mirrors -y -v # re-rank mirrors then upgrade, watch it live -up --changed --report out.md # show diff and export it in one shot -``` +## Install -```powershell -up -y -q --security # Windows, unattended security-only -up --dev -v # Windows, include dev toolchains, verbose -up -n --security # Windows, preview a security-only run -``` +`./install.sh`: -Flags that take a value (`--profile NAME`, `--changelog PKG`, -`--report FILE`, `--metrics FILE`, `--only LIST`, `--except LIST`) must -keep their argument adjacent; everything else is position-free. CLI flags -always win over config file and profile defaults, so you can override a -profile on the fly: +- adds `alias up='bash "/path/to/eMerger/src/emerger.sh"'` to your bash, zsh and fish startup files (`~/.zshrc` first on macOS); +- installs completions for bash, zsh and fish, and the man page in `~/.local/share/man/man1/` (`man up`); +- creates `~/.config/emerger/` with `config.sh`, `ignore.list`, `hooks/` and `profiles.d/`. -```sh -up --profile work --dev # work profile, but force dev toolchains this run -``` +A checkout path containing `'`, `"`, `$`, a backquote, `%`, `\` or a newline is refused: move the checkout first. -### Interactive mode +`.\install.ps1` needs no administrator rights: -```sh -up -i -``` +- if the `CurrentUser` execution policy is `Restricted` or `Undefined`, it asks before setting `RemoteSigned`; +- it adds an `up` function to `$PROFILE.CurrentUserAllHosts`; +- it creates `%APPDATA%\emerger\` with `config.ps1`, `hooks\` and `profiles.d\`. -Menu via `gum` (pretty), `whiptail` (classic), or plain read-loop. -Windows does not ship a TUI - use flags directly or a profile. +Without the install script, point an alias at the entry point: `alias up='bash /path/to/eMerger/src/emerger.sh'`, or in PowerShell `function up { & 'C:\path\to\eMerger\src\emerger.ps1' @args }`. -### Dry-run & verbose +## Use ```sh -up -n # see what would happen (safe, no sudo) -up -v # stream pkg-manager output live -up -n -v # both +up # update everything +up -n -v # preview, with each manager's output +up --security -y # unattended, security updates only +up --dev --firmware # also dev toolchains and firmware (Linux) +up --only apt,flatpak # these managers only +up --except snap # every manager but snap +up --download-only -y # download now, install on a later run +up --changed # what the last run added, removed, upgraded +up --history # the last runs +up --doctor # check the environment +up -au # install a weekly unattended run ``` -Example of `-n` output: +`up -au` runs `up -y -q -nl -ni` every Sunday at 10:00: a systemd user timer or cron on Linux, cron on macOS, Task Scheduler on Windows (a manager that needs admin raises a UAC prompt at that time). On Linux, a user timer needs a login session: run `loginctl enable-linger $USER` once to let it fire without one. -```text -$ up -n -[dry] sudo apt update -[dry] sudo apt upgrade -y -[dry] sudo apt autoremove -y -[dry] sudo apt clean -[dry] flatpak update -y -[dry] flatpak uninstall --unused -y -``` - -### Quiet levels - -- **default** - full UI with box and spinner -- `-q` - hide muted/info lines -- `-qq` - only step titles + one-line summary (great for systemd logs) -- `-qqq` - no output at all; exit code is the only signal +## Flags -### Security-only updates - -```sh -up --security -y -``` +`up --help` prints the same list. A flag that takes a value accepts `--flag VALUE` or `--flag=VALUE`. `--` ends the options. Short flags from the set `h V n v q y w` bundle: `-nv` is `-n -v`. -- Linux: `apt` (via `unattended-upgrade`), `dnf` (`--security`), - `zypper` (`patch --category security`). -- macOS: `softwareupdate --install --recommended`. -- Windows: `PSWindowsUpdate` respects KB severity if the module supports it. +On Windows, a flag marked "Unix" prints a warning. The run goes on without it, except `--changed`, `--changelog` and `--rollback`, which exit 0 without updating. -Other managers ignore the flag. - -### Dev toolchains - -Opt-in (every platform): - -```sh -up --dev -``` - -Updates: - -| Tool | Command | -|---|---| -| `rustup` | `rustup self update && rustup update stable` | -| `cargo` | `cargo install-update -a` | -| `npm` | `npm update -g` | -| `pnpm` | `pnpm -g update` | -| `pip` | user-site upgrades | -| `gem` | `gem update` | - -These never run under `sudo`. Missing toolchains are silently skipped. - -### Firmware (Linux) - -```sh -up --firmware -``` - -Runs `fwupdmgr refresh && fwupdmgr update -y --no-reboot-check`. Windows -firmware is handled by vendor tools (Dell Command Update, Lenovo Vantage) -and is out of scope. macOS firmware is handled by `softwareupdate`. - -### Parallel mode - -```sh -up --parallel -``` - -User-space managers that don't touch `/` run concurrently (`flatpak`, -`snap`, `brew`, `mas`, dev tools). System managers stay serial. Windows -side is currently always serial. - -### Snapshots (Linux) - -```sh -up --snapshot -``` - -Tries in order: `snapper`, `timeshift`, `btrfs subvolume snapshot`. Windows -users: enable **System Restore** manually; eMerger doesn't trigger it. - -### Mirrors refresh (Linux) - -```sh -up --refresh-mirrors -``` - -- Arch: `reflector --latest 20 --sort rate`. -- Debian/Ubuntu: `netselect-apt`. -- Fedora: handled by `fastestmirror` plugin automatically; no-op here. - -### Reboot handling - -After a run, eMerger checks for reboot flags: - -- Linux: `/var/run/reboot-required`, `needs-restarting -r`. -- Windows: registry keys (`CBS RebootPending`, `WindowsUpdate\RebootRequired`, - `PendingFileRenameOperations`). - -To reboot on demand: - -```sh -up --reboot # reboots if required, no-op otherwise -``` - -### Resume after interruption - -If you kill a run mid-way: - -```sh -up --resume -``` - -skips every manager that successfully completed in the last interrupted run. -State lives in `~/.local/state/emerger/resume`. Linux/macOS only. - -### Package diff & changelog - -Every run records installed packages before/after. View it: - -```sh -up --changed -``` - -Example output: - -```text -$ up --changed -~ firefox 123.0.1 -> 124.0 -~ libc6 2.39-0 -> 2.39-1 -+ flatpak-xdg-utils 1.0.6 -- old-package 2.1 -``` - -Legend: `+` added, `-` removed, `~` upgraded. Linux/macOS. - -Read a single package's upstream changelog: - -```sh -up --changelog firefox -``` - -Dispatches to `apt changelog`, `dnf changelog`/`updateinfo`, `pacman -Qi`, -or `brew log`. - -### Reports - -```sh -up --report report.md -``` - -Markdown export of the last run: JSON summary, managers, reboot advisory, -full package diff as a table. - -### History & errors - -```sh -up --history # last 10 runs -up --errors # tail of ERROR lines from the log -``` - -### Doctor - -```sh -up --doctor -``` - -Audits: -- shell / PowerShell version -- sudo cache / admin status -- disk space -- network reachability -- state dir writability -- per-manager native health (`dpkg --audit`, `pacman -Dk`, `brew doctor`, โ€ฆ) -- pending reboot flag -- (Windows) ExecutionPolicy - -Exits non-zero if issues are found. **Always attach `up --doctor` output -when reporting a bug.** - ---- - -## Configuration - -### config file - -**Linux / macOS** - `~/.config/emerger/config.sh` (sourced before arg parsing): - -```sh -# Defaults -ARG_DEV=1 # always include dev toolchains -ARG_WEATHER=1 # always show weather -ARG_PARALLEL=1 # user-space managers in parallel - -# Thresholds -DISK_MIN_FREE_MB=2048 # require >= 2 GB on / -RETRY_MAX=3 # transient-error retries - -# Scheduling -QUIET_HOURS="23:00-07:00" # skip scheduled runs inside this window -``` - -**Windows** - `%APPDATA%\emerger\config.ps1` (dot-sourced before arg parsing): - -```powershell -$script:ArgsGlobal.Dev = $true -$script:ArgsGlobal.Security = $true -$script:ArgsGlobal.NoTrash = $true -``` - -### All config variables - -| Variable | Default | Meaning | +| flag | effect | platforms | |---|---|---| -| `ARG_DEV` | 0 | include dev toolchains by default | -| `ARG_FIRMWARE` | 0 | include `fwupdmgr` by default | -| `ARG_NO_FIRMWARE` | 0 | force-skip firmware | -| `ARG_SECURITY` | 0 | security-only by default | -| `ARG_YES` | 0 | assume yes by default | -| `ARG_PARALLEL` | 0 | parallel user-space by default | -| `ARG_WEATHER` | 0 | show weather widget | -| `ARG_NO_EMOJI` | 0 | force ASCII glyphs | -| `ARG_NO_CACHE` | 0 | skip user cache cleaning | -| `ARG_NO_TRASH` | 0 | skip trash cleaning | -| `ARG_NO_LOGO` | 0 | hide logo | -| `ARG_NO_INFO` | 0 | hide system info line | -| `QUIET_LEVEL` | 0 | 0=full UI, 1=`-q`, 2=`-qq`, 3=`-qqq` | -| `DISK_MIN_FREE_MB` | 1024 | abort/warn below this many MiB | -| `BATTERY_MIN_PCT` | 20 | warn below this battery percent | -| `RETRY_MAX` | 2 | transient-error retries | -| `RETRY_DELAY` | 3 | seconds between retries | -| `QUIET_HOURS` | (unset) | `"HH:MM-HH:MM"` - skip scheduled runs inside window | -| `EMERGER_CACHE_TTL` | 86400 | detection cache TTL in seconds, 0 disables | - -> CLI flags always win. `ARG_SECURITY=1` in `config.sh` plus `up --dev` on -> the CLI will run security updates **and** dev toolchains. - -### Profiles - -Profiles are config snippets scoped to a name. - -```sh -up --profile work -up --list-profiles -``` - -Shipped defaults in `share/profiles/`: - -| Profile | Meant for | -|---|---| -| `work` | laptop at work - security, unattended, no cache/trash | -| `home` | desktop at home - everything, dev toolchains, parallel | -| `server` | headless - `-qq`, security, no prompts | -| `safe` | pre-presentation - security only, no big downloads | - -Each platform looks for its own extension: - -- Unix โ†’ `share/profiles/.sh` -- Windows โ†’ `share/profiles/.ps1` - -User profiles go in `~/.config/emerger/profiles.d/` (Unix) or -`%APPDATA%\emerger\profiles.d\` (Windows) and shadow the shipped ones. - -Example custom profile (`~/.config/emerger/profiles.d/train.sh`): - -```sh -# description: on a train, prefetch only, keep the fans quiet -ARG_DOWNLOAD_ONLY=1 -ARG_YES=1 -ARG_QUIET=1 -QUIET_LEVEL=2 -ARG_NO_TRASH=1 -ARG_NO_CACHE=1 -``` - -Then `up --profile train` does a silent prefetch. - -### Hooks - -Drop executable scripts in `hooks/pre.d/` (before updates) or -`hooks/post.d/` (after). They run alphabetically. A failing hook emits a -warning but never aborts the run. - -- Unix: `*.sh`, run under bash. -- Windows: `*.ps1`, dot-sourced under PowerShell. - -**Example 1 - backup dotfiles before every run:** - -```sh -# ~/.config/emerger/hooks/pre.d/10-backup-dotfiles.sh -#!/usr/bin/env bash -set -e -rsync -a --delete ~/.config/ ~/backups/dotfiles/ +| `-h`, `--help` | Show the help | all | +| `-V`, `--version` | Show the version | all | +| `--doctor` | Check the environment; exit non-zero on a warning | all | +| `-n`, `--dry-run` | Print the commands, change nothing | all | +| `-v`, `--verbose` | Stream each manager's output | all | +| `-q`, `--quiet` | One quieter level per use | all | +| `-qq` | Summary line only | all | +| `-qqq` | Nothing, exit code only | all | +| `-y`, `--yes` | Answer yes to every prompt | all | +| `--json` | One JSON summary on stdout | all | +| `--security` | Security updates only; managers without them are skipped | all | +| `--accept-licenses` | Let `softwareupdate`, `winget`, `choco` and Windows Update accept licence agreements; without it they only list updates | macOS, Windows | +| `--firmware` | Include `fwupdmgr` and the Raspberry Pi bootloader | Unix | +| `--no-firmware` | Skip firmware, even when the config sets `--firmware` | Unix | +| `--dev` | Include `rustup`, `cargo`, `npm`, `pnpm`, `pip`, `gem` | all | +| `--parallel` | Run user-space managers at the same time | Unix | +| `--profile NAME` | Load a profile before the flags | all | +| `--list-profiles` | List the profiles | all | +| `--only LIST` | Run only these managers (comma-separated) | all | +| `--except LIST` | Skip these managers; adds to the config's list | all | +| `--snapshot` | Take a snapper, timeshift or btrfs snapshot first, or exit 1 | Unix | +| `--rollback` | Revert to the latest eMerger snapshot | Unix | +| `--refresh-mirrors` | Re-rank the mirrors first | Unix | +| `--resume` | Skip the managers the last run finished | Unix | +| `--reboot` | Reboot now if the system needs it | all | +| `--reboot-exit` | Exit 4 instead of 0 when a reboot is pending | all | +| `--download-only` | Download without installing (apt, dnf, pacman, zypper, softwareupdate); skip every other manager | Unix | +| `-nl`, `--no-logo` | Hide the logo | all | +| `-ni`, `--no-info` | Hide the system line | all | +| `-w`, `--weather` | Show a weather line from wttr.in | all | +| `--ascii` | ASCII glyphs only | all | +| `-nc`, `--keep-cache` | Skip user cache cleaning (Windows: `%TEMP%`) | all | +| `-nt`, `--keep-trash` | Skip trash cleaning (Windows: Recycle Bin) | all | +| `--deep-clean` | Also clean the journal, old kernels, leftover configs, snap revisions, container images, crash dumps, npm and Go caches, asking for each | Unix | +| `--changed` | Show the last run's package changes | Unix | +| `--changelog PKG` | Show the upstream changelog of `PKG` | Unix | +| `--history` | Show the last runs | all | +| `--metrics FILE` | Export the last run as a Prometheus textfile | all | +| `-err`, `--errors` | Show logged errors | all | +| `-up`, `--self-update` | Update eMerger with `git pull --ff-only` | all | +| `-au`, `--auto-update` | Install the weekly run | all | +| `-rc`, `--rebuild-cache` | Clear the manager detection cache (Windows keeps none) | all | + +## Configure + +`~/.config/emerger/config.sh` (Windows: `%APPDATA%\emerger\config.ps1`) runs before the flags, so it sets your defaults. The flags win. + +```sh +# ~/.config/emerger/config.sh +ARG_DEV=1 # as --dev on every run +ARG_EXCEPT="snap" # as --except snap +DISK_MIN_FREE_MB=2048 # ask before updating with less free space +QUIET_HOURS="23:00-07:00" # a run with -y inside this window does nothing ``` -**Example 2 - Slack notification after every run:** - -```sh -# ~/.config/emerger/hooks/post.d/99-slack.sh -#!/usr/bin/env bash -state=~/.local/state/emerger -payload=$(tail -1 "$state/history.jsonl") -curl -sS -X POST -H 'Content-Type: application/json' \ - -d "{\"text\":\"eMerger: $payload\"}" "$SLACK_WEBHOOK_URL" -``` - -**Example 3 - copy last log to clipboard (Windows):** - -```powershell -# %APPDATA%\emerger\hooks\post.d\10-log-to-clipboard.ps1 -$log = Join-Path $env:LOCALAPPDATA 'emerger\state\emerger.log' -Get-Content $log -Tail 40 | Set-Clipboard -``` - -**Example 4 - export Prometheus metrics automatically:** - -```sh -# ~/.config/emerger/hooks/post.d/90-prom.sh -#!/usr/bin/env bash -up --metrics /var/lib/node_exporter/textfile_collector/emerger.prom -``` - -> Hooks run with the privileges that invoked `up`. If you need root-owned -> side effects, write them in `post.d` and guard with `sudo -n` or a -> targeted sudoers entry. - -### Ignore list (Linux) - -`~/.config/emerger/ignore.list` - one package per line, `#` comments ok. -Honored natively by **pacman** (`--ignore=`). For others it is -**advisory** - you still need to hold them via: - -- apt: `sudo apt-mark hold ` -- dnf: `sudo dnf versionlock add ` -- zypper: `sudo zypper al ` - -### Quiet hours - -Set `QUIET_HOURS="HH:MM-HH:MM"` in `config.sh`. When a scheduled run starts -inside that window **and** `-y` is set (i.e. from the timer), eMerger exits -immediately. Interactive runs always proceed. Windows across midnight is -supported (e.g. `"23:00-07:00"`). Linux/macOS. - -### Manager plugins - -Drop a bash script in `~/.config/emerger/managers.d/.sh` to add support -for a package manager without touching the repo. A minimal plugin: - -```sh -PM_PLUGIN_SLUG=mytool - -pm_mytool_detect() { command -v mytool >/dev/null 2>&1; } -pm_mytool_needs_sudo() { return 1; } # optional, default: no sudo -pm_mytool_parallel() { return 0; } # optional, default: serial -pm_mytool_dev() { return 1; } # optional, default: not gated by --dev -pm_mytool_icon() { printf '๐Ÿ”Œ'; } # optional - -pm_mytool_run() { - run_cmd "mytool refresh" mytool refresh || return 1 - run_cmd "mytool upgrade" mytool upgrade -y || return 1 -} -``` - -A complete, copy-pasteable template lives in -[`share/plugins/example.sh`](share/plugins/example.sh). - -Plugins are registered at the same level as native managers: they honour -`--only`, `--except`, `--parallel`, `--dev`, the detection cache, hooks and -the summary. They are invoked from inside `pkg_run`, so `run_cmd` automatically -gives them `--dry-run`, retry, logging and live-log handling for free. - -The detection cache is keyed by manager slug and lives at -`~/.cache/emerger/detected`. TTL defaults to 1 day; override via -`EMERGER_CACHE_TTL=` in `config.sh` (0 disables caching). After -installing or removing a package manager, run `up -rc` to clear the cache. - -Linux/macOS only. Windows plugins are not yet supported. - ---- - -## Integration - -### JSON output - -```sh -up --json -``` - -Emits a single-line JSON object on stdout. The logo, info line and summary -box are all suppressed, so the output is safe to pipe into `jq` or consume -from a CI job: - -```json -{"ts":"2026-04-14T07:24:31Z","duration":42,"freed_kb":15360, - "errors":0,"reboot":0, - "managers":[{"name":"apt","result":"ok"},{"name":"flatpak","result":"ok"}]} -``` - -Every run also appends one such line to -`~/.local/state/emerger/history.jsonl` (one JSON per line). Fields: - -| Field | Meaning | -|---|---| -| `ts` | ISO 8601 UTC timestamp of the run start | -| `duration` | total wall-clock seconds | -| `freed_kb` | cache and trash bytes freed, in KiB | -| `errors` | number of managers that returned non-zero | -| `reboot` | 1 if a reboot is required, else 0 | -| `managers` | array of `{name, result}` entries | - -### Prometheus metrics - -```sh -up --metrics /var/lib/node_exporter/textfile_collector/emerger.prom -``` - -Reads the most recent entry from `history.jsonl` and renders a Prometheus -textfile-collector snapshot. Exported gauges: - -- `emerger_last_run_timestamp_seconds` -- `emerger_last_run_duration_seconds` -- `emerger_last_run_freed_bytes` -- `emerger_last_run_errors` -- `emerger_reboot_required` -- `emerger_manager_ok{manager="..."}` (one per manager from the last run) - -Does not trigger a run - invoke it from a `post.d` hook or from your timer -after `up` completes. - -### Reboot exit code - -By default eMerger always exits 0 on success even when a reboot is pending -(the summary box prints `REBOOT RECOMMENDED`). Pass `--reboot-exit` to turn -that into exit code **4** instead, so an orchestrator can react: - -```sh -up -y --reboot-exit -rc=$? -case $rc in - 0) ;; # done, no reboot needed - 3) notify-send "eMerger: some managers failed" ;; - 4) systemctl reboot ;; # clean, reboot required -esac -``` - -### Download-only / offline - -```sh -up --download-only -y # or --offline -``` - -Refreshes indexes and **downloads** the pending upgrade set but does not -install it. Supported natively on `pacman` (`-Syuw`), `apt`/`apt-get` -(`--download-only`), `dnf` (`--downloadonly`) and `zypper` -(`update --download-only`). Other managers ignore the flag. - -Typical use cases: - -- laptop on a slow/metered connection at a cafรฉ: prefetch while online, - install later at the office -- servers in a maintenance window: prestage packages, then flip to - install-only when the change ticket opens -- pre-flight for `--snapshot`: confirm the whole update set is downloaded - before taking a snapshot - -### Manager filtering - -```sh -up --only apt,flatpak # only these managers (comma-separated) -up --except snap,fwupd # everything that would run, minus these -``` - -The filters are applied after detection and after `--dev`/`--firmware` -gating, so: - -- `--only X` with `X` not detected is a no-op (nothing runs). -- `--except` wins over `--only` when both mention the same name. - -Compose with profiles (`up --profile work --only apt`) to restrict a -profile on the fly. - -### Rollback - -```sh -up --rollback -``` - -Reverts to the most recent eMerger-created snapshot. Dispatches to: - -- **snapper**: native `snapper -c root rollback `. Grep-finds the last - snapshot whose description starts with `eMerger pre-update`. A reboot is - required to apply the rollback (snapper semantics, not ours). -- **timeshift**: hands off to `timeshift --restore` (interactive by design; - we don't pass `--yes` - rollback is too destructive for that). -- **raw btrfs**: refuses to swap subvolumes automatically, prints the path - of the latest snapshot under `/.snapshots/emerger/` so you can do it - manually. - -Combine with `--snapshot` for a safe update cycle: - -```sh -up --snapshot -y || up --rollback -``` - -### Short flag bundling - -Single-letter short flags can be bundled: - -```sh -up -nv # == up -n -v -up -ynv # == up -y -n -v -up -qv # == up -q -v -``` - -Only flags whose letters are all in the set `{h V n v q y i w}` bundle. -Compound short flags (`-nl`, `-ni`, `-nc`, `-nt`, `-qq`, `-qqq`, `-up`, -`-au`, `-err`, `-rc`) and long flags (`--foo`) pass through unchanged. - ---- - -## Auto-update (unattended) - -```sh -up -au # Linux / macOS -``` -```powershell -up -au # Windows -``` - -- **Linux**: systemd user timer (preferred) at - `~/.config/systemd/user/emerger.{service,timer}`; cron fallback. -- **macOS**: cron fallback (`crontab -l`), or use `launchd` manually. -- **Windows**: `Register-ScheduledTask -TaskName eMerger`. Weekly, Sunday - 10:00, ยฑ1h randomized delay. - -The scheduled run always uses `-y -q -nl -ni`. - -Manage: - -```sh -# Linux -systemctl --user status emerger.timer -systemctl --user disable emerger.timer - -# Windows -Get-ScheduledTask eMerger -Unregister-ScheduledTask eMerger -``` - -To avoid night-time runs, pair with `QUIET_HOURS` in `config.sh`. - -> On Linux, systemd **user** timers do not fire unless a login session is -> open for the user. Run `loginctl enable-linger $USER` once (as root) to -> make them fire in the background. - ---- - -## Cookbook / Recipes - -Concrete, copy-pasteable snippets for common situations. - -### Daily driver (desktop) - -```sh -up -v -``` - -Simple. Live output, everything updated, cache and trash wiped at the -end. Add `--firmware` once a month on Linux. - -### Unattended server - -One-off setup: - -```sh -cat > ~/.config/emerger/config.sh <<'EOF' -ARG_SECURITY=1 -ARG_YES=1 -ARG_NO_CACHE=1 -ARG_NO_TRASH=1 -QUIET_HOURS="08:00-18:00" -EOF -up -au -``` - -Pair with a Prometheus hook for dashboards: - -```sh -cat > ~/.config/emerger/hooks/post.d/90-prom.sh <<'EOF' -#!/usr/bin/env bash -up --metrics /var/lib/node_exporter/textfile_collector/emerger.prom -EOF -chmod +x ~/.config/emerger/hooks/post.d/90-prom.sh -``` - -### Developer workstation - -```sh -up --dev --firmware --parallel -v -# or, as a profile: -up --profile home -``` - -### Pre-demo machine - -The day before a presentation: security patches, no big downloads, no -reboot. - -```sh -up --profile safe -``` - -### Metered / mobile connection - -Prefetch when on good Wi-Fi: - -```sh -up --download-only -y -``` - -Install later, even without network (the cache is already warm): - -```sh -up -y -``` - -### CI runner / container image - -```sh -up --only apt -y -qq --reboot-exit -rc=$? -if [[ $rc -eq 4 ]]; then echo "reboot required"; exit 0; fi -exit $rc -``` - -### Maintenance window with rollback guard - -Snapshot, update, rollback on failure, reboot on success: - -```sh -set -e -up --snapshot -y || { up --rollback; exit 1; } -up -y --reboot-exit -rc=$? -if [[ $rc -eq 4 ]]; then systemctl reboot; fi -``` - -### macOS with Homebrew only - -```sh -up --only brew,mas -v -``` - -### Windows without Chocolatey - ```powershell -up --except choco -v -``` - -### Audit a single package - -```sh -up -n | grep -i firefox # what would happen to it -up --changelog firefox # what changed upstream -``` - -### Pin a package (Linux) - -Add to `~/.config/emerger/ignore.list`: - -```text -nvidia-driver-535 -``` - -Then tell `apt` explicitly: - -```sh -sudo apt-mark hold nvidia-driver-535 +# %APPDATA%\emerger\config.ps1 +$script:ArgsGlobal.Dev = $true +$script:MANAGER_TIMEOUT = 3600 ``` -(pacman respects the file natively.) - ---- - -## Safety & security - -- eMerger is a client-side tool. No network listener, no daemon, no - persistent background process. -- It reads and writes only three locations: `~/.config/emerger/`, - `~/.cache/emerger/`, `~/.local/state/emerger/`, plus the global lock at - `/tmp/emerger.lock` on Unix. -- `sudo` credentials are cached by `sudo` itself, not by eMerger. When - the run ends, the cached credentials expire on the usual `sudo` - schedule (5 minutes by default). -- On Windows, UAC elevation happens **only** when a detected manager - actually needs admin. The elevation is logged. -- Hooks and plugins run as the invoking user. They can do anything the - user can do - only install hooks from sources you trust. -- The only network calls eMerger itself makes are (a) the optional - weather widget via `wttr.in`, (b) `git pull` during `--self-update`, - (c) `fwupdmgr refresh` when `--firmware` is active. Everything else is - delegated to the package manager you asked for. -- **No telemetry.** `history.jsonl` stays on your machine unless a hook - you wrote ships it elsewhere. - ---- - -## Files & paths - -### Linux / macOS - -| Path | Purpose | -|---|---| -| `~/.config/emerger/config.sh` | User defaults | -| `~/.config/emerger/profiles.d/` | User profiles | -| `~/.config/emerger/hooks/pre.d/`, `post.d/` | Hooks | -| `~/.config/emerger/ignore.list` | Ignore list (pacman native) | -| `~/.config/emerger/managers.d/*.sh` | User-defined manager plugins | -| `~/.cache/emerger/detected` | Detection cache (TTL: `EMERGER_CACHE_TTL`, default 86400s) | -| `~/.local/state/emerger/emerger.log` | Log (rotated at 2000 lines) | -| `~/.local/state/emerger/history.jsonl` | One JSON per run | -| `~/.local/state/emerger/pkgs.before` | Pre-run package snapshot | -| `~/.local/state/emerger/pkgs.after` | Post-run package snapshot | -| `~/.local/state/emerger/pkgs.diff` | Last-run package diff | -| `~/.local/state/emerger/resume` | Resume cursor | -| `/tmp/emerger.lock` | Global lock (`flock`) | - -### Windows - -| Path | Purpose | -|---|---| -| `%APPDATA%\emerger\config.ps1` | User defaults | -| `%APPDATA%\emerger\profiles.d\` | User profiles | -| `%APPDATA%\emerger\hooks\pre.d\`, `post.d\` | Hooks | -| `%LOCALAPPDATA%\emerger\cache\` | Detection cache | -| `%LOCALAPPDATA%\emerger\state\emerger.log` | Log | -| `%LOCALAPPDATA%\emerger\state\history.jsonl` | Run history | - ---- +Everything you can customize lives in `~/.config/emerger/` (Windows: `%APPDATA%\emerger\`, with `.ps1` files): -## Supported package managers - -**Linux - system (need sudo):** -`pacman`, `apt`/`apt-get`, `dnf`, `yum`, `zypper`, `xbps`, `apk`, `eopkg`, -`emerge`, `nixos-rebuild`, `fwupdmgr`, `snap`. - -**Linux - AUR (no sudo):** `yay`, `paru`. - -**Linux - user-space:** `flatpak`, `nix-env`. - -**macOS:** `softwareupdate` (native), `brew`, `brew --cask`, `mas`. +| put this | in | and you get | +|---|---|---| +| your fixed settings | `config.sh` | defaults for every run, such as "always skip snap" | +| a named set of settings | `profiles.d/NAME.sh` | `up --profile NAME` applies it; `work`, `home`, `server` and `safe` ship ready to use | +| your own scripts | `hooks/pre.d/`, `hooks/post.d/` | they run before or after the update, in name order (a backup first, a notification after) | +| a package manager `up` does not know | `managers.d/NAME.sh` (Unix) | `up` updates it like the others; [share/plugins/example.sh](share/plugins/example.sh) is a template | +| packages to leave alone | `ignore.list` (Linux) | pacman never upgrades them | -**Windows:** `winget`, `scoop`, `choco`, `PSWindowsUpdate`, `wsl --update`. +`up` loads a config file, profile, hook or plugin only when you own it and no other user can write to it. -**Dev toolchains** (all platforms, opt-in with `--dev`): `rustup`, -`cargo install-update`, `npm`, `pnpm`, `pip` (user), `gem`. +Every variable, its default and the plugin API: [the documentation](doc/documentation.pdf), section Configuration. -Want another one? Add a case branch to -[`src/lib/packages.sh`](src/lib/packages.sh) (Unix) or -[`src/pslib/Packages.ps1`](src/pslib/Packages.ps1) (Windows) - they're -simple table-driven dispatchers. Or drop a [plugin](#manager-plugins). +## Files ---- +| file | Linux and macOS | Windows | +|---|---|---| +| config | `~/.config/emerger/config.sh` | `%APPDATA%\emerger\config.ps1` | +| profiles | `~/.config/emerger/profiles.d/`, shipped `share/profiles/` | `%APPDATA%\emerger\profiles.d\`, shipped `share\profiles\` | +| hooks | `~/.config/emerger/hooks/pre.d/`, `hooks/post.d/` | `%APPDATA%\emerger\hooks\pre.d\`, `hooks\post.d\` | +| plugins | `~/.config/emerger/managers.d/` | none | +| ignore list | `~/.config/emerger/ignore.list` | none | +| detection cache | `~/.cache/emerger/detected` | none | +| log | `~/.local/state/emerger/emerger.log` | `%LOCALAPPDATA%\emerger\state\emerger.log` | +| run history | `~/.local/state/emerger/history.jsonl` | `%LOCALAPPDATA%\emerger\state\history.jsonl` | +| package lists | `~/.local/state/emerger/pkgs.before`, `pkgs.after`, `pkgs.diff` | none | +| resume cursor | `~/.local/state/emerger/resume` | none | +| run lock | `~/.local/state/emerger/emerger.lock` | `%LOCALAPPDATA%\emerger\state\run.lock`, `elevated.lock` | +| parallel output | `~/.local/state/emerger/parallel-*.log` | none | + +`XDG_CONFIG_HOME`, `XDG_CACHE_HOME` and `XDG_STATE_HOME` move the Unix directories. ## Exit codes -| Code | Meaning | +| code | meaning | |---|---| | 0 | success | -| 1 | runtime failure (sudo, lock, disk, interrupted) | -| 2 | argument parsing error | -| 3 | one or more package managers returned non-zero | -| 4 | reboot required (only emitted with `--reboot-exit`) | - -Useful for CI / cron wrappers: - -```sh -up -y -q || case $? in - 3) notify-send "eMerger: some managers failed" ;; - *) logger -t eMerger "fatal $?" ;; -esac -``` - -```powershell -up -y -q -if ($LASTEXITCODE -eq 3) { Write-Warning "Some managers failed" } -``` - ---- - -## Troubleshooting - -**"Another eMerger run is in progress"** - stale `flock` on -`/tmp/emerger.lock`. Check `ps` for stragglers then remove it. - -**Emoji renders as boxes** - `--no-emoji`, or set `LANG` / Windows Terminal -font to a Unicode-capable one. - -**Spinner disappears on terminal resize** - harmless; the live-log width -recomputes every 120ms. - -**`up --self-update` aborts with "non fast-forward"** - you have local -commits on top of `main`. Rebase or reset manually; eMerger refuses to -clobber them. - -**`notify-send` (Linux) doesn't appear** - no `DISPLAY` / -`WAYLAND_DISPLAY` in the environment (typical for cron). Use systemd user -timer instead; it inherits the session. - -**A manager fails with exit code 3** - run `up --errors` to tail the log, -then `up --doctor` to inspect the environment. Most failures come from a -manager's own health state (for example `dpkg` interrupted); run the -native repair command (`sudo dpkg --configure -a`, `sudo pacman -Dk`) -before retrying. - -**Nothing happens on scheduled runs** - check -`systemctl --user status emerger.timer` or the Windows Task Scheduler -entry. On Linux, user timers don't fire without an open session unless -you run `loginctl enable-linger $USER`. - -**(Windows) "up : The term 'up' is not recognized"** - your PowerShell -profile didn't load. Run `. $PROFILE` or open a new window. If still -missing, re-run `.\setup.ps1`. - -**(Windows) "cannot be loaded because running scripts is disabled"** - -`ExecutionPolicy` is `Restricted`. Run as user: -```powershell -Set-ExecutionPolicy -Scope CurrentUser RemoteSigned -``` - -**(Windows) Elevation fails silently** - you canceled the UAC prompt. The -script logs `relaunching elevated` then exits; the elevated window does -the actual work. - -**Pacman keeps asking about ignored packages** - `ignore.list` is passed -as `--ignore=`; pacman still prints the warning line. Upstream behavior. +| 1 | runtime failure (sudo, lock, disk, interrupted), or aborted (a declined safety prompt, no snapshot taken with `--snapshot`) | +| 2 | bad argument | +| 3 | one or more managers failed | +| 4 | reboot pending, only with `--reboot-exit` | -**"command not found: gum" or "whiptail"** - the interactive menu (`-i`) -falls back to a plain read loop when neither is installed. Install -[gum](https://github.com/charmbracelet/gum) for a nicer UI or ignore the -warning. +## Security ---- +- `up` changes only what you ask for. Cleaning the cache, the Trash and `--deep-clean` ask before deleting anything. +- On its own, `up` goes online only for `--weather`, `--self-update`, `--firmware`, `--refresh-mirrors` and one connectivity check in `--doctor`. All other traffic comes from your package managers. +- `up` runs with `sudo`, so keep the eMerger folder writable by you alone. If other users can write to it, `up` refuses to start. +- Your config, profiles, plugins and hooks follow the same rule: `up` skips any that another user could change. -## FAQ +## Update and remove -**Is eMerger safe for production servers?** -Yes, but use it in security-only, unattended mode: `up --profile server`. -Pair with `--reboot-exit` so your orchestrator decides when to reboot. +- **Update:** run `up --self-update`. It never overwrites your own changes. +- **Remove:** run `./uninstall.sh` (Windows: `.\uninstall.ps1`). It removes everything the install script added, then asks whether to delete your settings, history and cache too (no by default). Then delete the eMerger folder. -**Does `up` install packages I don't already have?** -No. `up` only invokes managers that are already installed and only asks -them to upgrade what is already installed. No new software is added -unless a package upgrade pulls in a new dependency. +## Problems -**Does `up` reboot my machine?** -Only with `--reboot`. Without it, the summary prints a reboot advisory -and the run exits normally. +**"Another eMerger run is in progress"**: another `up` is still running. Wait for it to finish. Do not delete the lock file. -**Can I use `up` without `sudo`?** -Yes, in user-only mode: `up --only flatpak,brew,npm,pip,cargo` (adjust to -what you have). User-level managers never need elevation. +**A manager failed (exit code 3)**: run `up --errors` to see why, and `up --doctor` to check your system. Usually the manager needs a repair first (for apt: `sudo dpkg --configure -a`), then run `up` again. -**Can I use `up` inside a Docker image build?** -Yes. Use `up --only apt -y -qq` (or the relevant manager) and ignore the -reboot advisory. Avoid `--firmware`, `--snapshot` and interactive flags. +**It stops at "User cache" or "Trash"**: it is asking yes or no. After 60 seconds it answers no. Use `-y` to answer yes. -**What happens if two `up` runs start at the same time?** -The second one aborts with exit code 1 ("Another eMerger run is in -progress"). The lock is a plain `flock` on `/tmp/emerger.lock`. +**Emoji show up as boxes**: install a color-emoji font, or run `up --ascii`. -**How do I completely remove eMerger?** -Run the uninstaller, then: -```sh -rm -rf ~/.config/emerger ~/.cache/emerger ~/.local/state/emerger -rm -rf /path/to/eMerger # the repo itself -``` - -**Where is my data?** -All local, all in the paths listed in [Files & paths](#files--paths). -Nothing leaves your machine unless a hook you wrote ships it. - -**Can I contribute a new package manager?** -Absolutely - see [Development](#development). Most contributions are a -20-line dispatch branch plus a test case. +**macOS says "cannot read the Trash"**: give your terminal Full Disk Access in System Settings, Privacy & Security. -**Why is the terminal flashing during `--parallel -v`?** -Each user-space manager streams its own output concurrently. Drop `-v` -or narrow the parallel set with `--only` if you want a calm terminal. +**Windows does not recognize `up`**: open a new PowerShell window. ---- +**Windows says "running scripts is disabled"**: run `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`. -## Glossary - -- **Dry-run**: a simulation. The tool prints the commands it would run - without actually running them. -- **Hook**: a user script that runs before (`pre.d`) or after (`post.d`) - the update flow. -- **Manager (package manager)**: software like `apt`, `pacman`, `brew`, - `winget` that installs, upgrades and removes programs on your machine. -- **Parallel mode**: concurrent execution of user-space managers. -- **Plugin**: a user-provided manager definition. Registers a new - manager without modifying the repository. -- **Profile**: a named bundle of default flags, loaded via - `--profile NAME`. -- **Resume cursor**: a file that records which managers completed - successfully, consumed by `--resume`. -- **Snapshot**: a read-only filesystem checkpoint taken before the - upgrade. Linux only (snapper/timeshift/btrfs). -- **TUI**: Terminal User Interface. The interactive menu (`-i`) on Unix. -- **UAC**: User Account Control, the Windows elevation prompt. eMerger - relaunches itself elevated when needed. - ---- +More answers are in [the documentation](doc/documentation.pdf), section Troubleshooting. ## Development -### Repo layout - -```text -eMerger/ -โ”œโ”€โ”€ src/ -โ”‚ โ”œโ”€โ”€ emerger.sh # Unix entry (Linux + macOS) -โ”‚ โ”œโ”€โ”€ emerger.ps1 # Windows entry -โ”‚ โ”œโ”€โ”€ lib/ # bash libs -โ”‚ โ”œโ”€โ”€ pslib/ # PowerShell libs -โ”‚ โ””โ”€โ”€ logo/ -โ”œโ”€โ”€ share/profiles/ # shipped profiles (*.sh + *.ps1) -โ”œโ”€โ”€ share/plugins/ # example plugins -โ”œโ”€โ”€ completions/ # bash/zsh/fish completions -โ”œโ”€โ”€ tests/ # bats tests -โ”œโ”€โ”€ man/up.1 # man page -โ”œโ”€โ”€ doc/ # printable documentation -โ”œโ”€โ”€ setup.sh setup.ps1 -โ”œโ”€โ”€ uninstall.sh uninstall.ps1 -โ”œโ”€โ”€ update.sh update.ps1 -โ”œโ”€โ”€ VERSION -โ””โ”€โ”€ .github/workflows/ci.yml -``` - -### Unix lib modules (`src/lib/`) - -| File | Role | -|---|---| -| `ui.sh` | Colors, glyphs, spinner, box, live-log monitor | -| `log.sh` | Structured logging (rotated) | -| `sys.sh` | OS/shell/battery/disk detection | -| `run.sh` | Command runner (dry-run, retry, progress) | -| `args.sh` | Argument parser | -| `packages.sh` | Per-manager dispatcher | -| `clean.sh` | Cache and trash cleaners | -| `hooks.sh` | User hook runner | -| `update.sh` | Self-update + cron/timer setup | -| `notify.sh` | Desktop notifications | -| `summary.sh` | Final banner, history persistence | -| `tui.sh` | Interactive menu | -| `lock.sh` | Global `flock` | -| `retry.sh` | Retry on transient failures | -| `reboot.sh` | Reboot-required detection | -| `diff.sh` | Package snapshots + diff | -| `disk.sh` | Disk-space precheck | -| `snapshot.sh` | snapper/timeshift/btrfs | -| `mirrors.sh` | Mirror rank/refresh | -| `resume.sh` | Resume cursor | -| `doctor.sh` | `--doctor` | -| `changelog.sh` | `--changelog PKG` | -| `report.sh` | Markdown export | -| `wizard.sh` | First-run wizard | -| `profiles.sh` | Profile loader | -| `progress.sh` | Output summary + highlight | -| `estimate.sh` | Step ETA from history | -| `ignore.sh` | Ignore list loader | -| `plugins.sh` | User plugin loader | -| `metrics.sh` | Prometheus textfile export | - -### PowerShell lib modules (`src/pslib/`) - -| File | Role | -|---|---| -| `UI.ps1` | Colors, glyphs, box, step | -| `Log.ps1` | Structured logging | -| `Sys.ps1` | OS, admin, battery, disk, UAC elevation | -| `Args.ps1` | Arg parser (shift + regex) | -| `Packages.ps1` | Manager dispatcher + `Run-Cmd` | -| `Clean.ps1` | `%TEMP%` and Recycle Bin | -| `Hooks.ps1` | `hooks\{pre,post}.d\*.ps1` | -| `Update.ps1` | `git pull` self-update + Task Scheduler | -| `Notify.ps1` | BurntToast (optional) | -| `Summary.ps1` | Final box, history, reboot detection | -| `Doctor.ps1` | `--doctor` | -| `Profiles.ps1` | Profile loader | -| `Help.txt` | Help text | - -### Running tests - -```sh -sudo apt-get install bats shellcheck -bats tests/ -shellcheck -S error src/emerger.sh src/lib/*.sh setup.sh uninstall.sh update.sh -``` - -Both run on push via `.github/workflows/ci.yml`. - -### Adding a package manager - -**Unix** - edit [`src/lib/packages.sh`](src/lib/packages.sh): -1. Add its name to `PKG_MANAGERS`. -2. Add a branch in `_pkg_detect_raw`. -3. Add a branch in `pkg_run` with `run_cmd` calls. -4. If it doesn't need sudo, exclude it from `pkg_needs_sudo`. -5. Optional: emoji in `pkg_icon`, output parser in `progress.sh`. - -**Windows** - edit [`src/pslib/Packages.ps1`](src/pslib/Packages.ps1): -1. Add its name to `$script:PKG_MANAGERS` (or `PKG_DEV`). -2. Add a `Pkg-Detect` case. -3. Add a `Pkg-Run` case with `Run-Cmd` calls. -4. If it needs admin, add it to `Pkg-Need-Admin`. - -### Contributing - -See [CONTRIBUTING.md](./CONTRIBUTING.md). Open issues and PRs against -`dev`. Include `up --doctor` output and the relevant chunk of the log when -reporting bugs. - ---- +- **Tests:** `bats tests/`. Some tests need `pwsh`, `zsh`, `fish` or `shellcheck`, and are skipped when the tool is missing. +- **Lint:** `shopt -s globstar; shellcheck -S error install.sh uninstall.sh src/emerger.sh src/lib/**/*.sh share/plugins/*.sh share/profiles/*.sh completions/up.bash` (the same check CI runs). +- **Documentation:** edit [doc/documentation.tex](doc/documentation.tex), then run `pdflatex documentation.tex` twice inside `doc/` (the second run fills in the table of contents and the section references). +- **Code:** `src/emerger.sh` and [src/lib/](src/lib/) for Linux and macOS, `src/emerger.ps1` and [src/pslib/](src/pslib/) for Windows. Both halves must behave the same. +- **Adding a package manager:** see [the documentation](doc/documentation.pdf), section Development. +- **Third-party material:** [reference/third-party.md](reference/third-party.md). +- **Contributing:** [CONTRIBUTING.md](CONTRIBUTING.md). ## License -See [LICENSE](./LICENSE). - -## Credits - -Weather line via [wttr.in](https://github.com/chubin/wttr.in). +MIT, see [LICENSE](LICENSE). diff --git a/VERSION b/VERSION index 227cea2..4a36342 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.0.0 +3.0.0 diff --git a/completions/_up b/completions/_up index 6cf8ad6..36922bd 100644 --- a/completions/_up +++ b/completions/_up @@ -1,6 +1,9 @@ #compdef up # zsh completion for eMerger +# Scope: every flag the Unix parser accepts as its own word, manager names +# after --only and --except, profile names after --profile. +# Complete the flags of up, with manager and profile names as their values. _up() { local -a opts opts=( @@ -8,27 +11,32 @@ _up() { '--help[show help]' '-V[show version]' '--version[show version]' - '-i[interactive menu]' - '--interactive[interactive menu]' '--doctor[environment health check]' '-n[dry-run]' '--dry-run[dry-run]' '-v[verbose]' '--verbose[verbose]' - '-q[quiet (repeat for more)]' + '*-q[quiet (repeat for more)]' '-qq[quieter]' '-qqq[quietest]' '--quiet[quiet]' '-y[assume yes]' '--yes[assume yes]' + '--json[JSON summary on stdout]' '--security[security only]' + '--accept-licenses[accept licence agreements]' '--firmware[include firmware]' '--no-firmware[skip firmware]' '--dev[include dev toolchains]' '--parallel[parallel user-space managers]' - '--no-emoji[ASCII glyphs only]' + '--ascii[ASCII glyphs only]' '--profile[load named profile]:profile:_up_profiles' '--list-profiles[list profiles]' + '--only[only these managers]:managers:_up_managers' + '--except[skip these managers]:managers:_up_managers' + '--rollback[revert the last snapshot]' + '--reboot-exit[exit 4 if a reboot is required]' + '--download-only[download, do not install]' '--snapshot[pre-update snapshot]' '--refresh-mirrors[refresh mirrors]' '--resume[skip completed managers]' @@ -38,15 +46,16 @@ _up() { '-ni[no system info]' '--no-info[no system info]' '-nc[no cache clean]' - '--no-cache[no cache clean]' + '--keep-cache[no cache clean]' '-nt[no trash clean]' - '--no-trash[no trash clean]' + '--keep-trash[no trash clean]' + '--deep-clean[clean journal, old kernels, containers, crash dumps]' '-w[weather]' '--weather[weather]' '--changed[show package diff]' '--changelog[show changelog]:package' '--history[run history]' - '--report[export markdown]:file:_files' + '--metrics[export Prometheus textfile]:file:_files' '-err[show errors]' '--errors[show errors]' '-up[self-update]' @@ -59,16 +68,34 @@ _up() { _arguments -s $opts } +# Print the checkout root the `up` alias points at, or nothing. +_up_root() { + local alias_def="${aliases[up]:-}" + [[ $alias_def == *"/src/emerger.sh"* ]] || return 0 + alias_def="${alias_def%%/src/emerger.sh*}" + alias_def="${alias_def#*bash }" + alias_def="${alias_def#[\"\']}" + print -r -- "${alias_def//\\ / }" +} + +# Offer the profile names from the user's profiles.d and the shipped ones. _up_profiles() { - local -a p - local dir - for dir in "$HOME/.config/emerger/profiles.d" "${0:A:h}/../share/profiles"; do + local -a profiles + local dir file root + root=$(_up_root) + for dir in "${XDG_CONFIG_HOME:-$HOME/.config}/emerger/profiles.d" ${root:+"$root/share/profiles"}; do [[ -d $dir ]] || continue - for f in "$dir"/*.sh; do - [[ -f $f ]] && p+=(${f:t:r}) + for file in "$dir"/*.sh(N); do + profiles+=(${file:t:r}) done done - _values profile $p + # compadd takes names literally, _values would parse them as specs. + compadd -- ${(u)profiles} +} + +# Offer the built-in manager names, comma separated. +_up_managers() { + _values -s , manager pacman yay paru apt dnf yum zypper xbps apk eopkg emerge nix softwareupdate brew mas fwupd rpi-eeprom flatpak snap rustup cargo npm pnpm pip gem } compdef _up up diff --git a/completions/up.bash b/completions/up.bash index 0fe1166..ccdc1bd 100644 --- a/completions/up.bash +++ b/completions/up.bash @@ -1,30 +1,84 @@ # bash completion for eMerger +# Scope: every flag the Unix parser accepts as its own word, manager names +# after --only and --except, profile names after --profile. + +# Print the checkout root the `up` alias points at, or nothing. The alias body +# is `bash "/src/emerger.sh"`, quoted or not. +_up_root() { + local alias_def="${BASH_ALIASES[up]:-}" + # bash 3.2 has no BASH_ALIASES: read the definition `alias up` prints. + [[ -n $alias_def ]] || alias_def=$(alias up 2>/dev/null) + [[ $alias_def == *"/src/emerger.sh"* ]] || return 0 + alias_def="${alias_def%%/src/emerger.sh*}" + alias_def="${alias_def#*bash }" + alias_def="${alias_def#[\"\']}" + printf '%s' "${alias_def//\\ / }" +} + +# Fill COMPREPLY with the profile names starting with $1. Names come from file +# names, so they are matched as text and never expanded. Seen names are a +# newline-delimited string, since bash 3.2 has no associative arrays. +_up_profiles() { + local cur="$1" dir file name root + local seen=$'\n' + root=$(_up_root) + COMPREPLY=() + for dir in "${XDG_CONFIG_HOME:-$HOME/.config}/emerger/profiles.d" ${root:+"$root/share/profiles"}; do + [[ -d $dir ]] || continue + for file in "$dir"/*.sh; do + [[ -f $file ]] || continue + name="${file##*/}"; name="${name%.sh}" + [[ $name == "$cur"* && $seen != *$'\n'"$name"$'\n'* ]] || continue + seen+="$name"$'\n' + COMPREPLY+=("$name") + done + done +} + +# Fill COMPREPLY with the lines command $@ prints, one word per line, so file +# names keep their spaces. A read loop, since bash 3.2 has no mapfile. +_up_reply() { + local word + COMPREPLY=() + while IFS= read -r word; do + COMPREPLY+=("$word") + done < <("$@") +} + +# Fill COMPREPLY for the word under the cursor: profile names after +# --profile, files after --metrics, manager names after --only and --except, else flags. _up_completion() { - local cur prev opts profiles + local cur prev opts cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[COMP_CWORD-1]}" case "$prev" in --profile) - profiles=$(for d in "$HOME/.config/emerger/profiles.d" "$(dirname "$(command -v up 2>/dev/null || echo)")/../share/profiles"; do - [ -d "$d" ] && for f in "$d"/*.sh; do [ -f "$f" ] && basename "$f" .sh; done - done | sort -u) - COMPREPLY=( $(compgen -W "$profiles" -- "$cur") ) + _up_profiles "$cur" + return 0 + ;; + --metrics) + _up_reply compgen -f -- "$cur" return 0 ;; - --report) - COMPREPLY=( $(compgen -f -- "$cur") ) + --only|--except) + # Complete the item after the last comma, keep the ones before it. + local pre="" + [[ $cur == *,* ]] && pre="${cur%,*}," + _up_reply compgen -P "$pre" -W "pacman yay paru apt dnf yum zypper xbps apk eopkg emerge nix softwareupdate brew mas fwupd rpi-eeprom flatpak snap rustup cargo npm pnpm pip gem" -- "${cur##*,}" return 0 ;; esac - opts="-h --help -V --version -i --interactive --doctor - -n --dry-run -v --verbose -q -qq -qqq --quiet -y --yes - --security --firmware --no-firmware --dev --parallel --no-emoji - --profile --list-profiles --snapshot --refresh-mirrors --resume --reboot - -nl --no-logo -ni --no-info -nc --no-cache -nt --no-trash -w --weather - --changed --changelog --history --report -err --errors + opts="-h --help -V --version --doctor + -n --dry-run -v --verbose -q -qq -qqq --quiet -y --yes --json + --security --accept-licenses --firmware --no-firmware --dev --parallel --ascii + --profile --list-profiles --only --except + --snapshot --rollback --refresh-mirrors --resume --reboot --reboot-exit + --download-only + -nl --no-logo -ni --no-info -nc --keep-cache -nt --keep-trash --deep-clean -w --weather + --changed --changelog --history --metrics -err --errors -up --self-update -au --auto-update -rc --rebuild-cache" - COMPREPLY=( $(compgen -W "$opts" -- "$cur") ) + _up_reply compgen -W "$opts" -- "$cur" } complete -F _up_completion up diff --git a/completions/up.fish b/completions/up.fish index 3c8261e..abf9e8c 100644 --- a/completions/up.fish +++ b/completions/up.fish @@ -1,6 +1,14 @@ # fish completion for eMerger +# Scope: every flag the Unix parser accepts as its own word, manager names +# after --only and --except, profile names after --profile. +# Print the profile names from the user's profiles.d and the shipped ones. function __up_profiles - for d in ~/.config/emerger/profiles.d (status dirname)/../share/profiles + set -l config (set -q XDG_CONFIG_HOME; and echo $XDG_CONFIG_HOME; or echo ~/.config) + set -l dirs $config/emerger/profiles.d + # Alias `up` holds the checkout path: bash "/src/emerger.sh", quoted or not. + set -l root (functions up 2>/dev/null | string match -r -g '"?([^" ]*)/src/emerger\.sh') + set -q root[1]; and set -a dirs $root[1]/share/profiles + for d in $dirs test -d $d; and for f in $d/*.sh basename $f .sh end @@ -9,18 +17,32 @@ end complete -c up -s h -l help -d 'show help' complete -c up -s V -l version -d 'show version' -complete -c up -s i -l interactive -d 'interactive menu' complete -c up -l doctor -d 'environment health check' complete -c up -s n -l dry-run -d 'dry-run' complete -c up -s v -l verbose -d 'verbose output' complete -c up -s q -l quiet -d 'quieter output' +complete -c up -o qq -d 'quieter output' +complete -c up -o qqq -d 'quietest output' complete -c up -s y -l yes -d 'assume yes' complete -c up -l security -d 'security updates only' +complete -c up -l accept-licenses -d 'accept licence agreements' complete -c up -l firmware -d 'include firmware' complete -c up -l no-firmware -d 'skip firmware' complete -c up -l dev -d 'include dev toolchains' complete -c up -l parallel -d 'parallel user-space' -complete -c up -l no-emoji -d 'ASCII glyphs only' +complete -c up -l ascii -d 'ASCII glyphs only' +complete -c up -o nl -l no-logo -d 'hide logo' +complete -c up -o ni -l no-info -d 'hide system info' +complete -c up -o nc -l keep-cache -d 'skip cache cleaning' +complete -c up -o nt -l keep-trash -d 'skip trash cleaning' +complete -c up -l json -d 'JSON summary on stdout' +complete -c up -l only -d 'only these managers' -xa 'pacman yay paru apt dnf yum zypper xbps apk eopkg emerge nix softwareupdate brew mas fwupd rpi-eeprom flatpak snap rustup cargo npm pnpm pip gem' +complete -c up -l except -d 'skip these managers' -xa 'pacman yay paru apt dnf yum zypper xbps apk eopkg emerge nix softwareupdate brew mas fwupd rpi-eeprom flatpak snap rustup cargo npm pnpm pip gem' +complete -c up -l rollback -d 'revert last snapshot' +complete -c up -l reboot-exit -d 'exit 4 if reboot required' +complete -c up -l download-only -d 'download, do not install' +complete -c up -l metrics -d 'export Prometheus textfile' -r +complete -c up -l deep-clean -d 'journal, old kernels, containers, crash dumps' complete -c up -l profile -d 'load profile' -xa '(__up_profiles)' complete -c up -l list-profiles -d 'list profiles' complete -c up -l snapshot -d 'pre-update snapshot' @@ -31,8 +53,7 @@ complete -c up -s w -l weather -d 'weather line' complete -c up -l changed -d 'show package diff' complete -c up -l changelog -d 'show changelog' -x complete -c up -l history -d 'run history' -complete -c up -l report -d 'export markdown' -r -complete -c up -l errors -d 'show errors' -complete -c up -l self-update -d 'update eMerger' -complete -c up -l auto-update -d 'install auto-update' -complete -c up -l rebuild-cache -d 'clear detection cache' +complete -c up -o err -l errors -d 'show errors' +complete -c up -o up -l self-update -d 'update eMerger' +complete -c up -o au -l auto-update -d 'install auto-update' +complete -c up -o rc -l rebuild-cache -d 'clear detection cache' diff --git a/doc/documentation.pdf b/doc/documentation.pdf index a28f7d8..38b4d2d 100644 Binary files a/doc/documentation.pdf and b/doc/documentation.pdf differ diff --git a/doc/documentation.tex b/doc/documentation.tex index f167e93..afd4757 100644 --- a/doc/documentation.tex +++ b/doc/documentation.tex @@ -8,6 +8,7 @@ \usepackage{lmodern} \renewcommand{\familydefault}{\sfdefault} % Latin Modern Sans Serif as default \usepackage{microtype} +\setlength{\emergencystretch}{3em} \usepackage{textcomp} %------------------------------------------------------- @@ -98,7 +99,7 @@ %------------------------------------------------------- % Metadata %------------------------------------------------------- -\title{\textbf{eMerger}\\[4pt]\large One command to update your whole system} +\title{\textbf{eMerger}\\[4pt]\large A one-command system updater} \author{Roberto Antoniello \quad\textbf{\&}\quad Edoardo Ferrari} \date{\today} @@ -111,18 +112,14 @@ \begin{abstract} \noindent -\textbf{eMerger} is a cross-platform command line tool that refreshes, -upgrades and cleans a computer with a single command: \texttt{up}. It runs -on \textbf{Linux}, \textbf{macOS} and \textbf{Windows}, auto-detects every -package manager present on the host and invokes them in the right order, -returning one unified summary at the end. No daemon. No YAML. No embedded -DSL. Just a small, auditable script that drives the tools you already have. - -This document is written to be readable by anyone: newcomers will find an -explanation of what a package manager is, what \texttt{up} actually does on -your machine and how to try it safely; experienced users will find a -complete reference for every flag, profile, hook, plugin and integration -point, plus a cookbook of real-world recipes. +\textbf{eMerger} is a command line tool for Linux, macOS and Windows that +refreshes, upgrades and cleans a system with one command, \texttt{up}. It +detects the package managers installed on the host, runs them in order and +prints one summary at the end. Bash on Unix, PowerShell on Windows. + +\medskip\noindent +This manual covers every platform: every flag, configuration variable, +environment variable, file, exit code and JSON field, and the plugin API. \end{abstract} \tableofcontents @@ -130,202 +127,122 @@ \hrule \vspace{1em} -%------------------------------------------------------- -\section{How to read this document} -%------------------------------------------------------- -The document is organised in layers: - -\begin{itemize} - \item \textbf{Getting started} (sections \ref{sec:why}\,--\,\ref{sec:firstrun}): - what eMerger does, why you might want it, and a guided first run - that takes less than five minutes. - \item \textbf{User manual} (sections \ref{sec:flow}\,--\,\ref{sec:features}): - the execution flow, every command line flag with an example, and a - feature-by-feature walkthrough. - \item \textbf{Configuration} (sections \ref{sec:config}\,--\,\ref{sec:plugins}): - config file, profiles, hooks and user plugins, all with - copy-pasteable snippets. - \item \textbf{Integration} (sections \ref{sec:integration}\,--\,\ref{sec:auto}): - JSON, Prometheus, exit codes, CI, cron and systemd timers. - \item \textbf{Cookbook} (section \ref{sec:cookbook}): ready-to-use - recipes for laptops, servers, developer workstations, presentation - machines, CI runners and metered connections. - \item \textbf{Reference} (sections \ref{sec:files}\,--\,\ref{sec:glossary}): - file locations, supported managers, exit codes, troubleshooting, - FAQ and a glossary of terms. - \item \textbf{Development} (section \ref{sec:dev}): repo layout, module - responsibilities, running tests, adding a package manager. -\end{itemize} - -Throughout the document you will see three kinds of call-outs: - -\begin{tip} -\textbf{Tip} - a useful shortcut or a better way of doing something. -\end{tip} -\begin{note} -\textbf{Note} - background information or a clarification that is worth -remembering but not strictly required to move on. -\end{note} -\begin{warn} -\textbf{Warning} - something that can surprise you or cost you data if -ignored. Read these carefully. -\end{warn} - \clearpage %------------------------------------------------------- -\section{Why eMerger?}\label{sec:why} +\section{Overview}\label{sec:why} %------------------------------------------------------- -\subsection{The problem} -A modern desktop or laptop runs software that comes from many different -sources at once: +\subsection{Background} +Your software comes from lots of places: \begin{itemize} - \item the operating system distributor (\texttt{apt}, \texttt{dnf}, + \item the operating system (\texttt{apt}, \texttt{dnf}, \texttt{pacman}, \texttt{zypper}, \texttt{softwareupdate}, - \texttt{winget}\,\dots); - \item a cross-distro app store (\texttt{flatpak}, \texttt{snap}, - \texttt{brew --cask}, \texttt{choco}, \texttt{scoop}); - \item a user-level store (\texttt{brew}, \texttt{mas}); - \item language-specific ecosystems (\texttt{npm}, \texttt{pip}, - \texttt{cargo}, \texttt{gem}, \texttt{pnpm}\,\dots); + \texttt{winget} and others); + \item cross-distribution app stores (\texttt{flatpak}, \texttt{snap}, + \texttt{brew -{}-cask}, \texttt{choco}, \texttt{scoop}); + \item user-level stores (\texttt{brew}, \texttt{mas}); + \item language ecosystems (\texttt{npm}, \texttt{pip}, + \texttt{cargo}, \texttt{gem}, \texttt{pnpm} and others); \item vendor firmware (\texttt{fwupdmgr} on Linux, \texttt{softwareupdate} on macOS, Dell/Lenovo utilities on Windows). \end{itemize} -Each uses a slightly different command, has its own cache, its own notion -of ``security update'' and its own definition of ``clean''. Keeping all of -them up to date by hand is either tedious or error-prone, and writing a -personal wrapper that does the right thing on three operating systems is -a weekend project most people never finish. +Each has its own commands, its own cache and its own idea of what a +security update or a clean-up is. eMerger puts them behind one command. -\subsection{The solution} -eMerger is that wrapper, generalised. Typing \texttt{up} on any supported -platform will: +\subsection{What \texttt{up} does} +On any supported platform, \texttt{up}: \begin{enumerate} - \item detect every package manager installed on the host; - \item ask for \texttt{sudo} (or trigger a UAC elevation on Windows) only - if one of the detected managers actually needs it; - \item take an optional filesystem snapshot or a package list snapshot - so you can audit the run afterwards; - \item run refresh / upgrade / clean, in the right order, serially or in + \item detects the package managers installed on the host; + \item asks for \texttt{sudo} (or a UAC elevation on Windows) only if a + detected manager needs it; + \item optionally takes a filesystem snapshot, and records the package + list so the run can be audited afterwards; + \item runs refresh, upgrade and clean for each manager, serially or in parallel where safe; - \item clean user caches and the trash, optionally; - \item print a boxed summary with per-manager result, disk freed, run - duration and a reboot advisory; - \item export the same summary as JSON, Markdown or Prometheus textfile - if you ask. + \item optionally cleans user caches and the trash; + \item prints a summary with the result per manager, disk freed, run + duration and whether a reboot is needed; + \item on request, exports the same summary as JSON or a Prometheus + textfile. \end{enumerate} -It does this with no daemon, no YAML, no Python runtime and no Ruby -runtime: just a Bash script on Unix and a PowerShell script on Windows. - -\subsection{Design principles} -\begin{itemize} - \item \textbf{One command.} The user types \texttt{up}; everything else - is automatic detection, ordering and reporting. - \item \textbf{No runtime bloat.} Configuration is a plain shell or - PowerShell file that is sourced at startup. - \item \textbf{Use what is there.} eMerger never installs a package - manager on your behalf; it detects the ones already installed and - delegates work to them. - \item \textbf{Safe by default.} Dry-run, retries, filesystem snapshots, - resume after interruption and a pre-flight health check are all - first-class options. - \item \textbf{Cross-platform parity.} The core flow (detect, upgrade, - clean, summarise) is identical on Linux, macOS and Windows. - Platform-specific features are gated and labelled. -\end{itemize} - -\subsection{What eMerger is \emph{not}} -\begin{itemize} - \item It is \textbf{not} a package manager itself. It does not download - or install software directly: it asks the native tools to do it. - \item It is \textbf{not} a configuration management system. There is no - desired-state manifest, no idempotent resource graph. If you want - that, use Ansible, Salt or NixOS. - \item It is \textbf{not} a scheduler. It can install a weekly systemd - timer, cron job or Windows scheduled task, but it does not run as - a service. -\end{itemize} - -The project name is a wink at Gentoo's \texttt{emerge}: the tool started -under the name \textit{Updater} and was later renamed to \textit{eMerger} -to reflect its goal of merging the quirks of every supported package -manager behind a uniform interface. - %------------------------------------------------------- -\section{Platforms at a glance}\label{sec:platforms} +\section{Platforms}\label{sec:platforms} %------------------------------------------------------- \begin{center} +\footnotesize \begin{tabular}{@{}llll@{}} \toprule & \textbf{Linux} & \textbf{macOS} & \textbf{Windows} \\ \midrule Entry point & \texttt{src/emerger.sh} & \texttt{src/emerger.sh} & \texttt{src/emerger.ps1}\\ -Shell & bash 3.2+ & bash 3.2+ (system) & PowerShell 5.1+ \\ -Setup & \texttt{./setup.sh} & \texttt{./setup.sh} & \texttt{.\textbackslash setup.ps1} \\ +Shell & bash 4.4+ & bash 4.4+ (Homebrew) & PowerShell 5.1+ \\ +Install & \texttt{./install.sh} & \texttt{./install.sh} & \texttt{.\textbackslash install.ps1} \\ Uninstall & \texttt{./uninstall.sh} & \texttt{./uninstall.sh} & \texttt{.\textbackslash uninstall.ps1}\\ Auto-update & systemd timer / cron & cron & Task Scheduler \\ -Elevation & \texttt{sudo} & \texttt{sudo} & UAC relaunch \\ -TUI menu & yes (\texttt{-i}) & yes (\texttt{-i}) & no \\ +Elevation & \texttt{sudo} & \texttt{sudo} & UAC, admin managers only \\ Parallel mode & yes & yes & no (always serial) \\ -Snapshots & snapper/timeshift/btrfs & no & no (System Restore manual)\\ +Snapshots & snapper/timeshift/btrfs & no & no \\ Config dir & \verb|~/.config/emerger/| & \verb|~/.config/emerger/| & \verb|%APPDATA%\emerger\|\\ State dir & \verb|~/.local/state/emerger/| & \verb|~/.local/state/emerger/| & \verb|%LOCALAPPDATA%\emerger\state\|\\ \bottomrule \end{tabular} \end{center} -The core flow is identical across platforms. Features that depend on -operating system primitives (firmware updates, filesystem snapshots, TUI) -are gated to the platforms that support them and labelled as such -throughout this document. +The core flow (detect, upgrade, clean, summary) is the same everywhere. +Platform-specific features are marked as such. %------------------------------------------------------- \section{Requirements}\label{sec:requirements} %------------------------------------------------------- -eMerger never installs dependencies for you. The list below is what -``works out of the box'' vs. what unlocks optional features. +eMerger does not install any of these; it uses whatever is there. \subsection{Linux} -\textbf{Required:} \texttt{bash} 3.2+, \texttt{coreutils}, \texttt{git}, +\textbf{Required:} \texttt{bash} 4.4+, \texttt{coreutils}, \texttt{git}, \texttt{sudo}. \textbf{Optional:} \begin{itemize} - \item \texttt{gum} or \texttt{whiptail} for a nicer interactive menu. \item \texttt{notify-send} for desktop notifications. - \item \texttt{curl} for the weather widget (\texttt{-w}) and - \texttt{--self-update} checks. - \item \texttt{flock} for the global lock (pre-installed on every - mainstream distribution). - \item \texttt{reflector} (Arch) or \texttt{netselect-apt} (Debian / - Ubuntu) for \texttt{--refresh-mirrors}. + \item \texttt{curl} for the weather line (\texttt{-w}) and the + \texttt{-{}-doctor} connectivity check. + \item \texttt{flock} for the global lock (part of \texttt{util-linux}, + installed by default on most distributions). Without it the lock + is the directory \verb|emerger.lock.d|. + \item \texttt{timeout} (coreutils) for \verb|MANAGER_TIMEOUT|. + \item \texttt{pkill} (procps) to stop the \texttt{-{}-parallel} managers + when a run is interrupted; without it their commands finish first. + \item \texttt{reflector} (Arch) or \texttt{netselect-apt} (Debian) + for \texttt{-{}-refresh-mirrors}. \item \texttt{snapper}, \texttt{timeshift} or \texttt{btrfs-progs} for - \texttt{--snapshot} and \texttt{--rollback}. - \item \texttt{fwupdmgr} for \texttt{--firmware}. + \texttt{-{}-snapshot} and \texttt{-{}-rollback}. + \item \texttt{fwupdmgr} for \texttt{-{}-firmware}. \end{itemize} \subsection{macOS} -\textbf{Required:} the system \texttt{bash} at \texttt{/bin/bash} (3.2+ -is enough; no Homebrew Bash needed), and Xcode Command Line Tools for -\texttt{git}. +\textbf{Required:} \texttt{bash} 4.4 or later, and Xcode Command Line +Tools for \texttt{git}. The system \texttt{/bin/bash} is 3.2 and is too +old (eMerger uses \texttt{mapfile}, \verb|${var,,}|, \verb|{fd}| +redirections and empty-array expansion under \texttt{set -u}); install a current one with \texttt{brew install bash} and +make sure it comes first in \texttt{PATH}, since the \texttt{up} alias +runs \texttt{bash} from \texttt{PATH}. \textbf{Optional:} \begin{itemize} - \item Homebrew (\texttt{brew}), which in turn enables \texttt{brew --cask}. + \item Homebrew (\texttt{brew}), which also enables \texttt{brew -{}-cask}. \item \texttt{mas} (\texttt{brew install mas}) for Mac App Store upgrades. \end{itemize} \subsection{Windows} \textbf{Required:} PowerShell 5.1 (built-in on Windows 10 and later) or 7+, -Git for Windows (needed by \texttt{up --self-update}). +Git for Windows (needed by \texttt{up -{}-self-update}). \textbf{Optional:} \begin{itemize} @@ -339,12 +256,6 @@ \subsection{Windows} native toast notifications. \end{itemize} -\begin{note} -eMerger never installs these for you - it only uses what is already -installed. This is deliberate: \texttt{up} must never put software on -your machine that you didn't ask for. -\end{note} - %------------------------------------------------------- \section{Installation}\label{sec:install} %------------------------------------------------------- @@ -354,18 +265,19 @@ \subsection{Linux and macOS} \begin{lstlisting}[language=bashplus] git clone https://github.com/MasterCruelty/eMerger cd eMerger -./setup.sh +./install.sh # open a new shell, or: source ~/.bashrc up --help \end{lstlisting} -\texttt{setup.sh} performs the following actions, in order: +\texttt{install.sh}: \begin{enumerate} - \item Adds \verb|alias up='bash /path/to/eMerger/src/emerger.sh'| to - the appropriate shell rc file (\texttt{.bashrc}, \texttt{.zshrc}, - \texttt{config.fish}). If you use multiple shells it writes the - alias in all of them. + \item Adds \verb|alias up='bash "/path/to/eMerger/src/emerger.sh"'| to + your shell rc files (\texttt{.bashrc}, \texttt{.zshrc}, + \texttt{config.fish}). A checkout path containing a single or + double quote, \verb|$|, a backquote, \verb|%|, a backslash or a + newline is refused. \item Marks \texttt{src/emerger.sh} as executable. \item Installs shell completions for \texttt{bash}, \texttt{zsh} and \texttt{fish}: @@ -374,59 +286,60 @@ \subsection{Linux and macOS} \item \verb|~/.zsh/completions/_up| \item \verb|~/.config/fish/completions/up.fish| \end{itemize} - \item Scaffolds \verb|~/.config/emerger/| with the default - \texttt{config.sh}, \texttt{ignore.list}, \texttt{hooks/} and - \texttt{profiles.d/} layout. + \item Installs the man page as \verb|~/.local/share/man/man1/up.1|, so + \texttt{man up} shows it; if it does not, add + \verb|~/.local/share/man| to \texttt{MANPATH}. + \item Creates \verb|~/.config/emerger/| with \texttt{config.sh}, + \texttt{ignore.list}, \texttt{hooks/} and \texttt{profiles.d/}. \end{enumerate} -On macOS the alias is written to \texttt{\string~/.zshrc} first, since -\texttt{zsh} is the default interactive shell from Catalina onwards. When -Homebrew is present, completions are installed under the Homebrew prefix -so that they are loaded by the \texttt{brew}-managed shell environment. +On macOS the alias goes to \texttt{\string~/.zshrc} first, because +\texttt{zsh} is the default shell since Catalina. If Homebrew is present, +completions are installed under the Homebrew prefix. \subsection{Windows} \begin{lstlisting}[language=psplus] git clone https://github.com/MasterCruelty/eMerger cd eMerger -.\setup.ps1 +.\install.ps1 # open a new PowerShell window, or: . $PROFILE up --help \end{lstlisting} -\texttt{setup.ps1} does \emph{not} require administrator privileges: +\texttt{install.ps1} does not need administrator rights. It: \begin{enumerate} - \item Lifts \texttt{ExecutionPolicy} for \texttt{CurrentUser} to - \texttt{RemoteSigned} when it was \texttt{Restricted} or - \texttt{Undefined}. - \item Defines \verb|function up { & "...\emerger.ps1" @args }| inside - \verb|$PROFILE.CurrentUserAllHosts|, so \texttt{up} works from - every PowerShell host (cmd-hosted PS, ISE, Windows Terminal, - VS Code integrated terminal). - \item Scaffolds \verb|%APPDATA%\emerger\| with - \texttt{config.ps1}, \texttt{hooks\textbackslash pre.d\textbackslash}, - \texttt{hooks\textbackslash post.d\textbackslash}, - \texttt{profiles.d\textbackslash}. + \item When \texttt{ExecutionPolicy} for \texttt{CurrentUser} is + \texttt{Restricted} or \texttt{Undefined}, asks before setting it + to \texttt{RemoteSigned}; no answer (or no terminal) leaves it + unchanged. + \item Adds an \texttt{up} function that calls \texttt{emerger.ps1} to + \verb|$PROFILE.CurrentUserAllHosts|, so \texttt{up} works in + every PowerShell host (console, ISE, Windows Terminal, the + VS Code terminal). + \item Creates \verb|%APPDATA%\emerger\| with \texttt{config.ps1} and + the \texttt{hooks} and \texttt{profiles.d} folders. \end{enumerate} -When a package manager run later needs elevation, eMerger relaunches -itself under UAC. The relaunch is logged, so you always know when it -happened. +When admin managers (choco, wsl, Windows Update) are detected, eMerger +runs them in one elevated child behind a single UAC prompt. The child +loads no \texttt{config.ps1}, profile or hook; its results, exit status +and log lines come back to the unelevated run, which prints them. \subsection{Manual install} -When a packaged setup is undesirable (read-only home, corporate lockdown, -portable installation), pointing an alias at the entry point is enough: +Without the install script, point an alias or function at the entry +point: \begin{lstlisting}[language=bashplus] -# bash, zsh, fish - Linux or macOS +# bash, zsh, fish (Linux or macOS) alias up='bash /absolute/path/to/eMerger/src/emerger.sh' \end{lstlisting} \begin{lstlisting}[language=psplus] -# PowerShell - Windows -function up { & "C:\path\to\eMerger\src\emerger.ps1" @args } +# PowerShell (Windows) +function up { & 'C:\path\to\eMerger\src\emerger.ps1' @args } \end{lstlisting} \subsection{Uninstall} @@ -436,429 +349,477 @@ \subsection{Uninstall} .\uninstall.ps1 # Windows \end{lstlisting} -The uninstaller removes the shell alias, the cron job or systemd timer, -and the scheduled task. Configuration and state directories are -\textbf{kept} so that logs, profiles and hooks survive a reinstall; remove -them manually to start from a clean slate: +Removes the alias or \texttt{up} function, the completion files, the man +page and any cron job, systemd user timer or scheduled task. It then asks +whether to delete the settings, history and cache too; the answer defaults +to no, and without a terminal they are kept. To remove them later by hand: \begin{lstlisting}[language=bashplus] rm -rf ~/.config/emerger ~/.local/state/emerger ~/.cache/emerger \end{lstlisting} -The repository itself is not removed: \texttt{rm -rf} the directory when -you are done. +The repo itself stays where it is; delete it by hand. %------------------------------------------------------- \section{Self-update}\label{sec:selfupdate} %------------------------------------------------------- -Three equivalent forms are accepted: \begin{lstlisting}[language=bashplus] up -up # short flag up --self-update # long flag -./update.sh # out-of-band script (.\update.ps1 on Windows) \end{lstlisting} -Internally a \texttt{git pull --ff-only} is performed inside the clone -and the new commit range is printed. Non fast-forward updates are refused -so that local changes never silently disappear. If you want the -self-update to also run every time you update your system, add it to a -\texttt{post.d} hook (see section \ref{sec:hooks}). +This runs \texttt{git pull -{}-ff-only} in the clone and prints the new +commit range. Non fast-forward updates are refused, so local changes are +never overwritten. %------------------------------------------------------- \section{Quickstart}\label{sec:quickstart} %------------------------------------------------------- -Five minutes. No commitment. Nothing gets upgraded until you say so. +Steps 1 and 3 change nothing on the system. -\subsection{Step 1 - dry-run} +\subsection{Step 1: dry-run} \begin{lstlisting}[language=bashplus] up -n \end{lstlisting} -This is the safe preview. It shows which managers were detected and what -commands \emph{would} be invoked. No \texttt{sudo}, no downloads, no -changes on disk. +Shows the detected managers and the commands that would run. It does +not ask for \texttt{sudo}, download anything or write to disk. -\subsection{Step 2 - real run} +\subsection{Step 2: real run} \begin{lstlisting}[language=bashplus] up \end{lstlisting} -Refresh, upgrade, clean, one manager at a time. You will be asked for -\texttt{sudo} once (Unix) or get a UAC prompt (Windows) only if a detected -manager needs it. +Refreshes, upgrades and cleans each manager in turn. You get one +\texttt{sudo} prompt (Unix) or UAC prompt (Windows) if a manager needs it. -\subsection{Step 3 - see what changed} +\subsection{Step 3: see what changed} \begin{lstlisting}[language=bashplus] up --changed \end{lstlisting} Prints the package diff for the last run with \texttt{+} for added, \texttt{-} for removed and \texttt{\~} for upgraded. -\subsection{Step 4 - export a report} -\begin{lstlisting}[language=bashplus] -up --report last-run.md -\end{lstlisting} -Produces a Markdown file with the JSON summary, per-manager results, -reboot advisory and the full package diff as a table. - -\subsection{Step 5 (optional) - weekly unattended update} +\subsection{Step 4 (optional): weekly unattended update} \begin{lstlisting}[language=bashplus] up -au \end{lstlisting} -Installs a systemd user timer on Linux, a cron job on macOS or a -scheduled task on Windows. The trigger fires every Sunday at 10:00 -(local time) with $\pm$1h randomised delay, and always uses -\texttt{-y -q -nl -ni}. +Installs a systemd user timer (Linux), cron job (macOS) or scheduled task +(Windows): Sundays at 10:00 local time, with \texttt{-y -q -nl -ni}. +The timer and the task start up to one hour later at random; cron starts +at 10:00 sharp. %------------------------------------------------------- -\section{Your first real run}\label{sec:firstrun} +\section{Example run}\label{sec:firstrun} %------------------------------------------------------- -The very first time you run \texttt{up}, you should expect something like -this on a Debian/Ubuntu desktop with Flatpak and a couple of dev -toolchains: +Output with apt and flatpak: \begin{lstlisting}[basicstyle=\ttfamily\footnotesize] $ up - _____ __ __ - | ___| | \/ | eMerger v2.0.0 - | |__ | |\/| | one command for the whole system - |____| |_| |_| - Ubuntu 24.04 o x86_64 o 2026-04-16 10:12 - eMerger v2.0.0 o github.com/MasterCruelty/eMerger - [1/3] apt OK (38 upgraded, 0 removed, 0 new) - [2/3] flatpak OK (5 refreshed) - [3/3] fwupd SKIP (--firmware not set) - +---------------------------------------------+ - | eMerger - summary | - | duration 42s | - | freed 15 MiB | - | reboot not required | - | errors 0 | - +---------------------------------------------+ + (gradient-colored eMerger logo) + * Debian GNU/Linux 13 . x86_64 . 2026-10-16 10:12 . eMerger v3.0.0 + + * apt ~40s ------------------------------------------ #. 1/2 + [OK] fix broken ................ 1.2s + [OK] update .................... 6.8s + .:. full-upgrade .:::. 0:14 Unpacking libssl3 ... + + * flatpak -------------------------------------------- ## 2/2 + [OK] update .................... 12.4s 5 refreshed + + > User cache -------------------------------------------------- + ? Clean user cache? (812M) [y/N] y + [OK] cache cleaned ............. 812M + + +- eMerger summary ---------------------------+ + | managers [OK] apt [OK] flatpak | + | time 0m42s | + | freed 812.0MB | + | status [OK] all good | + +---------------------------------------------+ \end{lstlisting} -\begin{tip} -If the colours or the box look wrong, your terminal may not support -Unicode glyphs. Run \texttt{up --no-emoji} once, or add -\verb|ARG_NO_EMOJI=1| to your \texttt{config.sh}. -\end{tip} +This is the ASCII glyph set (\texttt{-{}-ascii} or a non-UTF-8 +locale). In a UTF-8 terminal you get rounded box corners, check marks, a +braille spinner and the \texttt{.:::.} wave; per-manager emoji icons need +a color-emoji font, otherwise plain symbols are used. A running step +shows the elapsed time and the last line the manager printed, then +collapses to one result line with duration and a short stat. \begin{warn} -\textbf{Do not} run \texttt{up} with \texttt{sudo} at the top level. eMerger -will ask for \texttt{sudo} itself, only for the managers that need it, and -will run user-level managers (\texttt{brew}, \texttt{flatpak} user -remotes, \texttt{npm} user globals, \texttt{pip --user}\,\dots) \emph{as -you}, not as root. Calling \verb|sudo up| will install user-level packages -into root's home. +Don't run \texttt{sudo up}. eMerger asks for \texttt{sudo} itself, only +for the managers that need it. Under \verb|sudo up|, user-level packages +(\texttt{pip -{}-user}, Homebrew, \texttt{npm -g}) end up in root's home. \end{warn} %------------------------------------------------------- \section{Execution flow}\label{sec:flow} %------------------------------------------------------- -A full run of \texttt{up} performs, in order: +In order: \begin{enumerate} \item Load \texttt{config.sh} (or \texttt{config.ps1}) if present. \item If \texttt{-{}-profile NAME} is on the command line, pre-load \verb|share/profiles/NAME.sh| (or the user override from \verb|~/.config/emerger/profiles.d/|). - \item Parse CLI flags. CLI always wins over config and profile defaults. - \item If \texttt{QUIET\_HOURS} is set and we are inside the window - \emph{and} \texttt{-y} is set, exit immediately (this shields - scheduled runs from night-time activity without blocking - interactive ones). - \item Acquire the global exclusive lock (\verb|/tmp/emerger.lock| via - \texttt{flock} on Unix). If another \texttt{up} is already + \item Parse CLI flags (they override config and profile). + \item Unix: if \texttt{QUIET\_HOURS} is set, \texttt{-y} is set and the + clock is inside the window, exit 0. Scheduled runs are skipped, + interactive ones are not. + \item Acquire the global exclusive lock (\verb|~/.local/state/emerger/emerger.lock| via + \texttt{flock} on Unix, \verb|%LOCALAPPDATA%\emerger\state\run.lock| on Windows). If another \texttt{up} is already running, abort with exit code 1. \item Print the logo, OS info line and the current timestamp. \item Warn on low battery (<20\% on a laptop) and on low free disk space (default: less than 1024\,MiB on \texttt{/} or \texttt{C:}). - \item Cache \texttt{sudo} credentials on Unix - or relaunch elevated on - Windows - only when a detected manager actually needs it. + On a Raspberry Pi, check power and temperature. + \item Cache \texttt{sudo} credentials on Unix, only when a detected + manager needs it. On Windows the admin managers run later in one + elevated child. + \item Unix: with \texttt{-{}-refresh-mirrors}, re-rank the mirrors; with + \texttt{-{}-snapshot}, take a snapshot or exit 1. \item Snapshot the installed-packages list into \texttt{pkgs.before} for the post-run diff. \item Execute \texttt{pre.d} hooks in alphabetical order. \item For each detected manager, run \textit{refresh}, \textit{upgrade}, \textit{clean}; serial for system managers, concurrent for safe - user-space ones when \texttt{--parallel} is active. + user-space ones when \texttt{-{}-parallel} is active. \item Optionally clear user cache and trash (skippable with - \texttt{-nc} and \texttt{-nt}). + \texttt{-nc} and \texttt{-nt}), then, with + \texttt{-{}-deep-clean}, the system leftovers (Unix). \item Execute \texttt{post.d} hooks. \item Snapshot the installed-packages list into \texttt{pkgs.after} and compute \texttt{pkgs.diff}. \item Render the boxed summary, the reboot advisory and an optional desktop notification. \item Exit 0 on success, 3 if any manager failed, 4 if a reboot is - required and \texttt{--reboot-exit} was passed. + required and \texttt{-{}-reboot-exit} was passed. \end{enumerate} %------------------------------------------------------- \section{Command line reference}\label{sec:cli} %------------------------------------------------------- -The authoritative reference is \texttt{up -\/-help}; the table below -summarises every flag and is annotated with the most common uses. - -\subsection{Full flag catalogue} +\subsection{All flags} \begin{center} \begin{longtable}{@{}p{0.26\linewidth} p{0.50\linewidth} p{0.18\linewidth}@{}} \toprule \textbf{Flag} & \textbf{Meaning} & \textbf{Platforms} \\ \midrule \endhead -\texttt{-h}, \texttt{--help} & Print help text and exit & all \\ -\texttt{-V}, \texttt{--version} & Print \texttt{eMerger X.Y.Z} & all \\ -\texttt{-n}, \texttt{--dry-run} & Preview without running & all \\ -\texttt{-v}, \texttt{--verbose} & Stream manager output live & all \\ -\texttt{-q} / \texttt{-qq} / \texttt{-qqq} & Progressive quiet levels & all \\ -\texttt{-y}, \texttt{--yes} & Assume yes on prompts & all \\ -\texttt{-i}, \texttt{--interactive} & TUI menu (gum / whiptail) & Unix \\ -\texttt{-w}, \texttt{--weather} & Show weather line via wttr.in & all \\ -\texttt{--no-emoji} & Force ASCII glyphs only & all \\ -\texttt{-nl}, \texttt{--no-logo} & Hide logo & all \\ -\texttt{-ni}, \texttt{--no-info} & Hide system info line & all \\ -\texttt{-nc}, \texttt{--no-cache} & Skip user cache cleaning & all \\ -\texttt{-nt}, \texttt{--no-trash} & Skip trash cleaning & all \\ -\texttt{--security} & Security-only updates & supported managers \\ -\texttt{--firmware} & Include \texttt{fwupdmgr} & Linux \\ -\texttt{--no-firmware} & Force-skip firmware & Linux \\ -\texttt{--dev} & Include dev toolchains & all \\ -\texttt{--parallel} & Run user-space in parallel & Unix \\ -\texttt{--profile NAME} & Load a profile & all \\ -\texttt{--list-profiles} & List available profiles & all \\ -\texttt{--only LIST} & Only these managers & all \\ -\texttt{--except LIST} & Skip these managers & all \\ -\texttt{--snapshot} & snapper / timeshift / btrfs & Linux \\ -\texttt{--rollback} & Revert last eMerger snapshot & Linux \\ -\texttt{--refresh-mirrors} & Re-rank distro mirrors & Linux \\ -\texttt{--resume} & Skip completed managers & Unix \\ -\texttt{--reboot} & Reboot if required & all \\ -\texttt{--reboot-exit} & Exit 4 if reboot required & all \\ -\texttt{--download-only}, \texttt{--offline} & Prefetch, don't install & Unix \\ -\texttt{--changed} & Show package diff & Unix \\ -\texttt{--changelog PKG} & Upstream changelog for PKG & Unix \\ -\texttt{--report [FILE]} & Export Markdown report & Unix \\ -\texttt{--history} & Recent runs & all \\ -\texttt{-err}, \texttt{--errors} & Tail of logged errors & all \\ -\texttt{--doctor} & Health check & all \\ -\texttt{--json} & Machine-readable summary & all \\ -\texttt{--metrics FILE} & Prometheus textfile export & all \\ -\texttt{-up}, \texttt{--self-update} & Self-update eMerger & all \\ -\texttt{-au}, \texttt{--auto-update} & Install weekly auto-update & all \\ -\texttt{-rc}, \texttt{--rebuild-cache} & Clear detection cache & all \\ +\texttt{-h}, \texttt{-{}-help} & Print help text and exit & all \\ +\texttt{-V}, \texttt{-{}-version} & Print \texttt{eMerger X.Y.Z} & all \\ +\texttt{-n}, \texttt{-{}-dry-run} & Preview without running & all \\ +\texttt{-v}, \texttt{-{}-verbose} & Stream manager output live & all \\ +\texttt{-q}, \texttt{-{}-quiet}, \texttt{-qq}, \texttt{-qqq} & Quieter by one level per \texttt{-q} & all \\ +\texttt{-y}, \texttt{-{}-yes} & Assume yes on prompts & all \\ +\texttt{-w}, \texttt{-{}-weather} & Show weather line via wttr.in & all \\ +\texttt{-{}-ascii} & Force ASCII glyphs only & all \\ +\texttt{-{}-deep-clean} & System leftovers (see \S\ref{sec:deepclean}) & Linux/macOS \\ +\texttt{-nl}, \texttt{-{}-no-logo} & Hide logo & all \\ +\texttt{-ni}, \texttt{-{}-no-info} & Hide system info line & all \\ +\texttt{-nc}, \texttt{-{}-keep-cache} & Skip user cache cleaning & all \\ +\texttt{-nt}, \texttt{-{}-keep-trash} & Skip trash cleaning & all \\ +\texttt{-{}-security} & Security-only updates & supported managers \\ +\texttt{-{}-firmware} & Include \texttt{fwupdmgr} & Linux \\ +\texttt{-{}-no-firmware} & Force-skip firmware & Linux \\ +\texttt{-{}-dev} & Include dev toolchains & all \\ +\texttt{-{}-parallel} & Run user-space in parallel & Unix \\ +\texttt{-{}-profile NAME} & Load a profile & all \\ +\texttt{-{}-only LIST} & Only these managers & all \\ +\texttt{-{}-except LIST} & Skip these managers & all \\ +\texttt{-{}-snapshot} & snapper / timeshift / btrfs & Linux \\ +\texttt{-{}-refresh-mirrors} & Re-rank distro mirrors & Linux \\ +\texttt{-{}-resume} & Skip completed managers & Unix \\ +\texttt{-{}-reboot-exit} & Exit 4 if reboot required & all \\ +\texttt{-{}-download-only} & Prefetch, don't install & Unix \\ +\texttt{-{}-accept-licenses} & Accept licence agreements & macOS, Windows \\ +\texttt{-err}, \texttt{-{}-errors} & Tail of logged errors & all \\ +\texttt{-{}-json} & Machine-readable summary & all \\ +\texttt{-up}, \texttt{-{}-self-update} & Self-update eMerger & all \\ +\texttt{-au}, \texttt{-{}-auto-update} & Install weekly auto-update & all \\ +\texttt{-rc}, \texttt{-{}-rebuild-cache} & Clear detection cache (Windows keeps none) & all \\ +\texttt{-{}-} & End of options: the words after it are ignored & all \\ \bottomrule \end{longtable} \end{center} +On Windows, \texttt{-{}-changed}, \texttt{-{}-changelog PKG} and +\texttt{-{}-rollback} print a warning and exit 0 without updating. +\texttt{-{}-firmware}, \texttt{-{}-no-firmware}, \texttt{-{}-snapshot}, +\texttt{-{}-parallel}, \texttt{-{}-resume}, \texttt{-{}-download-only}, +\texttt{-{}-deep-clean} and \texttt{-{}-refresh-mirrors} print a warning +and the run goes on without them. + \subsection{Combining flags} -Flags are independent tokens and can be combined freely, in any order. -Single-letter short flags in the set \texttt{\{h V n v q y i w\}} bundle +Any order, any combination. Single-letter short flags in the set \texttt{\{h V n v q y w\}} bundle (\texttt{up -nv} equals \texttt{up -n -v}; \texttt{up -ynv} equals \texttt{up -y -n -v}). Compound short flags (\texttt{-nl}, \texttt{-ni}, -\texttt{-qq}, \texttt{-up}, \texttt{-err}\,\dots) and long flags are never -bundled. +\texttt{-qq}, \texttt{-up}, \texttt{-err} and so on) and long flags are +never bundled. \begin{lstlisting}[language=bashplus] up -n -v # dry-run with live stream up -y -q --security # unattended security-only, minimal output up --dev --parallel -v # dev toolchains + user-space concurrency -up --snapshot --reboot -y # snapshot first, reboot at the end if needed +up --snapshot -y && up --reboot # snapshot, update, then reboot if needed up --profile server --resume # resume an interrupted headless run up -n --dev --firmware # preview a full run, no side effects -up -qq -y -nl -ni --security # exactly what the scheduled timer runs +up -y -q -nl -ni # what the scheduled timer runs up --refresh-mirrors -y -v # re-rank mirrors then upgrade, live -up --changed --report out.md # show diff and export in one shot \end{lstlisting} -Flags that take a value (\texttt{--profile NAME}, \texttt{--changelog PKG}, -\texttt{--report FILE}, \texttt{--metrics FILE}, \texttt{--only LIST}, -\texttt{--except LIST}) must keep their argument adjacent; every other -flag is position-free. CLI flags always win over config file and profile -defaults, so you can override a profile on the fly: +Flags that take a value (\texttt{-{}-profile NAME}, \texttt{-{}-changelog PKG}, +\texttt{-{}-metrics FILE}, \texttt{-{}-only LIST}, +\texttt{-{}-except LIST}) take it as the next word or as +\texttt{-{}-flag=VALUE} (\texttt{-{}-only=apt,flatpak}, \texttt{-{}-profile=work}, +\texttt{-{}-changelog=bash}, \texttt{-{}-metrics=FILE}, \texttt{-{}-except=snap}). +An empty value exits 2. CLI flags +override config and profile, so you can tweak a profile for one run: \begin{lstlisting}[language=bashplus] up --profile work --dev # work profile, but force --dev this time \end{lstlisting} %------------------------------------------------------- -\section{Features in depth}\label{sec:features} +\section{Features}\label{sec:features} %------------------------------------------------------- \subsection{Dry-run and verbose} -\texttt{-n} prints every command that \emph{would} be executed without -actually running it or asking for elevation, which makes it safe to run -in a terminal that does not own \texttt{sudo} credentials. Example -output: +\texttt{-n} prints each command instead of running it, and does not ask +for elevation. Example output (apt and flatpak): \begin{lstlisting}[basicstyle=\ttfamily\footnotesize] $ up -n - [dry] sudo apt update - [dry] sudo apt upgrade -y - [dry] sudo apt autoremove -y - [dry] sudo apt clean - [dry] flatpak update -y - [dry] flatpak uninstall --unused -y + . [dry-run] sudo apt -o APT::Status-Fd=1 --fix-broken install -y + . [dry-run] sudo apt -o APT::Status-Fd=1 update + . [dry-run] sudo apt -o APT::Status-Fd=1 full-upgrade -y + . [dry-run] sudo apt -o APT::Status-Fd=1 autoremove -y + . [dry-run] sudo apt autoclean -y + . [dry-run] sudo apt clean + . [dry-run] flatpak update -y --noninteractive + . [dry-run] flatpak uninstall --unused -y --noninteractive \end{lstlisting} -\texttt{-v} streams the output of each package manager live instead of -buffering it into the summary. The two combine naturally: -\texttt{up -n -v}. +\texttt{-v} streams each manager's output live instead of collapsing it +into one result line. Combine both with \texttt{up -n -v}. \subsection{Quiet levels} \begin{itemize} - \item \textbf{default} - full UI with logo, info line, step headers, - spinner, summary box. - \item \texttt{-q} - hides muted and informational lines but keeps the + \item Default: logo, info line, section headers with step progress, + spinner, per-step timings and the summary box. + \item \texttt{-q}: hides muted and informational lines; keeps the per-manager result and the summary. - \item \texttt{-qq} - only step titles and the one-line summary; suitable - for cron/systemd logs. - \item \texttt{-qqq} - no output at all; the exit code is the only - signal. Suitable for embedding in shell pipelines. + \item \texttt{-qq}: only the one-line summary (good for systemd + logs). + \item \texttt{-qqq}: nothing, only the exit code. \end{itemize} \subsection{Security-only updates} -When \texttt{--security} is passed, each supporting manager is asked to -limit the upgrade set to security advisories: +With \texttt{-{}-security}, managers that support it limit the upgrade to +security updates: \begin{itemize} - \item \textbf{apt} via \texttt{unattended-upgrade --security} (falls - back to \texttt{apt upgrade} for packages that are not in the - unattended security tree). - \item \textbf{dnf} with \texttt{upgrade --security}. - \item \textbf{zypper} with \texttt{patch --category security}. - \item \textbf{softwareupdate} (macOS) with \texttt{--recommended}. - \item \textbf{PSWindowsUpdate} (Windows) with severity filtering. + \item apt: \texttt{unattended-upgrade -v} when \texttt{unattended-upgrade} + is installed; otherwise apt is skipped. + \item dnf: \texttt{upgrade -{}-security}. + \item yum: \texttt{update -{}-security}. + \item zypper: \texttt{patch -{}-category security}. + \item softwareupdate (macOS): \texttt{-{}-install -{}-recommended} + (recommended updates, not only security ones), only with + \texttt{-{}-accept-licenses}; without it the updates are listed. \end{itemize} -Managers that do not distinguish between security and non-security -updates simply ignore the flag and skip the run. +On every platform every other manager is skipped with a warning, so +\texttt{-{}-security} never becomes a full upgrade; a plugin takes part +when it defines \verb|pm__security|. On Windows, +Windows Update (PSWindowsUpdate) installs only the ``Security Updates'' +category, and only with \texttt{-{}-accept-licenses}; without it the +updates are listed. \subsection{Dev toolchains} -\texttt{--dev} enables a separate track that runs: +Off by default; \texttt{-{}-dev} turns on: \begin{center} \begin{tabular}{@{}ll@{}} \toprule \textbf{Tool} & \textbf{Command} \\ \midrule -\texttt{rustup} & \texttt{rustup self update \&\& rustup update stable} \\ +\texttt{rustup} & \texttt{rustup update} \\ \texttt{cargo} & \texttt{cargo install-update -a} \\ \texttt{npm} & \texttt{npm update -g} \\ \texttt{pnpm} & \texttt{pnpm -g update} \\ -\texttt{pip} & \texttt{pip list --outdated}, then user-site upgrade \\ +\texttt{pip} & \texttt{pip list -{}-outdated}, then user-site upgrade \\ \texttt{gem} & \texttt{gem update} \\ \bottomrule \end{tabular} \end{center} -These run under the invoking user, never under \texttt{sudo}. If a -toolchain isn't installed it is silently skipped. +Never run under \texttt{sudo}. Missing toolchains are skipped silently. \subsection{Firmware (Linux)} -\texttt{--firmware} runs -\texttt{fwupdmgr refresh \&\& fwupdmgr update -y --no-reboot-check}. -If the LVFS (Linux Vendor Firmware Service) is not reachable the step is -skipped with a warning. On macOS firmware is handled by -\texttt{softwareupdate}; on Windows it is delegated to vendor tooling -(Dell Command Update, Lenovo Vantage\,\dots) and is out of scope. +\texttt{-{}-firmware} runs +\texttt{fwupdmgr refresh \&\& fwupdmgr update -y -{}-no-reboot-check}. +On macOS firmware comes through \texttt{softwareupdate}; on Windows it is +left to vendor tools (Dell Command Update, Lenovo Vantage). +On a Raspberry Pi with an SPI EEPROM (Pi 4, 400, 5, 500, CM4, CM5) +\texttt{-{}-firmware} also stages the bootloader update with +\texttt{rpi-eeprom-update -a}; it is flashed on the next reboot. + +\subsection{Raspberry Pi}\label{sec:rpi} +Detected from \verb|/proc/device-tree/model|. + +\begin{itemize} + \item Power and temperature: \texttt{vcgencmd get\_throttled} + and \texttt{measure\_temp} are read before anything is installed + and shown on one line. If the board is under-voltage \emph{right + now}, eMerger warns that a brown-out while \texttt{dpkg} writes can + corrupt the SD card and asks before continuing. With \texttt{-y} it + warns and continues, unless \verb|RPI_ABORT_ON_UNDERVOLTAGE=1|. + Past under-voltage since boot, and a SoC temperature above + \verb|RPI_TEMP_WARN| (default 80\,$^\circ$C), are reported as warnings. + \item Bootloader EEPROM (\texttt{rpi-eeprom} manager, boards with an + SPI EEPROM only): every run checks for an update and reports it; + \texttt{-{}-firmware} applies it and the reboot advisory says it + will be flashed on next boot. \texttt{-{}-no-firmware} skips the check. +\end{itemize} + +\subsection{Live progress}\label{sec:progress} +A running step shows a spinner, a progress bar, elapsed time and what +the manager is doing. The bar comes from parsing the manager's output as +it arrives (on Windows, \texttt{pslib/ui/Monitor.ps1} and +\texttt{pslib/managers/Progress.ps1}): + +\begin{longtable}{@{}p{0.30\linewidth} p{0.62\linewidth}@{}} +\toprule +\textbf{Manager} & \textbf{What drives the bar} \\ +\midrule \endhead +apt & \texttt{APT::Status-Fd}: files fetched during \texttt{update}, real + percent during downloads and \texttt{dpkg} \\ +pacman, yay, paru, zypper, apk & \texttt{(3/24) upgrading \dots} counters \\ +dnf, yum & \texttt{Upgrading : pkg 3/24}, dnf5 \texttt{[ 3/24]}, download + \texttt{(3/24):} lines \\ +emerge & \texttt{>>> Emerging (3 of 24)} \\ +flatpak & \texttt{Updating 2/5}, percentages \\ +snap, fwupd, softwareupdate, rustup & percentages \\ +brew & \texttt{==> Upgrading N outdated packages} against each upgrade \\ +pip & eMerger's own \texttt{[i/N] pkg} loop \\ +eopkg & \texttt{Downloading 3 / 24} \\ +gem, cargo, xbps, nix, mas & running count when no total is printed \\ +winget (Windows) & \texttt{(i/N) Found} counters, download sizes and percentages \\ +choco (Windows) & per-package upgrade lines, \texttt{Progress: 45\%} \\ +scoop (Windows) & \texttt{Updating N outdated apps} against each update \\ +PSWindowsUpdate (Windows) & accepted / downloaded / installed rows \\ +\bottomrule +\end{longtable} + +If there is nothing to count you get the \texttt{.:::.} wave instead. +\texttt{-v} shows the raw output. + +\subsection{Cache cleaning} +The user-cache step lists the entries of \verb|~/.cache| biggest first, +with a size bar, and asks which to remove: \texttt{a} (all), \texttt{n} +(none, the default) or a list such as \texttt{1 3 5-7}. Entries past +\verb|CACHE_MENU_ROWS| (12) are grouped as one ``others'' row. eMerger's +own cache is always kept; \verb|CACHE_EXCLUDE="mozilla,pip*"| keeps more. +With \texttt{-y} everything not excluded is cleaned. + +\subsection{Deep clean}\label{sec:deepclean} +\texttt{up -{}-deep-clean} goes after system-level leftovers a normal run +doesn't touch, asking about each one and showing how much it would free. +Skip tasks with \verb|DEEP_CLEAN_SKIP="docker,journal"|. + +\begin{longtable}{@{}p{0.22\linewidth} p{0.70\linewidth}@{}} +\toprule +\textbf{Key} & \textbf{Task} \\ +\midrule \endhead +\texttt{journal} & \verb|journalctl --vacuum-size=$JOURNAL_MAX_SIZE| (200M), only if bigger \\ +\texttt{kernels} & dnf: keep the 2 newest kernels; zypper: \texttt{purge-kernels} \\ +\texttt{residual} & \texttt{dpkg -{}-purge} config files of removed packages \\ +\texttt{snap} & remove disabled snap revisions \\ +\texttt{docker}, \texttt{podman} & \texttt{image prune -f} + \texttt{builder prune -f} + (dangling images and build cache only) \\ +\texttt{coredumps} & delete \verb|/var/lib/systemd/coredump| files \\ +\texttt{npm}, \texttt{go} & \texttt{npm cache clean -{}-force}, \texttt{go clean -cache} \\ +\bottomrule +\end{longtable} + +Respects \texttt{-n}; space freed on \texttt{/} goes into the summary. \subsection{Parallel mode} -\texttt{--parallel} runs user-space managers that do not touch the root +\texttt{-{}-parallel} runs user-space managers that do not touch the root filesystem concurrently: \texttt{flatpak}, \texttt{snap}, \texttt{brew}, \texttt{mas}, and the dev toolchains. System managers (\texttt{apt}, -\texttt{dnf}, \texttt{pacman}, \texttt{zypper}\,\dots) stay serial to +\texttt{dnf}, \texttt{pacman}, \texttt{zypper} and so on) stay serial to avoid lock contention on \texttt{/var/lib/dpkg}, \texttt{/var/cache/pacman} -and similar. The Windows side is currently always serial. +and similar. Windows is always serial. \subsection{Snapshots and rollback (Linux)} -\texttt{--snapshot} tries, in order: +\texttt{-{}-snapshot} tries, in order: \begin{enumerate} - \item \texttt{snapper} - creates a pre-update snapshot tagged - \texttt{eMerger pre-update} on the root subvolume. - \item \texttt{timeshift} - runs \texttt{timeshift --create --tags D}. - \item raw \texttt{btrfs subvolume snapshot} - only if neither of the - above is installed; the snapshot is placed under - \verb|/.snapshots/emerger/|. + \item \texttt{snapper}: a pre-update snapshot of the root subvolume, + tagged \texttt{eMerger pre-update}. + \item \texttt{timeshift}: \texttt{timeshift -{}-create -{}-tags D}. + \item \texttt{btrfs subvolume snapshot}, only if neither of the above is + installed. The snapshot goes under \verb|/.snapshots/emerger/|. \end{enumerate} -\texttt{--rollback} reverts to the most recent eMerger-created snapshot: +If none of them works, eMerger names each failure and exits 1 before any +manager runs. + +\texttt{-{}-rollback} goes back to the latest snapshot eMerger made: \begin{itemize} - \item \textbf{snapper}: native - \texttt{snapper -c root rollback }. A reboot is required - afterwards (snapper semantics, not ours). - \item \textbf{timeshift}: hands off to \texttt{timeshift --restore} - \emph{interactively} - silent rollback is too destructive to - automate. - \item \textbf{raw btrfs}: refuses to swap subvolumes automatically, - prints the path of the latest snapshot so you can do it - manually. + \item snapper: \texttt{snapper -c root rollback }, effective + after a reboot. + \item timeshift: runs \texttt{timeshift -{}-restore} interactively + (\texttt{-{}-yes} is not passed). + \item plain btrfs: eMerger does not swap subvolumes itself; it prints + the path of the latest snapshot so you can do it by hand. \end{itemize} -\begin{tip} -Combine with a guard to get a safe update cycle: - -\begin{lstlisting}[language=bashplus] -up --snapshot -y || up --rollback -\end{lstlisting} -\end{tip} - \subsection{Mirrors refresh (Linux)} -\texttt{--refresh-mirrors} re-ranks the repository mirrors before the -upgrade: +\texttt{-{}-refresh-mirrors} re-ranks mirrors before the upgrade: \begin{itemize} - \item \textbf{Arch}: \texttt{reflector --latest 20 --sort rate}. - \item \textbf{Debian/Ubuntu}: \texttt{netselect-apt} (requires - \texttt{netselect-apt} installed). - \item \textbf{Fedora}: no-op; the \texttt{fastestmirror} DNF plugin - already ranks mirrors at download time. + \item Arch: \texttt{reflector -{}-latest 20 -{}-sort rate}. + \item Debian (not its derivatives): \texttt{netselect-apt}, if installed, for the running release. + \item Fedora: no-op, the \texttt{fastestmirror} plugin already does + this. \end{itemize} \subsection{Reboot handling} On Unix, eMerger inspects \texttt{/var/run/reboot-required} and -\texttt{needs-restarting -r} (if available). On Windows it reads the -\texttt{CBS RebootPending}, -\texttt{WindowsUpdate\textbackslash RebootRequired} and -\texttt{PendingFileRenameOperations} registry entries. +\texttt{needs-restarting -r} (if available). On Windows it reads these +registry entries: + +\begin{itemize} + \item \texttt{CBS\textbackslash RebootPending} + \item \texttt{WindowsUpdate\textbackslash RebootRequired} + \item \texttt{PendingFileRenameOperations} +\end{itemize} \begin{itemize} \item The summary always prints a reboot advisory. - \item \texttt{--reboot} actually reboots the machine (requires + \item \texttt{-{}-reboot} reboots the machine if needed (requires elevation). - \item \texttt{--reboot-exit} exits with code \textbf{4} so that an - orchestrator can decide what to do next. + \item \texttt{-{}-reboot-exit} exits with code 4, so a calling script + can decide what to do. \end{itemize} \subsection{Resume} -When a run is interrupted (Ctrl-C, lost network, disk full, laptop -suspend), a cursor is written to \verb|~/.local/state/emerger/resume| -after every successful manager. A subsequent \texttt{up --resume} skips -every manager that completed successfully, so repeated failures do not -force a full retry. Unix only. - -\subsection{Download-only / offline} -\texttt{--download-only} (alias \texttt{--offline}) refreshes the package -indexes and \emph{downloads} the pending upgrade set but does not install -it. Supported natively on \texttt{pacman} (\texttt{-Syuw}), \texttt{apt} -(\texttt{--download-only}), \texttt{dnf} (\texttt{--downloadonly}) and -\texttt{zypper} (\texttt{update --download-only}). Typical use cases: - -\begin{itemize} - \item laptop on a slow or metered connection: prefetch while on good - Wi-Fi, install later at the office; - \item servers in a maintenance window: prestage the set, flip to - install-only when the change ticket opens; - \item pre-flight for \texttt{--snapshot}: verify the whole update set - is downloaded \emph{before} taking a snapshot. -\end{itemize} +After each successful manager eMerger writes a cursor to +\verb|~/.local/state/emerger/resume|. \texttt{up -{}-resume} skips the +managers that finished in the last run. A run without +\texttt{-{}-resume} starts a fresh cursor, and a dry run leaves it alone. +Unix only. \subsection{Package diff and changelog} -Each run records the installed package set before and after. \texttt{up ---changed} prints the diff with \texttt{+}, \texttt{-} and \texttt{\~} -markers: +Every run records installed packages before and after. \texttt{up +-{}-changed} prints the diff (\texttt{+} added, \texttt{-} removed, +\texttt{\~} upgraded): \begin{lstlisting}[basicstyle=\ttfamily\footnotesize] $ up --changed @@ -868,38 +829,39 @@ \subsection{Package diff and changelog} - old-package 2.1 \end{lstlisting} -\texttt{up --changelog PKG} dispatches to \texttt{apt changelog}, -\texttt{dnf changelog} (or \texttt{dnf updateinfo} if available), -\texttt{pacman -Qi} or \texttt{brew log} depending on the host. +\texttt{up -{}-changelog PKG} shows one package's upstream changelog via +\texttt{apt changelog}, \texttt{dnf changelog} (or \texttt{updateinfo}) +or \texttt{brew log}. pacman has no changelog: it shows the package info +(\texttt{pacman -Qi}) instead, labelled as such. -\subsection{Reports, history and errors} +\subsection{History and errors} \begin{itemize} - \item \texttt{--report FILE} exports a Markdown report of the last - run. Without a filename it writes to - \verb|$PWD/emerger-report.md|. - \item \texttt{--history} prints the last 10 runs as a table. - \item \texttt{-err} / \texttt{--errors} tails \texttt{ERROR} lines from + \item \texttt{-{}-history} prints the last 10 runs as a table. + \item \texttt{-err} / \texttt{-{}-errors} tails \texttt{ERROR} lines from \verb|~/.local/state/emerger/emerger.log|. \end{itemize} \subsection{Doctor} -\texttt{--doctor} audits the environment and prints a traffic-light -report: +\texttt{-{}-doctor} reports each of these as OK, warning or failure: \begin{itemize} \item shell / PowerShell version; \item \texttt{sudo} cache / admin status; - \item disk space on the state partition; - \item network reachability (IPv4 and IPv6); + \item free space on \texttt{/} (\texttt{C:} on Windows) against + \texttt{DISK\_MIN\_FREE\_MB}; + \item network reachability: one HTTPS request to \texttt{github.com} + (Windows: one connection test to it); \item state directory writability; - \item per-manager native health: \texttt{dpkg --audit}, - \texttt{pacman -Dk}, \texttt{brew doctor}, \texttt{pip check}; + \item glyph mode (UTF-8, emoji font) and how to get emoji icons; + \item per-manager native health: \texttt{dpkg -{}-audit}, + \texttt{pacman -Dk}, \texttt{dnf check} / \texttt{yum check}, + \texttt{brew doctor}; \item pending reboot flag; \item (Windows) the current ExecutionPolicy and elevation status. \end{itemize} -A non-zero exit code is returned when any issue is detected. Always run -\texttt{up --doctor} before opening a bug report. +Exits non-zero if any check warns or fails. Please attach its output to +bug reports. %------------------------------------------------------- \section{Configuration}\label{sec:config} @@ -907,8 +869,9 @@ \section{Configuration}\label{sec:config} \subsection{Config file (Unix)} -\verb|~/.config/emerger/config.sh| is a plain shell file sourced before -argument parsing. Every flag has a corresponding \texttt{ARG\_*} variable: +\verb|~/.config/emerger/config.sh| is a shell file sourced before +argument parsing. Each setting flag has a variable, listed under +``Every supported variable'' below: \begin{lstlisting}[language=bashplus] # ~/.config/emerger/config.sh @@ -917,16 +880,16 @@ \subsection{Config file (Unix)} ARG_DEV=1 # always include dev toolchains ARG_WEATHER=1 # show weather widget via wttr.in ARG_PARALLEL=1 # run user-space managers in parallel -ARG_NO_TRASH=1 # never empty the trash automatically +ARG_KEEP_TRASH=1 # never empty the trash automatically # Thresholds DISK_MIN_FREE_MB=2048 # require at least 2 GiB free on / BATTERY_MIN_PCT=25 # warn below 25% -RETRY_MAX=3 # transient-error retry count -RETRY_DELAY=5 # seconds between retries +RETRY_ATTEMPTS=3 # attempts on a transient network error +RETRY_DELAY=5 # first retry after 5s, second after 10s # Scheduling -QUIET_HOURS="23:00-07:00" # scheduled runs exit immediately inside this window +QUIET_HOURS="23:00-07:00" # runs with -y exit 0 inside this window # Caching EMERGER_CACHE_TTL=3600 # detection cache: 1h (0 = disabled, default 86400) @@ -940,127 +903,200 @@ \subsection{Config file (Windows)} \begin{lstlisting}[language=psplus] # %APPDATA%\emerger\config.ps1 -$script:ArgsGlobal.Dev = $true -$script:ArgsGlobal.Security = $true -$script:ArgsGlobal.NoTrash = $true +$script:ArgsGlobal.Dev = $true +$script:ArgsGlobal.Security = $true +$script:ArgsGlobal.KeepTrash = $true +$script:UI_VERBOSE = $true # as -v -# Thresholds (same semantics as Unix) +# Thresholds (same meaning as on Unix) $script:DISK_MIN_FREE_MB = 4096 -$script:RETRY_MAX = 3 +$script:RETRY_ATTEMPTS = 3 +$script:MANAGER_TIMEOUT = 3600 # seconds per manager step, 0 = no limit \end{lstlisting} \subsection{Every supported variable} +\paragraph{One variable per flag.} \texttt{config.sh} and profiles set the +Unix variable to 1 or to the flag's value; \texttt{config.ps1} and Windows +profiles set the field of \verb|$script:ArgsGlobal| to \verb|$true| or to the +value. \texttt{-{}-profile} has no variable: a profile cannot select a +profile. The flags that run an action or a query instead of an update +(\texttt{-h}, \texttt{-V}, \texttt{-{}-doctor}, \texttt{-{}-list-profiles}, +\texttt{-{}-rollback}, \texttt{-{}-reboot}, \texttt{-{}-changed}, +\texttt{-{}-changelog}, \texttt{-{}-history}, \texttt{-{}-metrics}, +\texttt{-err}, \texttt{-up}, \texttt{-au}, \texttt{-rc}) are taken from the +command line only: setting their variables in a file has no effect. + \begin{center} -\begin{longtable}{@{}p{0.34\linewidth} p{0.18\linewidth} p{0.40\linewidth}@{}} +\begin{longtable}{@{}p{0.28\linewidth} p{0.36\linewidth} p{0.30\linewidth}@{}} \toprule -\textbf{Variable} & \textbf{Default} & \textbf{Meaning} \\ +\textbf{Flag} & \textbf{Unix variable} & \textbf{Windows field} \\ \midrule \endhead -\texttt{ARG\_DEV} & 0 & include dev toolchains by default \\ -\texttt{ARG\_FIRMWARE} & 0 & include \texttt{fwupdmgr} by default \\ -\texttt{ARG\_NO\_FIRMWARE} & 0 & force-skip firmware \\ -\texttt{ARG\_SECURITY} & 0 & security-only by default \\ -\texttt{ARG\_YES} & 0 & assume yes by default \\ -\texttt{ARG\_PARALLEL} & 0 & parallel user-space by default \\ -\texttt{ARG\_WEATHER} & 0 & show weather widget \\ -\texttt{ARG\_NO\_EMOJI} & 0 & force ASCII glyphs \\ -\texttt{ARG\_NO\_CACHE} & 0 & skip user cache cleaning \\ -\texttt{ARG\_NO\_TRASH} & 0 & skip trash cleaning \\ -\texttt{ARG\_NO\_LOGO} & 0 & hide logo \\ -\texttt{ARG\_NO\_INFO} & 0 & hide system info line \\ -\texttt{QUIET\_LEVEL} & 0 & 0=full UI, 1=\texttt{-q}, 2=\texttt{-qq}, 3=\texttt{-qqq} \\ -\texttt{DISK\_MIN\_FREE\_MB} & 1024 & abort / warn below this many MiB \\ -\texttt{BATTERY\_MIN\_PCT} & 20 & warn below this battery percent \\ -\texttt{RETRY\_MAX} & 2 & transient-error retries \\ -\texttt{RETRY\_DELAY} & 3 & seconds between retries \\ -\texttt{QUIET\_HOURS} & (unset) & \texttt{"HH:MM-HH:MM"} - skip scheduled runs inside window \\ -\texttt{EMERGER\_CACHE\_TTL} & 86400 & detection-cache TTL in seconds; 0 disables \\ +\texttt{-{}-doctor} & \texttt{ARG\_DOCTOR} & \texttt{Doctor} \\ +\texttt{-n} & \texttt{DRY\_RUN} & \texttt{DryRun} \\ +\texttt{-v} & \texttt{UI\_VERBOSE} & \texttt{\$script:UI\_VERBOSE} \\ +\texttt{-q} & \texttt{QUIET\_LEVEL (0 to 3)} & \texttt{\$script:QUIET\_LEVEL} \\ +\texttt{-y} & \texttt{ARG\_YES} & \texttt{Yes} \\ +\texttt{-{}-json} & \texttt{ARG\_JSON} & \texttt{Json} \\ +\texttt{-{}-security} & \texttt{ARG\_SECURITY} & \texttt{Security} \\ +\texttt{-{}-accept-licenses} & \texttt{ARG\_ACCEPT\_LICENSES} & \texttt{AcceptLicenses} \\ +\texttt{-{}-firmware} & \texttt{ARG\_FIRMWARE} & \texttt{Firmware} \\ +\texttt{-{}-no-firmware} & \texttt{ARG\_NO\_FIRMWARE} & \texttt{NoFirmware} \\ +\texttt{-{}-dev} & \texttt{ARG\_DEV} & \texttt{Dev} \\ +\texttt{-{}-parallel} & \texttt{ARG\_PARALLEL} & \texttt{Parallel} \\ +\texttt{-{}-list-profiles} & \texttt{ARG\_LIST\_PROFILES} & \texttt{ListProfiles} \\ +\texttt{-{}-only LIST} & \texttt{ARG\_ONLY} & \texttt{Only} \\ +\texttt{-{}-except LIST} & \texttt{ARG\_EXCEPT} & \texttt{Except} \\ +\texttt{-{}-snapshot} & \texttt{ARG\_SNAPSHOT} & \texttt{Snapshot} \\ +\texttt{-{}-rollback} & \texttt{ARG\_ROLLBACK} & \texttt{Rollback} \\ +\texttt{-{}-refresh-mirrors} & \texttt{ARG\_REFRESH\_MIRRORS} & \texttt{RefreshMirrors} \\ +\texttt{-{}-resume} & \texttt{ARG\_RESUME} & \texttt{Resume} \\ +\texttt{-{}-reboot} & \texttt{ARG\_REBOOT} & \texttt{Reboot} \\ +\texttt{-{}-reboot-exit} & \texttt{ARG\_REBOOT\_EXIT} & \texttt{RebootExit} \\ +\texttt{-{}-download-only} & \texttt{ARG\_DOWNLOAD\_ONLY} & \texttt{DownloadOnly} \\ +\texttt{-nl} & \texttt{ARG\_NO\_LOGO} & \texttt{NoLogo} \\ +\texttt{-ni} & \texttt{ARG\_NO\_INFO} & \texttt{NoInfo} \\ +\texttt{-w} & \texttt{ARG\_WEATHER} & \texttt{Weather} \\ +\texttt{-{}-ascii} & \texttt{ARG\_ASCII} & \texttt{Ascii} \\ +\texttt{-nc} & \texttt{ARG\_KEEP\_CACHE} & \texttt{KeepCache} \\ +\texttt{-nt} & \texttt{ARG\_KEEP\_TRASH} & \texttt{KeepTrash} \\ +\texttt{-{}-deep-clean} & \texttt{ARG\_DEEP\_CLEAN} & \texttt{DeepClean} \\ +\texttt{-{}-changed} & \texttt{ARG\_CHANGED} & \texttt{Changed} \\ +\texttt{-{}-changelog PKG} & \texttt{ARG\_CHANGELOG} & \texttt{Changelog} \\ +\texttt{-{}-history} & \texttt{ARG\_HISTORY} & \texttt{History} \\ +\texttt{-{}-metrics FILE} & \texttt{ARG\_METRICS} & \texttt{Metrics} \\ \bottomrule \end{longtable} \end{center} -\begin{note} -The CLI always wins. \verb|ARG_SECURITY=1| in \texttt{config.sh} plus -\texttt{up --dev} on the CLI will run security updates \emph{and} dev -toolchains; passing \texttt{--no-firmware} will override -\verb|ARG_FIRMWARE=1|. -\end{note} +\paragraph{Settings.} Set in \texttt{config.sh}, a profile or the +environment on Unix; in \texttt{config.ps1} or a profile as +\verb|$script:NAME| on Windows, for the rows marked ``all''. -\subsection{Profiles}\label{sec:profiles} -Profiles are named configuration snippets loaded through -\texttt{--profile NAME}. They are ordinary config-file fragments scoped -to a name. +\begin{center} +\begin{longtable}{@{}p{0.34\linewidth} p{0.12\linewidth} p{0.12\linewidth} p{0.34\linewidth}@{}} +\toprule +\textbf{Variable} & \textbf{Default} & \textbf{Platforms} & \textbf{Meaning} \\ +\midrule \endhead +\texttt{DISK\_MIN\_FREE\_MB} & 1024 & all & warn and ask below this many MiB free on \texttt{/} or \texttt{C:} \\ +\texttt{BATTERY\_MIN\_PCT} & 20 & all & on battery, warn and ask below this percentage \\ +\texttt{RETRY\_ATTEMPTS} & 2 & all & attempts on a transient network error (2 = one retry) \\ +\texttt{RETRY\_DELAY} & 3 & all & seconds before the first retry; the n-th waits n times as long \\ +\texttt{MANAGER\_TIMEOUT} & 0 & all & seconds one manager command may run (exit 124); 0 = no limit \\ +\texttt{QUIET\_HOURS} & (unset) & Unix & \texttt{"HH:MM-HH:MM"}, may wrap past midnight: a run with \texttt{-y} inside it exits 0 \\ +\texttt{CACHE\_EXCLUDE} & (empty) & Unix & \verb|~/.cache| entries never offered (names or globs) \\ +\texttt{CACHE\_MENU\_ROWS} & 12 & Unix & rows in the cache menu before ``others'' \\ +\texttt{JOURNAL\_MAX\_SIZE} & 200M & Unix & journal target for \texttt{-{}-deep-clean} \\ +\texttt{DEEP\_CLEAN\_SKIP} & (empty) & Unix & deep-clean tasks to skip (\S\ref{sec:deepclean}) \\ +\texttt{RPI\_ABORT\_ON\_UNDERVOLTAGE} & 0 & Unix & abort even with \texttt{-y} on Pi under-voltage \\ +\texttt{RPI\_TEMP\_WARN} & 80 & Unix & Pi SoC temperature warning ($^\circ$C) \\ +\bottomrule +\end{longtable} +\end{center} -The shipped set lives under \texttt{share/profiles/} and includes: +\paragraph{Environment.} Read from the environment on the platforms listed; on +Unix \texttt{config.sh} can set them too, the \texttt{XDG\_*} ones excepted. + +\begin{center} +\begin{longtable}{@{}p{0.34\linewidth} p{0.12\linewidth} p{0.12\linewidth} p{0.34\linewidth}@{}} +\toprule +\textbf{Variable} & \textbf{Default} & \textbf{Platforms} & \textbf{Meaning} \\ +\midrule \endhead +\texttt{EMERGER\_EMOJI} & auto & all & emoji icons only with a color-emoji font; \texttt{1}/\texttt{0} to force \\ +\texttt{EMERGER\_SPINNER} & (auto) & all & \texttt{braille}, \texttt{dots}, \texttt{pulse} (ASCII \texttt{.:}), \texttt{line}; unset: braille on a UTF-8 terminal, pulse otherwise \\ +\texttt{EMERGER\_PROMPT\_TIMEOUT} & 60 & all & seconds a y/N prompt waits before taking the default (\texttt{0} = forever) \\ +\texttt{EMERGER\_CACHE\_TTL} & 86400 & Unix & detection-cache TTL in seconds; 0 disables \\ +\texttt{NO\_COLOR} & (unset) & all & any value turns colors off \\ +\texttt{COLORFGBG} & (unset) & all & \texttt{fg;bg} from the terminal: \texttt{bg} 7 or more picks the light-background palette \\ +\texttt{XDG\_CONFIG\_HOME} & (unset) & Unix & parent of the config directory; \verb|~/.config| when unset \\ +\texttt{XDG\_CACHE\_HOME} & (unset) & Unix & parent of the cache directory; \verb|~/.cache| when unset \\ +\texttt{XDG\_STATE\_HOME} & (unset) & Unix & parent of the state directory; \verb|~/.local/state| when unset \\ +\bottomrule +\end{longtable} +\end{center} + +Numeric variables take whole numbers only; any other value warns and the +default is used. On Windows a value above 999999999 is capped there. The +safety switches \verb|DRY_RUN| and \verb|RPI_ABORT_ON_UNDERVOLTAGE| exit 2 +on any other value instead. Without \texttt{timeout}, \verb|MANAGER_TIMEOUT| +warns once and is not applied. \texttt{config.sh}, user profiles, plugins +and hooks are loaded only when you own them and no other user can write +them (a file writable by your own private group is accepted). Running as +root with a \texttt{HOME} owned by another user, as \verb|sudo -E up| does, +is refused. + +CLI flags are applied after the config and the profile and win. Every flag +sets its variable, except \texttt{-{}-except}, which adds to it: +\verb|ARG_EXCEPT=snap| in \texttt{config.sh} plus +\texttt{up -{}-except flatpak} skips both. \texttt{-{}-no-firmware} wins +over \verb|ARG_FIRMWARE=1|. + +\subsection{Profiles}\label{sec:profiles} +A profile is a config snippet loaded with \texttt{-{}-profile NAME} +(\texttt{up -{}-list-profiles} lists them). Shipped in +\texttt{share/profiles/}: \begin{center} \begin{tabular}{@{}p{0.16\linewidth} p{0.78\linewidth}@{}} \toprule -\textbf{Profile} & \textbf{Meant for} \\ +\textbf{Profile} & \textbf{What it sets} \\ \midrule -\texttt{work} & laptop at the office - security-only, unattended, no - cache or trash wiping \\ -\texttt{home} & desktop at home - everything, including dev - toolchains, firmware and parallel mode \\ -\texttt{server} & headless - quiet (\texttt{-qq}), security only, no - prompts, no UI \\ -\texttt{safe} & before a demo or presentation - security only, no heavy - downloads \\ +\texttt{work} & security only, unattended, cache and trash + left alone; Unix also: no firmware, skips yay and paru \\ +\texttt{home} & everything: dev toolchains; Unix also: firmware, + parallel mode and the weather line \\ +\texttt{server} & headless: quiet (\texttt{-qq}), security only, no prompts, + logo or info line, cache and trash left alone; Unix also: + no firmware \\ +\texttt{safe} & least change: security only, unattended, + cache and trash left alone; Unix also: no firmware, skips + flatpak and snap \\ \bottomrule \end{tabular} \end{center} -User profiles go in \verb|~/.config/emerger/profiles.d/| (Unix) or -\verb|%APPDATA%\emerger\profiles.d\| (Windows). They shadow the shipped -defaults: a user \texttt{work.sh} wins over \texttt{share/profiles/work.sh}. +Your own profiles go in \verb|profiles.d| under the config directory +(\verb|~/.config/emerger/| or \verb|%APPDATA%\emerger\|) and take +precedence over shipped ones with the same name. A \texttt{-{}-except} on the command line +adds to the profile's \texttt{ARG\_EXCEPT} instead of replacing it, and the +shipped profiles add to an \texttt{ARG\_EXCEPT} set in \verb|config.sh|. -Full content of the shipped \texttt{work} profile: +The shipped \texttt{work} profile: \begin{lstlisting}[language=bashplus] -# description: laptop at work - security only, no firmware, never reboot +# shellcheck shell=bash +# description: security only, unattended, no firmware, skips yay and paru ARG_SECURITY=1 ARG_YES=1 ARG_NO_FIRMWARE=1 -ARG_NO_CACHE=1 -ARG_NO_TRASH=1 +ARG_EXCEPT="${ARG_EXCEPT:+$ARG_EXCEPT,}yay,paru" +ARG_KEEP_CACHE=1 +ARG_KEEP_TRASH=1 \end{lstlisting} -Writing a custom profile is just a shell fragment: +A custom one, used with \texttt{up -{}-profile train}: \begin{lstlisting}[language=bashplus] # ~/.config/emerger/profiles.d/train.sh -# description: on a train, prefetch only, keep the fans quiet +# description: prefetch only, quiet output ARG_DOWNLOAD_ONLY=1 ARG_YES=1 -ARG_QUIET=1 QUIET_LEVEL=2 -ARG_NO_TRASH=1 -ARG_NO_CACHE=1 -\end{lstlisting} - -Then: - -\begin{lstlisting}[language=bashplus] -up --profile train -\end{lstlisting} - -List what is available: - -\begin{lstlisting}[language=bashplus] -up --list-profiles +ARG_KEEP_TRASH=1 +ARG_KEEP_CACHE=1 \end{lstlisting} %------------------------------------------------------- \section{Hooks}\label{sec:hooks} %------------------------------------------------------- -Executable scripts in \texttt{hooks/pre.d/} and \texttt{hooks/post.d/} -run before and after the update flow, in alphabetical order. A failing -hook emits a warning but does not abort the run, so hooks are safe by -default. Unix hooks are \texttt{*.sh} under bash; Windows hooks are -\texttt{*.ps1} dot-sourced under PowerShell. +Scripts in \texttt{hooks/pre.d/} (before updates) and +\texttt{hooks/post.d/} (after), run in alphabetical order. A failing hook +prints a warning and the run goes on. Unix hooks are \texttt{*.sh} files, +run with \texttt{bash} (no executable bit needed); Windows hooks are +\texttt{*.ps1} files, run in a child scope. -\subsection{Example: backup your dotfiles before every run} +\subsection{Example: back up dotfiles before every run} \begin{lstlisting}[language=bashplus] # ~/.config/emerger/hooks/pre.d/10-backup-dotfiles.sh @@ -1088,53 +1124,46 @@ \subsection{Example: copy the last run log to the clipboard (Windows)} Get-Content $log -Tail 40 | Set-Clipboard \end{lstlisting} -\subsection{Example: auto self-update before upgrading} - -\begin{lstlisting}[language=bashplus] -# ~/.config/emerger/hooks/pre.d/00-self-update.sh -#!/usr/bin/env bash -( cd "$(dirname "$(readlink -f "$(command -v up | awk '{print $NF}')")")/.." && git pull --ff-only ) || true -\end{lstlisting} - \begin{warn} -Hooks run with the privileges that invoked \texttt{up}. A \texttt{pre.d} -hook that writes outside of \texttt{\$HOME} may silently fail until -\texttt{sudo} has been cached later in the run. If you need root-owned -side effects, write them in \texttt{post.d} and guard with -\texttt{sudo -n} or a \texttt{sudoers} entry. +Hooks run with the privileges of whoever ran \texttt{up}, never as root. +When a detected manager needs \texttt{sudo}, eMerger caches the +credentials before the \texttt{pre.d} hooks, so a hook can call +\texttt{sudo -n}; in a run that needs no \texttt{sudo}, \texttt{sudo -n} +fails. A dedicated \texttt{sudoers} entry works in both cases. A dry run +lists the hooks and runs none. \end{warn} -\subsection{Ignore list (Linux)} +\subsection{Ignore list (Linux)}\label{sec:ignore} \verb|~/.config/emerger/ignore.list| accepts one package per line, with -\texttt{\#} comments. Behaviour per manager: +\texttt{\#} comments. Per manager: \begin{center} \begin{tabular}{@{}p{0.15\linewidth} p{0.78\linewidth}@{}} \toprule -\textbf{Manager} & \textbf{Behaviour} \\ +\textbf{Manager} & \textbf{Behavior} \\ \midrule -\texttt{pacman} & Honoured natively via \texttt{--ignore=} on the +\texttt{pacman} & Honoured natively via \texttt{-{}-ignore=} on the command line. \\ -\texttt{apt} & Advisory: you must still \texttt{apt-mark hold PKG}. \\ -\texttt{dnf} & Advisory: you must \texttt{dnf versionlock add PKG}. \\ -\texttt{zypper} & Advisory: you must \texttt{zypper al PKG}. \\ +\texttt{apt} & Advisory only; also run \texttt{apt-mark hold PKG}. \\ +\texttt{dnf} & Advisory only; also run \texttt{dnf versionlock add PKG}. \\ +\texttt{zypper} & Advisory only; also run \texttt{zypper al PKG}. \\ \bottomrule \end{tabular} \end{center} \subsection{Quiet hours} -\texttt{QUIET\_HOURS="HH:MM-HH:MM"} in \texttt{config.sh} makes scheduled -runs that start inside the window exit immediately when \texttt{-y} is -set (i.e. the ones coming from the timer). Interactive invocations are -never blocked. The window may cross midnight: \texttt{"23:00-07:00"} is -valid. +\texttt{QUIET\_HOURS="HH:MM-HH:MM"} in \texttt{config.sh}. A run that +starts inside the window with \texttt{-y} set (as timer runs are) exits +immediately; runs without \texttt{-y} are not affected. Windows across +midnight (\texttt{"23:00-07:00"}) work. A value in another format is +ignored with a warning. %------------------------------------------------------- \section{Manager plugins}\label{sec:plugins} %------------------------------------------------------- -Dropping a bash script in \verb|~/.config/emerger/managers.d/.sh| -registers a custom manager without touching the repository. +To add a package manager without touching the repo, drop a bash script +named \texttt{.sh} in \verb|~/.config/emerger/managers.d/|. \subsection{Minimal plugin} @@ -1147,6 +1176,7 @@ \subsection{Minimal plugin} pm_mytool_parallel() { return 0; } # optional, default: serial pm_mytool_dev() { return 1; } # optional, default: not --dev gated pm_mytool_icon() { printf '\xf0\x9f\x94\x8c'; } # optional +pm_mytool_security() { return 1; } # optional, 0: run honours ARG_SECURITY pm_mytool_run() { run_cmd "mytool refresh" mytool refresh || return 1 @@ -1155,71 +1185,93 @@ \subsection{Minimal plugin} } \end{lstlisting} -\subsection{What you get for free} -Plugins are registered at the same level as native managers: they honour -\texttt{--only}, \texttt{--except}, \texttt{--parallel}, \texttt{--dev}, -the detection cache, the hooks and the summary. Because -\texttt{pm\_\_run} calls \texttt{run\_cmd}, your plugin -automatically gets: +\subsection{Plugin API} +The file sets \verb|PM_PLUGIN_SLUG| and defines functions named after +it. A file without the slug, \verb|pm__detect| or +\verb|pm__run| is skipped with a warning. + +\begin{center} +\begin{longtable}{@{}p{0.30\linewidth} p{0.12\linewidth} p{0.50\linewidth}@{}} +\toprule +\textbf{Name} & \textbf{Required} & \textbf{Contract} \\ +\midrule \endhead +\verb|PM_PLUGIN_SLUG| & yes & manager name, as shown and as matched by \texttt{-{}-only} \\ +\verb|pm__detect| & yes & return 0 if the manager is installed \\ +\verb|pm__run| & yes & refresh, upgrade, clean; return 0 on success \\ +\verb|pm__needs_sudo| & no & return 0 if it needs root (default: no) \\ +\verb|pm__parallel| & no & return 0 if safe under \texttt{-{}-parallel} (default: serial) \\ +\verb|pm__dev| & no & return 0 to run only with \texttt{-{}-dev} \\ +\verb|pm__security| & no & return 0 if \verb|pm__run| honours \verb|ARG_SECURITY|; without it \texttt{-{}-security} skips the plugin \\ +\verb|pm__icon| & no & print a short glyph \\ +\verb|run_cmd LABEL CMD...| & helper & run one command with the features below \\ +\bottomrule +\end{longtable} +\end{center} + +\subsection{Behavior} +Plugins behave like built-in managers: \texttt{-{}-only}, +\texttt{-{}-except}, \texttt{-{}-parallel}, \texttt{-{}-dev}, the detection +cache, hooks and the summary all apply to them. Commands run through +\texttt{run\_cmd} also get: \begin{itemize} - \item \texttt{--dry-run} support; - \item retry on transient failures (\texttt{RETRY\_MAX}, \texttt{RETRY\_DELAY}); + \item \texttt{-{}-dry-run} support; + \item retry on transient failures (\texttt{RETRY\_ATTEMPTS}, \texttt{RETRY\_DELAY}); \item logging to \verb|~/.local/state/emerger/emerger.log|; \item live-log streaming under \texttt{-v}. \end{itemize} -A copy-pasteable template lives at \texttt{share/plugins/example.sh}. +Full template: \texttt{share/plugins/example.sh}. \subsection{Detection cache} -The detection cache is keyed by manager slug and lives at -\verb|~/.cache/emerger/detected|. TTL defaults to 1 day; override via -\texttt{EMERGER\_CACHE\_TTL=} in \texttt{config.sh} (0 disables -caching entirely). After installing or removing a package manager run -\texttt{up -rc} to clear the cache. +Detection results are cached per manager slug in +\verb|~/.cache/emerger/detected| for 1 day. Set +\texttt{EMERGER\_CACHE\_TTL=} in \texttt{config.sh} to change +this (0 disables the cache). Run \texttt{up -rc} after installing or +removing a package manager. -\begin{note} -Plugins are Linux and macOS only. Windows plugins are not yet supported. -\end{note} +Windows loads no plugins. %------------------------------------------------------- \section{Integration}\label{sec:integration} %------------------------------------------------------- \subsection{JSON output} -\texttt{up --json} emits a single-line JSON object on stdout. The logo, -info line and summary box are all suppressed, so the output is safe to -pipe into \texttt{jq} or consume from a CI job: +\texttt{up -{}-json} prints one line of JSON on stdout, with no logo, info +line or summary box, so you can pipe it into \texttt{jq}: \begin{lstlisting}[language=jsonplus] {"ts":"2026-04-14T07:24:31Z","duration":42,"freed_kb":15360, "errors":0,"reboot":0, - "managers":[{"name":"apt","result":"ok"},{"name":"flatpak","result":"ok"}]} + "managers":[{"name":"apt","result":"ok","secs":30},{"name":"flatpak","result":"ok","secs":12}]} \end{lstlisting} -Every run also appends one such line to -\verb|~/.local/state/emerger/history.jsonl| (one JSON per line, a.k.a. -JSONL). Fields: +Hook output, plugin output and, with \texttt{-v}, manager output go to +stderr, so stdout holds the JSON line alone. + +Every run except a dry run also appends this line to +\verb|~/.local/state/emerger/history.jsonl| +(\verb|%LOCALAPPDATA%\emerger\state\history.jsonl| on Windows). Both +platforms write the same fields. \begin{center} \begin{tabular}{@{}p{0.20\linewidth} p{0.72\linewidth}@{}} \toprule \textbf{Field} & \textbf{Meaning} \\ \midrule -\texttt{ts} & ISO 8601 UTC timestamp of the run start \\ +\texttt{ts} & ISO 8601 UTC timestamp of the run end \\ \texttt{duration} & total wall-clock seconds \\ \texttt{freed\_kb} & cache and trash bytes freed, in KiB \\ \texttt{errors} & number of managers that returned non-zero \\ \texttt{reboot} & 1 if a reboot is required, else 0 \\ -\texttt{managers} & array of \texttt{\{name, result\}} entries \\ +\texttt{managers} & array of \texttt{\{name, result, secs\}} entries, \texttt{secs} being that manager's wall-clock seconds \\ \bottomrule \end{tabular} \end{center} \subsection{Prometheus metrics} -\texttt{up --metrics FILE} reads the most recent entry of -\texttt{history.jsonl} and writes a Prometheus textfile-collector -snapshot. Exposed gauges: +\texttt{up -{}-metrics FILE} writes the latest \texttt{history.jsonl} +entry in Prometheus textfile-collector format: \begin{itemize} \item \texttt{emerger\_last\_run\_timestamp\_seconds} @@ -1230,9 +1282,9 @@ \subsection{Prometheus metrics} \item \texttt{emerger\_manager\_ok\{manager="..."\}} (one per manager) \end{itemize} -The flag does \emph{not} trigger an update run. Invoke it from a -\texttt{post.d} hook or from the scheduler after \texttt{up} has -completed: +It doesn't start a run; call it from a \texttt{post.d} hook or after +\texttt{up} in your timer. A field missing from the entry reads 0. On +Windows a last line that is not valid JSON exits 1. \begin{lstlisting}[language=bashplus] # ~/.config/emerger/hooks/post.d/90-prom.sh @@ -1240,10 +1292,9 @@ \subsection{Prometheus metrics} \end{lstlisting} \subsection{Reboot exit code} -By default \texttt{up} exits 0 on success even when a reboot is pending -(the summary prints \texttt{REBOOT RECOMMENDED}). Pass -\texttt{--reboot-exit} to turn that into exit code \textbf{4} instead, -so an orchestrator can react: +A successful run exits 0 even with a reboot pending (the summary says +\texttt{Reboot recommended}). With \texttt{-{}-reboot-exit} it exits 4 +instead: \begin{lstlisting}[language=bashplus] up -y --reboot-exit @@ -1254,10 +1305,9 @@ \subsection{Reboot exit code} esac \end{lstlisting} -\subsection{Download-only and offline} -\texttt{--download-only} (alias \texttt{--offline}) refreshes the package -indexes and \emph{downloads} the pending upgrade set but does not install -it. Supported natively on: +\subsection{Download-only} +\texttt{-{}-download-only} refreshes indexes +and downloads pending upgrades without installing them: \begin{center} \begin{tabular}{@{}ll@{}} @@ -1265,36 +1315,38 @@ \subsection{Download-only and offline} \textbf{Manager} & \textbf{Command} \\ \midrule \texttt{pacman} & \texttt{pacman -Syuw} \\ -\texttt{apt} & \texttt{apt-get upgrade --download-only} \\ -\texttt{dnf} & \texttt{dnf upgrade --downloadonly} \\ -\texttt{zypper} & \texttt{zypper update --download-only} \\ +\texttt{apt} & \texttt{apt full-upgrade -y -{}-download-only} + (\texttt{dist-upgrade} with \texttt{apt-get}) \\ +\texttt{dnf} & \texttt{dnf upgrade -y -{}-downloadonly} \\ +\texttt{zypper} & \texttt{zypper update -{}-download-only} \\ +\texttt{softwareupdate} & \texttt{softwareupdate -{}-download -{}-all} + (\texttt{-{}-recommended} with \texttt{-{}-security}) \\ \bottomrule \end{tabular} \end{center} -Other managers ignore the flag. +The \texttt{apt} repair step (\texttt{-{}-fix-broken install}) also runs +with \texttt{-{}-download-only}. Every other manager, plugins included, +is skipped with a message, so nothing installs. \subsection{Manager filtering} -\begin{itemize} - \item \texttt{--only apt,flatpak} restricts the run to the listed - managers (comma-separated). - \item \texttt{--except snap,fwupd} runs everything that would normally - run, minus the listed managers. -\end{itemize} +\begin{lstlisting}[language=bashplus] +up --only apt,flatpak # only these managers +up --except snap,fwupd # everything else +\end{lstlisting} -Filtering is applied after detection and after \texttt{--dev} / -\texttt{--firmware} gating, so: +Filters apply after detection and after \texttt{-{}-dev} / +\texttt{-{}-firmware} gating, so: \begin{itemize} - \item \texttt{--only X} with \texttt{X} not detected is a no-op - (nothing runs). - \item \texttt{--except} always wins over \texttt{--only} when both - mention the same name. + \item \texttt{-{}-only X} runs nothing if \texttt{X} is not detected. + \item \texttt{-{}-except} beats \texttt{-{}-only} when both name the + same manager. + \item \texttt{-{}-except} adds to a list from \texttt{config.sh} or a + profile instead of replacing it (\texttt{up -{}-profile safe + -{}-except npm} skips flatpak, snap and npm). \end{itemize} -Compose with profiles (\texttt{up --profile work --only apt}) to restrict -a profile on the fly. - %------------------------------------------------------- \section{Auto-update (unattended)}\label{sec:auto} %------------------------------------------------------- @@ -1306,19 +1358,24 @@ \section{Auto-update (unattended)}\label{sec:auto} up -au # Windows \end{lstlisting} -Backends chosen automatically: - \begin{itemize} - \item \textbf{Linux}: systemd user timer (preferred) at - \verb|~/.config/systemd/user/emerger.{service,timer}|; cron - fallback when \texttt{systemctl --user} is not available. - \item \textbf{macOS}: cron fallback via \texttt{crontab -l} (you can - use \texttt{launchd} manually if you prefer). - \item \textbf{Windows}: \texttt{Register-ScheduledTask -TaskName eMerger}. + \item Linux: a systemd user timer at + \verb|~/.config/systemd/user/emerger.{service,timer}|, or cron + when \texttt{systemctl -{}-user} is not available. + \item macOS: cron, via \texttt{crontab -l} (set up \texttt{launchd} + yourself if you prefer it). + \item Windows: \texttt{Register-ScheduledTask -TaskName eMerger}. When + an admin manager (choco, wsl, Windows Update) is present, the run + raises a UAC prompt at the scheduled time and keeps the run lock + until it is answered. \end{itemize} -The trigger fires weekly on Sunday at 10:00 (local time) with $\pm$1h -randomised delay, and always uses \texttt{-y -q -nl -ni}. +Weekly, Sunday 10:00 local time (up to one hour later at random, except +under cron), always with +\texttt{-y -q -nl -ni}. On Linux and macOS, use \texttt{QUIET\_HOURS} to +keep runs out of a time window. On Linux, systemd user timers don't fire without an open +login session; run \texttt{loginctl enable-linger \$USER} once (as root) +to fix that. \subsection{Managing the schedule} @@ -1335,24 +1392,15 @@ \subsection{Managing the schedule} Unregister-ScheduledTask eMerger \end{lstlisting} -\begin{tip} -To avoid night-time runs, pair with \texttt{QUIET\_HOURS} in -\texttt{config.sh}. Scheduled runs started inside the window exit -immediately; interactive ones are unaffected. -\end{tip} - %------------------------------------------------------- \section{Cookbook}\label{sec:cookbook} %------------------------------------------------------- -Concrete, copy-pasteable recipes for common situations. - -\subsection{Daily driver (Linux desktop)} +\subsection{Interactive run} \begin{lstlisting}[language=bashplus] up -v \end{lstlisting} -Simple. Live output, everything updated, cache and trash wiped at the -end. Add \texttt{--firmware} occasionally. +Add \texttt{-{}-firmware} to include firmware. \subsection{Unattended server} Install the schedule once: @@ -1361,59 +1409,35 @@ \subsection{Unattended server} cat > ~/.config/emerger/config.sh <<'EOF' ARG_SECURITY=1 ARG_YES=1 -ARG_NO_CACHE=1 -ARG_NO_TRASH=1 +ARG_KEEP_CACHE=1 +ARG_KEEP_TRASH=1 QUIET_HOURS="08:00-18:00" EOF up -au \end{lstlisting} -You now get weekly security-only updates outside working hours. Pair -with Prometheus: - -\begin{lstlisting}[language=bashplus] -# post.d hook -up --metrics /var/lib/node_exporter/textfile_collector/emerger.prom -\end{lstlisting} - -\subsection{Developer workstation} -Everything, every time - including dev toolchains and firmware: +For monitoring, add a \texttt{post.d} hook with \texttt{up -{}-metrics} +(section \ref{sec:integration}). +\subsection{Dev toolchains and firmware} \begin{lstlisting}[language=bashplus] -up --dev --firmware --parallel -v +up --dev --firmware --parallel -v # or: up --profile home \end{lstlisting} -Or as a profile: - -\begin{lstlisting}[language=bashplus] -up --profile home -\end{lstlisting} - -\subsection{Pre-demo machine} -The day before a presentation you want security patches but no big user -downloads and definitely no reboots: +\subsection{Least change} +Security patches only, unattended, no firmware: \begin{lstlisting}[language=bashplus] up --profile safe \end{lstlisting} -\subsection{Metered / mobile connection} -Prefetch when you're on Wi-Fi: - +\subsection{Download now, install later} \begin{lstlisting}[language=bashplus] -up --download-only -y +up --download-only -y # on a good connection +up -y # later, installs from the package cache \end{lstlisting} -Then, later, without network: - -\begin{lstlisting}[language=bashplus] -up -y -\end{lstlisting} - -Native package managers will use the local cache populated by the -earlier run. - -\subsection{CI runner / container image builder} +\subsection{CI runner and container image build} \begin{lstlisting}[language=bashplus] up --only apt -y -qq --reboot-exit rc=$? @@ -1421,8 +1445,7 @@ \subsection{CI runner / container image builder} exit $rc \end{lstlisting} -\subsection{Gated maintenance window} -Snapshot, update, rollback on failure, reboot on success: +\subsection{Snapshot and rollback} \begin{lstlisting}[language=bashplus] set -e @@ -1431,77 +1454,82 @@ \subsection{Gated maintenance window} if [[ $? -eq 4 ]]; then systemctl reboot; fi \end{lstlisting} -\subsection{Slack-notified runs} +\subsection{One package} \begin{lstlisting}[language=bashplus] -# ~/.config/emerger/hooks/post.d/99-slack.sh -#!/usr/bin/env bash -state=~/.local/state/emerger -payload=$(tail -1 "$state/history.jsonl") -curl -sS -X POST -H 'Content-Type: application/json' \ - -d "{\"text\":\"eMerger: $payload\"}" "$SLACK_WEBHOOK_URL" -\end{lstlisting} - -\subsection{macOS with Homebrew only} -\begin{lstlisting}[language=bashplus] -up --only brew,mas -v -\end{lstlisting} - -\subsection{Windows without Chocolatey} -\begin{lstlisting}[language=psplus] -up --except choco -v -\end{lstlisting} - -\subsection{Audit a single package} -Is a specific package about to change? Preview the plan and read its -upstream changelog: - -\begin{lstlisting}[language=bashplus] -up -n | grep -i firefox -up --changelog firefox -\end{lstlisting} - -\subsection{Pinning a package (Linux)} -Add to \verb|~/.config/emerger/ignore.list|: - -\begin{lstlisting}[language=bashplus] -# ~/.config/emerger/ignore.list -nvidia-driver-535 -\end{lstlisting} - -Then, for \texttt{apt}: - -\begin{lstlisting}[language=bashplus] -sudo apt-mark hold nvidia-driver-535 +up -n | grep -i firefox # what would happen to it +up --changelog firefox # what changed upstream \end{lstlisting} -(pacman respects the file natively.) +To pin it, see the ignore list (section \ref{sec:ignore}). %------------------------------------------------------- \section{Security model}\label{sec:security} %------------------------------------------------------- \begin{itemize} - \item eMerger is a client-side tool. It has no network listener, no - daemon, no persistent background process. - \item It reads and writes only three locations: its config dir - (\verb|~/.config/emerger/|), its cache dir - (\verb|~/.cache/emerger/|) and its state dir - (\verb|~/.local/state/emerger/|), plus the global lock at - \verb|/tmp/emerger.lock| on Unix. - \item \texttt{sudo} credentials are cached by \texttt{sudo} itself, not - by eMerger. When the run ends, the cached credentials expire on - the usual \texttt{sudo} schedule (5 minutes by default). - \item On Windows, UAC elevation happens \emph{only} when a detected - manager actually needs admin. The elevation is logged. - \item Hooks and plugins run as the invoking user. They can do anything - the user can do - pin them to inodes you trust. - \item The only network calls eMerger itself makes are (a) the optional - weather widget via \texttt{wttr.in}, (b) \texttt{git pull} during - \texttt{--self-update}, (c) \texttt{fwupdmgr refresh} when - \texttt{--firmware} is active. Everything else is delegated to - the package manager you asked for. - \item There is no telemetry. \texttt{history.jsonl} stays on your - machine unless a hook you wrote ships it elsewhere. + \item Runs when you call it, or from the timer installed with + \texttt{-au}. No open ports. During a run it keeps two helper + processes, both gone when the run ends: the progress monitor and, + when a manager needs \texttt{sudo}, a refresher that renews the + \texttt{sudo} ticket every 60 seconds. + \item Its own state lives in \verb|~/.config/emerger/|, + \verb|~/.cache/emerger/| and \verb|~/.local/state/emerger/| + (the lock file \texttt{emerger.lock} included). State and cache + directories are private (mode 0700). + \item It also writes, only when asked: the \texttt{up} alias and + completion files (\texttt{install.sh}), a systemd user timer or + crontab line (\texttt{-au}), the mirror list + (\texttt{-{}-refresh-mirrors}), a snapshot (\texttt{-{}-snapshot}), + the \texttt{-{}-metrics} file, and deletions inside + \verb|~/.cache| and the Trash when cleaning. + \texttt{-{}-deep-clean} also deletes journal entries, old kernels, + leftover configs, snap revisions, container images and crash dumps + (\verb|/var/lib/systemd/coredump|), after asking for each. + \item On Windows, UAC elevation happens only for the managers that need + admin. They run in an elevated child that loads no config, profile + or hook. That child runs the code of the checkout: clone it into a + folder only administrators can write to if other programs running + as you must not reach admin rights. The child starts with + \texttt{PATH} and \texttt{PSModulePath} reduced to system folders, so + a tool or module in a folder you can write is not run elevated. + \texttt{ComSpec} and \texttt{PATHEXT} are reset, \texttt{ChocolateyInstall} + comes from the machine scope, and the \texttt{DOTNET\_*}, \texttt{COR\_*}, + \texttt{CORECLR\_*}, \texttt{COMPlus\_*} and + \texttt{PSExecutionPolicyPreference} variables are removed before + the managers run. Variables that act when a process starts (a + profiler or startup hook set in your user environment) have already + acted on the elevated PowerShell by then: keep your user environment + free of them. A + \texttt{choco} or \texttt{wsl} outside Windows, System32, Program + Files, or a \texttt{ProgramData\textbackslash chocolatey} that + standard users can write, is refused. + \texttt{choco upgrade all -y} accepts package licences and runs only + with \texttt{-{}-accept-licenses}; without it \texttt{choco outdated} + lists the upgrades. Every child PowerShell (elevated child, step + runner, scheduled task) starts with \texttt{-ExecutionPolicy Bypass}, + so the \texttt{RemoteSigned} policy does not apply to \texttt{up}'s + own scripts. + \item Linux and macOS: config files, profiles, plugins and hooks are + refused when another user could change them. The file and its + directory must belong to you and not be writable by group or + others (your own private group excepted). + \item The checkout runs as you, and as root under \texttt{sudo}. Keep it + writable by you alone: \texttt{up} refuses to start when a file + under \verb|src/| is writable by group or others (your private + group excepted). + \item Hooks and plugins run as you and can do anything you can. Only + install ones you trust. + \item With \texttt{-v} the managers write to the terminal directly; + otherwise their output is stripped of terminal control sequences. + \item eMerger's own network traffic: the optional weather line + (\texttt{wttr.in}), \texttt{git pull} for \texttt{-{}-self-update}, + \texttt{fwupdmgr refresh} with \texttt{-{}-firmware}, and one + connectivity check to \texttt{github.com} during + \texttt{-{}-doctor}, and with \texttt{-{}-refresh-mirrors} the mirror + lists that \texttt{reflector} and \texttt{netselect-apt} fetch. + Everything else comes from the package managers. + \item No telemetry. \texttt{history.jsonl} stays local + unless one of your hooks sends it somewhere. \end{itemize} %------------------------------------------------------- @@ -1510,7 +1538,7 @@ \section{Files and paths}\label{sec:files} \paragraph{Linux and macOS} \begin{center} -\begin{tabular}{@{}p{0.44\linewidth} p{0.50\linewidth}@{}} +\begin{tabular}{@{}p{0.60\linewidth} p{0.36\linewidth}@{}} \toprule \textbf{Path} & \textbf{Purpose} \\ \midrule @@ -1519,30 +1547,35 @@ \section{Files and paths}\label{sec:files} \verb|~/.config/emerger/hooks/{pre,post}.d/| & Hook scripts \\ \verb|~/.config/emerger/ignore.list| & Ignore list (pacman native) \\ \verb|~/.config/emerger/managers.d/*.sh| & User manager plugins \\ -\verb|~/.cache/emerger/detected| & Detection cache \\ -\verb|~/.local/state/emerger/emerger.log| & Log (rotated at 2000 lines) \\ +\verb|share/profiles/| & Shipped profiles, in the checkout \\ +\verb|~/.cache/emerger/detected| & Detection cache (directory mode 0700) \\ +\verb|~/.local/state/emerger/emerger.log| & Log (rotated at 2000 lines, mode 0600, directory 0700) \\ \verb|~/.local/state/emerger/history.jsonl| & One JSON record per run \\ \verb|~/.local/state/emerger/pkgs.before| & Package list snapshot (pre) \\ \verb|~/.local/state/emerger/pkgs.after| & Package list snapshot (post) \\ \verb|~/.local/state/emerger/pkgs.diff| & Last-run package diff \\ \verb|~/.local/state/emerger/resume| & Resume cursor \\ -\verb|/tmp/emerger.lock| & Global lock (flock) \\ +\verb|~/.local/state/emerger/emerger.lock| & Global lock (flock; \verb|emerger.lock.d| without it) \\ +\verb|~/.local/state/emerger/parallel-*.log| & Output of each manager of a \texttt{-{}-parallel} run \\ \bottomrule \end{tabular} \end{center} \paragraph{Windows} \begin{center} -\begin{tabular}{@{}p{0.44\linewidth} p{0.50\linewidth}@{}} +\begin{tabular}{@{}p{0.60\linewidth} p{0.36\linewidth}@{}} \toprule \textbf{Path} & \textbf{Purpose} \\ \midrule \verb|%APPDATA%\emerger\config.ps1| & User defaults \\ \verb|%APPDATA%\emerger\profiles.d\| & User profiles \\ -\verb|%APPDATA%\emerger\hooks\{pre,post}.d\| & Hook scripts \\ -\verb|%LOCALAPPDATA%\emerger\cache\| & Detection cache \\ +\verb|%APPDATA%\emerger\hooks\pre.d\| & Hook scripts run before the managers \\ +\verb|%APPDATA%\emerger\hooks\post.d\| & Hook scripts run after the managers \\ +\verb|share\profiles\| & Shipped profiles, in the checkout \\ \verb|%LOCALAPPDATA%\emerger\state\emerger.log| & Log \\ \verb|%LOCALAPPDATA%\emerger\state\history.jsonl| & Run history \\ +\verb|%LOCALAPPDATA%\emerger\state\run.lock| & Per-user run lock \\ +\verb|%LOCALAPPDATA%\emerger\state\elevated.lock| & Lock the elevated child holds while its managers run \\ \bottomrule \end{tabular} \end{center} @@ -1554,15 +1587,16 @@ \section{Supported package managers}\label{sec:managers} \item \textbf{Linux, system (need sudo):} \texttt{pacman}, \texttt{apt}, \texttt{apt-get}, \texttt{dnf}, \texttt{yum}, \texttt{zypper}, \texttt{xbps}, \texttt{apk}, \texttt{eopkg}, \texttt{emerge}, - \texttt{nixos-rebuild}, \texttt{fwupdmgr}, \texttt{snap}. + \texttt{nixos-rebuild}, \texttt{fwupdmgr}, \texttt{snap}, + \texttt{rpi-eeprom-update} (Raspberry Pi bootloader). \item \textbf{Linux, AUR (no sudo):} \texttt{yay}, \texttt{paru}. \item \textbf{Linux, user-space:} \texttt{flatpak}, \texttt{nix-env}. \item \textbf{macOS:} \texttt{softwareupdate} (native), - \texttt{brew}, \texttt{brew --cask}, \texttt{mas}. + \texttt{brew}, \texttt{brew -{}-cask}, \texttt{mas}. \item \textbf{Windows:} \texttt{winget}, \texttt{scoop}, \texttt{choco}, - \texttt{PSWindowsUpdate}, \texttt{wsl --update}. + \texttt{PSWindowsUpdate}, \texttt{wsl -{}-update}. \item \textbf{Dev toolchains} (all platforms, opt-in with - \texttt{--dev}): \texttt{rustup}, \texttt{cargo install-update}, + \texttt{-{}-dev}): \texttt{rustup}, \texttt{cargo install-update}, \texttt{npm}, \texttt{pnpm}, \texttt{pip}, \texttt{gem}. \end{itemize} @@ -1575,16 +1609,15 @@ \section{Exit codes}\label{sec:exit} \textbf{Code} & \textbf{Meaning} \\ \midrule 0 & Success \\ -1 & Runtime failure (sudo, lock, disk, interrupted) \\ +1 & Runtime failure (sudo, lock, disk, interrupted) or aborted \\ + & (a declined safety prompt, no snapshot taken with \texttt{-{}-snapshot}) \\ 2 & Argument parsing error \\ 3 & One or more package managers returned non-zero \\ -4 & Reboot required (only with \texttt{--reboot-exit}) \\ +4 & Reboot required (only with \texttt{-{}-reboot-exit}) \\ \bottomrule \end{tabular} \end{center} -Useful idioms: - \begin{lstlisting}[language=bashplus] up -y -q || case $? in 3) notify-send "eMerger: some managers failed" ;; @@ -1602,151 +1635,102 @@ \section{Troubleshooting}\label{sec:trouble} %------------------------------------------------------- \paragraph{``Another eMerger run is in progress''.} -A stale \texttt{flock} on \verb|/tmp/emerger.lock|. Inspect \texttt{ps} -for stragglers, then remove the lock file. +Another \texttt{up} holds the lock, and the message names its PID. Wait +for it, or stop that process (\texttt{kill PID}). Deleting the lock file +does not release a \texttt{flock}: it lets a second run start beside the +first. A process started by a hook or a manager never holds the lock. +On Windows the message names the lock file, not a PID: wait for the +other \texttt{up} window (or the scheduled task) to finish. An elevated +window left running by an interrupted \texttt{up} also holds off the next +run of the same account until it ends; the elevated child creates its lock +in the state directory of the account it runs under and does not start +without it. \paragraph{A manager fails with exit code 3.} -Run \texttt{up --errors} to tail the log, then \texttt{up --doctor} to -inspect the environment. Most failures come from a manager's own health -state (for example \texttt{dpkg} interrupted); run the native repair -command (\texttt{sudo dpkg --configure -a}, \texttt{sudo pacman -Dk}) -before retrying. +\texttt{up -{}-errors}, then \texttt{up -{}-doctor}. Usually it's the +manager's own state (e.g.\ an interrupted \texttt{dpkg}); run its repair +command (\texttt{sudo dpkg -{}-configure -a}, \texttt{sudo pacman -Dk}) +and retry. \paragraph{Nothing happens on scheduled runs.} -Check \texttt{systemctl --user status emerger.timer} or the Windows Task -Scheduler entry. On Unix the scheduled run always uses -\texttt{-y -q -nl -ni}; enable \texttt{-v} in the unit for one cycle to -see the output. On Linux systemd user timers do not fire if no session is -open unless \texttt{loginctl enable-linger} has been run for the user. +Check \texttt{systemctl -{}-user status emerger.timer} or Task Scheduler, +and the \texttt{enable-linger} note in section \ref{sec:auto}. To see the +output of a scheduled run, add \texttt{-v} in the unit once. \paragraph{Emoji renders as boxes or question marks.} -The terminal font does not include Unicode ranges eMerger uses. Either -pass \texttt{--no-emoji}, set \texttt{ARG\_NO\_EMOJI=1} in -\texttt{config.sh}, or switch to a Unicode-capable font. +Emoji icons are used only when fontconfig reports a color-emoji font. +Install one (\texttt{sudo apt install fonts-noto-color-emoji} on +Debian/Raspberry Pi OS), force the mode with \verb|EMERGER_EMOJI=1| or +\verb|EMERGER_EMOJI=0|, or use \texttt{-{}-ascii}. +\texttt{up -{}-doctor} shows the active mode. + +\paragraph{The run seems stuck at ``User cache'' or ``Trash''.} +It's waiting at a y/N prompt (read from \verb|/dev/tty|, defaults to +``no'' after \verb|EMERGER_PROMPT_TIMEOUT| seconds). \texttt{-y} skips it. -\paragraph{Spinner disappears on terminal resize.} -Harmless. The live-log width recomputes every 120\,ms. +\paragraph{``cannot read the Trash (macOS privacy settings)''.} +macOS hides \verb|~/.Trash| from a terminal without Full Disk Access. +Grant it to your terminal in System Settings, Privacy \& Security, Full +Disk Access. -\paragraph{\texttt{up --self-update} aborts with ``non fast-forward''.} -You have local commits on top of \texttt{main}. Rebase or reset them -manually; eMerger refuses to clobber local work. +\paragraph{Warnings appear even with \texttt{-{}-json}.} +They go to stderr, so stdout is only the JSON. Add \verb|2>/dev/null|. + +\paragraph{\texttt{up -{}-self-update} aborts with ``non fast-forward''.} +You have local commits on top of \texttt{main}. Rebase or reset yourself. \paragraph{\texttt{notify-send} (Linux) never shows a notification.} -No \texttt{DISPLAY} / \texttt{WAYLAND\_DISPLAY} in the environment -(typical for cron). Use a systemd user timer instead: it inherits the -session. Alternatively, write a \texttt{post.d} hook that notifies your -own channel (Slack, Telegram, Discord, email). +No \texttt{DISPLAY} / \texttt{WAYLAND\_DISPLAY} (usual under cron). Use +the systemd user timer, which inherits the session. \paragraph{(Windows) ``up : The term `up' is not recognized''.} -Your PowerShell profile did not load. Run \texttt{. \$PROFILE} or open -a new window. If still missing, re-run \texttt{.\textbackslash setup.ps1}. +The profile wasn't loaded. Run \texttt{. \$PROFILE} or open a new +window; if that fails, run \texttt{.\textbackslash install.ps1} again. \paragraph{(Windows) ``cannot be loaded because running scripts is disabled''.} -\texttt{ExecutionPolicy} is \texttt{Restricted}. Lift it for the user: +\texttt{ExecutionPolicy} is \texttt{Restricted}. Run: \begin{lstlisting}[language=psplus] Set-ExecutionPolicy -Scope CurrentUser RemoteSigned \end{lstlisting} -\paragraph{(Windows) Elevation fails silently.} -You canceled the UAC prompt. The script logs \texttt{relaunching -elevated} and exits: the elevated window does the actual work. - -\paragraph{Pacman keeps asking about ignored packages.} -\texttt{ignore.list} is passed as \texttt{--ignore=}; \texttt{pacman} -still prints the warning line. This is upstream behaviour, not an -eMerger bug. +\paragraph{(Windows) choco, wsl or Windows Update fail with ``elevation failed''.} +The UAC prompt was cancelled. Those managers count as failed (exit 3), +the rest of the run goes on. Run \texttt{up} again and accept the prompt. -\paragraph{``command not found: gum'' or ``whiptail''.} -The interactive menu (\texttt{-i}) falls back to a plain-read loop when -neither tool is installed. Install \texttt{gum} -(\url{https://github.com/charmbracelet/gum}) for a nicer UI, or ignore -the warning. +\paragraph{Pacman warns about ignored packages.} +That's pacman's own message for \texttt{-{}-ignore=}. %------------------------------------------------------- \section{Frequently asked questions}\label{sec:faq} %------------------------------------------------------- -\paragraph{Is eMerger safe for production servers?} -Yes, but use it in ``security only, unattended'' mode: -\verb|up --profile server| (or its inlined equivalent). The -\texttt{--reboot-exit} idiom lets your orchestrator decide when to -reboot. +\paragraph{Can I use it on production servers?} +Yes: \verb|up --profile server| (unattended, security-only). Add +\texttt{-{}-reboot-exit} and let your own tooling decide when to reboot. -\paragraph{Does \texttt{up} install packages I don't already have?} -No. \texttt{up} only invokes managers that are already installed and -only asks them to upgrade what is already installed. No new software is -added unless a package upgrade pulls a new dependency in. +\paragraph{Does \texttt{up} install packages I don't have?} +No. It only upgrades what's installed, with managers that are installed. +New packages show up only as new dependencies of an upgrade. \paragraph{Does \texttt{up} reboot my machine?} -Only with \texttt{--reboot}. Without it, the summary prints a reboot -advisory and the run exits normally. +Only with \texttt{-{}-reboot}. -\paragraph{Can I use \texttt{up} without \texttt{sudo}?} -Yes, in user-only mode: \verb|up --only flatpak,brew,npm,pip,cargo| -(adjust to what you have). User-level managers never need elevation. - -\paragraph{Why is my terminal flashing during the parallel run?} -Under \texttt{--parallel} each user-space manager streams its own -output; when \texttt{-v} is not set, output is buffered and flushed at -the end. If you want a calm terminal, drop \texttt{-v} or narrow the -parallel set with \texttt{--only}. - -\paragraph{Can I use \texttt{up} inside a Docker image build?} -Yes. Use \verb|up --only apt -y -qq| (or the relevant manager) and -ignore the reboot advisory. Avoid \texttt{--firmware}, \texttt{--snapshot} -and interactive flags. - -\paragraph{What happens if two \texttt{up} runs start at the same time?} -The second one aborts with exit code 1 (``Another eMerger run is in -progress''). The lock is a plain \texttt{flock} on -\verb|/tmp/emerger.lock|. - -\paragraph{How do I completely remove eMerger?} -Run the uninstaller, then: +\paragraph{Can I use it without \texttt{sudo}?} +Yes, limit it to user-level managers: \begin{lstlisting}[language=bashplus] -rm -rf ~/.config/emerger ~/.cache/emerger ~/.local/state/emerger -rm -rf /path/to/eMerger # the repo itself +up --only flatpak,brew,npm,pip,cargo \end{lstlisting} -\paragraph{Where is my data?} -All local, all in the paths listed in section \ref{sec:files}. Nothing -leaves your machine unless a hook you wrote ships it. +\paragraph{Why does the terminal flicker with \texttt{-{}-parallel -v}?} +Every user-space manager streams output at once. Drop \texttt{-v}, or +narrow the set with \texttt{-{}-only}. -\paragraph{Can I contribute a new package manager?} -Absolutely - see section \ref{sec:dev}. Most contributions are a 20-line -dispatch branch plus a test case. - -%------------------------------------------------------- -\section{Glossary}\label{sec:glossary} -%------------------------------------------------------- - -\begin{itemize} - \item \textbf{Dry-run} - a simulation: the tool prints the commands it - would run without actually running them. - \item \textbf{Hook} - a user script that runs before (\texttt{pre.d}) - or after (\texttt{post.d}) the update flow. - \item \textbf{Manager (package manager)} - software such as - \texttt{apt}, \texttt{pacman}, \texttt{brew}, \texttt{winget} - that installs, upgrades and removes programs on your machine. - \item \textbf{Parallel mode} - concurrent execution of user-space - managers. Safer than it sounds, because user-space managers do - not share a lock. - \item \textbf{Plugin} - a user-provided manager definition. Registers - a new manager without modifying the repository. - \item \textbf{Profile} - a named bundle of default flags, loaded via - \texttt{--profile NAME}. - \item \textbf{Resume cursor} - a file that records which managers - completed successfully, consumed by \texttt{--resume}. - \item \textbf{Snapshot} - a read-only filesystem checkpoint taken - before the upgrade. Linux only - (snapper/timeshift/btrfs). - \item \textbf{TUI} - Terminal User Interface. The interactive menu - (\texttt{-i}) on Unix. - \item \textbf{UAC} - User Account Control, the Windows elevation - prompt. eMerger relaunches itself elevated when needed. -\end{itemize} +\paragraph{Can I use it in a Docker image build?} +Yes: \verb|up --only apt -y -qq| (or your manager). Skip +\texttt{-{}-firmware} and \texttt{-{}-snapshot}, and ignore the reboot +advisory. %------------------------------------------------------- \section{Development}\label{sec:dev} @@ -1767,9 +1751,10 @@ \subsection{Repository layout} completions/ # bash/zsh/fish completions tests/ # bats tests man/up.1 # man page - setup.sh setup.ps1 + doc/documentation.tex # this manual + reference/ # third-party audit + install.sh install.ps1 uninstall.sh uninstall.ps1 - update.sh update.ps1 VERSION .github/workflows/ci.yml \end{lstlisting} @@ -1781,37 +1766,54 @@ \subsection{Bash library modules (\texttt{src/lib/})} \toprule \textbf{File} & \textbf{Role} \\ \midrule \endhead -\texttt{ui.sh} & Colors, glyphs, spinner, box, live-log monitor \\ -\texttt{log.sh} & Structured logging (rotated at 2000 lines) \\ -\texttt{sys.sh} & OS / shell / battery / disk detection \\ -\texttt{run.sh} & Command runner (dry-run, retry, progress) \\ -\texttt{args.sh} & Argument parser and short-bundle expander \\ -\texttt{packages.sh} & Per-manager dispatcher \\ -\texttt{clean.sh} & Cache and trash cleaners \\ -\texttt{hooks.sh} & User hook runner \\ -\texttt{update.sh} & Self-update + cron / timer setup \\ -\texttt{notify.sh} & Desktop notifications \\ -\texttt{summary.sh} & Final banner, history persistence \\ -\texttt{tui.sh} & Interactive menu \\ -\texttt{lock.sh} & Global \texttt{flock} \\ -\texttt{retry.sh} & Retry on transient failures \\ -\texttt{reboot.sh} & Reboot-required detection \\ -\texttt{diff.sh} & Package snapshots + diff \\ -\texttt{disk.sh} & Disk-space precheck \\ -\texttt{snapshot.sh} & snapper / timeshift / btrfs \\ -\texttt{mirrors.sh} & Mirror rank / refresh \\ -\texttt{resume.sh} & Resume cursor \\ -\texttt{doctor.sh} & \texttt{--doctor} \\ -\texttt{changelog.sh} & \texttt{--changelog PKG} \\ -\texttt{report.sh} & Markdown export \\ -\texttt{wizard.sh} & First-run wizard \\ -\texttt{profiles.sh} & Profile loader \\ -\texttt{progress.sh} & Output summary + highlight \\ -\texttt{estimate.sh} & Step ETA from history \\ -\texttt{ignore.sh} & Ignore list loader \\ -\texttt{plugins.sh} & User plugin loader \\ -\texttt{metrics.sh} & Prometheus textfile export \\ -\texttt{help.txt} & \texttt{up --help} content \\ +\texttt{load.sh} & Module loader: every module in load order, or the ones named \\ +\texttt{args.sh} & Argument parser \\ +\texttt{knobs.sh} & Numeric knob and safety switch validation \\ +\texttt{sys.sh} & OS, shell, root, free space and process probes \\ +\texttt{log.sh} & Structured logging (rotated), \texttt{-{}-errors} \\ +\texttt{trust.sh} & Owner and mode checks on user files \\ +\texttt{hooks.sh} & User hook runner \\ +\texttt{ignore.sh} & Ignore list loader \\ +\texttt{profiles.sh} & Profile loader \\ +\texttt{doctor.sh} & \texttt{-{}-doctor} \\ +\texttt{summary.sh} & Final box and \texttt{-{}-json} line \\ +\texttt{quiet\_hours.sh} & \texttt{QUIET\_HOURS} gate \\ +\texttt{selfupdate.sh} & \texttt{git pull} self-update \\ +\texttt{autoupdate.sh} & Weekly systemd timer or cron line \\ +\texttt{help.txt} & Help text \\ +\texttt{ui/term.sh} & Colour, UTF-8 and emoji detection, glyphs, width, cursor \\ +\texttt{ui/text.sh} & Escape stripping, visible width, percentage bar, highlighting \\ +\texttt{ui/print.sh} & Section headers, status lines, logo, box \\ +\texttt{ui/monitor.sh} & Live monitor: spinner, wave, bar \\ +\texttt{ui/prompt.sh} & Free answer and y/N prompts \\ +\texttt{run/command.sh} & \texttt{run\_cmd}: dry run, timeout, retry, captured output \\ +\texttt{run/select.sh} & Which detected managers a run updates \\ +\texttt{run/parallel.sh} & \texttt{-{}-parallel} group \\ +\texttt{run/sudo.sh} & sudo keep-alive \\ +\texttt{managers/registry.sh} & Manager list and capabilities \\ +\texttt{managers/detect.sh} & Detection and its cache \\ +\texttt{managers/icon.sh} & Section icons \\ +\texttt{managers/recipes.sh} & \texttt{pkg\_run} and one recipe per manager \\ +\texttt{managers/rpi\_eeprom.sh} & Raspberry Pi bootloader recipe \\ +\texttt{managers/plugins.sh} & User plugin loader \\ +\texttt{managers/progress.sh} & Output summary, live progress parsers (\texttt{progress\_feed}) \\ +\texttt{managers/changelog.sh} & \texttt{-{}-changelog PKG} \\ +\texttt{system/preflight.sh} & Disk-space and battery prechecks \\ +\texttt{system/rpi.sh} & Raspberry Pi model, power and thermal pre-flight \\ +\texttt{system/reboot.sh} & Reboot-required detection \\ +\texttt{system/snapshot.sh} & snapper/timeshift/btrfs \\ +\texttt{system/mirrors.sh} & Mirror rank/refresh \\ +\texttt{system/notify.sh} & Desktop notifications \\ +\texttt{state/history.sh} & \texttt{history.jsonl} and \texttt{-{}-history} \\ +\texttt{state/estimate.sh} & Step ETA from history \\ +\texttt{state/metrics.sh} & Prometheus textfile export \\ +\texttt{state/diff.sh} & Package snapshots + diff \\ +\texttt{state/resume.sh} & Resume cursor \\ +\texttt{state/lock.sh} & Global \texttt{flock}, \texttt{mkdir} fallback \\ +\texttt{clean/size.sh} & Size of a path, short size format \\ +\texttt{clean/cache.sh} & Selective \texttt{\textasciitilde{}/.cache} menu \\ +\texttt{clean/trash.sh} & Trash \\ +\texttt{clean/deep.sh} & \texttt{-{}-deep-clean} tasks \\ \bottomrule \end{longtable} \end{center} @@ -1823,48 +1825,76 @@ \subsection{PowerShell library modules (\texttt{src/pslib/})} \toprule \textbf{File} & \textbf{Role} \\ \midrule -\texttt{UI.ps1} & Colors, glyphs, box, step \\ -\texttt{Log.ps1} & Structured logging \\ -\texttt{Sys.ps1} & OS, admin, battery, disk, UAC elevation \\ -\texttt{Args.ps1} & Arg parser (shift + regex) \\ -\texttt{Packages.ps1} & Manager dispatcher + \texttt{Run-Cmd} \\ -\texttt{Clean.ps1} & \texttt{\%TEMP\%} and Recycle Bin \\ -\texttt{Hooks.ps1} & \texttt{hooks\textbackslash \{pre,post\}.d\textbackslash *.ps1} \\ -\texttt{Update.ps1} & \texttt{git pull} self-update + Task Scheduler \\ -\texttt{Notify.ps1} & BurntToast (optional) \\ -\texttt{Summary.ps1} & Final box, history, reboot detection \\ -\texttt{Doctor.ps1} & \texttt{--doctor} \\ -\texttt{Profiles.ps1} & Profile loader \\ -\texttt{Help.txt} & Help text \\ +\texttt{Args.ps1} & Arg parser (shift + regex), Unix-only flag warnings \\ +\texttt{Sys.ps1} & OS, architecture, admin, numeric knobs, weather \\ +\texttt{Log.ps1} & Structured logging, \texttt{-{}-errors} \\ +\texttt{Run.ps1} & \texttt{Run-Cmd}: child process, live output, timeout, retry \\ +\texttt{Elevated.ps1} & Elevated child for the admin managers \\ +\texttt{Summary.ps1} & Final box and \texttt{-{}-json} line \\ +\texttt{Hooks.ps1} & \texttt{hooks\textbackslash \{pre,post\}.d\textbackslash *.ps1} \\ +\texttt{Profiles.ps1} & Profile loader \\ +\texttt{Doctor.ps1} & \texttt{-{}-doctor} \\ +\texttt{SelfUpdate.ps1} & \texttt{git pull} self-update \\ +\texttt{AutoUpdate.ps1} & Task Scheduler registration \\ +\texttt{Help.txt} & Help text \\ +\texttt{ui/Term.ps1} & Console setup, colors, glyphs, width \\ +\texttt{ui/Text.ps1} & Escape stripping, visible width, elapsed time \\ +\texttt{ui/Print.ps1} & Section headers, status lines, logo, box \\ +\texttt{ui/Monitor.ps1} & Live monitor: spinner, wave, bar \\ +\texttt{ui/Prompt.ps1} & y/N prompt \\ +\texttt{managers/Packages.ps1} & Manager registry, detection, selection, \texttt{Pkg-Run} recipes \\ +\texttt{managers/Progress.ps1} & Live progress parsers for the Windows managers (\texttt{Progress-Feed}) \\ +\texttt{system/Preflight.ps1} & Battery and free disk checks \\ +\texttt{system/Reboot.ps1} & Pending reboot detection and advisory \\ +\texttt{system/Notify.ps1} & BurntToast (optional) \\ +\texttt{state/Lock.ps1} & Per-user run lock, elevated child lock \\ +\texttt{state/History.ps1} & \texttt{history.jsonl} and \texttt{-{}-history} \\ +\texttt{state/Estimate.ps1} & Step ETA from history \\ +\texttt{state/Metrics.ps1} & Prometheus textfile export \\ +\texttt{clean/Size.ps1} & Size formatting \\ +\texttt{clean/Temp.ps1} & \texttt{\%TEMP\%} folders \\ +\texttt{clean/RecycleBin.ps1} & Recycle Bin \\ \bottomrule \end{tabular} \end{center} \subsection{Running tests} +With bats-core and ShellCheck on \texttt{PATH}: + \begin{lstlisting}[language=bashplus] -sudo apt-get install bats shellcheck bats tests/ -shellcheck -S error src/emerger.sh src/lib/*.sh setup.sh uninstall.sh update.sh +shopt -s globstar +shellcheck -S error src/emerger.sh src/lib/**/*.sh install.sh uninstall.sh \end{lstlisting} -Both run on push via \texttt{.github/workflows/ci.yml}. +Each \texttt{tests/.bats} covers one feature: \texttt{cli.bats} +the flags, \texttt{lock.bats} the run lock, \texttt{clean.bats} the cache, +trash and \texttt{-{}-deep-clean}, and so on. +\texttt{tests/test\_helper.bash} holds the shared fixture (temp +\texttt{HOME}, stubs on \texttt{PATH}, \texttt{lib} to source modules). The +\texttt{tests/ps\_*.bats} files cover the PowerShell half and skip without +\texttt{pwsh}. All of them run on push via +\texttt{.github/workflows/ci.yml}. \subsection{Adding a package manager} -\paragraph{Unix} - edit \texttt{src/lib/packages.sh}: +\paragraph{Unix:} edit \texttt{src/lib/managers/}. \begin{enumerate} - \item Add the name to \texttt{PKG\_MANAGERS}. - \item Add a branch in \texttt{\_pkg\_detect\_raw}. - \item Add a branch in \texttt{pkg\_run} with \texttt{run\_cmd} calls. + \item Add the name to \texttt{PKG\_MANAGERS} (\texttt{registry.sh}). + \item Add a branch in \texttt{\_pkg\_detect\_raw} (\texttt{detect.sh}). + \item Add a \texttt{\_pkg\_run\_} recipe with \texttt{run\_cmd} + calls and its case in \texttt{pkg\_run} (\texttt{recipes.sh}). \item If the manager does not need sudo, exclude it from - \texttt{pkg\_needs\_sudo}. - \item Optional: add an emoji in \texttt{pkg\_icon}, a regex in - \texttt{progress.sh} to parse its output, a completion entry. + \texttt{pkg\_needs\_sudo} (\texttt{registry.sh}). + \item Optional: an emoji (and plain-symbol fallback) in + \texttt{pkg\_icon} (\texttt{icon.sh}), a stat parser in + \texttt{progress\_summarize}, a live-progress case in + \texttt{progress\_feed} (\texttt{progress.sh}) and a completion entry. \end{enumerate} -\paragraph{Windows} - edit \texttt{src/pslib/Packages.ps1}: +\paragraph{Windows:} edit \texttt{src/pslib/managers/Packages.ps1}. \begin{enumerate} \item Add the name to \texttt{\$script:PKG\_MANAGERS} (or @@ -1874,29 +1904,21 @@ \subsection{Adding a package manager} \item If it needs admin, add it to \texttt{Pkg-Need-Admin}. \end{enumerate} -Both files are table-driven dispatchers; most contributions end up being -a twenty-line patch plus a test case under \texttt{tests/}. +Both dispatchers are table-driven, so a new manager is usually a short +patch plus a test under \texttt{tests/}. \subsection{Contributing} -Pull requests and issues are welcome on -\href{https://github.com/MasterCruelty/eMerger}{GitHub}. Before opening -a PR: +Issues and pull requests go to +\href{https://github.com/MasterCruelty/eMerger}{GitHub}, against +\texttt{dev}. Before opening a PR: \begin{itemize} \item Run the test suite in \texttt{tests/} on the platform you touched. - \item Attach \texttt{up --doctor} output and the relevant chunk of the + \item Attach \texttt{up -{}-doctor} output and the relevant chunk of the log when reporting bugs. - \item Keep feature parity in mind: when a feature makes sense on both - Bash and PowerShell, please implement it on both sides or flag - it for follow-up. + \item If a feature applies to both Bash and PowerShell, implement it on + both or say in the PR that the other side is missing. \end{itemize} -\vspace{1em} -\hrule -\vspace{0.5em} -\noindent\textit{If your question is not answered here, open an issue on -GitHub: we would rather improve the documentation than answer the same -question twice.} - \end{document} diff --git a/install.ps1 b/install.ps1 new file mode 100644 index 0000000..e2d1181 --- /dev/null +++ b/install.ps1 @@ -0,0 +1,86 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Install eMerger on Windows: register the `up` function, offer to allow + scripts in the execution policy, scaffold %APPDATA%\emerger. +#> +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' +$REPO = Split-Path -Parent $PSCommandPath +. "$REPO\src\pslib\ui\Term.ps1" +. "$REPO\src\pslib\ui\Text.ps1" +. "$REPO\src\pslib\ui\Print.ps1" +. "$REPO\src\pslib\ui\Prompt.ps1" +. "$REPO\src\pslib\Sys.ps1" + +UI-Title 'eMerger install (Windows)' + +# ExecutionPolicy: changed only on an explicit yes (no answer means no). +$policy = Get-ExecutionPolicy -Scope CurrentUser +if ($policy -eq 'Restricted' -or $policy -eq 'Undefined') { + UI-Info "ExecutionPolicy for CurrentUser is '$policy': the profile and 'up' may be blocked." + if (UI-Confirm 'Set it to RemoteSigned for CurrentUser?' 'n') { + try { + Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force + UI-Ok 'ExecutionPolicy updated.' + } catch { + UI-Warn "Could not change ExecutionPolicy: $($_.Exception.Message)" + } + } else { + UI-Info 'ExecutionPolicy left unchanged. To allow it later: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned' + } +} + +# PowerShell profile: add `up` function. +$profilePath = $PROFILE.CurrentUserAllHosts +$profileDir = Split-Path $profilePath +if (-not (Test-Path $profileDir)) { New-Item -ItemType Directory -Path $profileDir -Force | Out-Null } +if (-not (Test-Path $profilePath)) { New-Item -ItemType File -Path $profilePath -Force | Out-Null } + +$entry = "$REPO\src\emerger.ps1" +# Stop rather than silently shadow another command named `up`. +$other = Get-Command up -ErrorAction SilentlyContinue | Where-Object { "$($_.Definition)" -notmatch 'emerger\.ps1' } | Select-Object -First 1 +if ($other) { + UI-Err "A command named 'up' already exists: $($other.Source) $($other.CommandType)" + UI-Info "eMerger did not add its function. Remove or rename the other 'up' and run install.ps1 again." + exit 1 +} +$existing = Get-Content $profilePath -Raw -ErrorAction SilentlyContinue +if ($existing -and $existing -match 'emerger\.ps1') { + UI-Ok "'up' already registered in $profilePath" +} else { + # Single-quoted, every quote the parser accepts (' and U+2018 to U+201B) + # doubled: the path is data, never code. + $literal = "'" + [System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($entry) + "'" + $block = @" + +# eMerger (https://github.com/MasterCruelty/eMerger) +function up { & $literal @args } +"@ + Add-Content -Path $profilePath -Value $block + UI-Ok "Added 'up' function to $profilePath" +} + +# Config + hooks + profiles skeleton. +$configDir = Join-Path $env:APPDATA 'emerger' +@('hooks\pre.d','hooks\post.d','profiles.d') | ForEach-Object { + $dir = Join-Path $configDir $_ + if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null } +} + +$configFile = Join-Path $configDir 'config.ps1' +if (-not (Test-Path $configFile)) { + @' +# eMerger user config (Windows). Dot-sourced before argument parsing. +# Uncomment to set defaults. + +# $script:ArgsGlobal.Dev = $true +# $script:ArgsGlobal.KeepTrash = $true +# $script:ArgsGlobal.Security = $true +'@ | Set-Content $configFile -Encoding UTF8 + UI-Ok "Created $configFile" +} + +UI-Info "Open a new PowerShell window (or: . `$PROFILE) and run: up --help" diff --git a/setup.sh b/install.sh similarity index 56% rename from setup.sh rename to install.sh index 0e232e1..35c002c 100755 --- a/setup.sh +++ b/install.sh @@ -3,15 +3,23 @@ set -Eeuo pipefail REPO_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -# shellcheck source=src/lib/ui.sh -source "$REPO_DIR/src/lib/ui.sh" -# shellcheck source=src/lib/sys.sh -source "$REPO_DIR/src/lib/sys.sh" +# Installers take no flags: the environment never reaches ui_* arithmetic. +# Both read by the ui functions. +# shellcheck disable=SC2034 +QUIET_LEVEL=0 +# shellcheck disable=SC2034 +UI_VERBOSE=0 -ui_title "eMerger setup" +# shellcheck source=src/lib/load.sh +source "$REPO_DIR/src/lib/load.sh" ui sys autoupdate + +ui_title "eMerger install" +install_path_check "$REPO_DIR" || exit 1 ALIAS_CMD="bash \"$REPO_DIR/src/emerger.sh\"" +# Append the `up` alias to bash or zsh start-up file $1, created when +# missing. A file already naming emerger.sh is left alone. _add_alias_bashzsh() { local rc="$1" touch "$rc" @@ -26,6 +34,8 @@ _add_alias_bashzsh() { ui_ok "Added 'up' alias to $rc" } +# Append the `up` alias to fish's config.fish, created when missing. A file +# already naming emerger.sh is left alone. _add_alias_fish() { local conf="$HOME/.config/fish/config.fish" mkdir -p "$(dirname "$conf")" @@ -41,21 +51,44 @@ _add_alias_fish() { ui_ok "Added 'up' alias to $conf" } -installed_any=0 -# macOS default shell is zsh (since Catalina); prioritize accordingly. +# Stop rather than silently shadow another command or alias named `up`. +_check_no_other_up() { + local rc other + other=$(type -P up || true) + if [[ -n $other ]]; then + ui_err "A command named 'up' already exists: $other" + ui_info "eMerger did not add its alias. Remove or rename the other 'up' and run install.sh again." + exit 1 + fi + # Definition lines of `up` in the files a shell reads at start, eMerger's own excepted. + local defs='^[[:space:]]*(alias[[:space:]]+up([=[:space:]]|$)|function[[:space:]]+up([[:space:];({]|$)|up[[:space:]]*\(\))' + for rc in "$HOME/.bashrc" "$HOME/.bash_aliases" "$HOME/.bash_profile" "$HOME/.profile" \ + "${ZDOTDIR:-$HOME}/.zshrc" "$HOME/.config/fish/config.fish" "$HOME/.config/fish/functions/up.fish"; do + [[ -f $rc ]] || continue + if grep -E "$defs" "$rc" | grep -qv "emerger.sh"; then + ui_err "An alias or function named 'up' already exists in $rc" + ui_info "eMerger did not add its alias. Remove or rename the other 'up' and run install.sh again." + exit 1 + fi + done +} +_check_no_other_up + +has_installed=0 +# macOS default shell is zsh (since Catalina): its rc file comes first. if sys_is_macos; then - _add_alias_bashzsh "${ZDOTDIR:-$HOME}/.zshrc"; installed_any=1 + _add_alias_bashzsh "${ZDOTDIR:-$HOME}/.zshrc"; has_installed=1 [[ -f "$HOME/.bashrc" ]] && { _add_alias_bashzsh "$HOME/.bashrc"; } elif [[ -f "$HOME/.bashrc" ]] || [[ $(basename "${SHELL:-}") == bash ]]; then - _add_alias_bashzsh "$HOME/.bashrc"; installed_any=1 + _add_alias_bashzsh "$HOME/.bashrc"; has_installed=1 fi if [[ -f "$HOME/.zshrc" ]] || [[ $(basename "${SHELL:-}") == zsh ]]; then - _add_alias_bashzsh "${ZDOTDIR:-$HOME}/.zshrc"; installed_any=1 + _add_alias_bashzsh "${ZDOTDIR:-$HOME}/.zshrc"; has_installed=1 fi if [[ -f "$HOME/.config/fish/config.fish" ]] || [[ $(basename "${SHELL:-}") == fish ]]; then - _add_alias_fish; installed_any=1 + _add_alias_fish; has_installed=1 fi -if (( ! installed_any )); then +if (( ! has_installed )); then _add_alias_bashzsh "$(sys_shell_rc)" fi @@ -86,6 +119,17 @@ install_completion "$REPO_DIR/completions/up.bash" "$bash_comp/up" install_completion "$REPO_DIR/completions/_up" "$zsh_comp/_up" install_completion "$REPO_DIR/completions/up.fish" "$fish_comp/up.fish" +# Man page where man looks for the user's own pages: `man up` after install. +man_dir="${XDG_DATA_HOME:-$HOME/.local/share}/man/man1" +if [[ -f "$REPO_DIR/man/up.1" ]]; then + mkdir -p "$man_dir" + install -m 0644 "$REPO_DIR/man/up.1" "$man_dir/up.1" + ui_ok "Installed man page: $man_dir/up.1" + if command -v manpath >/dev/null 2>&1 && ! manpath 2>/dev/null | tr ':' '\n' | grep -qx "${man_dir%/man1}"; then + ui_muted "If 'man up' finds nothing, add ${man_dir%/man1} to MANPATH." + fi +fi + # Default config skeleton. CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/emerger" mkdir -p "$CONFIG_DIR/hooks/pre.d" "$CONFIG_DIR/hooks/post.d" "$CONFIG_DIR/profiles.d" @@ -96,7 +140,7 @@ if [[ ! -f "$CONFIG_DIR/config.sh" ]]; then # ARG_DEV=1 # always include dev toolchains # ARG_WEATHER=1 # always show weather -# ARG_NO_TRASH=1 # never touch trash +# ARG_KEEP_TRASH=1 # never touch trash # DISK_MIN_FREE_MB=2048 # QUIET_HOURS="23:00-07:00" # skip when timer fires inside this window EOF diff --git a/man/up.1 b/man/up.1 index 6f772fd..462a131 100644 --- a/man/up.1 +++ b/man/up.1 @@ -1,85 +1,378 @@ -.TH UP 1 "2026" "eMerger 2.0" "User Commands" +.TH UP 1 "2026" "eMerger 3.0.0" "User Commands" .SH NAME up \- eMerger, one-command system updater .SH SYNOPSIS .B up -[\fIoptions\fR] +[\fIoptions\fR] [\fB\-\-\fR] .SH DESCRIPTION -eMerger detects installed package managers on the host and runs each of them -in turn to refresh, upgrade and clean the system. It also offers optional -cleanup of the user cache and trash. -.SH OPTIONS +This page covers \fBup\fR on Linux and macOS: every flag, environment and +configuration variable, file, exit status and JSON field. The plugin API and +the Windows build are in the eMerger manual, \fIdoc/documentation.pdf\fR. +.PP +eMerger detects the package managers installed on the host and runs each of +them in turn to refresh, upgrade and clean the system, then prints a summary. +It can also clean the user cache, the trash and, with \fB\-\-deep\-clean\fR, +system leftovers. Every cleaning step asks first unless \fB\-y\fR is given. +.PP +Short flags from the set \fBh V n v q y w\fR can be bundled: \fB\-nv\fR is +\fB\-n \-v\fR. Other short flags (\fB\-nl\fR, \fB\-qq\fR, \fB\-up\fR and so on) +and long flags stay whole. A flag that takes a value accepts it as the next +word or as \fB\-\-flag=VALUE\fR (\fB\-\-only=apt,flatpak\fR); an empty value +exits 2. \fB\-\-\fR marks the end of options: the words after it are ignored. +.SH GENERAL .TP -.B -h, --help -Show help and exit. +.B \-h, \-\-help +Show the help text. .TP -.B -V, --version -Show version and exit. +.B \-V, \-\-version +Print the version. .TP -.B -i, --interactive -Interactive menu (gum, whiptail, or plain fallback). +.B \-\-doctor +Run the environment health check. Exits non-zero if any check warns or fails. +.SH EXECUTION .TP -.B -n, --dry-run -Print what would be done; do nothing. +.B \-n, \-\-dry\-run +Print the commands that would run, change nothing. .TP -.B -v, --verbose -Stream package manager output live. +.B \-v, \-\-verbose +Stream package manager output instead of the live progress line. .TP -.B -q, --quiet -Minimal output. +.B \-q, \-\-quiet, \-qq, \-qqq +Quieter output, one level per \fB\-q\fR or \fB\-\-quiet\fR. \fB\-q\fR hides +informational lines, \fB\-qq\fR prints only the one-line summary, +\fB\-qqq\fR prints nothing. .TP -.B -y, --yes -Assume "yes" on prompts. +.B \-y, \-\-yes +Answer yes to every prompt. .TP -.B --security -Only security updates when the manager supports them. +.B \-\-json +Print the run summary as one JSON object on stdout, fields as in +\fBJSON OUTPUT\fR. Implies \fB\-nl \-ni \-qqq\fR. Warnings go to stderr. +.SH SELECTION .TP -.B --firmware -Include firmware updates via fwupdmgr. +.B \-\-security +Security updates only, where the manager supports it (apt via +unattended-upgrade, dnf, yum, zypper, softwareupdate). Other managers are +skipped with a warning. .TP -.B --dev -Include dev toolchains (rustup, cargo, npm, pnpm, pip, gem). +.B \-\-firmware +Include firmware: \fBfwupdmgr\fR, and on a Raspberry Pi with an EEPROM, stage +the bootloader update (\fBrpi\-eeprom\-update \-a\fR). .TP -.B --parallel -Run independent user-space managers in parallel. +.B \-\-no\-firmware +Skip firmware, including the Raspberry Pi bootloader check. Wins over +.B ARG_FIRMWARE=1 +set in the config file or a profile. .TP -.B -nl, -ni, -nc, -nt -Skip logo, system info, cache clean, trash clean. +.B \-\-dev +Include dev toolchains: rustup, cargo, npm, pnpm, pip, gem. .TP -.B -w, --weather -Show the current weather. +.B \-\-parallel +Run independent user-space managers at the same time. .TP -.B -up -Self-update eMerger via git. +.BI \-\-profile " NAME" +Load \fI~/.config/emerger/profiles.d/NAME.sh\fR, else the shipped +\fIshare/profiles/NAME.sh\fR of the checkout, before the command-line flags. +The last \fB\-\-profile\fR wins. .TP -.B -au -Install a weekly auto-update (systemd user timer or cron). +.B \-\-list\-profiles +List the available profiles. .TP -.B -err -Print logged errors. +.BI \-\-only " LIST" +Comma-separated managers to run (e.g. apt,flatpak). .TP -.B --history -Print a summary of recent runs. +.BI \-\-except " LIST" +Comma-separated managers to skip. Adds to a list set by the config or a +profile. +.SH SAFETY AND INTEGRATION +.TP +.B \-\-snapshot +Take a pre-update snapshot (snapper, timeshift or btrfs). Exit 1 before +any manager runs when none works. +.TP +.B \-\-rollback +Revert to the latest eMerger snapshot and exit. +.TP +.B \-\-refresh\-mirrors +Re-rank mirrors (reflector, netselect-apt) before upgrading. +.TP +.B \-\-resume +Skip managers that completed in the last run. A run without +\fB\-\-resume\fR starts a fresh cursor. +.TP +.B \-\-reboot +Reboot now if the system requires it. +.TP +.B \-\-reboot\-exit +Exit with status 4 instead of 0 when a reboot is required. +.TP +.B \-\-download\-only +Download packages without installing them (apt, dnf, pacman, zypper, +softwareupdate). +Every other manager is skipped with a message. +.TP +.B \-\-accept\-licenses +Let macOS +.B softwareupdate +accept licence agreements. Without it, it lists the available updates and +installs nothing. +.SH DISPLAY +.TP +.B \-nl, \-\-no\-logo +Hide the logo. +.TP +.B \-ni, \-\-no\-info +Hide the system information line. +.TP +.B \-w, \-\-weather +Show a weather line from wttr.in. +.TP +.B \-\-ascii +ASCII glyphs only. The spinner becomes the ".:" pulse. +.SH CLEANING +.TP +.B \-nc, \-\-keep\-cache +Skip user cache cleaning. +.TP +.B \-nt, \-\-keep\-trash +Skip trash cleaning. +.TP +.B \-\-deep\-clean +Also clean system leftovers, asking for each: journal above +\fBJOURNAL_MAX_SIZE\fR, old kernels (dnf, zypper), config files of removed +packages, disabled snap revisions, dangling docker/podman images and build +cache, crash dumps, npm and Go caches. +.SH INSPECTION +.TP +.B \-\-changed +Show packages added, removed or upgraded in the last run. +.TP +.BI \-\-changelog " PKG" +Show the upstream changelog of \fIPKG\fR. +.TP +.B \-\-history +Show the last runs. +.TP +.BI \-\-metrics " FILE" +Export the last run as a Prometheus textfile with the gauges +\fBemerger_last_run_timestamp_seconds\fR, +\fBemerger_last_run_duration_seconds\fR, \fBemerger_last_run_errors\fR, +\fBemerger_last_run_freed_bytes\fR, \fBemerger_reboot_required\fR and one +\fBemerger_manager_ok\fR per manager. +.TP +.B \-err, \-\-errors +Show logged errors. +.SH MAINTENANCE +.TP +.B \-up, \-\-self\-update +Update eMerger with git (fast-forward only). +.TP +.B \-au, \-\-auto\-update +Install a weekly run (systemd user timer, or cron). +.TP +.B \-rc, \-\-rebuild\-cache +Clear the package manager detection cache. +.SH ENVIRONMENT +Each variable below except the \fBXDG_*\fR ones can also be set in +\fI~/.config/emerger/config.sh\fR or a profile. +.TP +.B EMERGER_EMOJI +\fBauto\fR (default) uses emoji icons only when fontconfig reports a +color-emoji font; \fB1\fR or \fB0\fR forces the choice. +.TP +.B EMERGER_SPINNER +Spinner style: \fBbraille\fR, \fBdots\fR, \fBpulse\fR or \fBline\fR. Unset, +\fBbraille\fR on a UTF-8 terminal and \fBpulse\fR otherwise; without UTF-8 +every style but \fBline\fR falls back to \fBpulse\fR. +.TP +.B EMERGER_PROMPT_TIMEOUT +Seconds a prompt waits before taking its default (60; 0 waits forever). +.TP +.B EMERGER_CACHE_TTL +Seconds the package manager detection cache stays valid (86400; 0 disables it). +.TP +.B DISK_MIN_FREE_MB +Warn and ask below this many MiB free on / (1024). +.TP +.B BATTERY_MIN_PCT +Warn and ask below this battery percentage (20). +.TP +.B RETRY_ATTEMPTS +Attempts for a step that fails with a transient network error (2, one retry). +.TP +.B RETRY_DELAY +Seconds before the first retry; the n-th retry waits n times as long (3). +.TP +.B CACHE_EXCLUDE +~/.cache entries never offered for cleaning (names or globs). +.TP +.B CACHE_MENU_ROWS +Cache entries listed before the rest is grouped as "others" (12). +.TP +.B JOURNAL_MAX_SIZE +Journal size \fB\-\-deep\-clean\fR vacuums down to (200M). +.TP +.B DEEP_CLEAN_SKIP +Deep-clean tasks to skip: journal, kernels, residual, snap, docker, podman, +coredumps, npm, go. +.TP +.B RPI_ABORT_ON_UNDERVOLTAGE +On a Raspberry Pi, abort even with \-y when the board is under-voltage (0). +.TP +.B RPI_TEMP_WARN +Raspberry Pi SoC temperature, in degrees C, at or above which to warn (80). +.TP +.B MANAGER_TIMEOUT +Seconds one manager command may run before \fBtimeout\fR stops it with +exit 124 (0, no limit). +.TP +.B DRY_RUN +1 previews every run, as \fB\-n\fR does (0). +.TP +.B UI_VERBOSE +1 streams manager output, as \fB\-v\fR does (0). +.TP +.B QUIET_HOURS +\fIHH:MM\-HH:MM\fR window, may wrap past midnight, in which a run with +\fB\-y\fR prints "quiet hours, skipping" and exits 0. A malformed value +warns and is ignored. +.TP +.B NO_COLOR +Any non-empty value disables colors. +.TP +.B COLORFGBG +\fIfg;bg\fR as set by the terminal: a background of 7 or more selects the +palette for light backgrounds. +.TP +.B XDG_CONFIG_HOME, XDG_CACHE_HOME, XDG_STATE_HOME +Base directories of the config, cache and state directories under +\fBFILES\fR (\fI~/.config\fR, \fI~/.cache\fR and \fI~/.local/state\fR when unset). +.PP +Numeric variables take whole numbers; any other value warns and the +default is used. The safety switches \fBDRY_RUN\fR and +\fBRPI_ABORT_ON_UNDERVOLTAGE\fR exit 2 on any other value instead. +\fBMANAGER_TIMEOUT\fR without a \fBtimeout\fR command warns once and is not applied. +.SH CONFIGURATION +\fIconfig.sh\fR and profiles can set the variable of each flag below, to 1 +or to the flag's value. Command-line flags are applied after them and win. +A profile cannot select a profile. The flags that run an action or a query +instead of an update (\-h, \-V, \-\-doctor, \-\-list\-profiles, +\-\-rollback, \-\-reboot, \-\-changed, \-\-changelog, \-\-history, +\-\-metrics, \-err, \-up, \-au, \-rc) are taken from the command line +only: setting their variables in a file has no effect. +.PP +.nf +.ft CR +DRY_RUN \-n +UI_VERBOSE \-v +QUIET_LEVEL \-q (0 to 3) +ARG_YES \-y +ARG_JSON \-\-json +ARG_SECURITY \-\-security +ARG_FIRMWARE \-\-firmware +ARG_NO_FIRMWARE \-\-no\-firmware +ARG_DEV \-\-dev +ARG_PARALLEL \-\-parallel +ARG_ONLY \-\-only LIST +ARG_EXCEPT \-\-except LIST +ARG_SNAPSHOT \-\-snapshot +ARG_REFRESH_MIRRORS \-\-refresh\-mirrors +ARG_RESUME \-\-resume +ARG_REBOOT_EXIT \-\-reboot\-exit +ARG_DOWNLOAD_ONLY \-\-download\-only +ARG_ACCEPT_LICENSES \-\-accept\-licenses +ARG_NO_LOGO \-nl +ARG_NO_INFO \-ni +ARG_WEATHER \-w +ARG_ASCII \-\-ascii +ARG_KEEP_CACHE \-nc +ARG_KEEP_TRASH \-nt +ARG_DEEP_CLEAN \-\-deep\-clean +.ft +.fi +.PP +\fB\-\-except\fR adds to \fBARG_EXCEPT\fR; every other flag replaces its +variable. +.SH JSON OUTPUT +\fB\-\-json\fR prints one object, and \fIhistory.jsonl\fR holds one per run: +.TP +.B ts +End time of the run, UTC, ISO 8601 (2026-01-31T09:00:00Z). +.TP +.B duration +Run time in seconds. +.TP +.B freed_kb +KiB freed by cache and trash cleaning. +.TP +.B errors +Number of managers that failed. +.TP +.B reboot +1 when a reboot is pending, else 0. +.TP +.B managers +One object per manager run: \fBname\fR, \fBresult\fR (\fBok\fR or \fBfail\fR) +and \fBsecs\fR, its run time in seconds. .SH FILES .TP .I ~/.config/emerger/config.sh -Sourced before argument parsing. +Sourced before argument parsing. This file, user profiles, plugins and +hooks are refused unless you own them and no other user can write them. +.TP +.I ~/.config/emerger/profiles.d/*.sh +User profiles. +.TP +.I ~/.config/emerger/hooks/pre.d/*.sh, ~/.config/emerger/hooks/post.d/*.sh +User hook scripts, run in name order before and after the managers. +.TP +.I ~/.config/emerger/managers.d/*.sh +Manager plugins. +.TP +.I ~/.config/emerger/ignore.list +Packages pacman never upgrades, one per line; other managers get an advisory. .TP -.I ~/.config/emerger/hooks/pre.d/*.sh, post.d/*.sh -User hook scripts. +.I share/profiles/*.sh +Shipped profiles, in the eMerger checkout. +.TP +.I ~/.cache/emerger/detected +Detection cache, valid for \fBEMERGER_CACHE_TTL\fR seconds. .TP .I ~/.local/state/emerger/emerger.log Log file. .TP .I ~/.local/state/emerger/history.jsonl One JSON record per run. +.TP +.I ~/.local/state/emerger/pkgs.before, pkgs.after, pkgs.diff +Installed packages before and after the last real run, and the difference +\fB\-\-changed\fR shows. +.TP +.I ~/.local/state/emerger/resume +Managers that completed in the last run, read by \fB\-\-resume\fR. +.TP +.I ~/.local/state/emerger/parallel-*.log +Output of each manager of a \fB\-\-parallel\fR run. +.TP +.I ~/.local/state/emerger/emerger.lock +Global lock (\fBflock\fR; the directory \fIemerger.lock.d\fR without it). .SH EXIT STATUS .TP -0 success +0 +Success. +.TP +1 +Runtime failure (sudo, lock, disk, interrupted) or aborted (a declined +safety prompt, no snapshot taken with \fB\-\-snapshot\fR). +.TP +2 +Argument parsing error. .TP -1 runtime failure +3 +One or more package managers failed. .TP -2 argument parsing error +4 +Reboot required (only with \fB\-\-reboot\-exit\fR). .SH SEE ALSO .BR cron (8), .BR systemd.timer (5) diff --git a/reference/third-party.md b/reference/third-party.md new file mode 100644 index 0000000..ba86c19 --- /dev/null +++ b/reference/third-party.md @@ -0,0 +1,6 @@ +# Third-party material + +eMerger ships no third-party code, asset or data. A change that adds some adds a row here: what it is, where it lives, its licence with the source checked, and what the licence asks of this project. + +| item | where | licence (source) | obligation | +|---|---|---|---| diff --git a/setup.ps1 b/setup.ps1 deleted file mode 100644 index 8fc134e..0000000 --- a/setup.ps1 +++ /dev/null @@ -1,69 +0,0 @@ -#Requires -Version 5.1 -<# -.SYNOPSIS - Install eMerger on Windows: register the `up` function, ensure execution - policy allows it, scaffold %APPDATA%\emerger. -#> -[CmdletBinding()] -param() - -$ErrorActionPreference = 'Stop' -$REPO = Split-Path -Parent $PSCommandPath -. "$REPO\src\pslib\UI.ps1" -. "$REPO\src\pslib\Sys.ps1" - -UI-Title 'eMerger setup (Windows)' - -# ExecutionPolicy fix. -$ep = Get-ExecutionPolicy -Scope CurrentUser -if ($ep -eq 'Restricted' -or $ep -eq 'Undefined') { - UI-Info "ExecutionPolicy is '$ep'; setting to RemoteSigned for CurrentUser." - try { - Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force - UI-Ok 'ExecutionPolicy updated.' - } catch { - UI-Warn "Could not change ExecutionPolicy: $($_.Exception.Message)" - } -} - -# PowerShell profile: add `up` function. -$profilePath = $PROFILE.CurrentUserAllHosts -$profileDir = Split-Path $profilePath -if (-not (Test-Path $profileDir)) { New-Item -ItemType Directory -Path $profileDir -Force | Out-Null } -if (-not (Test-Path $profilePath)) { New-Item -ItemType File -Path $profilePath -Force | Out-Null } - -$entry = "$REPO\src\emerger.ps1" -$existing = Get-Content $profilePath -Raw -ErrorAction SilentlyContinue -if ($existing -and $existing -match 'emerger\.ps1') { - UI-Ok "'up' already registered in $profilePath" -} else { - $block = @" - -# eMerger (https://github.com/MasterCruelty/eMerger) -function up { & "$entry" @args } -"@ - Add-Content -Path $profilePath -Value $block - UI-Ok "Added 'up' function to $profilePath" -} - -# Config + hooks + profiles skeleton. -$cfg = Join-Path $env:APPDATA 'emerger' -@('hooks\pre.d','hooks\post.d','profiles.d') | ForEach-Object { - $p = Join-Path $cfg $_ - if (-not (Test-Path $p)) { New-Item -ItemType Directory -Path $p -Force | Out-Null } -} - -$configFile = Join-Path $cfg 'config.ps1' -if (-not (Test-Path $configFile)) { - @' -# eMerger user config (Windows). Dot-sourced before argument parsing. -# Uncomment to set defaults. - -# $script:ArgsGlobal.Dev = $true -# $script:ArgsGlobal.NoTrash = $true -# $script:ArgsGlobal.Security = $true -'@ | Set-Content $configFile -Encoding UTF8 - UI-Ok "Created $configFile" -} - -UI-Info "Open a new PowerShell window (or: . `$PROFILE) and run: up --help" diff --git a/share/plugins/example.sh b/share/plugins/example.sh index 4576f9b..27b4236 100644 --- a/share/plugins/example.sh +++ b/share/plugins/example.sh @@ -2,21 +2,34 @@ # Example eMerger plugin. Copy to ~/.config/emerger/managers.d/.sh # and edit. The slug below becomes the manager name shown by eMerger. +# Read by the plugin loader. +# shellcheck disable=SC2034 PM_PLUGIN_SLUG=example +# Return 0 if the tool is installed on this system. pm_example_detect() { - # Return 0 if the tool is installed on this system. command -v example-tool >/dev/null 2>&1 } -pm_example_needs_sudo() { return 1; } # remove or flip to 0 if sudo is needed -pm_example_parallel() { return 0; } # safe to run concurrently with others -pm_example_dev() { return 1; } # return 0 to gate under --dev +# Return 0 if the tool needs root. Optional: without it, never. +pm_example_needs_sudo() { return 1; } -pm_example_icon() { printf '\xf0\x9f\x94\x8c'; } # plug emoji +# Return 0 if the tool can run beside other managers under --parallel. +pm_example_parallel() { return 0; } +# Return 0 to run the tool only under --dev. +pm_example_dev() { return 1; } + +# Return 0 if pm_example_run honours ARG_SECURITY. Without it, --security +# skips the plugin. +pm_example_security() { return 1; } + +# Print the section icon (a plug emoji). +pm_example_icon() { printf '\xf0\x9f\x94\x8c'; } + +# Refresh and upgrade through run_cmd, which honours --dry-run, --verbose, +# retries and logging. Return non-zero on failure. pm_example_run() { - # Use run_cmd so --dry-run, --verbose, retry, logging all work. run_cmd "example refresh" example-tool refresh || return 1 run_cmd "example upgrade" example-tool upgrade -y || return 1 return 0 diff --git a/share/profiles/home.ps1 b/share/profiles/home.ps1 index 9215b5d..278631e 100644 --- a/share/profiles/home.ps1 +++ b/share/profiles/home.ps1 @@ -1,2 +1,2 @@ -# description: PC fisso a casa - tutto, dev toolchains incluse +# description: everything: dev toolchains $script:ArgsGlobal.Dev = $true diff --git a/share/profiles/home.sh b/share/profiles/home.sh index fdca3cf..9143646 100644 --- a/share/profiles/home.sh +++ b/share/profiles/home.sh @@ -1,4 +1,7 @@ -# description: PC fisso a casa - tutto, in parallelo, anche firmware e dev +# shellcheck shell=bash +# description: everything: dev toolchains, firmware, parallel mode and the weather line +# Settings read by the entry point after sourcing. +# shellcheck disable=SC2034 ARG_DEV=1 ARG_FIRMWARE=1 ARG_PARALLEL=1 diff --git a/share/profiles/safe.ps1 b/share/profiles/safe.ps1 index 63db271..d927ea3 100644 --- a/share/profiles/safe.ps1 +++ b/share/profiles/safe.ps1 @@ -1,5 +1,5 @@ -# description: pre-presentazione - security only, niente cache/trash -$script:ArgsGlobal.Security = $true -$script:ArgsGlobal.Yes = $true -$script:ArgsGlobal.NoCache = $true -$script:ArgsGlobal.NoTrash = $true +# description: least change: security only, unattended, cache and trash left alone +$script:ArgsGlobal.Security = $true +$script:ArgsGlobal.Yes = $true +$script:ArgsGlobal.KeepCache = $true +$script:ArgsGlobal.KeepTrash = $true diff --git a/share/profiles/safe.sh b/share/profiles/safe.sh index d251954..22e18c0 100644 --- a/share/profiles/safe.sh +++ b/share/profiles/safe.sh @@ -1,6 +1,10 @@ -# description: pre-presentazione - solo security, niente flatpak/snap pesanti +# shellcheck shell=bash +# description: least change: security only, no firmware, skips flatpak and snap +# Settings read by the entry point after sourcing. +# shellcheck disable=SC2034 ARG_SECURITY=1 ARG_YES=1 -ARG_NO_CACHE=1 -ARG_NO_TRASH=1 +ARG_KEEP_CACHE=1 +ARG_KEEP_TRASH=1 ARG_NO_FIRMWARE=1 +ARG_EXCEPT="${ARG_EXCEPT:+$ARG_EXCEPT,}flatpak,snap" diff --git a/share/profiles/server.ps1 b/share/profiles/server.ps1 index 29b794c..b3403a2 100644 --- a/share/profiles/server.ps1 +++ b/share/profiles/server.ps1 @@ -1,8 +1,8 @@ -# description: headless / unattended - security, quiet, nessun prompt -$script:ArgsGlobal.Security = $true -$script:ArgsGlobal.Yes = $true -$script:ArgsGlobal.NoLogo = $true -$script:ArgsGlobal.NoInfo = $true -$script:ArgsGlobal.NoCache = $true -$script:ArgsGlobal.NoTrash = $true -$script:QUIET_LEVEL = 2 +# description: headless: quiet, security only, no prompts, cache and trash left alone +$script:ArgsGlobal.Security = $true +$script:ArgsGlobal.Yes = $true +$script:ArgsGlobal.NoLogo = $true +$script:ArgsGlobal.NoInfo = $true +$script:ArgsGlobal.KeepCache = $true +$script:ArgsGlobal.KeepTrash = $true +$script:QUIET_LEVEL = 2 diff --git a/share/profiles/server.sh b/share/profiles/server.sh index 1a59345..97fad95 100644 --- a/share/profiles/server.sh +++ b/share/profiles/server.sh @@ -1,10 +1,12 @@ -# description: headless/unattended - quiet, security, niente prompt, niente UI +# shellcheck shell=bash +# description: headless: quiet, security only, no prompts, no firmware +# Settings read by the entry point after sourcing. +# shellcheck disable=SC2034 ARG_SECURITY=1 ARG_YES=1 -ARG_QUIET=1 QUIET_LEVEL=2 ARG_NO_LOGO=1 ARG_NO_INFO=1 -ARG_NO_CACHE=1 -ARG_NO_TRASH=1 +ARG_KEEP_CACHE=1 +ARG_KEEP_TRASH=1 ARG_NO_FIRMWARE=1 diff --git a/share/profiles/work.ps1 b/share/profiles/work.ps1 index 72470ff..7e3fa8f 100644 --- a/share/profiles/work.ps1 +++ b/share/profiles/work.ps1 @@ -1,5 +1,5 @@ -# description: laptop al lavoro - security, unattended, niente cache/trash -$script:ArgsGlobal.Security = $true -$script:ArgsGlobal.Yes = $true -$script:ArgsGlobal.NoCache = $true -$script:ArgsGlobal.NoTrash = $true +# description: security only, unattended, cache and trash left alone +$script:ArgsGlobal.Security = $true +$script:ArgsGlobal.Yes = $true +$script:ArgsGlobal.KeepCache = $true +$script:ArgsGlobal.KeepTrash = $true diff --git a/share/profiles/work.sh b/share/profiles/work.sh index 9808bb5..fecb87e 100644 --- a/share/profiles/work.sh +++ b/share/profiles/work.sh @@ -1,6 +1,10 @@ -# description: laptop al lavoro - solo security, niente firmware/AUR, riavvio mai +# shellcheck shell=bash +# description: security only, unattended, no firmware, skips yay and paru +# Settings read by the entry point after sourcing. +# shellcheck disable=SC2034 ARG_SECURITY=1 ARG_YES=1 ARG_NO_FIRMWARE=1 -ARG_NO_CACHE=1 -ARG_NO_TRASH=1 +ARG_EXCEPT="${ARG_EXCEPT:+$ARG_EXCEPT,}yay,paru" +ARG_KEEP_CACHE=1 +ARG_KEEP_TRASH=1 diff --git a/src/emerger.ps1 b/src/emerger.ps1 index 8c30f22..21c9ff1 100644 --- a/src/emerger.ps1 +++ b/src/emerger.ps1 @@ -1,9 +1,9 @@ #Requires -Version 5.1 -[CmdletBinding()] -param( - [Parameter(ValueFromRemainingArguments = $true)] - [string[]]$Arguments -) +# No param block: an advanced script would bind -v, -V, -w and -err to +# the common parameters (-Verbose, -WarningAction...). Every word goes to $args. +# Profile function's @args hands `--only a,b` over as one array: join it +# back with commas, as the shell spelled it. +$Arguments = [string[]]@(foreach ($word in $args) { if ($word -is [array]) { @($word) -join ',' } else { $word } }) $ErrorActionPreference = 'Stop' @@ -15,164 +15,193 @@ $versionFile = Join-Path $script:EMERGER_ROOT 'VERSION' $script:EMERGER_VERSION = if (Test-Path $versionFile) { (Get-Content $versionFile -Raw).Trim() } else { '0.0.0' } $script:EMERGER_CONFIG = Join-Path $env:APPDATA 'emerger' -$script:EMERGER_CACHE = Join-Path $env:LOCALAPPDATA 'emerger\cache' $script:EMERGER_STATE = Join-Path $env:LOCALAPPDATA 'emerger\state' -foreach ($d in @($script:EMERGER_CONFIG, $script:EMERGER_CACHE, $script:EMERGER_STATE)) { - if (-not (Test-Path $d)) { New-Item -ItemType Directory -Path $d -Force | Out-Null } +# Elevated child (see Elevated.ps1): admin managers only, it creates no +# directory and loads no config.ps1, profile or hook. +$script:IS_ELEVATED_CHILD = ($Arguments.Count -gt 0 -and $Arguments[0] -eq '--elevated-child') +if (-not $script:IS_ELEVATED_CHILD) { + foreach ($dir in @($script:EMERGER_CONFIG, $script:EMERGER_STATE)) { + if (-not (Test-Path -LiteralPath $dir)) { [void][IO.Directory]::CreateDirectory($dir) } + } } # Load libs. -. (Join-Path $script:EMERGER_LIB 'UI.ps1') -. (Join-Path $script:EMERGER_LIB 'Log.ps1') -. (Join-Path $script:EMERGER_LIB 'Sys.ps1') -. (Join-Path $script:EMERGER_LIB 'Args.ps1') -. (Join-Path $script:EMERGER_LIB 'Packages.ps1') -. (Join-Path $script:EMERGER_LIB 'Clean.ps1') -. (Join-Path $script:EMERGER_LIB 'Hooks.ps1') -. (Join-Path $script:EMERGER_LIB 'Update.ps1') -. (Join-Path $script:EMERGER_LIB 'Notify.ps1') -. (Join-Path $script:EMERGER_LIB 'Summary.ps1') -. (Join-Path $script:EMERGER_LIB 'Doctor.ps1') -. (Join-Path $script:EMERGER_LIB 'Profiles.ps1') +foreach ($lib in @('ui\Term', 'ui\Text', 'ui\Print', 'ui\Monitor', 'ui\Prompt', 'managers\Progress', + 'Log', 'Sys', 'state\Lock', 'system\Preflight', 'Args', 'Run', + 'managers\Packages', 'state\Estimate', 'state\Metrics', 'clean\Size', + 'clean\Temp', 'clean\RecycleBin', 'Hooks', 'SelfUpdate', 'AutoUpdate', + 'system\Notify', 'Summary', 'state\History', 'system\Reboot', 'Doctor', + 'Profiles', 'Elevated')) { + . (Join-Path $script:EMERGER_LIB "$lib.ps1") +} + +if ($script:IS_ELEVATED_CHILD) { + Elevated-Restrict-Env + $script:RETRY_ATTEMPTS = 2; $script:RETRY_DELAY = 3; $script:MANAGER_TIMEOUT = 0 + exit (Elevated-Child $Arguments) +} + +# Defaults first, config.ps1 and profiles write into it. +$script:ArgsGlobal = Args-Parse @() + +# config.ps1 can change them. +$script:DISK_MIN_FREE_MB = 1024 +$script:BATTERY_MIN_PCT = 20 +$script:RETRY_ATTEMPTS = 2 +$script:RETRY_DELAY = 3 +$script:MANAGER_TIMEOUT = 0 # seconds per manager step, 0 = no limit # User config. -$userCfg = Join-Path $script:EMERGER_CONFIG 'config.ps1' -if (Test-Path $userCfg) { . $userCfg } +$userConfig = Join-Path $script:EMERGER_CONFIG 'config.ps1' +if (Test-Path -LiteralPath $userConfig) { . $userConfig } # Profile prescan (profile sets defaults, CLI wins). $profileName = Args-Prescan-Profile $Arguments -if ($profileName) { Load-Profile $profileName } +if ($profileName) { Profiles-Load $profileName } # Parse CLI flags. -$script:ArgsGlobal = Parse-Args $Arguments +$script:ArgsGlobal = Args-Parse $Arguments -Into $script:ArgsGlobal $script:Summary = New-Object System.Collections.Generic.List[PSCustomObject] +# --ascii changes the glyph table. +UI-Init + +# Numeric knobs from config.ps1 or the profile, validated. +foreach ($knob in @(@('DISK_MIN_FREE_MB', 1024), @('BATTERY_MIN_PCT', 20), @('RETRY_ATTEMPTS', 2), + @('RETRY_DELAY', 3), @('MANAGER_TIMEOUT', 0))) { + Sys-Knob-Int $knob[0] $knob[1] +} + +Args-Warn-Unsupported Log-Init # Subcommand-style short-circuits. if ($script:ArgsGlobal.Help) { Get-Content (Join-Path $script:EMERGER_LIB 'Help.txt') ; exit 0 } if ($script:ArgsGlobal.Version) { Write-Host "eMerger $script:EMERGER_VERSION"; exit 0 } -if ($script:ArgsGlobal.Errors) { Show-Errors; exit 0 } -if ($script:ArgsGlobal.History) { Show-History; exit 0 } +if ($script:ArgsGlobal.Errors) { Log-Show-Errors; exit 0 } +if ($script:ArgsGlobal.History) { History-Show; exit 0 } +if ($script:ArgsGlobal.Changed) { UI-Warn '--changed is not supported on Windows, nothing to show.'; exit 0 } if ($script:ArgsGlobal.Doctor) { $rc = Doctor-Run; exit $rc } -if ($script:ArgsGlobal.SelfUpdate) { $rc = Self-Update $script:EMERGER_ROOT; exit $rc } -if ($script:ArgsGlobal.AutoUpdate) { $rc = Setup-Task $script:EMERGER_ROOT; exit $rc } -if ($script:ArgsGlobal.ListProfiles) { List-Profiles; exit 0 } -if ($script:ArgsGlobal.Metrics) { - $hist = Join-Path $script:EMERGER_STATE 'history.jsonl' - if (-not (Test-Path $hist)) { UI-Err 'No history yet'; exit 1 } - $last = Get-Content $hist -Tail 1 | ConvertFrom-Json - $epoch = [int64](([DateTime]$last.ts).ToUniversalTime() - [DateTime]'1970-01-01').TotalSeconds - $tmp = "$($script:ArgsGlobal.Metrics).tmp" - $out = @() - $out += "# HELP emerger_last_run_timestamp_seconds Unix timestamp of the last eMerger run" - $out += "# TYPE emerger_last_run_timestamp_seconds gauge" - $out += "emerger_last_run_timestamp_seconds $epoch" - $out += "# HELP emerger_last_run_duration_seconds Duration of the last run" - $out += "# TYPE emerger_last_run_duration_seconds gauge" - $out += "emerger_last_run_duration_seconds $($last.duration)" - $out += "# HELP emerger_last_run_errors Manager failures in the last run" - $out += "# TYPE emerger_last_run_errors gauge" - $out += "emerger_last_run_errors $($last.errors)" - $out += "# HELP emerger_reboot_required Whether a reboot is pending (0/1)" - $out += "# TYPE emerger_reboot_required gauge" - $out += "emerger_reboot_required $($last.reboot)" - $out += "# HELP emerger_manager_ok Per-manager success (1=ok,0=fail)" - $out += "# TYPE emerger_manager_ok gauge" - foreach ($m in $last.managers) { - $v = if ($m.result -eq 'ok') { 1 } else { 0 } - $out += "emerger_manager_ok{manager=`"$($m.name)`"} $v" - } - $out | Set-Content -Path $tmp - Move-Item -Force $tmp $script:ArgsGlobal.Metrics - UI-Ok "metrics written to $($script:ArgsGlobal.Metrics)" - exit 0 -} -if ($script:ArgsGlobal.RebuildCache) { - Remove-Item $script:EMERGER_CACHE -Recurse -Force -ErrorAction SilentlyContinue - New-Item -ItemType Directory -Path $script:EMERGER_CACHE -Force | Out-Null - UI-Ok 'Detection cache cleared' +if ($script:ArgsGlobal.ListProfiles) { Profiles-List; exit 0 } +if ($script:ArgsGlobal.Changelog) { UI-Warn '--changelog is not supported on Windows, nothing to show.'; exit 0 } +if ($script:ArgsGlobal.Rollback) { UI-Warn '--rollback is not supported on Windows, nothing to revert.'; exit 0 } +if ($script:ArgsGlobal.Metrics) { $rc = Metrics-Export $script:ArgsGlobal.Metrics; exit $rc } +# One run per user at a time, taken before +# anything that changes the system or eMerger's state. Released in finally, +# and by the OS if the process dies. +try { $script:RunLock = Lock-Acquire } catch { + UI-Err "Cannot open the run lock $(Lock-Path): $($_.Exception.GetBaseException().Message)" + exit 1 } -if ($script:ArgsGlobal.Reboot) { - if (Reboot-Pending) { - UI-Warn 'Rebooting now.' - Restart-Computer -Force - exit 0 - } else { UI-Ok 'No reboot needed.'; exit 0 } +if (-not $script:RunLock) { + UI-Err "Another eMerger run is in progress (lock: $(Lock-Path))." + UI-Muted 'Wait for it to finish.' + exit 1 } - -# Elevation: relaunch elevated if any detected manager needs it. -if (Pkg-Need-Admin-Any -IncludeDev:$script:ArgsGlobal.Dev) { - if (-not (Sys-IsAdmin) -and -not $script:ArgsGlobal.DryRun) { - UI-Warn 'Admin privileges required by one of the detected managers. Relaunching elevatedโ€ฆ' - Log-Info 'relaunching elevated' - Sys-Start-Elevated (Join-Path $script:EMERGER_SRC 'emerger.ps1') $Arguments - exit 0 +# Set before every exit of the run below, so the finally block can tell an +# interrupted run from one that ended. +$script:HasRunEnded = $false +try { + if ($script:ArgsGlobal.SelfUpdate) { $rc = SelfUpdate-Run $script:EMERGER_ROOT; $script:HasRunEnded = $true; exit $rc } + if ($script:ArgsGlobal.AutoUpdate) { $rc = AutoUpdate-Register $script:EMERGER_ROOT; $script:HasRunEnded = $true; exit $rc } + if ($script:ArgsGlobal.RebuildCache) { UI-Muted 'Windows keeps no detection cache, nothing to clear.' } + if ($script:ArgsGlobal.Reboot) { + if (Reboot-Pending) { + if ($script:ArgsGlobal.DryRun) { UI-Sub '[dry-run] would reboot'; $script:HasRunEnded = $true; exit 0 } + UI-Warn 'Rebooting now.' + Restart-Computer -Force + $script:HasRunEnded = $true + exit 0 + } else { UI-Ok 'No reboot needed.'; $script:HasRunEnded = $true; exit 0 } } -} -# Battery check. -if (Sys-On-Battery) { - $pct = Sys-Battery-Percent - if ($pct -lt 20 -and -not $script:ArgsGlobal.Yes) { - UI-Warn "On battery at ${pct}%. Updates are I/O heavy." - $a = Read-Host ' Continue anyway? [y/N]' - if ($a -notmatch '^[Yy]') { UI-Muted 'Aborted.'; exit 0 } - } -} + if (-not (Preflight-Battery)) { $script:HasRunEnded = $true; exit 1 } + if (-not (Preflight-Disk)) { $script:HasRunEnded = $true; exit 1 } -# Main flow. -$start = [DateTime]::UtcNow + # Main flow. + $start = [DateTime]::UtcNow -if ($script:ArgsGlobal.Json) { - $script:ArgsGlobal.NoLogo = $true; $script:ArgsGlobal.NoInfo = $true; $script:QUIET_LEVEL = 3 -} -if (-not $script:ArgsGlobal.NoLogo -and $script:QUIET_LEVEL -lt 1) { - UI-Logo (Join-Path $script:EMERGER_SRC 'logo\logo.txt') -} -if ($script:QUIET_LEVEL -lt 2) { - if (-not $script:ArgsGlobal.NoInfo) { - UI-Muted ("{0} $(UI-Glyph dot) {1} $(UI-Glyph dot) {2}" -f (Sys-OS), (Sys-Arch), (Get-Date -Format 'yyyy-MM-dd HH:mm')) + if ($script:ArgsGlobal.Json) { + $script:ArgsGlobal.NoLogo = $true; $script:ArgsGlobal.NoInfo = $true; $script:QUIET_LEVEL = 3 + } + if (-not $script:ArgsGlobal.NoLogo -and $script:QUIET_LEVEL -lt 1) { + UI-Logo (Join-Path (Join-Path $script:EMERGER_SRC 'logo') 'logo.txt') + } + if ($script:QUIET_LEVEL -lt 2) { + $versionText = UI-Color cyan "eMerger v$script:EMERGER_VERSION" + if (-not $script:ArgsGlobal.NoInfo) { + UI-Header @((UI-Color bold (Sys-OS)), (Sys-Architecture), (Get-Date -Format 'yyyy-MM-dd HH:mm'), $versionText) + } else { + UI-Header @($versionText) + } } - UI-Muted ("eMerger v$script:EMERGER_VERSION $(UI-Glyph dot) github.com/MasterCruelty/eMerger") -} - -Hooks-Run 'pre' - -$detected = Pkg-Detect-All -IncludeDev:$script:ArgsGlobal.Dev -$total = $detected.Count -if ($total -eq 0) { UI-Warn 'No supported package managers detected.' } -$onlyList = @(); if ($script:ArgsGlobal.Only) { $onlyList = $script:ArgsGlobal.Only -split ',' | ForEach-Object { $_.Trim() } } -$exceptList = @(); if ($script:ArgsGlobal.Except) { $exceptList = $script:ArgsGlobal.Except -split ',' | ForEach-Object { $_.Trim() } } + if ($script:ArgsGlobal.Weather -and $script:QUIET_LEVEL -lt 1) { + $weather = Sys-Fetch-Weather + if ($weather) { UI-Muted $weather } + } -$filtered = @() -foreach ($m in $detected) { - if ($onlyList.Count -gt 0 -and ($onlyList -notcontains $m)) { continue } - if ($exceptList.Count -gt 0 -and ($exceptList -contains $m)) { UI-Muted "skip $m (--except)"; continue } - $filtered += $m -} -$detected = $filtered -$total = $detected.Count - -$i = 0 -foreach ($m in $detected) { - $i++ - UI-Step $i $total $m - $ok = Pkg-Run $m - $script:Summary.Add([pscustomobject]@{ Name = $m; Result = $(if ($ok) { 'ok' } else { 'fail' }) }) -} + Hooks-Run 'pre' + + $detected = Pkg-Detect-All -IncludeDev:$script:ArgsGlobal.Dev + $total = $detected.Count + if ($total -eq 0) { UI-Warn 'No supported package managers detected.' } + + $detected = Pkg-Select $detected + $total = $detected.Count + + # Unelevated: the admin managers run in one elevated child (Elevated.ps1), + # everything else, hooks included, stays in this process. + $needsElevation = -not $script:ArgsGlobal.DryRun -and -not (Sys-IsAdmin) + $adminManagers = @($detected | Where-Object { Pkg-Need-Admin $_ }) + $elevated = $null + + $step = 0 + foreach ($manager in $detected) { + $step++ + UI-Step $step $total $manager + if ($needsElevation -and (Pkg-Need-Admin $manager)) { + if (-not $elevated) { + UI-Warn "Admin privileges required by $($adminManagers -join ', '). Starting them elevated..." + Log-Info "elevating: $($adminManagers -join ',')" + $elevated = Elevated-Run $adminManagers + } + $result = $elevated[$manager] + Elevated-Show $manager $result + $script:Summary.Add([pscustomobject]@{ Name = $manager; Result = [string]$result.result; Secs = [int]$result.secs }) + continue + } + $started = [DateTime]::UtcNow + $isOk = Pkg-Run $manager + $seconds = Sys-Elapsed-Seconds $started + $script:Summary.Add([pscustomobject]@{ Name = $manager; Result = $(if ($isOk) { 'ok' } else { 'fail' }); Secs = $seconds }) + } -if (-not $script:ArgsGlobal.NoCache) { Clean-Temp } -if (-not $script:ArgsGlobal.NoTrash) { Clean-RecycleBin } + if (-not $script:ArgsGlobal.KeepCache) { Clean-Temp } + if (-not $script:ArgsGlobal.KeepTrash) { Clean-RecycleBin } -Hooks-Run 'post' + Hooks-Run 'post' -$duration = [int]([DateTime]::UtcNow - $start).TotalSeconds -Summary-Print $duration -Notify-Send-Result + $duration = Sys-Elapsed-Seconds $start + Summary-Print $duration + Notify-Send-Result -$errors = @($script:Summary | Where-Object { $_.Result -eq 'fail' }).Count -if ($errors -gt 0) { exit 3 } -if ($script:ArgsGlobal.RebootExit -and (Reboot-Pending)) { exit 4 } -exit 0 + $errors = Summary-Fail-Count + $script:HasRunEnded = $true + if ($errors -gt 0) { exit 3 } + if ($script:ArgsGlobal.RebootExit -and (Reboot-Pending)) { exit 4 } + exit 0 +} catch { + # Crashes keep their own error and exit code. + $script:HasRunEnded = $true + throw +} finally { + Lock-Release $script:RunLock + # Neither an exit nor an error: Ctrl-C stopped the script, whose finally + # blocks still run. Without this exit, pwsh -File reports 0. + if (-not $script:HasRunEnded) { + try { UI-Err 'Interrupted (SIGINT), stopping.' } catch { [Console]::Error.WriteLine('Interrupted (SIGINT), stopping.') } + try { Log-Warn 'interrupted by SIGINT' } catch {} + exit 1 + } +} diff --git a/src/emerger.sh b/src/emerger.sh index 7b8f678..7e72dd3 100755 --- a/src/emerger.sh +++ b/src/emerger.sh @@ -10,79 +10,42 @@ EMERGER_ROOT=$(dirname "$EMERGER_SRC") EMERGER_LIB="$EMERGER_SRC/lib" EMERGER_VERSION=$(cat "$EMERGER_ROOT/VERSION" 2>/dev/null || echo "0.0.0") +# The checkout's own code runs as this user, as root under sudo: refuse to start +# when another local user can rewrite it. Group write counts only outside the +# user's private group. +if [[ $(id -gn) == "$(id -un)" ]]; then + _tree_bad=$(find "$EMERGER_SRC" ! -type l \( -perm /002 -o \( -perm /020 ! -gid "$(id -g)" \) \) -print -quit 2>/dev/null || true) +else + _tree_bad=$(find "$EMERGER_SRC" ! -type l -perm /022 -print -quit 2>/dev/null || true) +fi +if [[ -n $_tree_bad ]]; then + printf 'eMerger: %s is writable by group or other, not run. Fix: chmod -R go-w "%s"\n' "$_tree_bad" "$EMERGER_SRC" >&2 + exit 1 +fi +unset _tree_bad + : "${XDG_CACHE_HOME:=$HOME/.cache}" : "${XDG_CONFIG_HOME:=$HOME/.config}" : "${XDG_STATE_HOME:=$HOME/.local/state}" EMERGER_CACHE="$XDG_CACHE_HOME/emerger" EMERGER_CONFIG="$XDG_CONFIG_HOME/emerger" EMERGER_STATE="$XDG_STATE_HOME/emerger" -mkdir -p "$EMERGER_CACHE" "$EMERGER_STATE" -# shellcheck source=lib/ui.sh -source "$EMERGER_LIB/ui.sh" -# shellcheck source=lib/log.sh -source "$EMERGER_LIB/log.sh" -# shellcheck source=lib/sys.sh -source "$EMERGER_LIB/sys.sh" -# shellcheck source=lib/progress.sh -source "$EMERGER_LIB/progress.sh" -# shellcheck source=lib/estimate.sh -source "$EMERGER_LIB/estimate.sh" -# shellcheck source=lib/retry.sh -source "$EMERGER_LIB/retry.sh" -# shellcheck source=lib/run.sh -source "$EMERGER_LIB/run.sh" -# shellcheck source=lib/args.sh -source "$EMERGER_LIB/args.sh" -# shellcheck source=lib/ignore.sh -source "$EMERGER_LIB/ignore.sh" -# shellcheck source=lib/packages.sh -source "$EMERGER_LIB/packages.sh" -# shellcheck source=lib/clean.sh -source "$EMERGER_LIB/clean.sh" -# shellcheck source=lib/hooks.sh -source "$EMERGER_LIB/hooks.sh" -# shellcheck source=lib/update.sh -source "$EMERGER_LIB/update.sh" -# shellcheck source=lib/notify.sh -source "$EMERGER_LIB/notify.sh" -# shellcheck source=lib/reboot.sh -source "$EMERGER_LIB/reboot.sh" -# shellcheck source=lib/diff.sh -source "$EMERGER_LIB/diff.sh" -# shellcheck source=lib/disk.sh -source "$EMERGER_LIB/disk.sh" -# shellcheck source=lib/snapshot.sh -source "$EMERGER_LIB/snapshot.sh" -# shellcheck source=lib/mirrors.sh -source "$EMERGER_LIB/mirrors.sh" -# shellcheck source=lib/resume.sh -source "$EMERGER_LIB/resume.sh" -# shellcheck source=lib/lock.sh -source "$EMERGER_LIB/lock.sh" -# shellcheck source=lib/doctor.sh -source "$EMERGER_LIB/doctor.sh" -# shellcheck source=lib/changelog.sh -source "$EMERGER_LIB/changelog.sh" -# shellcheck source=lib/report.sh -source "$EMERGER_LIB/report.sh" -# shellcheck source=lib/wizard.sh -source "$EMERGER_LIB/wizard.sh" -# shellcheck source=lib/profiles.sh -source "$EMERGER_LIB/profiles.sh" -# shellcheck source=lib/summary.sh -source "$EMERGER_LIB/summary.sh" -# shellcheck source=lib/tui.sh -source "$EMERGER_LIB/tui.sh" -# shellcheck source=lib/plugins.sh -source "$EMERGER_LIB/plugins.sh" -# shellcheck source=lib/metrics.sh -source "$EMERGER_LIB/metrics.sh" +# shellcheck source=lib/load.sh +source "$EMERGER_LIB/load.sh" all + +trust_home || exit 1 +mkdir -p "$EMERGER_CACHE" "$EMERGER_STATE" +# Log and history hold manager output: no other user reads them. +chmod 700 "$EMERGER_CACHE" "$EMERGER_STATE" # 1) User global config if [[ -f "$EMERGER_CONFIG/config.sh" ]]; then + trust_file "$EMERGER_CONFIG/config.sh" || exit 1 # shellcheck disable=SC1091 - source "$EMERGER_CONFIG/config.sh" + # `|| true`: a final `[[ test ]] && VAR=1` returns 1 and a failing line + # must not end the run silently under errexit. + source "$EMERGER_CONFIG/config.sh" || true fi # 2) Profile (if --profile seen in argv) - loaded BEFORE explicit flags so @@ -93,236 +56,218 @@ args_prescan_profile "$@" # 3) Explicit CLI flags args_parse "$@" -# Quiet-hours gating (user can set QUIET_HOURS="22:00-07:00" in config). -if [[ -n ${QUIET_HOURS:-} ]] && (( ARG_YES )); then - _now=$(date +%H%M) - _from=$(printf '%s' "${QUIET_HOURS%%-*}" | tr -d :) - _to=$(printf '%s' "${QUIET_HOURS##*-}" | tr -d :) - if (( _from < _to )); then - (( _now >= _from && _now < _to )) && { echo "quiet hours, skipping"; exit 0; } - else - (( _now >= _from || _now < _to )) && { echo "quiet hours, skipping"; exit 0; } - fi -fi +knobs_validate +# Config and profile may set NO_COLOR, EMERGER_EMOJI or ARG_ASCII. +ui_reinit + +quiet_hours_check SUDO_KEEPALIVE_PID=0 +# Stop the monitor and the sudo keep-alive, remove the capture and +# --parallel timing files, show the cursor and release the lock. EXIT trap. _cleanup() { ui_monitor_stop + run_cmd_cleanup + rm -f "$EMERGER_STATE"/parallel-*.secs 2>/dev/null || true + ui_cursor_show if (( SUDO_KEEPALIVE_PID > 0 )); then kill "$SUDO_KEEPALIVE_PID" 2>/dev/null || true fi lock_release } -trap _cleanup EXIT INT TERM + +# Stop the run on signal $1 (INT or TERM): end the parallel managers, then +# exit 1 so the EXIT trap removes temp files and releases the lock last. +_interrupted() { + trap '' INT TERM + local pid + # Manager first, so its subshell reaches its trap and cleans up. + for pid in "${_PARALLEL_PIDS[@]}"; do + pkill -TERM -P "$pid" 2>/dev/null || true + kill "$pid" 2>/dev/null || true + done + ui_monitor_stop + printf '\n' >&2 + ui_err "Interrupted (SIG$1), stopping." + log_warn "interrupted by SIG$1" + exit 1 +} +trap _cleanup EXIT +trap '_interrupted INT' INT +trap '_interrupted TERM' TERM log_init # Subcommand-style short-circuits. (( ARG_HELP )) && { cat "$EMERGER_LIB/help.txt"; exit 0; } (( ARG_VERSION )) && { printf 'eMerger %s\n' "$EMERGER_VERSION"; exit 0; } -(( ARG_ERR )) && { show_errors; exit 0; } -(( ARG_HISTORY )) && { show_history; exit 0; } +(( ARG_ERRORS )) && { log_show_errors; exit 0; } +(( ARG_HISTORY )) && { history_show; exit 0; } (( ARG_CHANGED )) && { diff_show; exit 0; } (( ARG_DOCTOR )) && { doctor_run; exit $?; } (( ARG_LIST_PROFILES )) && { profile_list; exit 0; } [[ -n $ARG_CHANGELOG ]] && { changelog_show "$ARG_CHANGELOG"; exit $?; } -(( ARG_UP )) && { self_update "$EMERGER_ROOT"; exit $?; } -(( ARG_AU )) && { setup_cron "$EMERGER_ROOT"; exit $?; } -(( ARG_RC )) && { rm -rf "$EMERGER_CACHE"; mkdir -p "$EMERGER_CACHE"; ui_ok "Detection cache cleared"; } -[[ -n $ARG_REPORT ]] && { report_export "$ARG_REPORT"; exit $?; } [[ -n $ARG_METRICS ]] && { metrics_export "$ARG_METRICS"; exit $?; } + +# Global lock, before anything that changes the system or eMerger's state. +if ! lock_acquire; then exit 1; fi + +(( ARG_SELF_UPDATE )) && { self_update "$EMERGER_ROOT"; exit $?; } +(( ARG_AUTO_UPDATE )) && { autoupdate_install "$EMERGER_ROOT"; exit $?; } +if (( ARG_REBUILD_CACHE )); then + if (( DRY_RUN )); then + ui_sub "[dry-run] rm -rf $EMERGER_CACHE" + else + rm -rf "$EMERGER_CACHE"; mkdir -p "$EMERGER_CACHE"; chmod 700 "$EMERGER_CACHE"; ui_ok "Detection cache cleared" + fi +fi (( ARG_ROLLBACK )) && { snapshot_rollback; exit $?; } if (( ARG_REBOOT )); then reboot_check - if (( REBOOT_NEEDED )); then - ui_warn "Rebooting now." - exec sudo reboot + if (( REBOOT_IS_NEEDED )); then + reboot_now; exit 0 else ui_ok "No reboot needed."; exit 0 fi fi -(( ARG_INTERACTIVE )) && tui_menu - -# First-run wizard (only if interactive and no config). -[[ ! -f $EMERGER_CONFIG/.wizard-done ]] && wizard_maybe_run - -# Global lock. -if ! lock_acquire; then exit 1; fi ignore_load plugins_load resume_load +# Each run starts a fresh resume cursor: only --resume reads the last one. +(( ARG_RESUME )) || resume_clear -# Build --only / --except filters (comma-separated manager names). -_arg_list_has() { - local list="$1" item="$2" x - IFS=',' read -r -a __al <<<"$list" - for x in "${__al[@]}"; do - [[ $x == "$item" ]] && return 0 - done - return 1 -} - -main() { - local start=$SECONDS - +# Print the logo, the system line and the weather, as flags and quiet level +# allow. --json turns all of them off. +_main_header() { if (( ARG_JSON )); then ARG_NO_LOGO=1; ARG_NO_INFO=1; QUIET_LEVEL=3 fi - if (( ! ARG_NO_LOGO )) && (( ! ARG_QUIET )); then + if (( ! ARG_NO_LOGO )); then ui_print_logo "$EMERGER_SRC/logo/logo.txt" fi if (( QUIET_LEVEL < 2 )); then if (( ! ARG_NO_INFO )); then - ui_muted "$(sys_distro) $(ui_glyph dot) $(uname -m) $(ui_glyph dot) $(date '+%Y-%m-%d %H:%M')" + ui_header "${C_BOLD}$(sys_read_distro)${C_RESET}" "$(uname -m)" "$(date '+%Y-%m-%d %H:%M')" \ + "${C_CYAN}eMerger v$EMERGER_VERSION${C_RESET}" + else + ui_header "${C_CYAN}eMerger v$EMERGER_VERSION${C_RESET}" fi - ui_muted "eMerger v$EMERGER_VERSION $(ui_glyph dot) github.com/MasterCruelty/eMerger" fi if (( ARG_WEATHER )) && sys_has curl; then - local w - w=$(curl -sS --max-time 3 'https://wttr.in/?format=%l:+%c+%t+%w+%m' 2>/dev/null || true) - [[ -n $w ]] && ui_muted "$w" + local weather + weather=$(curl -sS --max-time 3 'https://wttr.in/?format=%l:+%c+%t+%w+%m' 2>/dev/null | head -c 512 | run_sanitize || true) + weather=${weather//$'\n'/ } + [[ -n $weather ]] && ui_muted "$weather" + fi + return 0 +} + +# Close the run started at SECONDS value $1: package diff, summary, +# notification, ibus restart, resume cleanup. Exit 3 when a manager failed, +# 4 under --reboot-exit with a reboot pending. +_main_finish() { + local start="$1" + if (( ! DRY_RUN )); then + diff_snapshot "$DIFF_AFTER" 2>/dev/null || true + diff_compute "$DIFF_BEFORE" "$DIFF_AFTER" "$DIFF_LAST" 2>/dev/null || true fi - ignore_advisory + summary_print $((SECONDS - start)) + notify_send_result - # Battery safety. - if sys_on_battery; then - local pct; pct=$(sys_battery_percent) - if (( pct < 20 )) && (( ! ARG_YES )); then - ui_warn "On battery at ${pct}%. Updates are I/O heavy." - local ans - read -r -p " Continue anyway? [y/N]: " ans || ans=n - [[ $ans == [yY]* ]] || { ui_muted "Aborted."; exit 0; } - fi + # Restart ibus if running: updates to ibus/glib/gtk replace files on + # disk while the daemon keeps the old versions mapped in memory, which + # breaks input methods until the daemon is recycled. No-op if absent. + if (( ! DRY_RUN )) && command -v ibus >/dev/null 2>&1 && pgrep -x ibus-daemon >/dev/null 2>&1; then + # Keep the lock fd from the restarted daemon. + ibus restart >/dev/null 2>&1 9>&- || true + fi + + if (( SUMMARY_ERRORS == 0 )); then + resume_clear fi + if (( SUMMARY_ERRORS > 0 )); then + exit 3 + fi + if (( ARG_REBOOT_EXIT )) && (( ${REBOOT_IS_NEEDED:-0} == 1 )); then + exit 4 + fi +} + +# Run one update: header, pre-flight checks, sudo, snapshot, hooks, every +# selected manager, cleaning, then _main_finish, which sets the exit status. +main() { + local start=$SECONDS + + _main_header + + ignore_advisory + + battery_precheck disk_precheck + rpi_health_check # sudo keep-alive only if some manager needs it. - local need_sudo=0 m - for m in "${PKG_MANAGERS[@]}"; do - pkg_detect "$m" || continue - pkg_is_dev "$m" && (( ! ARG_DEV )) && continue - [[ $m == fwupd ]] && (( ! ARG_FIRMWARE )) && continue - if pkg_needs_sudo "$m"; then need_sudo=1; break; fi - done - if (( need_sudo )) && (( ! DRY_RUN )) && ! sys_is_root; then + local manager + if run_needs_sudo && (( ! DRY_RUN )) && ! sys_is_root; then if ! sudo -v; then ui_err "sudo authentication failed" exit 1 fi - ( while kill -0 "$$" 2>/dev/null; do sudo -n true 2>/dev/null; sleep 60; done ) & - SUDO_KEEPALIVE_PID=$! - disown "$SUDO_KEEPALIVE_PID" 2>/dev/null || true + run_sudo_keepalive fi (( ARG_REFRESH_MIRRORS )) && mirrors_refresh - (( ARG_SNAPSHOT )) && snapshot_create + # --snapshot asks for a safety net: no snapshot, no update. + if (( ARG_SNAPSHOT )) && ! snapshot_create; then + ui_err "No snapshot taken. Rerun without --snapshot to update anyway." + exit 1 + fi - # Snapshot installed packages for diff. - diff_snapshot "$DIFF_BEFORE" 2>/dev/null || true + # Snapshot installed packages for diff. A dry run keeps the last real diff. + (( DRY_RUN )) || diff_snapshot "$DIFF_BEFORE" 2>/dev/null || true hooks_run pre + # Filled by run_select in this scope. + # shellcheck disable=SC2034 local detected=() parallel=() serial=() - for m in "${PKG_MANAGERS[@]}"; do - pkg_detect "$m" || continue - if pkg_is_dev "$m" && (( ! ARG_DEV )); then continue; fi - if [[ $m == fwupd ]]; then - (( ARG_NO_FIRMWARE )) && continue - (( ARG_FIRMWARE )) || continue - fi - if (( ARG_RESUME )) && resume_has "$m"; then - ui_muted "skip $m (resume)"; continue - fi - if [[ -n $ARG_ONLY ]] && ! _arg_list_has "$ARG_ONLY" "$m"; then - continue - fi - if [[ -n $ARG_EXCEPT ]] && _arg_list_has "$ARG_EXCEPT" "$m"; then - ui_muted "skip $m (--except)"; continue - fi - detected+=("$m") - if (( ARG_PARALLEL )) && pkg_is_parallelizable "$m"; then - parallel+=("$m") - else - serial+=("$m") - fi - done + run_select - local total=${#detected[@]} + # Count the parallel group as one step. + local total=${#serial[@]} + (( ${#parallel[@]} > 0 )) && total=$(( total + 1 )) (( total == 0 )) && ui_warn "No supported package managers detected." - local idx=0 - for m in "${serial[@]}"; do - idx=$((idx+1)) - ui_step "$idx" "$total" "$m" - if pkg_run "$m"; then - SUMMARY_MANAGERS+=("$m"); SUMMARY_RESULTS+=("ok") - resume_mark "$m" + local step=0 step_start + for manager in "${serial[@]}"; do + step=$((step+1)) + ui_step "$step" "$total" "$manager" + step_start=$SECONDS + if pkg_run "$manager"; then + summary_add "$manager" ok $(( SECONDS - step_start )) + resume_mark "$manager" else - SUMMARY_MANAGERS+=("$m"); SUMMARY_RESULTS+=("fail") - SUMMARY_ERRORS=$((SUMMARY_ERRORS+1)) + summary_add "$manager" fail $(( SECONDS - step_start )) fi done if (( ${#parallel[@]} > 0 )); then - ui_step "$((idx+1))" "$total" "parallel: ${parallel[*]}" - local pids=() names=() logs=() - for m in "${parallel[@]}"; do - local lf="$EMERGER_STATE/parallel-$m.log" - ( pkg_run "$m" >"$lf" 2>&1 ) & - pids+=($!); names+=("$m"); logs+=("$lf") - done - local i - for i in "${!pids[@]}"; do - if wait "${pids[i]}"; then - SUMMARY_MANAGERS+=("${names[i]}"); SUMMARY_RESULTS+=("ok") - ui_done "${names[i]}" - resume_mark "${names[i]}" - else - SUMMARY_MANAGERS+=("${names[i]}"); SUMMARY_RESULTS+=("fail") - SUMMARY_ERRORS=$((SUMMARY_ERRORS+1)) - ui_fail "${names[i]}" - tail -n 10 "${logs[i]}" | progress_highlight >&2 || true - fi - done + run_parallel "$((step+1))" "$total" "${parallel[@]}" fi - (( ARG_NO_CACHE )) || clean_cache - (( ARG_NO_TRASH )) || clean_trash + (( ARG_KEEP_CACHE )) || clean_cache + (( ARG_KEEP_TRASH )) || clean_trash + if (( ARG_DEEP_CLEAN )); then clean_deep; fi hooks_run post - # Post-snapshot diff. - diff_snapshot "$DIFF_AFTER" 2>/dev/null || true - diff_compute "$DIFF_BEFORE" "$DIFF_AFTER" "$DIFF_LAST" 2>/dev/null || true - - summary_print $((SECONDS - start)) - notify_send_result - - # Restart ibus if it's running: updates to ibus/glib/gtk replace files on - # disk while the daemon keeps the old versions mapped in memory, which - # breaks input methods until the daemon is recycled. No-op if absent. - if command -v ibus >/dev/null 2>&1 && pgrep -x ibus-daemon >/dev/null 2>&1; then - ibus restart >/dev/null 2>&1 || true - fi - - # Clean resume file on full success. - if (( SUMMARY_ERRORS == 0 )); then - resume_clear - fi - - # Propagate failure upward. - if (( SUMMARY_ERRORS > 0 )); then - exit 3 - fi - if (( ARG_REBOOT_EXIT )) && (( ${REBOOT_NEEDED:-0} == 1 )); then - exit 4 - fi + _main_finish "$start" } main diff --git a/src/lib/args.sh b/src/lib/args.sh index 655ff06..a4d9cf5 100644 --- a/src/lib/args.sh +++ b/src/lib/args.sh @@ -1,99 +1,130 @@ #!/usr/bin/env bash # Argument parser. Shift-based so flags can take values. +# ARG_* are read by the modules that act on them. +# shellcheck disable=SC2034 ARG_HELP=0; ARG_VERSION=0 -ARG_UP=0; ARG_AU=0; ARG_ERR=0; ARG_RC=0; ARG_HISTORY=0 -ARG_NO_LOGO=0; ARG_NO_INFO=0; ARG_NO_CACHE=0; ARG_NO_TRASH=0 +ARG_SELF_UPDATE=0; ARG_AUTO_UPDATE=0; ARG_ERRORS=0; ARG_REBUILD_CACHE=0; ARG_HISTORY=0 +ARG_NO_LOGO=0; ARG_NO_INFO=0; ARG_KEEP_CACHE=0; ARG_KEEP_TRASH=0; ARG_DEEP_CLEAN=0 ARG_WEATHER=0 -ARG_QUIET=0; ARG_VERBOSE=0; ARG_DRY=0 -ARG_INTERACTIVE=0 ARG_FIRMWARE=0; ARG_NO_FIRMWARE=0; ARG_DEV=0; ARG_SECURITY=0 ARG_YES=0; ARG_PARALLEL=0 -ARG_NO_EMOJI=0 +ARG_ASCII=0 ARG_SNAPSHOT=0 ARG_REFRESH_MIRRORS=0 ARG_RESUME=0 ARG_CHANGED=0 ARG_DOCTOR=0 ARG_CHANGELOG="" -ARG_REPORT="" -ARG_PROFILE="" ARG_LIST_PROFILES=0 ARG_REBOOT=0 ARG_JSON=0 ARG_REBOOT_EXIT=0 ARG_ROLLBACK=0 ARG_DOWNLOAD_ONLY=0 +ARG_ACCEPT_LICENSES=0 ARG_METRICS="" ARG_ONLY="" ARG_EXCEPT="" QUIET_LEVEL=0 -_missing_value() { printf 'Missing value for %s\n' "$1" >&2; exit 2; } +# Print "Missing value for" flag $1 to stderr and exit 2. +_args_missing_value() { printf 'Missing value for %s\n' "$1" >&2; exit 2; } -# Expand short-flag bundles: "-nv" -> "-n -v", "-ynv" -> "-y -n -v". -# Only bundles whose letters all map to known single-letter short flags are -# expanded; anything else is passed through unchanged so the main parser can -# still error on unknown flags. +# Exit 2 when value $2 of flag $1 is empty: an empty filter or path would +# otherwise widen the run to everything. +_args_require_value() { + [[ -n $2 ]] || _args_missing_value "$1" +} + +# Return 0 if comma-separated list $1 names item $2. Spaces around each name +# are ignored ("apt, flatpak"). +args_list_has() { + local list="$1" item="$2" name + local -a items=() + IFS=',' read -r -a items <<<"$list" + for name in "${items[@]}"; do + name=${name#"${name%%[![:space:]]*}"} + name=${name%"${name##*[![:space:]]}"} + [[ $name == "$item" ]] && return 0 + done + return 1 +} + +# Set _ARGS_EXPANDED to arguments $@ with short-flag bundles expanded: "-nv" -> +# "-n -v". Only bundles made of known single-letter flags expand, anything +# else passes through unchanged so args_parse still refuses unknown flags. _args_expand_bundles() { - local a letters i ch expanded - local -a out=() - for a in "$@"; do + local arg letters i letter is_expanded + _ARGS_EXPANDED=() + for arg in "$@"; do # Known compound short flags that must stay atomic. - case "$a" in - -up|-au|-err|-rc|-nl|-ni|-nc|-nt|-qq|-qqq|-xyzzy|--*|-h|-V|-n|-v|-q|-y|-i|-w) - out+=("$a"); continue ;; + case "$arg" in + -up|-au|-err|-rc|-nl|-ni|-nc|-nt|-qq|-qqq|--*|-h|-V|-n|-v|-q|-y|-w) + _ARGS_EXPANDED+=("$arg"); continue ;; esac # Only consider single-dash, 3+ chars, no '=', no numerics. - if [[ $a =~ ^-[A-Za-z]{2,}$ ]]; then - letters="${a#-}"; expanded=1 + if [[ $arg =~ ^-[A-Za-z]{2,}$ ]]; then + letters="${arg#-}"; is_expanded=1 for (( i=0; i<${#letters}; i++ )); do - ch="${letters:i:1}" - case "$ch" in - h|V|n|v|q|y|i|w) : ;; - *) expanded=0; break ;; + letter="${letters:i:1}" + case "$letter" in + h|V|n|v|q|y|w) : ;; + *) is_expanded=0; break ;; esac done - if (( expanded )); then + if (( is_expanded )); then for (( i=0; i<${#letters}; i++ )); do - out+=("-${letters:i:1}") + _ARGS_EXPANDED+=("-${letters:i:1}") done continue fi fi - out+=("$a") + _ARGS_EXPANDED+=("$arg") done - printf '%s\n' "${out[@]}" } +# Set the ARG_* globals, QUIET_LEVEL, UI_VERBOSE and DRY_RUN from argument +# list $@. Exit 2 on an unknown flag or a value flag without its value. args_parse() { - local -a argv=() + # Actions and queries come from the command line only: config.sh and + # profiles hold settings, so a stray ARG_SELF_UPDATE=1 there cannot run + # an update of eMerger itself, or anything else, on every run. + ARG_HELP=0; ARG_VERSION=0; ARG_SELF_UPDATE=0; ARG_AUTO_UPDATE=0; ARG_ERRORS=0 + ARG_REBUILD_CACHE=0; ARG_HISTORY=0; ARG_DOCTOR=0; ARG_LIST_PROFILES=0 + ARG_CHANGED=0; ARG_CHANGELOG=""; ARG_METRICS=""; ARG_ROLLBACK=0; ARG_REBOOT=0 + _ARGS_EXPANDED=() if (( $# > 0 )); then - mapfile -t argv < <(_args_expand_bundles "$@") + _args_expand_bundles "$@" fi - set -- "${argv[@]}" + set -- "${_ARGS_EXPANDED[@]}" while (( $# > 0 )); do + # Read a value flag's --flag=VALUE form as --flag VALUE. case "$1" in - -h|--help|-help) ARG_HELP=1 ;; + --profile=*|--changelog=*|--metrics=*|--only=*|--except=*) + set -- "${1%%=*}" "${1#*=}" "${@:2}" ;; + esac + case "$1" in + -h|--help) ARG_HELP=1 ;; -V|--version) ARG_VERSION=1 ;; - -up|--self-update) ARG_UP=1 ;; - -au|--auto-update) ARG_AU=1 ;; - -err|--errors) ARG_ERR=1 ;; - -rc|--rebuild-cache) ARG_RC=1 ;; + -up|--self-update) ARG_SELF_UPDATE=1 ;; + -au|--auto-update) ARG_AUTO_UPDATE=1 ;; + -err|--errors) ARG_ERRORS=1 ;; + -rc|--rebuild-cache) ARG_REBUILD_CACHE=1 ;; --history) ARG_HISTORY=1 ;; -nl|--no-logo) ARG_NO_LOGO=1 ;; -ni|--no-info) ARG_NO_INFO=1 ;; - -nc|--no-cache) ARG_NO_CACHE=1 ;; - -nt|--no-trash) ARG_NO_TRASH=1 ;; + -nc|--keep-cache) ARG_KEEP_CACHE=1 ;; + -nt|--keep-trash) ARG_KEEP_TRASH=1 ;; + --deep-clean) ARG_DEEP_CLEAN=1 ;; -w|--weather) ARG_WEATHER=1 ;; - -q|--quiet) ARG_QUIET=1; QUIET_LEVEL=$(( QUIET_LEVEL + 1 )) ;; - -qq) ARG_QUIET=1; QUIET_LEVEL=2 ;; - -qqq) ARG_QUIET=1; QUIET_LEVEL=3 ;; - -v|--verbose) ARG_VERBOSE=1; UI_VERBOSE=1 ;; - -n|--dry-run) ARG_DRY=1; DRY_RUN=1 ;; - -i|--interactive) ARG_INTERACTIVE=1 ;; + -q|--quiet) QUIET_LEVEL=$(( QUIET_LEVEL + 1 )) ;; + -qq) QUIET_LEVEL=2 ;; + -qqq) QUIET_LEVEL=3 ;; + -v|--verbose) UI_VERBOSE=1 ;; + -n|--dry-run) DRY_RUN=1 ;; --firmware) ARG_FIRMWARE=1 ;; --no-firmware) ARG_NO_FIRMWARE=1 ;; @@ -101,7 +132,7 @@ args_parse() { --security) ARG_SECURITY=1 ;; -y|--yes) ARG_YES=1 ;; --parallel) ARG_PARALLEL=1 ;; - --no-emoji) ARG_NO_EMOJI=1; ui_reinit ;; + --ascii) ARG_ASCII=1; ui_reinit ;; --snapshot) ARG_SNAPSHOT=1 ;; --refresh-mirrors) ARG_REFRESH_MIRRORS=1 ;; @@ -110,27 +141,20 @@ args_parse() { --reboot) ARG_REBOOT=1 ;; --reboot-exit) ARG_REBOOT_EXIT=1 ;; --rollback) ARG_ROLLBACK=1 ;; - --download-only|--offline) ARG_DOWNLOAD_ONLY=1 ;; + --download-only) ARG_DOWNLOAD_ONLY=1 ;; + --accept-licenses) ARG_ACCEPT_LICENSES=1 ;; --json) ARG_JSON=1 ;; --doctor) ARG_DOCTOR=1 ;; --list-profiles) ARG_LIST_PROFILES=1 ;; - --profile) shift; [[ $# -gt 0 ]] || _missing_value --profile; ARG_PROFILE="$1" ;; - --profile=*) ARG_PROFILE="${1#*=}" ;; - --changelog) shift; [[ $# -gt 0 ]] || _missing_value --changelog; ARG_CHANGELOG="$1" ;; - --changelog=*) ARG_CHANGELOG="${1#*=}" ;; - --report) shift; [[ $# -gt 0 ]] || _missing_value --report; ARG_REPORT="$1" ;; - --report=*) ARG_REPORT="${1#*=}" ;; - --metrics) shift; [[ $# -gt 0 ]] || _missing_value --metrics; ARG_METRICS="$1" ;; - --metrics=*) ARG_METRICS="${1#*=}" ;; - --only) shift; [[ $# -gt 0 ]] || _missing_value --only; ARG_ONLY="$1" ;; - --only=*) ARG_ONLY="${1#*=}" ;; - --except) shift; [[ $# -gt 0 ]] || _missing_value --except; ARG_EXCEPT="$1" ;; - --except=*) ARG_EXCEPT="${1#*=}" ;; + --profile) shift; _args_require_value --profile "${1:-}" ;; + --changelog) shift; _args_require_value --changelog "${1:-}"; ARG_CHANGELOG="$1" ;; + --metrics) shift; _args_require_value --metrics "${1:-}"; ARG_METRICS="$1" ;; + --only) shift; _args_require_value --only "${1:-}"; ARG_ONLY="$1" ;; + # --except appends to the list from config.sh or the profile. + --except) shift; _args_require_value --except "${1:-}"; ARG_EXCEPT="${ARG_EXCEPT:+$ARG_EXCEPT,}$1" ;; - -xyzzy) - printf "Let's keep its memory alive.\n"; exit 0 ;; --) shift; break ;; *) printf 'Unknown argument: %s (try "up --help")\n' "$1" >&2 @@ -141,15 +165,17 @@ args_parse() { done } -# Pre-scan for --profile so the profile file can set defaults BEFORE the -# explicit CLI flags parsed by args_parse take effect (CLI wins). +# Set PROFILE_PRELOAD to the last --profile of argument list $@ (args_parse +# keeps the last too), read before args_parse so explicit flags override the +# profile's defaults. Words after -- are not read. args_prescan_profile() { local i argv=("$@") + PROFILE_PRELOAD="" for (( i=0; i<${#argv[@]}; i++ )); do case "${argv[i]}" in - --profile=*) PROFILE_PRELOAD="${argv[i]#*=}"; return ;; - --profile) PROFILE_PRELOAD="${argv[i+1]:-}"; return ;; + --profile=*) PROFILE_PRELOAD="${argv[i]#*=}" ;; + --profile) PROFILE_PRELOAD="${argv[i+1]:-}"; i=$(( i + 1 )) ;; + --) return ;; esac done - PROFILE_PRELOAD="" } diff --git a/src/lib/autoupdate.sh b/src/lib/autoupdate.sh new file mode 100644 index 0000000..f1b6a53 --- /dev/null +++ b/src/lib/autoupdate.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Auto-update scheduling: a weekly systemd user timer or a cron line. + +# Return 0 if install path $1 can be written inside the generated alias, +# cron line and systemd unit as a double-quoted string. Characters that +# quoting, cron or systemd would interpret are refused with a message. +install_path_check() { + local root="$1" bad=$'\'"$`%\\\n' + if [[ $root == *["$bad"]* ]]; then + ui_err "The install path contains a character eMerger cannot quote safely: $root" + ui_info "Move the checkout to a path without ' \" \$ \` % \\ or a newline and run this again." + return 1 + fi + return 0 +} + +# Print the user's crontab without the lines eMerger's own cron entry +# wrote ("... bash "/src/emerger.sh" -y -q -nl -ni"). Return 0 when +# there is no crontab yet, 1 (message on stderr) when it cannot be read, so a +# read failure never ends as a crontab holding the eMerger line alone. +autoupdate_crontab_others() { + local current rc=0 + current=$(LC_ALL=C crontab -l 2>&1) || rc=$? + if (( rc != 0 )); then + grep -q -i -E 'no crontab|no such file' <<<"$current" && return 0 + ui_err "Cannot read the current crontab, leaving it unchanged: $current" + return 1 + fi + printf '%s\n' "$current" | { grep -v -E '^0 10 \* \* 0 bash ".*/src/emerger\.sh" -y -q -nl -ni$' || true; } +} + +# Install a weekly run of "$1/src/emerger.sh": a systemd user timer when the +# user manager is reachable, else a crontab line. Honours DRY_RUN. +autoupdate_install() { + local root="$1" + ui_title "Enable auto-update" + install_path_check "$root" || return 1 + if sys_has systemctl && [[ -d /run/systemd/system ]] || sys_has systemctl && systemctl --user show-environment >/dev/null 2>&1; then + local unit_dir="$HOME/.config/systemd/user" + if (( DRY_RUN )); then + ui_sub "[dry-run] write $unit_dir/emerger.service and emerger.timer" + ui_sub "[dry-run] systemctl --user enable --now emerger.timer" + return 0 + fi + mkdir -p "$unit_dir" + cat >"$unit_dir/emerger.service" <"$unit_dir/emerger.timer" <" - return 2 - fi - ui_title "Changelog: $pkg" - if sys_has apt && apt changelog "$pkg" 2>/dev/null | head -n 60 | grep -q .; then - apt changelog "$pkg" 2>/dev/null | head -n 60 - return 0 - fi - if sys_has dnf; then - if dnf changelog "$pkg" 2>/dev/null | grep -q .; then - dnf changelog "$pkg" 2>/dev/null | head -n 60 - return 0 - fi - if dnf updateinfo info "$pkg" 2>/dev/null | grep -q .; then - dnf updateinfo info "$pkg" 2>/dev/null | head -n 60 - return 0 - fi - fi - if sys_has pacman; then - pacman -Qi "$pkg" 2>/dev/null || pacman -Si "$pkg" 2>/dev/null - ui_muted "(pacman has no native changelog; see https://archlinux.org/packages/)" - return 0 - fi - if sys_has brew; then - brew log --oneline -n 20 "$pkg" 2>/dev/null || brew info "$pkg" - return 0 - fi - ui_err "No supported package manager with changelog info found." - return 1 -} diff --git a/src/lib/clean.sh b/src/lib/clean.sh deleted file mode 100644 index 954a3e9..0000000 --- a/src/lib/clean.sh +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env bash -# Cache and trash cleaners. Safe-by-default: prompt unless -y. - -_clean_size_kb() { - [[ -d "$1" ]] || { echo 0; return; } - du -sk "$1" 2>/dev/null | awk '{print $1}' -} - -_clean_confirm() { - local prompt="$1" - if (( ARG_YES )); then echo y; return; fi - local ans - read -r -p " $prompt [y/N]: " ans || ans=n - printf '%s' "$ans" -} - -clean_cache() { - local target="$HOME/.cache" - ui_title "User cache" - if [[ ! -d $target ]]; then - ui_ok "empty"; return 0 - fi - local size; size=$(du -sh "$target" 2>/dev/null | cut -f1) - ui_muted "$target ($size)" - local ans; ans=$(_clean_confirm "Clean user cache?") - if [[ $ans == [yY]* ]]; then - local before; before=$(_clean_size_kb "$target") - if (( DRY_RUN )); then - ui_sub "[dry-run] would remove contents of $target" - else - find "$target" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true - fi - local after; after=$(_clean_size_kb "$target") - SUMMARY_FREED=$(( SUMMARY_FREED + before - after )) - ui_ok "cache cleaned" - else - ui_muted "skipped" - fi -} - -clean_trash() { - local files="$HOME/.local/share/Trash/files" - local info="$HOME/.local/share/Trash/info" - ui_title "Trash" - if [[ ! -d $files ]]; then - ui_ok "empty"; return 0 - fi - local count - count=$(find "$files" -mindepth 1 -maxdepth 1 2>/dev/null | wc -l) - if (( count == 0 )); then - ui_ok "empty"; return 0 - fi - local size; size=$(du -sh "$files" 2>/dev/null | cut -f1) - ui_muted "$files ($size, $count items)" - local ans; ans=$(_clean_confirm "Empty trash?") - if [[ $ans == [yY]* ]]; then - local before; before=$(_clean_size_kb "$files") - if (( DRY_RUN )); then - ui_sub "[dry-run] would empty trash" - else - find "$files" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true - [[ -d $info ]] && find "$info" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true - fi - local after; after=$(_clean_size_kb "$files") - SUMMARY_FREED=$(( SUMMARY_FREED + before - after )) - ui_ok "trash emptied" - else - ui_muted "skipped" - fi -} diff --git a/src/lib/clean/cache.sh b/src/lib/clean/cache.sh new file mode 100644 index 0000000..4389063 --- /dev/null +++ b/src/lib/clean/cache.sh @@ -0,0 +1,169 @@ +#!/usr/bin/env bash +# User cache cleaning: a menu of ~/.cache entries, biggest first. Prompts +# before deleting unless -y. + +# ~/.cache entries to leave alone (names or globs). ~/.cache/emerger is +# always kept. +: "${CACHE_EXCLUDE:=}" +: "${CACHE_MENU_ROWS:=12}" + +# Return 0 if ~/.cache entry name $1 is kept: emerger always, else any +# glob of CACHE_EXCLUDE (comma, space or tab separated) that matches it. +_clean_is_excluded() { + local name="$1" pattern + [[ $name == emerger ]] && return 0 + local -a patterns=() + # read -a splits without pathname expansion: a pattern never globs the cwd. + IFS=$', \t\n' read -r -a patterns <<<"$CACHE_EXCLUDE" + for pattern in ${patterns[@]+"${patterns[@]}"}; do + # shellcheck disable=SC2053 + [[ $name == $pattern ]] && return 0 + done + return 1 +} + +# Parse "1 3 5-7", "a" or "n" against a menu of $2 rows into _CLEAN_PICK: +# 1-based, ascending, each row once. Numbers are decimal (leading zeros +# allowed), out-of-range rows are dropped. +_clean_parse_pick() { + local input="$1" max="$2" token first last i + _CLEAN_PICK=() + input=${input//,/ } + case "${input,,}" in + a|all|'*') for (( i=1; i<=max; i++ )); do _CLEAN_PICK+=("$i"); done; return 0 ;; + ''|n|none|no) return 0 ;; + esac + local -a seen=() tokens=() + IFS=$' \t' read -r -a tokens <<<"$input" + for token in ${tokens[@]+"${tokens[@]}"}; do + if [[ $token =~ ^([0-9]+)-([0-9]+)$ ]]; then + first=$(( 10#${BASH_REMATCH[1]} )); last=$(( 10#${BASH_REMATCH[2]} )) + elif [[ $token =~ ^[0-9]+$ ]]; then + first=$(( 10#$token )); last=$first + else + continue + fi + (( first < 1 )) && first=1 + (( last > max )) && last=$max + for (( i=first; i<=last; i++ )); do seen[i]=1; done + done + for i in "${!seen[@]}"; do _CLEAN_PICK+=("$i"); done + return 0 +} + +# Offer the ~/.cache entries as a numbered menu, biggest first, and remove +# the rows picked (all of them under -y). Adds the space freed to SUMMARY_FREED_KB. +clean_cache() { + local target="$HOME/.cache" + if [[ ! -d $target ]]; then + ui_title "User cache"; ui_ok "empty"; return 0 + fi + + # Biggest first, one du for everything. + local -a names=() sizes=() kept=() + local total=0 + _clean_cache_scan "$target" + + ui_section "" "User cache" "$(_clean_format_kb "$total")" + if (( ${#names[@]} == 0 )) || (( total < 64 )); then + ui_ok "already clean"; return 0 + fi + + local -a menu_names=() menu_sizes=() menu_paths=() + _clean_cache_menu + + local max=${menu_sizes[0]} row_count=${#menu_names[@]} + (( max < 1 )) && max=1 + if (( QUIET_LEVEL < 1 )) && (( ! ARG_YES )); then + _clean_cache_print + fi + + local pick + if (( ARG_YES )); then + pick=all + else + ui_ask "Clean which?" "a/N" "a = all, n = none, or numbers like 1 3 5-7" || true + pick=$UI_ANSWER + fi + _clean_parse_pick "$pick" "$row_count" + if (( ${#_CLEAN_PICK[@]} == 0 )); then + ui_muted "skipped"; return 0 + fi + + _clean_cache_remove "$target" +} + +# Fill clean_cache's names, sizes (KiB) and kept with the entries of cache +# directory $1, biggest first, and add their sizes to its total. Excluded +# entries go to kept, entries under 16 KiB are left out. +_clean_cache_scan() { + local target="$1" kb path name + while IFS=$'\t' read -r kb path; do + [[ -z $path ]] && continue + name=${path##*/} + if _clean_is_excluded "$name"; then kept+=("$name"); continue; fi + (( kb < 16 )) && continue + names+=("$name"); sizes+=("$kb"); total=$(( total + kb )) + done < <(du -sk -- "$target"/* "$target"/.[!.]* 2>/dev/null | sort -rn) + return 0 +} + +# Fill clean_cache's menu_names, menu_sizes and menu_paths from its names +# and sizes: the first CACHE_MENU_ROWS rows, the rest lumped into one +# "N others" row whose path lists them separated by "/", which no entry name holds. +_clean_cache_menu() { + local rows=${#names[@]} i + (( rows > CACHE_MENU_ROWS )) && rows=$CACHE_MENU_ROWS + for (( i=0; i rows )); then + local rest=0 rest_list="" + for (( i=rows; i<${#names[@]}; i++ )); do + rest=$(( rest + sizes[i] )); rest_list+="${names[i]}/" + done + menu_names+=("$(( ${#names[@]} - rows )) others"); menu_sizes+=("$rest"); menu_paths+=("$rest_list") + fi +} + +# Print clean_cache's menu, one bar per row scaled to its max, then the +# kept entries. +_clean_cache_print() { + local i + for (( i=0; i 0 )); then + local kept_text; printf -v kept_text '%s ' "${kept[@]}" + ui_muted "kept: ${kept_text% }" + fi +} + +# Remove the rows of clean_cache's menu picked in _CLEAN_PICK from cache +# directory $1 (listed only under --dry-run) and add the space freed to +# SUMMARY_FREED_KB. +_clean_cache_remove() { + local target="$1" + local before freed=0 row part + before=$(_clean_size_kb "$target") + local -a parts=() + for row in "${_CLEAN_PICK[@]}"; do + IFS=/ read -r -a parts <<<"${menu_paths[row-1]}" + for part in "${parts[@]}"; do + [[ -z $part ]] && continue + if (( DRY_RUN )); then + ui_sub "[dry-run] would remove $target/$part" + else + rm -rf -- "${target:?}/$part" 2>/dev/null || true + fi + done + done + if (( ! DRY_RUN )); then + freed=$(( before - $(_clean_size_kb "$target") )) + (( freed < 0 )) && freed=0 + SUMMARY_FREED_KB=$(( SUMMARY_FREED_KB + freed )) + fi + ui_done "cache cleaned" "${#_CLEAN_PICK[@]} item(s), $(_clean_format_kb "$freed")" +} diff --git a/src/lib/clean/deep.sh b/src/lib/clean/deep.sh new file mode 100644 index 0000000..18e1111 --- /dev/null +++ b/src/lib/clean/deep.sh @@ -0,0 +1,190 @@ +#!/usr/bin/env bash +# --deep-clean: system leftovers a normal run does not touch. Every task +# asks first unless -y. + +# --deep-clean. Task names for DEEP_CLEAN_SKIP: +# journal kernels residual snap docker podman coredumps npm go +: "${JOURNAL_MAX_SIZE:=200M}" +: "${DEEP_CLEAN_SKIP:=}" + +# Return 0 when task key $1 is listed in DEEP_CLEAN_SKIP (comma, space or +# tab separated, compared literally). +_deep_is_skipped() { + local key + local -a keys=() + # read -a splits without pathname expansion: a key never globs the cwd. + IFS=$', \t\n' read -r -a keys <<<"${DEEP_CLEAN_SKIP:-}" + for key in ${keys[@]+"${keys[@]}"}; do [[ $key == "$1" ]] && return 0; done + return 1 +} + +# Ask "label $2?" with detail $3 and run command $4... on yes, under label $2. +# Skip silently when DEEP_CLEAN_SKIP lists task key $1, else count the offer +# in _DEEP_TASK_COUNT. +_deep_task() { + local key="$1" label="$2" detail="$3"; shift 3 + _deep_is_skipped "$key" && return 0 + _DEEP_TASK_COUNT=$(( _DEEP_TASK_COUNT + 1 )) + if ui_confirm "$label?" n "$detail"; then + run_cmd "$label" "$@" || true + else + ui_muted "skipped" + fi +} + +# Print the docker/podman command line for $1, one word per line: plain if +# the daemon answers, else sudo (probed with sudo -n, never under --dry-run, +# where sudo is assumed). Empty when the daemon is not reachable. +_deep_container_cmd() { + local bin="$1" + if "$bin" info >/dev/null 2>&1; then + printf '%s' "$bin" + elif sys_is_root; then + return 0 + elif (( DRY_RUN )) || sudo -n "$bin" info >/dev/null 2>&1; then + printf 'sudo\n%s' "$bin" + fi +} + +# Offer each --deep-clean task that has something to remove, then add the +# growth of free space on / to SUMMARY_FREED_KB (not under --dry-run). +clean_deep() { + local sudo_cmd free_before free_after + sudo_cmd=$(sys_sudo_prefix) + ui_title "Deep clean" + _DEEP_TASK_COUNT=0 + free_before=$(sys_free_space k /) + + _deep_journal + _deep_kernels + _deep_residual + _deep_snap + _deep_containers + _deep_coredumps + _deep_devcaches + + if (( _DEEP_TASK_COUNT == 0 )); then + ui_ok "nothing to clean" + return 0 + fi + free_after=$(sys_free_space k /) + if [[ -n $free_before && -n $free_after ]] && (( ! DRY_RUN )) && (( free_after > free_before )); then + SUMMARY_FREED_KB=$(( SUMMARY_FREED_KB + free_after - free_before )) + ui_ok "freed $(_clean_format_kb $(( free_after - free_before ))) on /" + fi + return 0 +} + +# Deep clean tasks, called by clean_deep only: each reads its local sudo_cmd +# (privilege prefix) and returns 0, offered or not. + +# Offer to shrink the systemd journal to JOURNAL_MAX_SIZE when it is larger. +_deep_journal() { + if sys_has journalctl; then + local usage + # "take up 1.5G" or, under 1 KiB, "take up 512B". + usage=$({ journalctl --disk-usage 2>/dev/null || true; } | sed -nE 's/.*take up ([0-9.]+[KMGTPE]?)B?.*/\1/p' | head -n 1) + if [[ -n $usage ]]; then + local usage_bytes limit_bytes + usage_bytes=$(numfmt --from=iec "$usage" 2>/dev/null || echo 0) + limit_bytes=$(numfmt --from=iec "$JOURNAL_MAX_SIZE" 2>/dev/null || echo 0) + if (( usage_bytes > limit_bytes )); then + _deep_task journal "Shrink journal to $JOURNAL_MAX_SIZE" "(now $usage)" \ + $sudo_cmd journalctl --vacuum-size="$JOURNAL_MAX_SIZE" + fi + fi + fi + return 0 +} + +# Offer to remove installed kernels beyond the newest two (dnf, zypper). +_deep_kernels() { + if sys_has dnf; then + local old_count + old_count=$({ dnf repoquery --installonly --latest-limit=-2 -q 2>/dev/null || true; } | wc -l) + (( old_count > 0 )) && _deep_task kernels "Remove old kernels" "($old_count packages, keeps 2)" \ + $sudo_cmd dnf remove -y --oldinstallonly --setopt installonly_limit=2 + elif sys_has zypper; then + _deep_task kernels "Purge old kernels" "(zypper purge-kernels)" $sudo_cmd zypper --non-interactive purge-kernels + fi + return 0 +} + +# Offer to purge the configs dpkg keeps for removed packages (state "rc"). +_deep_residual() { + if sys_has dpkg-query; then + local -a rc_pkgs=() + mapfile -t rc_pkgs < <(dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' 2>/dev/null | awk '$1=="rc"{print $2}') + if (( ${#rc_pkgs[@]} > 0 )); then + _deep_task residual "Purge leftover configs" "(${#rc_pkgs[@]} removed packages)" \ + $sudo_cmd dpkg --purge "${rc_pkgs[@]}" + fi + fi + return 0 +} + +# Offer to remove the disabled revisions snap keeps, often GBs of them. +_deep_snap() { + if sys_has snap; then + local -a revisions=() + mapfile -t revisions < <(snap list --all 2>/dev/null | awk '/disabled/{print $1" "$3}') + if (( ${#revisions[@]} > 0 )); then + local -a rev_args=() revision + for revision in "${revisions[@]}"; do rev_args+=("${revision%% *}" "${revision##* }"); done + _deep_task snap "Remove disabled snap revisions" "(${#revisions[@]})" \ + bash -c 'sc=$1; shift; while (( $# >= 2 )); do $sc snap remove "$1" --revision="$2" || exit 1; shift 2; done' \ + _ "$sudo_cmd" "${rev_args[@]}" + fi + fi + return 0 +} + +# Offer to prune dangling images and build cache of docker and podman. +_deep_containers() { + local bin + for bin in docker podman; do + sys_has "$bin" || continue + local -a command=() + mapfile -t command < <(_deep_container_cmd "$bin") + if (( ${#command[@]} == 0 )); then + ui_muted "$bin: daemon not reachable (not in the $bin group?), skipped" + continue + fi + local reclaim="" + # Under --dry-run a sudo command line is not run, not even to read. + if [[ ${command[0]} != sudo ]] || (( ! DRY_RUN )); then + reclaim=$({ "${command[@]}" system df --format '{{.Type}}|{{.Reclaimable}}' 2>/dev/null || true; } | awk -F'|' ' + $1 == "Images" || $1 ~ /^Build/ { + v = $2; sub(/ *\(.*/, "", v) + printf "%s%s %s", sep, ($1 == "Images" ? "images" : "build cache"), v; sep = ", " + }') + fi + _deep_task "$bin" "Prune $bin dangling images + build cache" "(reclaimable: ${reclaim:-?})" \ + bash -c '"$@" image prune -f && { "$@" builder prune -f 2>/dev/null || true; }' _ "${command[@]}" + done + return 0 +} + +# Offer to delete systemd crash dumps. +_deep_coredumps() { + if [[ -d /var/lib/systemd/coredump ]]; then + local core_count + core_count=$({ find /var/lib/systemd/coredump -type f 2>/dev/null || true; } | wc -l) + (( core_count > 0 )) && _deep_task coredumps "Delete crash dumps" "($core_count files)" \ + $sudo_cmd find /var/lib/systemd/coredump -type f -delete + fi + return 0 +} + +# Offer to clean the npm and Go caches kept outside ~/.cache. +_deep_devcaches() { + if sys_has npm && [[ -d $HOME/.npm/_cacache ]]; then + _deep_task npm "Clean npm cache" "($(_clean_size_human "$HOME/.npm/_cacache"))" npm cache clean --force + fi + if sys_has go; then + local gocache; gocache=$(go env GOCACHE 2>/dev/null || true) + [[ -n $gocache && -d $gocache && $gocache != "$HOME/.cache/"* ]] && \ + _deep_task go "Clean Go build cache" "($(_clean_size_human "$gocache"))" go clean -cache + fi + return 0 +} diff --git a/src/lib/clean/size.sh b/src/lib/clean/size.sh new file mode 100644 index 0000000..188c778 --- /dev/null +++ b/src/lib/clean/size.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Size of a path on disk and its short human-readable form. + +# Print the size of path $1 in KiB, 0 when it is missing. du exits non-zero +# on any unreadable entry: its partial total is still the best figure. +_clean_size_kb() { + [[ -e "$1" ]] || { echo 0; return; } + { du -sk "$1" 2>/dev/null || true; } | awk 'NR == 1 { n = $1 + 0 } END { print n + 0 }' +} + +# Print the human-readable size of path $1, empty when du prints nothing. +_clean_size_human() { + { du -sh "$1" 2>/dev/null || true; } | cut -f1 +} + +# Print KiB count $1 as 1.5G, 42M or 512K (G with one decimal, M and K +# whole, rounded down). +_clean_format_kb() { + local kb="$1" + if (( kb >= 1048576 )); then + printf '%d.%dG' $(( kb / 1048576 )) $(( kb % 1048576 * 10 / 1048576 )) + elif (( kb >= 1024 )); then + printf '%dM' $(( kb / 1024 )) + else + printf '%dK' "$kb" + fi +} diff --git a/src/lib/clean/trash.sh b/src/lib/clean/trash.sh new file mode 100644 index 0000000..594f2b0 --- /dev/null +++ b/src/lib/clean/trash.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# Trash emptying, after a prompt unless -y. + +# Empty the user's Trash after a prompt: the freedesktop Trash on Linux, +# ~/.Trash on macOS (no info directory there). +clean_trash() { + local files="$HOME/.local/share/Trash/files" + local info="$HOME/.local/share/Trash/info" + if sys_is_macos; then files="$HOME/.Trash"; info=""; fi + ui_title "Trash" + if [[ ! -d $files ]]; then + ui_ok "empty"; return 0 + fi + local listing count=0 rc=0 + listing=$(find "$files" -mindepth 1 -maxdepth 1 2>/dev/null) || rc=$? + [[ -n $listing ]] && count=$(wc -l <<<"$listing") + if (( count == 0 && rc != 0 )); then + # macOS denies ~/.Trash to a terminal without Full Disk Access. + if sys_is_macos; then + ui_warn "cannot read the Trash (macOS privacy settings)" + else + ui_warn "cannot read the Trash" + fi + return 0 + fi + if (( count == 0 )); then + ui_ok "empty"; return 0 + fi + local size; size=$(_clean_size_human "$files") + ui_muted "$files" + if ui_confirm "Empty trash?" n "($size, $count items)"; then + local before; before=$(_clean_size_kb "$files") + if (( DRY_RUN )); then + ui_sub "[dry-run] would empty trash" + else + find "$files" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true + [[ -n $info && -d $info ]] && find "$info" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true + fi + local after freed; after=$(_clean_size_kb "$files") + freed=$(( before - after )) + (( freed < 0 )) && freed=0 + SUMMARY_FREED_KB=$(( SUMMARY_FREED_KB + freed )) + ui_done "trash emptied" "$size" + else + ui_muted "skipped" + fi +} diff --git a/src/lib/diff.sh b/src/lib/diff.sh deleted file mode 100644 index fa89ce4..0000000 --- a/src/lib/diff.sh +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env bash -# Snapshot installed packages before/after; compute diff on demand. - -: "${DIFF_BEFORE:=$EMERGER_STATE/pkgs.before}" -: "${DIFF_AFTER:=$EMERGER_STATE/pkgs.after}" -: "${DIFF_LAST:=$EMERGER_STATE/pkgs.diff}" - -diff_snapshot() { - local out="$1" - : >"$out" - if sys_has dpkg-query; then - dpkg-query -W -f='apt\t${Package}\t${Version}\n' 2>/dev/null >>"$out" - fi - if sys_has pacman; then - pacman -Q 2>/dev/null | awk '{print "pacman\t"$1"\t"$2}' >>"$out" - fi - if sys_has rpm; then - rpm -qa --qf 'rpm\t%{NAME}\t%{VERSION}-%{RELEASE}\n' 2>/dev/null >>"$out" - fi - if sys_has flatpak; then - flatpak list --columns=application,version 2>/dev/null | awk -F'\t' 'NR>1 || tolower($1) !~ /^application$/ {if ($1!="") print "flatpak\t"$1"\t"$2}' >>"$out" - fi - if sys_has snap; then - snap list 2>/dev/null | tail -n +2 | awk '{print "snap\t"$1"\t"$2}' >>"$out" - fi - if sys_has brew; then - brew list --versions 2>/dev/null | awk '{print "brew\t"$1"\t"$2}' >>"$out" - fi - sort -o "$out" "$out" 2>/dev/null || true -} - -diff_compute() { - local before="$1" after="$2" out="$3" - : >"$out" - [[ -f $before && -f $after ]] || return 0 - # Build maps by "mgr\tname" -> version - awk -F'\t' '{print $1"\t"$2"\t"$3}' "$before" | sort -u >"${out}.b" - awk -F'\t' '{print $1"\t"$2"\t"$3}' "$after" | sort -u >"${out}.a" - # added - comm -13 <(awk -F'\t' '{print $1"\t"$2}' "${out}.b") <(awk -F'\t' '{print $1"\t"$2}' "${out}.a") | while IFS=$'\t' read -r mgr name; do - local v; v=$(awk -F'\t' -v m="$mgr" -v n="$name" '$1==m&&$2==n{print $3; exit}' "${out}.a") - printf '+\t%s\t%s\t%s\n' "$mgr" "$name" "$v" >>"$out" - done - # removed - comm -23 <(awk -F'\t' '{print $1"\t"$2}' "${out}.b") <(awk -F'\t' '{print $1"\t"$2}' "${out}.a") | while IFS=$'\t' read -r mgr name; do - local v; v=$(awk -F'\t' -v m="$mgr" -v n="$name" '$1==m&&$2==n{print $3; exit}' "${out}.b") - printf -- '-\t%s\t%s\t%s\n' "$mgr" "$name" "$v" >>"$out" - done - # upgraded: same mgr+name, different version - join -t$'\t' -j1 <(awk -F'\t' '{print $1"_"$2"\t"$3}' "${out}.b" | sort) \ - <(awk -F'\t' '{print $1"_"$2"\t"$3}' "${out}.a" | sort) \ - | awk -F'\t' '$2!=$3{split($1,x,"_"); print "~\t"x[1]"\t"x[2]"\t"$2" -> "$3}' >>"$out" - rm -f "${out}.a" "${out}.b" -} - -diff_show() { - local f="${1:-$DIFF_LAST}" - if [[ ! -s $f ]]; then - ui_muted "No package changes recorded." - return - fi - ui_title "Package changes" - local added removed upgraded - added=$(grep -c '^+' "$f" || true) - removed=$(grep -c '^-' "$f" || true) - upgraded=$(grep -c '^~' "$f" || true) - printf ' %s+%s %d added %s-%s %d removed %s~%s %d upgraded\n\n' \ - "$C_GREEN" "$C_RESET" "${added:-0}" \ - "$C_RED" "$C_RESET" "${removed:-0}" \ - "$C_YELLOW" "$C_RESET" "${upgraded:-0}" - awk -F'\t' ' - $1=="~"{printf " \033[33m~\033[0m %-10s %-30s %s\n", $2, $3, $4} - $1=="+"{printf " \033[32m+\033[0m %-10s %-30s %s\n", $2, $3, $4} - $1=="-"{printf " \033[31m-\033[0m %-10s %-30s %s\n", $2, $3, $4} - ' "$f" -} - -diff_count_changed() { - local f="${1:-$DIFF_LAST}" - [[ -s $f ]] || { echo 0; return; } - wc -l <"$f" -} diff --git a/src/lib/disk.sh b/src/lib/disk.sh deleted file mode 100644 index d9fc705..0000000 --- a/src/lib/disk.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env bash -# Disk-space precheck: warn/abort if the update target is tight. - -: "${DISK_MIN_FREE_MB:=1024}" - -disk_free_mb() { - local path="${1:-/}" - df -Pm "$path" 2>/dev/null | awk 'NR==2{print $4}' -} - -disk_precheck() { - local free; free=$(disk_free_mb /) - [[ -z $free ]] && return 0 - if (( free < DISK_MIN_FREE_MB )); then - ui_warn "Low disk space on / (${free}MB free, threshold ${DISK_MIN_FREE_MB}MB)." - if (( ARG_YES == 0 )); then - local ans - read -r -p " Continue anyway? [y/N]: " ans || ans=n - [[ $ans == [yY]* ]] || { ui_muted "Aborted by user."; exit 1; } - fi - else - log_info "disk precheck ok: ${free}MB free on /" - fi -} diff --git a/src/lib/doctor.sh b/src/lib/doctor.sh index 5f384d4..48be4a5 100644 --- a/src/lib/doctor.sh +++ b/src/lib/doctor.sh @@ -1,109 +1,161 @@ #!/usr/bin/env bash # Health check: run `up --doctor` and see what's wrong with the environment. -_doctor_issue=0 +_DOCTOR_ISSUE_COUNT=0 -_dok() { ui_ok "$*"; } -_dwarn() { ui_warn "$*"; _doctor_issue=$((_doctor_issue+1)); } -_derr() { ui_err "$*"; _doctor_issue=$((_doctor_issue+1)); } +# Print a finding: ok, or a warning or error that counts as an issue. +_doctor_ok() { ui_ok "$*"; } +_doctor_warn() { ui_warn "$*"; _DOCTOR_ISSUE_COUNT=$((_DOCTOR_ISSUE_COUNT+1)); } +_doctor_error() { ui_err "$*"; _DOCTOR_ISSUE_COUNT=$((_DOCTOR_ISSUE_COUNT+1)); } +# Check the environment, print every finding and return 1 when any is an +# issue. doctor_run() { - _doctor_issue=0 + _DOCTOR_ISSUE_COUNT=0 ui_title "eMerger doctor" - # Shell/env - if [[ -n $BASH_VERSION ]]; then - _dok "bash $BASH_VERSION" - else - _dwarn "running outside bash" - fi - - # sudo - if sys_is_root; then - _dok "running as root" - elif sudo -n true 2>/dev/null; then - _dok "sudo cached" - else - ui_info "sudo: will prompt when needed" - fi - - # Disk - local free_mb; free_mb=$(df -Pm / | awk 'NR==2{print $4}') - if [[ -n $free_mb ]] && (( free_mb < 1024 )); then - _dwarn "low disk space on / (${free_mb}MB free)" - else - _dok "disk: ${free_mb:-?}MB free on /" - fi - - # Network - if sys_has curl && curl -fsS --max-time 4 -o /dev/null https://github.com 2>/dev/null; then - _dok "network: reachable" - elif sys_has curl; then - _dwarn "network: github.com unreachable" - fi + _doctor_shell + _doctor_sudo + _doctor_disk + _doctor_network + _doctor_state + _doctor_glyphs + _doctor_managers + _doctor_reboot - # State dir writable - if [[ -w $EMERGER_STATE ]] || mkdir -p "$EMERGER_STATE" 2>/dev/null; then - _dok "state: $EMERGER_STATE writable" - else - _derr "state not writable: $EMERGER_STATE" - fi - - # Package manager health - local mgr - for mgr in "${PKG_MANAGERS[@]}"; do - pkg_detect "$mgr" || continue - _doctor_pkg "$mgr" - done - - # Reboot flag - reboot_check - if (( REBOOT_NEEDED )); then - ui_warn "reboot pending ($REBOOT_REASON)" - fi - - ui_hr - if (( _doctor_issue == 0 )); then - _dok "all clear" + ui_rule + if (( _DOCTOR_ISSUE_COUNT == 0 )); then + _doctor_ok "all clear" return 0 fi - ui_warn "$_doctor_issue issue(s) found" + ui_warn "$_DOCTOR_ISSUE_COUNT issue(s) found" return 1 } +# Run manager $1's own health check and report it, counting a warning as an +# issue. A check the installed version lacks is informational only. _doctor_pkg() { - local m="$1" - case "$m" in + local manager="$1" out rc + case "$manager" in apt) - if ! dpkg --audit 2>/dev/null | grep -q .; then - _dok "apt: dpkg --audit clean" + # Captured whole: `| grep -q` would SIGPIPE dpkg on long output. + out=$(dpkg --audit 2>/dev/null || true) + if [[ -z $out ]]; then + _doctor_ok "apt: dpkg --audit clean" else - _dwarn "apt: dpkg --audit reports issues" + _doctor_warn "apt: dpkg --audit reports issues" fi ;; pacman) if pacman -Dk >/dev/null 2>&1; then - _dok "pacman: database ok" + _doctor_ok "pacman: database ok" else - _dwarn "pacman: database has issues (pacman -Dk)" + _doctor_warn "pacman: database has issues (pacman -Dk)" fi ;; dnf|yum) - if "$m" check --quiet >/dev/null 2>&1; then - _dok "$m: check ok" + rc=0; out=$("$manager" check --quiet 2>&1) || rc=$? + if (( rc == 0 )); then + _doctor_ok "$manager: check ok" + elif [[ $out == *"No such command"* || $out == *"Unknown argument"* ]]; then + ui_info "$manager: check not available" else - ui_info "$m: check not available or ran clean" + _doctor_warn "$manager: check reports problems ($manager check)" fi ;; brew) if brew doctor >/dev/null 2>&1; then - _dok "brew: doctor ok" + _doctor_ok "brew: doctor ok" else - _dwarn "brew: doctor reports issues" + _doctor_warn "brew: doctor reports issues" fi ;; *) - _dok "$m: detected" + _doctor_ok "$manager: detected" ;; esac } + +# Report the shell running eMerger. +_doctor_shell() { + if [[ -n $BASH_VERSION ]]; then + _doctor_ok "bash $BASH_VERSION" + else + _doctor_warn "running outside bash" + fi +} + +# Report whether commands can run as root without a prompt. +_doctor_sudo() { + if sys_is_root; then + _doctor_ok "running as root" + elif sudo -n true 2>/dev/null; then + _doctor_ok "sudo cached" + else + ui_info "sudo: will prompt when needed" + fi +} + +# Warn about low free space on /. +_doctor_disk() { + # Same threshold as the run's pre-flight check. + local free_mb; free_mb=$(sys_free_space m /) + if [[ -n $free_mb ]] && (( free_mb < ${DISK_MIN_FREE_MB:-1024} )); then + _doctor_warn "low disk space on / (${free_mb}MB free)" + else + _doctor_ok "disk: ${free_mb:-?}MB free on /" + fi +} + +# Report whether github.com answers, when curl is installed. +_doctor_network() { + if sys_has curl && curl -fsS --max-time 4 -o /dev/null https://github.com 2>/dev/null; then + _doctor_ok "network: reachable" + elif sys_has curl; then + _doctor_warn "network: github.com unreachable" + fi +} + +# Report whether the state directory is writable. +_doctor_state() { + if [[ -w $EMERGER_STATE ]] || mkdir -p "$EMERGER_STATE" 2>/dev/null; then + _doctor_ok "state: $EMERGER_STATE writable" + else + _doctor_error "state not writable: $EMERGER_STATE" + fi +} + +# Report the glyph mode and how to get emoji icons. +_doctor_glyphs() { + if (( ! UI_HAS_UNICODE )); then + ui_info "terminal: ASCII mode (no UTF-8 locale or --ascii)" + elif (( UI_HAS_EMOJI )); then + _doctor_ok "terminal: UTF-8 + emoji font" + else + ui_info "terminal: no emoji font, using plain symbols" + if sys_has apt; then + ui_muted "for emoji icons: sudo apt install fonts-noto-color-emoji" + elif sys_has pacman; then + ui_muted "for emoji icons: sudo pacman -S noto-fonts-emoji" + elif sys_has dnf; then + ui_muted "for emoji icons: sudo dnf install google-noto-emoji-color-fonts" + fi + fi +} + +# Run the health check of every detected manager. +_doctor_managers() { + local manager + for manager in "${PKG_MANAGERS[@]}"; do + pkg_detect "$manager" || continue + _doctor_pkg "$manager" + done +} + +# Warn about a pending reboot. +_doctor_reboot() { + reboot_check + if (( REBOOT_IS_NEEDED )); then + ui_warn "reboot pending ($REBOOT_REASON)" + fi +} diff --git a/src/lib/estimate.sh b/src/lib/estimate.sh deleted file mode 100644 index 360a254..0000000 --- a/src/lib/estimate.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env bash -# Estimate step duration based on recent history.jsonl entries. - -estimate_for() { - local mgr="$1" - local hist="$EMERGER_STATE/history.jsonl" - [[ -f $hist ]] || { printf ''; return; } - # Crude: average run duration over last 5 runs that included this manager. - tail -n 20 "$hist" 2>/dev/null | awk -v m="\"$mgr\"" ' - index($0, m) > 0 { - match($0, /"duration":[0-9]+/) - if (RLENGTH > 0) { - d = substr($0, RSTART+11, RLENGTH-11) - sum += d; n += 1 - } - } - END { - if (n > 0) printf "~%ds", int(sum/n) - } - ' -} diff --git a/src/lib/help.txt b/src/lib/help.txt index a134cc0..6bad8c9 100644 --- a/src/lib/help.txt +++ b/src/lib/help.txt @@ -1,29 +1,34 @@ eMerger - one-command system updater +Lists every flag of up on Linux and macOS, the config and state files and +the exit codes. Config and environment variables: man up. USAGE - up [options] + up [options] [--] GENERAL -h, --help Show this help -V, --version Show version - -i, --interactive Interactive menu (gum / whiptail / plain) --doctor Run environment health check EXECUTION -n, --dry-run Show what would be done, do nothing -v, --verbose Stream package manager output live - -q, --quiet Quieter output (repeat for more: -q, -qq, -qqq) + -q, --quiet Quieter by one level per use: no info lines + -qq, -qqq Summary line only, nothing at all -y, --yes Assume "yes" on prompts --json Machine-readable run summary on stdout - Short single-letter flags bundle: -nv == -n -v, -ynv == -y -n -v + -- End of options: the words after it are ignored + Short flags from the set h V n v q y w bundle: -nv == -n -v + A value flag also takes --flag=VALUE: --only=apt,flatpak SELECTION - --security Only security updates when supported + --security Only security updates; managers without them are skipped + --accept-licenses Let macOS softwareupdate accept licence agreements --firmware Include firmware via fwupdmgr - --no-firmware Force-skip firmware - --dev Include dev toolchains (rustup, cargo, npm, pip, gem) + --no-firmware Skip fwupd and the Pi bootloader check, even if config sets --firmware + --dev Include dev toolchains (rustup, cargo, npm, pnpm, pip, gem) --parallel Run independent user-space managers in parallel - --profile NAME Load a profile from profiles.d/.sh + --profile NAME Load profiles.d/NAME.sh, else the shipped share/profiles/NAME.sh --list-profiles List available profiles --only LIST Comma-separated managers to keep (e.g. apt,flatpak) --except LIST Comma-separated managers to skip @@ -32,25 +37,29 @@ SAFETY / INTEGRATION --snapshot Take a pre-update snapshot (snapper/timeshift/btrfs) --rollback Revert to the latest eMerger snapshot and exit --refresh-mirrors Rank/refresh mirrors (reflector, netselect-apt) - --resume Skip managers that completed in the last interrupted run + --resume Skip managers that completed in the last run --reboot Reboot now if the system requires it --reboot-exit Exit 4 instead of 0 when a reboot is required - --download-only Download packages but do not install (apt/dnf/pacman/zypper) - --offline Alias for --download-only + --download-only Download packages but do not install (apt/dnf/pacman/zypper/softwareupdate, + every other manager is skipped) DISPLAY -nl, --no-logo Hide logo -ni, --no-info Hide system info line - -nc, --no-cache Skip user cache cleaning - -nt, --no-trash Skip trash cleaning -w, --weather Show weather line via wttr.in - --no-emoji Force ASCII glyphs only + --ascii Force ASCII glyphs only + +CLEANING + -nc, --keep-cache Skip user cache cleaning + -nt, --keep-trash Skip trash cleaning + --deep-clean Also clean journal, old kernels, leftover configs, + snap revisions, docker/podman dangling data, + crash dumps, npm/go caches (asks for each) INSPECTION --changed Show packages added/removed/upgraded in the last run --changelog PKG Show upstream changelog for PKG --history Show the last runs - --report [FILE] Export the last report to Markdown --metrics FILE Export last run as Prometheus textfile -err, --errors Show logged errors @@ -66,7 +75,7 @@ EXAMPLES up --dev --firmware # full refresh + toolchains + firmware up --snapshot --refresh-mirrors -y up --only apt,flatpak # limit to specific managers - up --except snap,firmware # run everything else + up --except snap,fwupd # run everything else up --download-only -y # prefetch while online, install later up --rollback # revert the last pre-update snapshot up --json | jq . # consume in scripts / CI @@ -80,16 +89,24 @@ CONFIG ~/.config/emerger/hooks/post.d/*.sh Post-update hooks ~/.config/emerger/managers.d/*.sh Third-party package manager plugins ~/.config/emerger/ignore.list Packages to never upgrade (pacman native) - EMERGER_CACHE_TTL Detection cache TTL in seconds (default 86400, 0 disables) + share/profiles/*.sh Shipped profiles, in the checkout STATE + ~/.cache/emerger/detected Detection cache (EMERGER_CACHE_TTL) ~/.local/state/emerger/emerger.log Log ~/.local/state/emerger/history.jsonl Run history (one JSON per line) + ~/.local/state/emerger/pkgs.before Package list before the last run + ~/.local/state/emerger/pkgs.after Package list after the last run ~/.local/state/emerger/pkgs.diff Last run package diff + ~/.local/state/emerger/resume Managers done in the last run (--resume) + ~/.local/state/emerger/emerger.lock Run lock, one run at a time + ~/.local/state/emerger/parallel-*.log Per-manager output of a --parallel run + XDG_CONFIG_HOME, XDG_CACHE_HOME and XDG_STATE_HOME move these directories. EXIT CODES 0 success - 1 runtime failure (e.g. sudo, disk, lock) + 1 runtime failure (e.g. sudo, disk, lock, interrupted) or aborted + (a declined safety prompt, no snapshot taken with --snapshot) 2 argument parsing error 3 one or more package managers failed (script itself ran to completion) 4 reboot required (only with --reboot-exit) diff --git a/src/lib/hooks.sh b/src/lib/hooks.sh index f31aace..7420f13 100644 --- a/src/lib/hooks.sh +++ b/src/lib/hooks.sh @@ -1,20 +1,25 @@ #!/usr/bin/env bash # Run user hook scripts from $EMERGER_CONFIG/hooks/{pre,post}.d/*.sh +# Run every trusted hook of phase $1 (pre or post) in name order. A hook +# failing, or refused by trust_file, is a warning, never an abort. Under +# --json a hook's stdout goes to stderr, so stdout holds the JSON alone. hooks_run() { - local phase="$1" + local phase="$1" out_fd=1 + (( ${ARG_JSON:-0} )) && out_fd=2 local dir="$EMERGER_CONFIG/hooks/${phase}.d" [[ -d $dir ]] || return 0 - local h ran=0 - for h in "$dir"/*.sh; do - [[ -f $h ]] || continue - (( ran == 0 )) && ui_title "Hooks ($phase)" - ran=1 - ui_sub "$(basename "$h")" + local hook has_run=0 + for hook in "$dir"/*.sh; do + [[ -f $hook ]] || continue + (( has_run == 0 )) && ui_title "Hooks ($phase)" + has_run=1 + ui_sub "$(basename "$hook")" if (( DRY_RUN )); then continue; fi - if ! bash "$h"; then - ui_warn "hook $(basename "$h") failed" - log_warn "hook $phase/$h failed" + trust_file "$hook" || continue + if ! bash "$hook" 9>&- >&"$out_fd"; then + ui_warn "hook $(basename "$hook") failed" + log_warn "hook $phase/$hook failed" fi done } diff --git a/src/lib/ignore.sh b/src/lib/ignore.sh index bad1f7b..851a162 100644 --- a/src/lib/ignore.sh +++ b/src/lib/ignore.sh @@ -3,9 +3,11 @@ # File: $EMERGER_CONFIG/ignore.list (one pattern per line, # comments allowed) # Native support: pacman (--ignore). Others: advisory only. -: "${IGNORE_FILE:=$EMERGER_CONFIG/ignore.list}" +IGNORE_FILE="$EMERGER_CONFIG/ignore.list" IGNORE_LIST=() +# Fill IGNORE_LIST from IGNORE_FILE: one pattern per line, text after # and +# all whitespace dropped. Empty when the file is missing. ignore_load() { IGNORE_LIST=() [[ -f $IGNORE_FILE ]] || return 0 @@ -18,12 +20,15 @@ ignore_load() { done <"$IGNORE_FILE" } +# Print the pacman --ignore=a,b option for IGNORE_LIST, nothing when empty. ignore_pacman_flag() { (( ${#IGNORE_LIST[@]} == 0 )) && return local joined; joined=$(IFS=,; printf '%s' "${IGNORE_LIST[*]}") printf -- '--ignore=%s' "$joined" } +# Print IGNORE_LIST and, without pacman, that the other managers need their +# own hold command. ignore_advisory() { (( ${#IGNORE_LIST[@]} == 0 )) && return 0 ui_muted "Ignore list: ${IGNORE_LIST[*]}" diff --git a/src/lib/knobs.sh b/src/lib/knobs.sh new file mode 100644 index 0000000..d1d6ba9 --- /dev/null +++ b/src/lib/knobs.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Validation of numeric knobs read from the environment, config or profile. + +# Normalise numeric knob $1 to a base-10 whole number, or set it to default +# $2 with a warning when it holds anything else (it is later evaluated in +# arithmetic, where text would run as code). Empty means the default. +knob_int() { + local name="$1" default="$2" value="${!1:-}" + if [[ $value =~ ^[0-9]{1,15}$ ]]; then + printf -v "$name" '%d' "$(( 10#$value ))" + return 0 + fi + [[ -n $value ]] && ui_warn "$name=\"$value\" is not a whole number, using $default" + printf -v "$name" '%s' "$default" +} + +# Normalise safety switch $1 (a knob whose 0 is the unsafe side) to a base-10 +# whole number, empty meaning 0. Any other value exits 2: guessing could turn +# a misspelt dry run into a real upgrade. +knob_switch() { + local name="$1" value="${!1:-}" + if [[ -z $value ]]; then + printf -v "$name" '%d' 0 + elif [[ $value =~ ^[0-9]{1,15}$ ]]; then + printf -v "$name" '%d' "$(( 10#$value ))" + else + ui_err "$name=\"$value\" is not a whole number (0 or 1)." + exit 2 + fi +} + +# Validate every numeric knob and safety switch from the environment, config +# or profile, before any arithmetic reads them. +knobs_validate() { + for _knob in DISK_MIN_FREE_MB:1024 BATTERY_MIN_PCT:20 RPI_TEMP_WARN:80 \ + RETRY_ATTEMPTS:2 RETRY_DELAY:3 CACHE_MENU_ROWS:12 \ + EMERGER_CACHE_TTL:86400 EMERGER_PROMPT_TIMEOUT:60 MANAGER_TIMEOUT:0 \ + UI_VERBOSE:0 ARG_ASCII:0; do + knob_int "${_knob%%:*}" "${_knob#*:}" + done + # Safety switches refuse what they cannot read. + for _knob in DRY_RUN RPI_ABORT_ON_UNDERVOLTAGE; do + knob_switch "$_knob" + done +} diff --git a/src/lib/load.sh b/src/lib/load.sh new file mode 100644 index 0000000..f88c416 --- /dev/null +++ b/src/lib/load.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Module loader of the bash half: source it with `all`, or with the modules +# to load. A name is a module path under src/lib (`ui/term`), a directory +# (`ui`, every module in it) or a file stem (`term`). Modules load in the +# order of _LOAD_MODULES whatever the order of the names. An unknown name +# loads nothing and returns 1. + +# Every module, in load order. +_LOAD_MODULES=( + ui/term ui/text ui/print ui/monitor ui/prompt knobs log sys + managers/progress state/estimate + run/command run/select run/parallel run/sudo args ignore + managers/registry managers/detect managers/icon managers/recipes + clean/size clean/cache clean/trash clean/deep hooks selfupdate autoupdate + system/notify system/rpi managers/rpi_eeprom system/reboot state/diff + system/preflight system/snapshot system/mirrors state/resume state/lock + doctor managers/changelog profiles summary state/history quiet_hours + managers/plugins state/metrics trust +) + +_load_dir=${BASH_SOURCE[0]%/*} +_load_names=("$@") +for _load_name in "${_load_names[@]}"; do + [[ $_load_name == all ]] && continue + _load_hit=0 + for _load_module in "${_LOAD_MODULES[@]}"; do + if [[ $_load_name == "$_load_module" || $_load_name == "${_load_module%%/*}" \ + || $_load_name == "${_load_module##*/}" ]]; then + _load_hit=1 + fi + done + if (( ! _load_hit )); then + printf 'load.sh: unknown module %s\n' "$_load_name" >&2 + unset _load_dir _load_names _load_name _load_hit _load_module + return 1 + fi +done +for _load_module in "${_LOAD_MODULES[@]}"; do + for _load_name in "${_load_names[@]}"; do + if [[ $_load_name == all || $_load_name == "$_load_module" \ + || $_load_name == "${_load_module%%/*}" || $_load_name == "${_load_module##*/}" ]]; then + # shellcheck source=/dev/null + source "$_load_dir/$_load_module.sh" + break + fi + done +done +unset _load_dir _load_names _load_name _load_hit _load_module diff --git a/src/lib/lock.sh b/src/lib/lock.sh deleted file mode 100644 index 9d531eb..0000000 --- a/src/lib/lock.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash -# Global lock: prevent two concurrent eMerger runs from stepping on each other. - -: "${EMERGER_LOCK:=${XDG_RUNTIME_DIR:-${EMERGER_STATE:-${XDG_STATE_HOME:-$HOME/.local/state}/emerger}}/emerger.lock}" - -lock_acquire() { - exec 9>"$EMERGER_LOCK" 2>/dev/null || return 0 - if ! command -v flock >/dev/null 2>&1; then - return 0 - fi - if ! flock -n 9; then - ui_err "Another eMerger run is in progress (lock: $EMERGER_LOCK)." - ui_muted "Wait for it, or remove the lock file if you're sure it's stale." - return 1 - fi - printf '%d\n' "$$" >&9 - return 0 -} - -lock_release() { - exec 9>&- 2>/dev/null || true -} diff --git a/src/lib/log.sh b/src/lib/log.sh index 0fc4c19..b5f8077 100644 --- a/src/lib/log.sh +++ b/src/lib/log.sh @@ -1,21 +1,46 @@ #!/usr/bin/env bash -# Structured logging to $EMERGER_LOG. +# Structured logging to $EMERGER_LOG and its --errors viewer. : "${EMERGER_STATE:=${XDG_STATE_HOME:-$HOME/.local/state}/emerger}" : "${EMERGER_LOG:=$EMERGER_STATE/emerger.log}" +# Create the log readable by its owner only and keep its last 2000 lines. log_init() { mkdir -p "$(dirname "$EMERGER_LOG")" touch "$EMERGER_LOG" + # Failing managers' output lands here and may carry URLs or tokens. + chmod 600 "$EMERGER_LOG" 2>/dev/null || true if [[ $(wc -l <"$EMERGER_LOG" 2>/dev/null || echo 0) -gt 2000 ]]; then tail -n 2000 "$EMERGER_LOG" >"${EMERGER_LOG}.tmp" && mv "${EMERGER_LOG}.tmp" "$EMERGER_LOG" fi } +# Append "||" to EMERGER_LOG. A write +# failure is ignored. _log() { local level="$1"; shift printf '%s|%s|%s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$level" "$*" >>"$EMERGER_LOG" 2>/dev/null || true } +# Log message $* at INFO, WARN or ERROR level. log_info() { _log INFO "$@"; } log_warn() { _log WARN "$@"; } log_error() { _log ERROR "$@"; } + +# Print the count of ERROR lines in EMERGER_LOG and the last 30 of them, +# highlighted, or that there are none. +log_show_errors() { + local log="$EMERGER_LOG" + if [[ ! -f $log ]]; then + ui_ok "No log yet." + return 0 + fi + local count + count=$(grep -c '|ERROR|' "$log" 2>/dev/null || true) + : "${count:=0}" + if (( count == 0 )); then + ui_ok "No errors logged." + else + ui_warn "$count error line(s) in $log:" + grep '|ERROR|' "$log" | tail -n 30 | ui_terminal_bytes | ui_highlight | sed 's/^/ /' + fi +} diff --git a/src/lib/managers/changelog.sh b/src/lib/managers/changelog.sh new file mode 100644 index 0000000..bcd1472 --- /dev/null +++ b/src/lib/managers/changelog.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# Fetch recent changelog for a package using the installed manager. + +# Print, stripped of terminal control sequences, the first 60 lines of package +# $1's changelog from the first manager that has one (apt, dnf changelog, dnf +# updateinfo), else pacman's package info or brew's log. Return 2 without a name, 1 when nothing answers. +changelog_show() { + local package="$1" output + if [[ -z $package ]]; then + ui_err "usage: up --changelog " + return 2 + fi + ui_title "Changelog: $package" + # Capture once: under pipefail, `head` closing the pipe early fails the + # producer with SIGPIPE, so its status says nothing about the output. + if sys_has apt; then + output=$({ apt changelog "$package" 2>/dev/null || true; } | head -n 60) + if [[ -n $output ]]; then printf '%s\n' "$output" | run_sanitize; return 0; fi + fi + if sys_has dnf; then + output=$({ dnf changelog "$package" 2>/dev/null || true; } | head -n 60) + if [[ -n $output ]]; then printf '%s\n' "$output" | run_sanitize; return 0; fi + output=$({ dnf updateinfo info "$package" 2>/dev/null || true; } | head -n 60) + if [[ -n $output ]]; then printf '%s\n' "$output" | run_sanitize; return 0; fi + fi + if sys_has pacman; then + ui_muted "package info (pacman has no changelog), changes at https://archlinux.org/packages/" + { pacman -Qi "$package" 2>/dev/null || pacman -Si "$package" 2>/dev/null || true; } | run_sanitize + return 0 + fi + if sys_has brew; then + { brew log --oneline -n 20 "$package" 2>/dev/null || brew info "$package"; } | run_sanitize + return 0 + fi + ui_err "No supported package manager with changelog info found." + return 1 +} diff --git a/src/lib/managers/detect.sh b/src/lib/managers/detect.sh new file mode 100644 index 0000000..60da914 --- /dev/null +++ b/src/lib/managers/detect.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Package manager detection, cached in $EMERGER_CACHE/detected for speed. + +# Cache TTL in seconds for the per-manager detection cache. +# Override with EMERGER_CACHE_TTL (0 disables caching). +: "${EMERGER_CACHE_TTL:=86400}" + +# Return 0 if manager $1 is installed, probed now without the cache. +# Unknown names return 1. +_pkg_detect_raw() { + case "$1" in + pacman) sys_has pacman ;; + apt) sys_has apt || sys_has apt-get ;; + dnf) sys_has dnf ;; + yum) sys_has yum && ! sys_has dnf ;; + zypper) sys_has zypper ;; + xbps) sys_has xbps-install ;; + apk) sys_has apk ;; + eopkg) sys_has eopkg ;; + emerge) sys_has emerge ;; + nix) sys_has nixos-rebuild || sys_has nix-env ;; + brew) sys_has brew ;; + mas) sys_has mas ;; + softwareupdate) + [[ $(uname -s) == Darwin ]] && sys_has softwareupdate ;; + flatpak) sys_has flatpak ;; + snap) sys_has snap ;; + yay) sys_has yay ;; + paru) sys_has paru ;; + fwupd) sys_has fwupdmgr ;; + rpi-eeprom) sys_has rpi-eeprom-update && rpi_has_eeprom ;; + rustup) sys_has rustup ;; + cargo) sys_has cargo && cargo install-update --version >/dev/null 2>&1 ;; + npm) sys_has npm ;; + pnpm) sys_has pnpm ;; + pip) sys_has pip || sys_has pip3 ;; + gem) sys_has gem ;; + *) return 1 ;; + esac +} + +# Return 0 if the detection cache $1 is younger than EMERGER_CACHE_TTL. +_pkg_is_cache_fresh() { + local cache="$1" + (( EMERGER_CACHE_TTL <= 0 )) && return 1 + [[ -f $cache ]] || return 1 + local now mtime age + now=$(date +%s) + mtime=$(stat -c %Y "$cache" 2>/dev/null || stat -f %m "$cache" 2>/dev/null || echo 0) + age=$(( now - mtime )) + (( age < EMERGER_CACHE_TTL )) +} + +# Return 0 if manager $1 is installed. Results are cached one line per +# manager in $EMERGER_CACHE/detected ("name" or "!name"). A stale cache is +# emptied as a whole, by rename so a reader never sees a half-written file, +# and every manager is probed again. +pkg_detect() { + local manager="$1" cache="${EMERGER_CACHE:-}/detected" line + if _pkg_is_cache_fresh "$cache"; then + while IFS= read -r line; do + [[ $line == "$manager" ]] && return 0 + [[ $line == "!$manager" ]] && return 1 + done <"$cache" + elif [[ -n ${EMERGER_CACHE:-} && -f $cache ]]; then + : >"$cache.tmp.$$" 2>/dev/null && mv -f "$cache.tmp.$$" "$cache" 2>/dev/null + rm -f "$cache.tmp.$$" 2>/dev/null + fi + local rc + if declare -F plugin_is >/dev/null && plugin_is "$manager"; then + plugin_detect "$manager"; rc=$? + else + _pkg_detect_raw "$manager"; rc=$? + fi + local entry="$manager" + (( rc == 0 )) || entry="!$manager" + if [[ -n ${EMERGER_CACHE:-} ]] && (( EMERGER_CACHE_TTL > 0 )); then + printf '%s\n' "$entry" >>"$cache" 2>/dev/null || true + fi + (( rc == 0 )) +} diff --git a/src/lib/managers/icon.sh b/src/lib/managers/icon.sh new file mode 100644 index 0000000..454ffc7 --- /dev/null +++ b/src/lib/managers/icon.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Package manager icons for the section headers. + +# Print the section icon of manager $1: an emoji with an emoji font, a +# plain Unicode symbol without one, a bullet in ASCII mode. +pkg_icon() { + if (( UI_HAS_EMOJI )); then + case "$1" in + pacman|yay|paru) printf '\xf0\x9f\x8f\xb9' ;; + apt) printf '\xf0\x9f\x8c\x80' ;; + dnf|yum) printf '\xf0\x9f\xa4\xa0' ;; + zypper) printf '\xf0\x9f\xa6\x8e' ;; + apk) printf '\xe2\x9b\xb0' ;; + xbps) printf '\xf0\x9f\x95\xb3' ;; + emerge) printf '\xf0\x9f\x90\xa7' ;; + nix) printf '\xe2\x9d\x84' ;; + brew) printf '\xf0\x9f\x8d\xba' ;; + mas) printf '\xf0\x9f\x9b\x8d' ;; + softwareupdate) printf '\xf0\x9f\x92\xbb' ;; + flatpak) printf '\xf0\x9f\x93\xa6' ;; + snap) printf '\xf0\x9f\x90\xa2' ;; + eopkg) printf '\xf0\x9f\xa7\xb1' ;; + fwupd) printf '\xf0\x9f\x94\xa7' ;; + rpi-eeprom) printf '\xf0\x9f\x8d\x93' ;; + rustup|cargo) printf '\xf0\x9f\xa6\x80' ;; + npm|pnpm) printf '\xf0\x9f\x93\x97' ;; + pip) printf '\xf0\x9f\x90\x8d' ;; + gem) printf '\xf0\x9f\x92\x8e' ;; + *) + if declare -F plugin_is >/dev/null && plugin_is "$1"; then + plugin_icon "$1" + else + printf '%s' "$(ui_glyph bullet)" + fi + ;; + esac + elif (( UI_HAS_UNICODE )); then + # No emoji font: plain symbols any font has. + case "$1" in + flatpak|snap|brew|mas) printf '\xe2\x96\xa3' ;; + nix) printf '\xe2\x9d\x84' ;; + fwupd|rpi-eeprom) printf '\xe2\x9a\x99' ;; + rustup|cargo|npm|pnpm|pip|gem) printf '\xce\xbb' ;; + *) printf '\xe2\x97\x86' ;; + esac + else + printf '%s' "$(ui_glyph bullet)" + fi +} diff --git a/src/lib/managers/plugins.sh b/src/lib/managers/plugins.sh new file mode 100644 index 0000000..3204efd --- /dev/null +++ b/src/lib/managers/plugins.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# External package-manager plugins: *.sh files in ~/.config/emerger/managers.d/ +# that set PM_PLUGIN_SLUG and define pm__detect and pm__run, plus the +# optional pm__{needs_sudo,parallel,dev,security,icon} queries. A file not +# owned by the user, or writable by group or other, is not loaded (trust_file). +# Template: share/plugins/example.sh. + +PLUGIN_SLUGS=() + +# Source every trusted managers.d/*.sh and register each one that sets +# PM_PLUGIN_SLUG and defines its detect and run functions. Others are warned about. +plugins_load() { + local dir="$EMERGER_CONFIG/managers.d" + [[ -d $dir ]] || return 0 + local file slug + for file in "$dir"/*.sh; do + [[ -e $file ]] || continue + trust_file "$file" || continue + PM_PLUGIN_SLUG="" + # shellcheck disable=SC1090 + source "$file" || { ui_warn "plugin $file failed to load"; continue; } + slug="$PM_PLUGIN_SLUG" + if [[ -z $slug ]]; then + ui_warn "plugin $file did not set PM_PLUGIN_SLUG"; continue + fi + if ! declare -F "pm_${slug}_detect" >/dev/null; then + ui_warn "plugin $slug: missing pm_${slug}_detect"; continue + fi + if ! declare -F "pm_${slug}_run" >/dev/null; then + ui_warn "plugin $slug: missing pm_${slug}_run"; continue + fi + PLUGIN_SLUGS+=("$slug") + PKG_MANAGERS+=("$slug") + done +} + +# Return 0 if name $1 is a registered plugin slug. +plugin_is() { + local name="$1" slug + for slug in "${PLUGIN_SLUGS[@]}"; do + [[ $slug == "$name" ]] && return 0 + done + return 1 +} + +# Return 0 if plugin $1 defines pm__needs_sudo and it answers yes. +plugin_needs_sudo() { + declare -F "pm_${1}_needs_sudo" >/dev/null && "pm_${1}_needs_sudo" +} +# Return 0 if plugin $1 defines pm__parallel and it answers yes. +plugin_is_parallel() { + declare -F "pm_${1}_parallel" >/dev/null && "pm_${1}_parallel" +} +# Return 0 if plugin $1 defines pm__security and it answers yes. +plugin_has_security() { + declare -F "pm_${1}_security" >/dev/null && "pm_${1}_security" +} +# Return 0 if plugin $1 defines pm__dev and it answers yes. +plugin_is_dev() { + declare -F "pm_${1}_dev" >/dev/null && "pm_${1}_dev" +} +# Return 0 if plugin $1 reports its tool installed. Lock fd 9 is closed for it. +plugin_detect() { + "pm_${1}_detect" 9>&- +} +# Run plugin $1. Under --json its stdout goes to stderr, so stdout holds +# the JSON line alone. +plugin_run() { + if (( ${ARG_JSON:-0} )); then + "pm_${1}_run" 9>&- >&2 + else + "pm_${1}_run" 9>&- + fi +} +# Print plugin $1's pm__icon, or a bullet when it defines none. +plugin_icon() { + if declare -F "pm_${1}_icon" >/dev/null; then + "pm_${1}_icon" + else + printf '%s' "$(ui_glyph bullet)" + fi +} diff --git a/src/lib/managers/progress.sh b/src/lib/managers/progress.sh new file mode 100644 index 0000000..95e86a1 --- /dev/null +++ b/src/lib/managers/progress.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# One-line stat of a step, parsed from a command's captured output. + +# Print a one-line stat for manager $1 from its captured output file $2 +# ("3 upgraded, 1 new, 0 removed"), nothing when no parser matches. +progress_summarize() { + local manager="$1" file="$2" + [[ -f $file ]] || { printf ''; return; } + case "$manager" in + apt) + awk '/[0-9]+ upgraded/{for(i=1;i<=NF;i++)if($i=="upgraded,"){u=$(i-1)} for(i=1;i<=NF;i++)if($i=="newly"){n=$(i-1)} for(i=1;i0)print $1" refreshed"}' + ;; + snap) + grep -cE 'refreshed' "$file" | awk '{if($1>0)print $1" refreshed"}' + ;; + *) : ;; + esac + return 0 # no match is not an error (set -e) +} + +# Live progress. The monitor feeds every new output line to progress_feed, +# which sets PROGRESS_PERCENT (0-100, -1 unknown), PROGRESS_CURRENT/PROGRESS_TOTAL +# (0 unknown) and PROGRESS_MESSAGE (shown instead of the raw line). Runs once per +# output line: no forks in here. + +# Clear the live progress state: percent and counters unknown, no message. +progress_reset() { PROGRESS_PERCENT=-1; PROGRESS_CURRENT=0; PROGRESS_TOTAL=0; PROGRESS_MESSAGE=""; } +progress_reset + +# Set the counter to $1 of $2, both decimal digit strings (leading zeros +# allowed). Skip things like (0/0) or (9/3). +_progress_set_count() { + local current=$(( 10#$1 )) total=$(( 10#$2 )) + (( total > 0 && current <= total )) || return 0 + PROGRESS_CURRENT=$current; PROGRESS_TOTAL=$total; PROGRESS_PERCENT=-1 +} + +# Set PROGRESS_PERCENT to percentage $1 (decimals dropped, capped at 100) and +# clear the counter total. A value that is not a number is ignored. +_progress_set_percent() { + local percent=${1%%.*} + [[ $percent =~ ^[0-9]+$ ]] || return 0 + percent=$(( 10#$percent )) + (( percent > 100 )) && percent=100 + PROGRESS_PERCENT=$percent; PROGRESS_TOTAL=0 +} + +# Update the PROGRESS_* globals from output line $2 of manager $1: its own +# format first, then the shared "(n/N)" and "[n/N]" forms. Never forks. +progress_feed() { + local manager="$1" line="$2" + case "$manager" in + apt) + # From -o APT::Status-Fd=1 (see pkg_run). + if [[ $line =~ ^(dl|pm)status:[^:]*:([0-9.]+):(.*)$ ]]; then + local kind=${BASH_REMATCH[1]} percent=${BASH_REMATCH[2]} message=${BASH_REMATCH[3]} + if [[ $message =~ ^Retrieving\ file\ ([0-9]+)\ of\ ([0-9]+) ]] && [[ ${percent%%.*} == 0 ]]; then + _progress_set_count "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" + else + _progress_set_percent "$percent" + fi + if [[ $kind == dl ]]; then PROGRESS_MESSAGE="download: $message"; else PROGRESS_MESSAGE="$message"; fi + return 0 + fi + [[ $line =~ ^Progress:\ \[\ *([0-9]+)%\] ]] && _progress_set_percent "${BASH_REMATCH[1]}" + ;; + dnf|yum) + # " Upgrading : foo-1.2.x86_64 3/24" and dnf5 "[ 3/24] ..." + if [[ $line =~ ^\ +[A-Z][a-z]+[^:]*:\ .*[[:space:]]([0-9]+)/([0-9]+)[[:space:]]*$ ]]; then + _progress_set_count "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" + elif [[ $line =~ ^\[\ *([0-9]+)/([0-9]+)\] ]]; then + _progress_set_count "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" + elif [[ $line =~ ^\(([0-9]+)/([0-9]+)\): ]]; then + _progress_set_count "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" + PROGRESS_MESSAGE="download: ${line#*: }" + return 0 + fi + ;; + emerge) + # ">>> Emerging (3 of 24) app-misc/foo-1.2::gentoo" + if [[ $line =~ \(([0-9]+)\ of\ ([0-9]+)\)\ (.*) ]]; then + _progress_set_count "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" + PROGRESS_MESSAGE="${BASH_REMATCH[3]}" + return 0 + fi + ;; + flatpak) + # "Updating 2/5โ€ฆ" / "Installing 1/3โ€ฆ" + if [[ $line =~ (Installing|Updating|Uninstalling)\ ([0-9]+)/([0-9]+) ]]; then + _progress_set_count "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}" + elif [[ $line =~ ([0-9]{1,3})%[[:space:]] ]]; then + _progress_set_percent "${BASH_REMATCH[1]}" + fi + ;; + snap|fwupd|softwareupdate|rustup) + [[ $line =~ ([0-9]{1,3}(\.[0-9]+)?)\ ?% ]] && _progress_set_percent "${BASH_REMATCH[1]}" + ;; + brew) + # "==> Upgrading 3 outdated packages:" then one "==> Upgrading foo" each. + if [[ $line =~ ^==\>\ Upgrading\ ([0-9]+)\ outdated ]]; then + # Read by the monitor. + # shellcheck disable=SC2034 + PROGRESS_TOTAL=$(( 10#${BASH_REMATCH[1]} )); PROGRESS_CURRENT=0 + # Read by the monitor. + # shellcheck disable=SC2034 + PROGRESS_PERCENT=-1 + elif [[ $line =~ ^==\>\ Upgrading\ (.+) ]]; then + PROGRESS_CURRENT=$(( PROGRESS_CURRENT + 1 )) + (( PROGRESS_TOTAL > 0 && PROGRESS_CURRENT > PROGRESS_TOTAL )) && PROGRESS_TOTAL=$PROGRESS_CURRENT + PROGRESS_MESSAGE="upgrading ${BASH_REMATCH[1]}" + return 0 + fi + ;; + gem) + [[ $line =~ ^Updating\ ([^ ]+)$ ]] && { PROGRESS_CURRENT=$(( PROGRESS_CURRENT + 1 )); PROGRESS_MESSAGE="updating ${BASH_REMATCH[1]}"; return 0; } + ;; + cargo) + [[ $line =~ ^Updating\ (.+)$ ]] && { PROGRESS_CURRENT=$(( PROGRESS_CURRENT + 1 )); PROGRESS_MESSAGE="updating ${BASH_REMATCH[1]}"; return 0; } + ;; + xbps) + [[ $line =~ :\ updated\ successfully ]] && PROGRESS_CURRENT=$(( PROGRESS_CURRENT + 1 )) + ;; + eopkg) + [[ $line =~ ^Downloading\ ([0-9]+)\ /\ ([0-9]+) ]] && _progress_set_count "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" + ;; + nix) + [[ $line =~ ^(copying\ path|building)\ ]] && PROGRESS_CURRENT=$(( PROGRESS_CURRENT + 1 )) + ;; + mas) + [[ $line =~ ^==\>\ Installed ]] && PROGRESS_CURRENT=$(( PROGRESS_CURRENT + 1 )) + ;; + esac + # Shared formats: pacman/yay/paru/zypper/apk "(3/24) upgrading foo", + # zypper "Retrieving: foo (3/24)", and the "[3/24] foo" lines of the pip loop. + if [[ $line =~ ^\(\ *([0-9]+)/([0-9]+)\)\ (.*) ]]; then + _progress_set_count "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" + PROGRESS_MESSAGE="${BASH_REMATCH[3]}" + elif [[ $line =~ ^\[\ *([0-9]+)/([0-9]+)\]\ (.*) ]]; then + _progress_set_count "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" + # Read by the monitor. + # shellcheck disable=SC2034 + PROGRESS_MESSAGE="${BASH_REMATCH[3]}" + elif [[ $line =~ \(([0-9]+)/([0-9]+)\)[[:space:]]*$ ]]; then + _progress_set_count "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" + fi + return 0 +} diff --git a/src/lib/managers/recipes.sh b/src/lib/managers/recipes.sh new file mode 100644 index 0000000..3970fde --- /dev/null +++ b/src/lib/managers/recipes.sh @@ -0,0 +1,307 @@ +#!/usr/bin/env bash +# Package manager dispatcher: the commands each manager runs. + +# Update manager $1: print its section, then run its plugin or its recipe +# with the privilege prefix it needs. Return the last failing step's code, 0 when all pass. +pkg_run() { + local manager="$1" sudo_cmd="" rc=0 + _PKG_CURRENT="$manager" + # Root runs managers directly: a container or CI image may have no sudo. + if pkg_needs_sudo "$manager"; then sudo_cmd=$(sys_sudo_prefix); fi + + local icon estimate + icon=$(pkg_icon "$manager") + estimate=$(estimate_for "$manager") + ui_section "$icon" "$manager" "$estimate" + log_info "starting $manager" + + if (( ${ARG_DOWNLOAD_ONLY:-0} )) && ! pkg_has_download_only "$manager"; then + ui_warn "skip $manager: no download-only mode, --download-only never installs" + log_warn "$manager skipped: no download-only mode" + _PKG_CURRENT="" + return 0 + fi + + if declare -F plugin_is >/dev/null && plugin_is "$manager"; then + plugin_run "$manager"; rc=$? + _PKG_CURRENT="" + (( rc == 0 )) && log_info "$manager: ok" || log_error "$manager: rc=$rc" + return $rc + fi + + # Pacman can natively honor an ignore list. + local pacman_ignore="" + sys_has pacman && pacman_ignore=$(ignore_pacman_flag) + + case "$manager" in + pacman) _pkg_run_pacman ;; + apt) _pkg_run_apt ;; + dnf) _pkg_run_dnf ;; + yum) _pkg_run_yum ;; + zypper) _pkg_run_zypper ;; + xbps) _pkg_run_xbps ;; + apk) _pkg_run_apk ;; + eopkg) _pkg_run_eopkg ;; + emerge) _pkg_run_emerge ;; + nix) _pkg_run_nix ;; + brew) _pkg_run_brew ;; + mas) _pkg_run_mas ;; + softwareupdate) _pkg_run_softwareupdate ;; + flatpak) _pkg_run_flatpak ;; + snap) _pkg_run_snap ;; + yay) _pkg_run_yay ;; + paru) _pkg_run_paru ;; + fwupd) _pkg_run_fwupd ;; + rpi-eeprom) _pkg_run_rpi_eeprom ;; + rustup) _pkg_run_rustup ;; + cargo) _pkg_run_cargo ;; + npm) _pkg_run_npm ;; + pnpm) _pkg_run_pnpm ;; + pip) _pkg_run_pip ;; + gem) _pkg_run_gem ;; + esac + + _PKG_CURRENT="" + if (( rc == 0 )); then + log_info "$manager: ok" + else + log_error "$manager: rc=$rc" + fi + return $rc +} + +# Recipes, one per manager, called by pkg_run only: each reads its locals +# sudo_cmd (privilege prefix) and pacman_ignore, and sets its rc on failure. + +# Run pacman: refresh, then upgrade (or download only) and trim the package cache. +_pkg_run_pacman() { + # shellcheck disable=SC2086 + run_cmd "refresh databases" $sudo_cmd pacman -Syy --noconfirm $pacman_ignore || rc=$? + if (( ARG_DOWNLOAD_ONLY )); then + # shellcheck disable=SC2086 + run_cmd "download only" $sudo_cmd pacman -Syuw --noconfirm $pacman_ignore || rc=$? + else + # shellcheck disable=SC2086 + run_cmd "upgrade system" $sudo_cmd pacman -Syu --noconfirm $pacman_ignore || rc=$? + if sys_has paccache; then + run_cmd "clean package cache" $sudo_cmd paccache -rk2 || true + fi + fi +} + +# Run apt: repair, update, then upgrade (security or download only on request), autoremove and clean. +_pkg_run_apt() { + local apt_bin=apt-get + sys_has apt && apt_bin=apt + # Status-Fd lines feed the progress bar, useless with -v. + local -a apt_options=() + (( UI_VERBOSE )) || apt_options=(-o APT::Status-Fd=1) + # Under --download-only the repair only fetches what it would install. + local -a fix_options=() + (( ARG_DOWNLOAD_ONLY )) && fix_options=(--download-only) + run_cmd "fix broken" $sudo_cmd "$apt_bin" "${apt_options[@]}" --fix-broken install -y "${fix_options[@]}" || rc=$? + run_cmd "update" $sudo_cmd "$apt_bin" "${apt_options[@]}" update || rc=$? + if (( ARG_DOWNLOAD_ONLY )) && (( ARG_SECURITY )); then + run_cmd "security download only" $sudo_cmd unattended-upgrade -v --download-only || rc=$? + elif (( ARG_DOWNLOAD_ONLY )); then + local upgrade_command=full-upgrade + [[ $apt_bin == apt-get ]] && upgrade_command=dist-upgrade + run_cmd "$upgrade_command --download-only" $sudo_cmd "$apt_bin" "${apt_options[@]}" "$upgrade_command" -y --download-only || rc=$? + else + if (( ARG_SECURITY )); then + run_cmd "security upgrade" $sudo_cmd unattended-upgrade -v || rc=$? + else + local upgrade_command=full-upgrade + [[ $apt_bin == apt-get ]] && upgrade_command=dist-upgrade + run_cmd "$upgrade_command" $sudo_cmd "$apt_bin" "${apt_options[@]}" "$upgrade_command" -y || rc=$? + fi + run_cmd "autoremove" $sudo_cmd "$apt_bin" "${apt_options[@]}" autoremove -y || rc=$? + run_cmd "autoclean" $sudo_cmd "$apt_bin" autoclean -y || rc=$? + run_cmd "clean" $sudo_cmd "$apt_bin" clean || rc=$? + fi +} + +# Run dnf: upgrade (security or download only on request), autoremove and clean. +_pkg_run_dnf() { + local security_flag="" + (( ARG_SECURITY )) && security_flag="--security" + if (( ARG_DOWNLOAD_ONLY )); then + run_cmd "download only" $sudo_cmd dnf upgrade -y --downloadonly $security_flag || rc=$? + else + run_cmd "upgrade" $sudo_cmd dnf upgrade -y $security_flag || rc=$? + run_cmd "autoremove" $sudo_cmd dnf autoremove -y || rc=$? + run_cmd "clean all" $sudo_cmd dnf clean all || rc=$? + fi +} + +# Run yum: update (security only on request) and clean. +_pkg_run_yum() { + local security_flag="" + (( ARG_SECURITY )) && security_flag="--security" + run_cmd "update" $sudo_cmd yum update -y $security_flag || rc=$? + run_cmd "clean all" $sudo_cmd yum clean all || rc=$? +} + +# Run zypper: refresh, then update or patch (security or download only on request) and clean. +_pkg_run_zypper() { + run_cmd "refresh" $sudo_cmd zypper --non-interactive refresh || rc=$? + if (( ARG_DOWNLOAD_ONLY )) && (( ARG_SECURITY )); then + run_cmd "security download only" $sudo_cmd zypper --non-interactive patch --category security --download-only || rc=$? + elif (( ARG_DOWNLOAD_ONLY )); then + run_cmd "download only" $sudo_cmd zypper --non-interactive update --download-only || rc=$? + elif (( ARG_SECURITY )); then + run_cmd "security patch" $sudo_cmd zypper --non-interactive patch --category security || rc=$? + else + run_cmd "update" $sudo_cmd zypper --non-interactive update || rc=$? + fi + # zypper clean would delete what --download-only just fetched. + (( ARG_DOWNLOAD_ONLY )) || run_cmd "clean" $sudo_cmd zypper clean || true +} + +# Run xbps: sync and upgrade, remove orphans. +_pkg_run_xbps() { + run_cmd "sync & upgrade" $sudo_cmd xbps-install -Suy || rc=$? + run_cmd "remove orphans" $sudo_cmd xbps-remove -Oy || true +} + +# Run apk: update, upgrade, clean the cache. +_pkg_run_apk() { + run_cmd "update" $sudo_cmd apk update || rc=$? + run_cmd "upgrade" $sudo_cmd apk upgrade || rc=$? + run_cmd "clean cache" $sudo_cmd apk cache clean || true +} + +# Run eopkg: upgrade, delete the cache. +_pkg_run_eopkg() { + run_cmd "upgrade" $sudo_cmd eopkg upgrade -y || rc=$? + run_cmd "delete cache" $sudo_cmd eopkg delete-cache || true +} + +# Run emerge: sync, update @world, depclean. +_pkg_run_emerge() { + run_cmd "sync" $sudo_cmd emerge --sync --quiet || rc=$? + run_cmd "update world" $sudo_cmd emerge -uDN --quiet @world || rc=$? + run_cmd "depclean" $sudo_cmd emerge --depclean --quiet || true +} + +# Run nix: NixOS rebuild or channel update and upgrade, then collect garbage. +_pkg_run_nix() { + if sys_has nixos-rebuild; then + run_cmd "nixos-rebuild switch --upgrade" $sudo_cmd nixos-rebuild switch --upgrade || rc=$? + run_cmd "collect garbage" $sudo_cmd nix-collect-garbage -d || true + else + run_cmd "channel update" nix-channel --update || rc=$? + run_cmd "upgrade" nix-env -u || rc=$? + run_cmd "collect garbage" nix-collect-garbage -d || true + fi +} + +# Run brew: update, upgrade formulae and casks, cleanup. +_pkg_run_brew() { + run_cmd "update" brew update || rc=$? + run_cmd "upgrade" brew upgrade || rc=$? + run_cmd "upgrade casks" brew upgrade --cask || true + run_cmd "cleanup" brew cleanup -s || true +} + +# Run mas: upgrade App Store apps. +_pkg_run_mas() { + run_cmd "mas upgrade" mas upgrade || rc=$? +} + +# Run softwareupdate: list, download or install macOS updates, licences agreed only with --accept-licenses. +_pkg_run_softwareupdate() { + # Installing can mean agreeing to Apple's licence: only on request. + # Downloading agrees to nothing. + if (( ARG_DOWNLOAD_ONLY )) && (( ARG_SECURITY )); then + run_cmd "download recommended" $sudo_cmd softwareupdate --download --recommended || rc=$? + elif (( ARG_DOWNLOAD_ONLY )); then + run_cmd "download all" $sudo_cmd softwareupdate --download --all || rc=$? + elif (( ! ARG_ACCEPT_LICENSES )); then + run_cmd "list" softwareupdate --list || true + ui_muted "updates not installed: they may need licence agreement, run with --accept-licenses" + elif (( ARG_SECURITY )); then + run_cmd "install recommended" $sudo_cmd softwareupdate --install --recommended --agree-to-license || rc=$? + else + run_cmd "list" softwareupdate --list || true + run_cmd "install all" $sudo_cmd softwareupdate --install --all --agree-to-license --no-scan || rc=$? + fi +} + +# Run flatpak: update, uninstall unused runtimes. +_pkg_run_flatpak() { + run_cmd "update" flatpak update -y --noninteractive || rc=$? + run_cmd "uninstall unused" flatpak uninstall --unused -y --noninteractive || true +} + +# Run snap: refresh. +_pkg_run_snap() { + run_cmd "refresh" $sudo_cmd snap refresh || rc=$? +} + +# Run yay: AUR upgrade. +_pkg_run_yay() { + # shellcheck disable=SC2086 + run_cmd "AUR upgrade" yay -Syu --noconfirm $pacman_ignore || rc=$? +} + +# Run paru: AUR upgrade. +_pkg_run_paru() { + # shellcheck disable=SC2086 + run_cmd "AUR upgrade" paru -Syu --noconfirm $pacman_ignore || rc=$? +} + +# Run fwupd: refresh metadata, update firmware. +_pkg_run_fwupd() { + run_cmd "refresh metadata" $sudo_cmd fwupdmgr refresh --force || rc=$? + run_cmd "firmware update" $sudo_cmd fwupdmgr update -y --no-reboot-check || true +} + +# Run rpi-eeprom: check, and with --firmware stage, the Pi bootloader. +_pkg_run_rpi_eeprom() { + rpi_eeprom_run "$sudo_cmd" || rc=$? +} + +# Run rustup: update toolchains. +_pkg_run_rustup() { + run_cmd "rustup update" rustup update || rc=$? +} + +# Run cargo: update installed crates (cargo-update). +_pkg_run_cargo() { + run_cmd "cargo install-update" cargo install-update -a || rc=$? +} + +# Run npm: update global packages. +_pkg_run_npm() { + run_cmd "npm update -g" npm update -g || rc=$? +} + +# Run pnpm: update global packages. +_pkg_run_pnpm() { + run_cmd "pnpm -g update" pnpm -g update || rc=$? +} + +# Run pip: upgrade outdated packages one at a time, printing [i/N]. +_pkg_run_pip() { + local pip_bin=pip + sys_has pip3 && pip_bin=pip3 + local flags="--user" + sys_is_root && flags="" + # One at a time, printing [i/N] for the progress bar. + # pip >= 22.3 refuses --outdated with --format=freeze. + run_cmd "pip upgrade" bash -c ' + pip_bin=$1; shift + mapfile -t pkgs < <("$pip_bin" list --outdated "$@" 2>/dev/null | awk "NR>2 {print \$1}") + n=${#pkgs[@]} i=0 rc=0 + for p in "${pkgs[@]}"; do + i=$((i+1)); echo "[$i/$n] $p" + "$pip_bin" install -U "$@" "$p" || rc=1 + done + exit $rc' _ "$pip_bin" $flags || rc=$? +} + +# Run gem: update gems. +_pkg_run_gem() { + run_cmd "gem update" gem update || rc=$? +} diff --git a/src/lib/managers/registry.sh b/src/lib/managers/registry.sh new file mode 100644 index 0000000..51f4f17 --- /dev/null +++ b/src/lib/managers/registry.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# Package manager registry: the supported managers and what each can do. + +# Read by the modules that loop over managers. +# shellcheck disable=SC2034 +PKG_MANAGERS=( + pacman yay paru + apt dnf yum zypper xbps apk eopkg emerge nix + softwareupdate brew mas + fwupd rpi-eeprom + flatpak snap + rustup cargo npm pnpm pip gem +) + +# Return 0 if manager $1 runs its commands as root: nix only on NixOS, +# rpi-eeprom only with --firmware. +pkg_needs_sudo() { + case "$1" in + pacman|apt|dnf|yum|zypper|xbps|apk|eopkg|emerge|fwupd|snap|softwareupdate) return 0 ;; + nix) sys_has nixos-rebuild ;; + rpi-eeprom) (( ${ARG_FIRMWARE:-0} )) ;; + *) _pkg_plugin_ask plugin_needs_sudo "$1" ;; + esac +} + +# Return 0 if manager $1 updates developer tooling, which runs only with --dev. +pkg_is_dev() { + case "$1" in + rustup|cargo|npm|pnpm|pip|gem) return 0 ;; + *) _pkg_plugin_ask plugin_is_dev "$1" ;; + esac +} + +# Return 0 if manager $1 can install security updates alone, which is what +# --security runs. apt needs unattended-upgrade, a plugin needs +# pm__security. Every other manager is skipped under --security. +pkg_has_security() { + case "$1" in + dnf|yum|zypper|softwareupdate) return 0 ;; + apt) sys_has unattended-upgrade ;; + *) _pkg_plugin_ask plugin_has_security "$1" ;; + esac +} + +# Return 0 if manager $1 has a mode that downloads updates without +# installing them, which is all --download-only runs. Every other manager, +# plugins included, is skipped under --download-only. +pkg_has_download_only() { + case "$1" in + pacman|apt|dnf|zypper|softwareupdate) return 0 ;; + *) return 1 ;; + esac +} + +# Return 0 if manager $1 can run beside others under --parallel. +pkg_is_parallelizable() { + case "$1" in + flatpak|snap|brew|mas|rustup|cargo|npm|pnpm|pip|gem) return 0 ;; + *) _pkg_plugin_ask plugin_is_parallel "$1" ;; + esac +} + +# Run plugin query $1 (plugin_needs_sudo, plugin_is_dev, ...) for manager $2: +# its answer when $2 is a registered plugin, else 1. +_pkg_plugin_ask() { + if declare -F plugin_is >/dev/null && plugin_is "$2"; then + "$1" "$2" + else + return 1 + fi +} diff --git a/src/lib/managers/rpi_eeprom.sh b/src/lib/managers/rpi_eeprom.sh new file mode 100644 index 0000000..7d8879f --- /dev/null +++ b/src/lib/managers/rpi_eeprom.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Raspberry Pi bootloader EEPROM recipe. + +RPI_EEPROM_IS_PENDING=0 + +# Check the Pi bootloader with privilege prefix $1 and, only with --firmware +# (as fwupd), stage the update and set RPI_EEPROM_IS_PENDING. +# rpi-eeprom-update: 0 up to date, 1 update available, 2+ error. +rpi_eeprom_run() { + local sudo_cmd="$1" rc=0 output + if (( DRY_RUN )); then + ui_sub "[dry-run] $sudo_cmd rpi-eeprom-update" + return 0 + fi + output=$($sudo_cmd rpi-eeprom-update 2>&1 9>&-) || rc=$? + case $rc in + 0) + ui_done "bootloader" "up to date" + return 0 + ;; + 1) + local current="" latest="" + [[ $output =~ CURRENT:\ ([^$'\n']*)\ \( ]] && current=${BASH_REMATCH[1]} + [[ $output =~ LATEST:\ ([^$'\n']*)\ \( ]] && latest=${BASH_REMATCH[1]} + if (( ARG_FIRMWARE )); then + if run_cmd "bootloader update" $sudo_cmd rpi-eeprom-update -a; then + # Read by the run loop. + # shellcheck disable=SC2034 + RPI_EEPROM_IS_PENDING=1 + ui_muted "staged; it is flashed on the next reboot" + return 0 + fi + return 1 + fi + ui_done "bootloader" "update available" + [[ -n $latest ]] && ui_muted "current: ${current:-?} -> latest: $latest" + ui_muted "apply it with: up --firmware" + return 0 + ;; + *) + # Read by ui_done. + # shellcheck disable=SC2034 + UI_LAST_ELAPSED="" + ui_fail "bootloader check" "$rc" + printf '%s\n' "$output" | tail -n 5 | sed "s/^/ $(ui_glyph v) /" >&2 + log_error "rpi-eeprom-update: rc=$rc" + return "$rc" + ;; + esac +} diff --git a/src/lib/metrics.sh b/src/lib/metrics.sh deleted file mode 100644 index 6f93c92..0000000 --- a/src/lib/metrics.sh +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env bash -# Prometheus textfile-collector export. -# Reads the most recent entry of history.jsonl and renders a .prom file. - -metrics_export() { - local out="$1" - local hist="$EMERGER_STATE/history.jsonl" - if [[ ! -f $hist ]]; then - ui_err "No history yet ($hist missing)" - return 1 - fi - local last - last=$(tail -n 1 "$hist") - [[ -z $last ]] && { ui_err "history.jsonl is empty"; return 1; } - - local ts dur freed errs reboot - ts=$(printf '%s' "$last" | sed -n 's/.*"ts":"\([^"]*\)".*/\1/p') - dur=$(printf '%s' "$last" | sed -n 's/.*"duration":\([0-9]*\).*/\1/p') - freed=$(printf '%s' "$last" | sed -n 's/.*"freed_kb":\([0-9]*\).*/\1/p') - errs=$(printf '%s' "$last" | sed -n 's/.*"errors":\([0-9]*\).*/\1/p') - reboot=$(printf '%s' "$last" | sed -n 's/.*"reboot":\([0-9]*\).*/\1/p') - - # epoch (best-effort, GNU date syntax). - local epoch=0 - if [[ -n $ts ]]; then - epoch=$(date -d "$ts" +%s 2>/dev/null || echo 0) - fi - - local tmp="$out.tmp.$$" - { - printf '# HELP emerger_last_run_timestamp_seconds Unix timestamp of the last eMerger run\n' - printf '# TYPE emerger_last_run_timestamp_seconds gauge\n' - printf 'emerger_last_run_timestamp_seconds %s\n' "${epoch:-0}" - printf '# HELP emerger_last_run_duration_seconds Duration of the last run\n' - printf '# TYPE emerger_last_run_duration_seconds gauge\n' - printf 'emerger_last_run_duration_seconds %s\n' "${dur:-0}" - printf '# HELP emerger_last_run_freed_bytes Bytes freed by the last run\n' - printf '# TYPE emerger_last_run_freed_bytes gauge\n' - printf 'emerger_last_run_freed_bytes %s\n' "$(( ${freed:-0} * 1024 ))" - printf '# HELP emerger_last_run_errors Manager failures in the last run\n' - printf '# TYPE emerger_last_run_errors gauge\n' - printf 'emerger_last_run_errors %s\n' "${errs:-0}" - printf '# HELP emerger_reboot_required Whether a reboot is pending (0/1)\n' - printf '# TYPE emerger_reboot_required gauge\n' - printf 'emerger_reboot_required %s\n' "${reboot:-0}" - - # Per-manager success flag. - printf '# HELP emerger_manager_ok Per-manager success in the last run (1=ok,0=fail)\n' - printf '# TYPE emerger_manager_ok gauge\n' - printf '%s\n' "$last" | grep -oE '"name":"[^"]*","result":"[^"]*"' | \ - while IFS= read -r pair; do - local name result val - name=$(printf '%s' "$pair" | sed -n 's/.*"name":"\([^"]*\)".*/\1/p') - result=$(printf '%s' "$pair" | sed -n 's/.*"result":"\([^"]*\)".*/\1/p') - val=0 - [[ $result == ok ]] && val=1 - printf 'emerger_manager_ok{manager="%s"} %s\n' "$name" "$val" - done - } >"$tmp" - mv "$tmp" "$out" - ui_ok "metrics written to $out" -} diff --git a/src/lib/mirrors.sh b/src/lib/mirrors.sh deleted file mode 100644 index f2c418d..0000000 --- a/src/lib/mirrors.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env bash -# Rank / refresh package mirrors where supported. - -mirrors_refresh() { - ui_title "Refresh mirrors" - if (( DRY_RUN )); then - ui_sub "[dry-run] would refresh mirrors" - return 0 - fi - local did=0 - if sys_has reflector; then - if sudo reflector --latest 20 --sort rate --protocol https --save /etc/pacman.d/mirrorlist >/dev/null 2>&1; then - ui_ok "reflector: pacman mirrorlist updated" - did=1 - else - ui_warn "reflector failed" - fi - fi - if sys_has netselect-apt; then - local tmp; tmp=$(mktemp -t emerger.XXXXXX) - if sudo netselect-apt -o "$tmp" >/dev/null 2>&1 && [[ -s $tmp ]]; then - sudo install -m 0644 "$tmp" /etc/apt/sources.list.d/netselect.list - ui_ok "netselect-apt: wrote /etc/apt/sources.list.d/netselect.list" - did=1 - fi - rm -f "$tmp" - fi - if sys_has dnf && dnf config-manager --help >/dev/null 2>&1; then - ui_muted "dnf: fastestmirror plugin handles this automatically when enabled" - fi - (( did )) || ui_muted "No mirror tool available; install 'reflector' (arch) or 'netselect-apt' (debian)." -} diff --git a/src/lib/notify.sh b/src/lib/notify.sh deleted file mode 100644 index 2aaf1f2..0000000 --- a/src/lib/notify.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash -# Optional desktop notification at end of run. - -notify_send_result() { - sys_has notify-send || return 0 - [[ -n ${DISPLAY:-} || -n ${WAYLAND_DISPLAY:-} ]] || return 0 - local msg urgency=normal icon=emblem-default - if (( SUMMARY_ERRORS > 0 )); then - urgency=critical; icon=dialog-error - msg="Finished with $SUMMARY_ERRORS error(s)." - else - msg="${#SUMMARY_MANAGERS[@]} manager(s) updated." - fi - notify-send -a eMerger -u "$urgency" -i "$icon" "eMerger" "$msg" 2>/dev/null || true -} diff --git a/src/lib/packages.sh b/src/lib/packages.sh deleted file mode 100644 index 641136f..0000000 --- a/src/lib/packages.sh +++ /dev/null @@ -1,337 +0,0 @@ -#!/usr/bin/env bash -# Package manager registry and dispatcher. -# Detection is cached in $EMERGER_CACHE/detected for speed. - -PKG_MANAGERS=( - pacman yay paru - apt dnf yum zypper xbps apk eopkg emerge nix - softwareupdate brew mas - fwupd - flatpak snap - rustup cargo npm pnpm pip gem -) - -pkg_needs_sudo() { - case "$1" in - pacman|apt|dnf|yum|zypper|xbps|apk|eopkg|emerge|fwupd|snap|softwareupdate) return 0 ;; - nix) sys_has nixos-rebuild ;; - *) - if declare -F plugin_is >/dev/null && plugin_is "$1"; then - plugin_needs_sudo "$1" - else - return 1 - fi - ;; - esac -} - -pkg_is_dev() { - case "$1" in - rustup|cargo|npm|pnpm|pip|gem) return 0 ;; - *) - if declare -F plugin_is >/dev/null && plugin_is "$1"; then - plugin_is_dev "$1" - else - return 1 - fi - ;; - esac -} - -pkg_is_parallelizable() { - case "$1" in - flatpak|snap|brew|mas|rustup|cargo|npm|pnpm|pip|gem) return 0 ;; - *) - if declare -F plugin_is >/dev/null && plugin_is "$1"; then - plugin_is_parallel "$1" - else - return 1 - fi - ;; - esac -} - -# Cache TTL in seconds for the per-manager detection cache. -# Override with EMERGER_CACHE_TTL (0 disables caching). -: "${EMERGER_CACHE_TTL:=86400}" - -_pkg_detect_raw() { - case "$1" in - pacman) sys_has pacman ;; - apt) sys_has apt || sys_has apt-get ;; - dnf) sys_has dnf ;; - yum) sys_has yum && ! sys_has dnf ;; - zypper) sys_has zypper ;; - xbps) sys_has xbps-install ;; - apk) sys_has apk ;; - eopkg) sys_has eopkg ;; - emerge) sys_has emerge ;; - nix) sys_has nixos-rebuild || sys_has nix-env ;; - brew) sys_has brew ;; - mas) sys_has mas ;; - softwareupdate) - [[ $(uname -s) == Darwin ]] && sys_has softwareupdate ;; - flatpak) sys_has flatpak ;; - snap) sys_has snap ;; - yay) sys_has yay ;; - paru) sys_has paru ;; - fwupd) sys_has fwupdmgr ;; - rustup) sys_has rustup ;; - cargo) sys_has cargo && cargo install-update --version >/dev/null 2>&1 ;; - npm) sys_has npm ;; - pnpm) sys_has pnpm ;; - pip) sys_has pip || sys_has pip3 ;; - gem) sys_has gem ;; - *) return 1 ;; - esac -} - -_pkg_cache_fresh() { - local cache="$1" - (( EMERGER_CACHE_TTL <= 0 )) && return 1 - [[ -f $cache ]] || return 1 - local now mtime age - now=$(date +%s) - mtime=$(stat -c %Y "$cache" 2>/dev/null || stat -f %m "$cache" 2>/dev/null || echo 0) - age=$(( now - mtime )) - (( age < EMERGER_CACHE_TTL )) -} - -pkg_detect() { - local m="$1" cache="${EMERGER_CACHE:-}/detected" - if _pkg_cache_fresh "$cache"; then - grep -q "^$m\$" "$cache" && return 0 - grep -q "^!$m\$" "$cache" && return 1 - fi - local rc - if declare -F plugin_is >/dev/null && plugin_is "$m"; then - plugin_detect "$m"; rc=$? - else - _pkg_detect_raw "$m"; rc=$? - fi - if (( rc == 0 )); then - [[ -n ${EMERGER_CACHE:-} ]] && printf '%s\n' "$m" >>"$cache" 2>/dev/null - return 0 - else - [[ -n ${EMERGER_CACHE:-} ]] && printf '!%s\n' "$m" >>"$cache" 2>/dev/null - return 1 - fi -} - -pkg_icon() { - if (( UI_UNICODE )); then - case "$1" in - pacman|yay|paru) printf '\xf0\x9f\x8f\xb9' ;; - apt) printf '\xf0\x9f\x8c\x80' ;; - dnf|yum) printf '\xf0\x9f\xa4\xa0' ;; - zypper) printf '\xf0\x9f\xa6\x8e' ;; - apk) printf '\xe2\x9b\xb0' ;; - xbps) printf '\xf0\x9f\x95\xb3' ;; - emerge) printf '\xf0\x9f\x90\xa7' ;; - nix) printf '\xe2\x9d\x84' ;; - brew) printf '\xf0\x9f\x8d\xba' ;; - mas) printf '\xef\xa3\xbf' ;; - softwareupdate) printf '\xef\xa3\xbf' ;; - flatpak) printf '\xf0\x9f\x93\xa6' ;; - snap) printf '\xf0\x9f\x90\xa2' ;; - eopkg) printf '\xf0\x9f\xa7\xb1' ;; - fwupd) printf '\xf0\x9f\x94\xa7' ;; - rustup|cargo) printf '\xf0\x9f\xa6\x80' ;; - npm|pnpm) printf '\xf0\x9f\x93\x97' ;; - pip) printf '\xf0\x9f\x90\x8d' ;; - gem) printf '\xf0\x9f\x92\x8e' ;; - *) - if declare -F plugin_is >/dev/null && plugin_is "$1"; then - plugin_icon "$1" - else - printf '%s' "$(ui_glyph bullet)" - fi - ;; - esac - else - printf '%s' "$(ui_glyph bullet)" - fi -} - -pkg_run() { - local mgr="$1" sudo_cmd="" rc=0 - _PKG_CURRENT="$mgr" - if pkg_needs_sudo "$mgr"; then sudo_cmd="sudo"; fi - - local ic est - ic=$(pkg_icon "$mgr") - est=$(estimate_for "$mgr") - ui_title "$ic $mgr${est:+ $est}" - log_info "starting $mgr" - - # Route to plugin if registered. - if declare -F plugin_is >/dev/null && plugin_is "$mgr"; then - plugin_run "$mgr"; rc=$? - _PKG_CURRENT="" - (( rc == 0 )) && log_info "$mgr: ok" || log_error "$mgr: rc=$rc" - return $rc - fi - - # Pacman can natively honor an ignore list. - local pacman_ignore="" - sys_has pacman && pacman_ignore=$(ignore_pacman_flag) - - case "$mgr" in - pacman) - # shellcheck disable=SC2086 - run_cmd "refresh databases" $sudo_cmd pacman -Syy --noconfirm $pacman_ignore || rc=$? - if (( ARG_DOWNLOAD_ONLY )); then - # shellcheck disable=SC2086 - run_cmd "download only" $sudo_cmd pacman -Syuw --noconfirm $pacman_ignore || rc=$? - else - # shellcheck disable=SC2086 - run_cmd "upgrade system" $sudo_cmd pacman -Syu --noconfirm $pacman_ignore || rc=$? - if sys_has paccache; then - run_cmd "clean package cache" $sudo_cmd paccache -rk2 || true - fi - fi - ;; - apt) - local apt_bin=apt-get - sys_has apt && apt_bin=apt - run_cmd "fix broken" $sudo_cmd "$apt_bin" --fix-broken install -y || rc=$? - run_cmd "update" $sudo_cmd "$apt_bin" update || rc=$? - if (( ARG_DOWNLOAD_ONLY )); then - local upflag=full-upgrade - [[ $apt_bin == apt-get ]] && upflag=dist-upgrade - run_cmd "$upflag --download-only" $sudo_cmd "$apt_bin" "$upflag" -y --download-only || rc=$? - else - if (( ARG_SECURITY )) && sys_has unattended-upgrade; then - run_cmd "security upgrade" $sudo_cmd unattended-upgrade -v || rc=$? - else - local upflag=full-upgrade - [[ $apt_bin == apt-get ]] && upflag=dist-upgrade - run_cmd "$upflag" $sudo_cmd "$apt_bin" "$upflag" -y || rc=$? - fi - run_cmd "autoremove" $sudo_cmd "$apt_bin" autoremove -y || rc=$? - run_cmd "autoclean" $sudo_cmd "$apt_bin" autoclean -y || rc=$? - run_cmd "clean" $sudo_cmd "$apt_bin" clean || rc=$? - fi - ;; - dnf) - local sec="" - (( ARG_SECURITY )) && sec="--security" - if (( ARG_DOWNLOAD_ONLY )); then - run_cmd "download only" $sudo_cmd dnf upgrade -y --downloadonly $sec || rc=$? - else - run_cmd "upgrade" $sudo_cmd dnf upgrade -y $sec || rc=$? - run_cmd "autoremove" $sudo_cmd dnf autoremove -y || rc=$? - run_cmd "clean all" $sudo_cmd dnf clean all || rc=$? - fi - ;; - yum) - run_cmd "update" $sudo_cmd yum update -y || rc=$? - run_cmd "clean all" $sudo_cmd yum clean all || rc=$? - ;; - zypper) - run_cmd "refresh" $sudo_cmd zypper --non-interactive refresh || rc=$? - if (( ARG_DOWNLOAD_ONLY )); then - run_cmd "download only" $sudo_cmd zypper --non-interactive update --download-only || rc=$? - elif (( ARG_SECURITY )); then - run_cmd "security patch" $sudo_cmd zypper --non-interactive patch --category security || rc=$? - else - run_cmd "update" $sudo_cmd zypper --non-interactive update || rc=$? - fi - run_cmd "clean" $sudo_cmd zypper clean || true - ;; - xbps) - run_cmd "sync & upgrade" $sudo_cmd xbps-install -Suy || rc=$? - run_cmd "remove orphans" $sudo_cmd xbps-remove -Oy || true - ;; - apk) - run_cmd "update" $sudo_cmd apk update || rc=$? - run_cmd "upgrade" $sudo_cmd apk upgrade || rc=$? - run_cmd "clean cache" $sudo_cmd apk cache clean || true - ;; - eopkg) - run_cmd "upgrade" $sudo_cmd eopkg upgrade -y || rc=$? - run_cmd "delete cache" $sudo_cmd eopkg delete-cache || true - ;; - emerge) - run_cmd "sync" $sudo_cmd emerge --sync --quiet || rc=$? - run_cmd "update world" $sudo_cmd emerge -uDN --quiet @world || rc=$? - run_cmd "depclean" $sudo_cmd emerge --depclean --quiet || true - ;; - nix) - if sys_has nixos-rebuild; then - run_cmd "nixos-rebuild switch --upgrade" $sudo_cmd nixos-rebuild switch --upgrade || rc=$? - run_cmd "collect garbage" $sudo_cmd nix-collect-garbage -d || true - else - run_cmd "channel update" nix-channel --update || rc=$? - run_cmd "upgrade" nix-env -u || rc=$? - run_cmd "collect garbage" nix-collect-garbage -d || true - fi - ;; - brew) - run_cmd "update" brew update || rc=$? - run_cmd "upgrade" brew upgrade || rc=$? - run_cmd "upgrade casks" brew upgrade --cask || true - run_cmd "cleanup" brew cleanup -s || true - ;; - mas) - run_cmd "mas upgrade" mas upgrade || rc=$? - ;; - softwareupdate) - if (( ARG_SECURITY )); then - run_cmd "install recommended" $sudo_cmd softwareupdate --install --recommended --agree-to-license || rc=$? - else - run_cmd "list" softwareupdate --list || true - run_cmd "install all" $sudo_cmd softwareupdate --install --all --agree-to-license --no-scan || rc=$? - fi - ;; - flatpak) - run_cmd "update" flatpak update -y --noninteractive || rc=$? - run_cmd "uninstall unused" flatpak uninstall --unused -y --noninteractive || true - ;; - snap) - run_cmd "refresh" $sudo_cmd snap refresh || rc=$? - ;; - yay) - # shellcheck disable=SC2086 - run_cmd "AUR upgrade" yay -Syu --noconfirm $pacman_ignore || rc=$? - ;; - paru) - # shellcheck disable=SC2086 - run_cmd "AUR upgrade" paru -Syu --noconfirm $pacman_ignore || rc=$? - ;; - fwupd) - run_cmd "refresh metadata" $sudo_cmd fwupdmgr refresh --force || rc=$? - run_cmd "firmware update" $sudo_cmd fwupdmgr update -y --no-reboot-check || true - ;; - rustup) - run_cmd "rustup update" rustup update || rc=$? - ;; - cargo) - run_cmd "cargo install-update" cargo install-update -a || rc=$? - ;; - npm) - run_cmd "npm update -g" npm update -g || rc=$? - ;; - pnpm) - run_cmd "pnpm -g update" pnpm -g update || rc=$? - ;; - pip) - local pip_bin=pip - sys_has pip3 && pip_bin=pip3 - local flags="--user" - sys_is_root && flags="" - run_cmd "pip upgrade" bash -c "$pip_bin list --outdated --format=freeze $flags 2>/dev/null | cut -d= -f1 | xargs -r $pip_bin install -U $flags" || rc=$? - ;; - gem) - run_cmd "gem update" gem update || rc=$? - ;; - esac - - _PKG_CURRENT="" - if (( rc == 0 )); then - log_info "$mgr: ok" - else - log_error "$mgr: rc=$rc" - fi - return $rc -} diff --git a/src/lib/plugins.sh b/src/lib/plugins.sh deleted file mode 100644 index 24053c9..0000000 --- a/src/lib/plugins.sh +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env bash -# External package-manager plugins. -# -# A plugin is a *.sh file in ~/.config/emerger/managers.d/ that defines, -# at minimum, three functions named after its slug : -# -# pm__detect -> return 0 if the manager is present -# pm__run -> perform refresh/upgrade/clean, return 0/non-0 -# -# And optionally: -# -# pm__needs_sudo -> return 0 if the manager needs elevation -# pm__parallel -> return 0 if it's safe to run in parallel -# pm__dev -> return 0 if it belongs to --dev -# pm__icon -> print a short glyph -# -# The plugin must also declare its slug via: -# -# PM_PLUGIN_SLUG= -# -# when sourced. Example plugin at share/plugins/example.sh. - -PLUGIN_SLUGS=() - -plugins_load() { - local dir="$EMERGER_CONFIG/managers.d" - [[ -d $dir ]] || return 0 - local f slug - for f in "$dir"/*.sh; do - [[ -e $f ]] || continue - PM_PLUGIN_SLUG="" - # shellcheck disable=SC1090 - source "$f" || { ui_warn "plugin $f failed to load"; continue; } - slug="$PM_PLUGIN_SLUG" - if [[ -z $slug ]]; then - ui_warn "plugin $f did not set PM_PLUGIN_SLUG"; continue - fi - if ! declare -F "pm_${slug}_detect" >/dev/null; then - ui_warn "plugin $slug: missing pm_${slug}_detect"; continue - fi - if ! declare -F "pm_${slug}_run" >/dev/null; then - ui_warn "plugin $slug: missing pm_${slug}_run"; continue - fi - PLUGIN_SLUGS+=("$slug") - PKG_MANAGERS+=("$slug") - done -} - -plugin_is() { - local name="$1" s - for s in "${PLUGIN_SLUGS[@]}"; do - [[ $s == "$name" ]] && return 0 - done - return 1 -} - -plugin_needs_sudo() { - declare -F "pm_${1}_needs_sudo" >/dev/null && "pm_${1}_needs_sudo" -} -plugin_is_parallel() { - declare -F "pm_${1}_parallel" >/dev/null && "pm_${1}_parallel" -} -plugin_is_dev() { - declare -F "pm_${1}_dev" >/dev/null && "pm_${1}_dev" -} -plugin_detect() { - "pm_${1}_detect" -} -plugin_run() { - "pm_${1}_run" -} -plugin_icon() { - if declare -F "pm_${1}_icon" >/dev/null; then - "pm_${1}_icon" - else - printf '%s' "$(ui_glyph bullet)" - fi -} diff --git a/src/lib/profiles.sh b/src/lib/profiles.sh index 7f8f773..58782fe 100644 --- a/src/lib/profiles.sh +++ b/src/lib/profiles.sh @@ -4,6 +4,8 @@ # 1) $EMERGER_CONFIG/profiles.d/.sh (user) # 2) $EMERGER_ROOT/share/profiles/.sh (shipped) +# Source profile $1 from the first directory that has it. Exit 2 when the +# name is invalid, no file exists, or the user file fails trust_file. profile_load() { local name="$1" [[ -z $name ]] && return 0 @@ -15,12 +17,16 @@ profile_load() { "$EMERGER_CONFIG/profiles.d/${name}.sh" "$EMERGER_ROOT/share/profiles/${name}.sh" ) - local f - for f in "${candidates[@]}"; do - if [[ -f $f ]]; then + local file + for file in "${candidates[@]}"; do + if [[ -f $file ]]; then + # Shipped profiles are part of the checkout being run. + if [[ $file == "$EMERGER_CONFIG/"* ]] && ! trust_file "$file"; then + exit 2 + fi # shellcheck disable=SC1090 - source "$f" - log_info "profile loaded: $name ($f)" + source "$file" || true + log_info "profile loaded: $name ($file)" return 0 fi done @@ -29,21 +35,23 @@ profile_load() { exit 2 } +# Print every profile name with its "# description:" line, user profiles +# first and a shipped one only when no user file has its name. profile_list() { ui_title "Available profiles" - local seen=() p n + local seen=() file name for dir in "$EMERGER_CONFIG/profiles.d" "$EMERGER_ROOT/share/profiles"; do [[ -d $dir ]] || continue - for p in "$dir"/*.sh; do - [[ -f $p ]] || continue - n=$(basename "$p" .sh) - local dup=0 s - for s in "${seen[@]:-}"; do [[ $s == "$n" ]] && dup=1; done - (( dup )) && continue - seen+=("$n") + for file in "$dir"/*.sh; do + [[ -f $file ]] || continue + name=$(basename "$file" .sh) + local is_seen=0 seen_name + for seen_name in "${seen[@]:-}"; do [[ $seen_name == "$name" ]] && is_seen=1; done + (( is_seen )) && continue + seen+=("$name") local desc="" - desc=$(grep -m1 '^# description:' "$p" 2>/dev/null | sed 's/^# description:[[:space:]]*//' || true) - printf ' %s%s%s %s%s%s\n' "$C_CYAN" "$n" "$C_RESET" "$C_GRAY" "$desc" "$C_RESET" + desc=$(grep -m1 '^# description:' "$file" 2>/dev/null | sed 's/^# description:[[:space:]]*//' || true) + printf ' %s%s%s %s%s%s\n' "$C_CYAN" "$name" "$C_RESET" "$C_GRAY" "$desc" "$C_RESET" done done } diff --git a/src/lib/progress.sh b/src/lib/progress.sh deleted file mode 100644 index 43710ff..0000000 --- a/src/lib/progress.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env bash -# Extract a short one-line stat from a command's captured output. -# Used to produce a collapsed summary at end of each step. - -progress_summarize() { - local mgr="$1" file="$2" - [[ -f $file ]] || { printf ''; return; } - case "$mgr" in - apt) - awk '/[0-9]+ upgraded/{for(i=1;i<=NF;i++)if($i=="upgraded,"){u=$(i-1)} for(i=1;i<=NF;i++)if($i=="newly"){n=$(i-1)} for(i=1;i<=NF;i++)if($i=="remove."){r=$(i-1)} printf "%s upgraded, %s new, %s removed", u+0, n+0, r+0; exit}' "$file" - ;; - pacman|yay|paru) - local pkgs - pkgs=$(grep -E '^Packages \([0-9]+\)' "$file" | tail -n1 | sed -E 's/^Packages \(([0-9]+)\).*/\1/') - [[ -n $pkgs ]] && printf '%s packages' "$pkgs" - ;; - dnf|yum) - awk '/^Upgrade +[0-9]+ Package/{print $2" upgraded"; exit} /^Install +[0-9]+ Package/{ins=$2} END{if(ins)print ins" installed"}' "$file" - ;; - flatpak) - grep -cE '^Updating|^Installing' "$file" | awk '{if($1>0)print $1" refreshed"}' - ;; - snap) - grep -cE 'refreshed' "$file" | awk '{if($1>0)print $1" refreshed"}' - ;; - *) : ;; - esac -} - -progress_highlight() { - # Colorize common error keywords in a stream. - sed -E \ - -e "s/(ERROR|Error|error)/$(printf '\033[31m')\1$(printf '\033[0m')/g" \ - -e "s/(WARNING|Warning|warning|WARN)/$(printf '\033[33m')\1$(printf '\033[0m')/g" \ - -e "s/^(E: .*)/$(printf '\033[31m')\1$(printf '\033[0m')/g" \ - -e "s/^(W: .*)/$(printf '\033[33m')\1$(printf '\033[0m')/g" -} diff --git a/src/lib/quiet_hours.sh b/src/lib/quiet_hours.sh new file mode 100644 index 0000000..78a7c7e --- /dev/null +++ b/src/lib/quiet_hours.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Quiet hours: an unattended run (-y) inside QUIET_HOURS does nothing. + +# Exit 0 printing "quiet hours, skipping" when -y is set and the clock is +# inside QUIET_HOURS ("22:00-07:00", may wrap past midnight). A malformed +# value is warned about and ignored. +quiet_hours_check() { + # Times compare as base-10 HHMM: a leading zero must not read as octal. + if [[ -n ${QUIET_HOURS:-} ]] && (( ARG_YES )); then + _hm='([01]?[0-9]|2[0-3]):([0-5][0-9])' + if [[ $QUIET_HOURS =~ ^$_hm-$_hm$ ]]; then + _from=$(( 10#${BASH_REMATCH[1]} * 100 + 10#${BASH_REMATCH[2]} )) + _to=$(( 10#${BASH_REMATCH[3]} * 100 + 10#${BASH_REMATCH[4]} )) + _now=$(date +%H%M) + [[ $_now =~ ^[0-9]{4}$ ]] || _now=0 + _now=$(( 10#$_now )) + if (( _from < _to )); then + (( _now >= _from && _now < _to )) && { echo "quiet hours, skipping"; exit 0; } + else + (( _now >= _from || _now < _to )) && { echo "quiet hours, skipping"; exit 0; } + fi + else + ui_warn "QUIET_HOURS=\"$QUIET_HOURS\" is not HH:MM-HH:MM, ignored" + fi + fi + return 0 +} diff --git a/src/lib/reboot.sh b/src/lib/reboot.sh deleted file mode 100644 index ef31caa..0000000 --- a/src/lib/reboot.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash -# Detect whether the system needs a reboot after updates. - -REBOOT_NEEDED=0 -REBOOT_REASON="" - -reboot_check() { - REBOOT_NEEDED=0; REBOOT_REASON="" - if [[ -f /var/run/reboot-required ]]; then - REBOOT_NEEDED=1 - REBOOT_REASON="/var/run/reboot-required exists" - if [[ -f /var/run/reboot-required.pkgs ]]; then - REBOOT_REASON+=" ($(wc -l /dev/null 2>&1; then - REBOOT_NEEDED=1 - REBOOT_REASON="needs-restarting -r says so" - return - fi - fi - if sys_has dnf && dnf -q needs-restarting -r >/dev/null 2>&1; then - : - elif sys_has dnf; then - REBOOT_NEEDED=1; REBOOT_REASON="dnf needs-restarting"; return - fi - # Kernel version mismatch (running vs latest installed) - local running latest="" - running=$(uname -r) - if sys_has pacman; then - latest=$(pacman -Q linux 2>/dev/null | awk '{print $2}') - elif sys_has dpkg-query; then - latest=$(dpkg-query -W -f='${Version}' linux-image-generic 2>/dev/null || true) - fi - if [[ -n $latest ]] && [[ $running != *"$latest"* ]] && [[ -n $latest ]]; then - : # informational only; don't force reboot just for this - fi -} - -reboot_advisory() { - (( REBOOT_NEEDED )) || return 0 - printf '\n %s%s REBOOT RECOMMENDED%s %s%s%s\n' \ - "$C_YELLOW$C_BOLD" "$(ui_glyph warn)" "$C_RESET" \ - "$C_GRAY" "$REBOOT_REASON" "$C_RESET" - printf ' %srun:%s sudo reboot\n' "$C_DIM" "$C_RESET" -} diff --git a/src/lib/report.sh b/src/lib/report.sh deleted file mode 100644 index d070af3..0000000 --- a/src/lib/report.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env bash -# Export the last run's summary + diff as Markdown. - -report_export() { - local out="${1:-$EMERGER_STATE/last-report.md}" - local hist="$EMERGER_STATE/history.jsonl" - { - printf '# eMerger report\n\n' - printf '- host: `%s`\n' "$(hostname 2>/dev/null || echo '?')" - printf '- date: `%s`\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" - printf '- distro: `%s`\n' "$(sys_distro)" - printf '- version: `eMerger %s`\n\n' "${EMERGER_VERSION:-?}" - if [[ -f $hist ]]; then - printf '## Last run\n\n```json\n' - tail -n 1 "$hist" - printf '```\n\n' - fi - if (( ${#SUMMARY_MANAGERS[@]:-0} > 0 )); then - printf '## Managers\n\n' - local i - for i in "${!SUMMARY_MANAGERS[@]}"; do - printf '- `%s` - **%s**\n' "${SUMMARY_MANAGERS[i]}" "${SUMMARY_RESULTS[i]}" - done - printf '\n' - fi - if [[ -s $DIFF_LAST ]]; then - printf '## Package changes\n\n' - printf '| kind | manager | package | version |\n|---|---|---|---|\n' - awk -F'\t' '{printf "| %s | %s | %s | %s |\n", $1, $2, $3, $4}' "$DIFF_LAST" - printf '\n' - fi - if (( REBOOT_NEEDED )); then - printf '> **Reboot recommended** - %s\n\n' "$REBOOT_REASON" - fi - } >"$out" - ui_ok "Report written to $out" -} diff --git a/src/lib/resume.sh b/src/lib/resume.sh deleted file mode 100644 index 0a6aa11..0000000 --- a/src/lib/resume.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env bash -# Resume support: remember completed managers so an interrupted run can continue. - -: "${RESUME_FILE:=$EMERGER_STATE/resume}" - -resume_load() { - RESUME_DONE=() - [[ -f $RESUME_FILE ]] || return 0 - local line - while IFS= read -r line || [[ -n $line ]]; do - RESUME_DONE+=("$line") - done <"$RESUME_FILE" -} - -resume_has() { - local m="$1" x - for x in "${RESUME_DONE[@]:-}"; do - [[ $x == "$m" ]] && return 0 - done - return 1 -} - -resume_mark() { - local m="$1" - printf '%s\n' "$m" >>"$RESUME_FILE" -} - -resume_clear() { - rm -f "$RESUME_FILE" -} diff --git a/src/lib/retry.sh b/src/lib/retry.sh deleted file mode 100644 index 31d61d2..0000000 --- a/src/lib/retry.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env bash -# Retry a command with exponential backoff on transient failures. -# Detects network errors by scanning output for common keywords. - -retry_cmd() { - local max="${1:-3}"; shift - local attempt=1 rc=0 - while :; do - "$@" - rc=$? - (( rc == 0 )) && return 0 - if (( attempt >= max )); then return "$rc"; fi - local backoff=$(( attempt * 3 )) - log_warn "retry attempt $attempt/$max for: $* (sleeping ${backoff}s)" - sleep "$backoff" - attempt=$(( attempt + 1 )) - done -} - -# Pattern tester: returns 0 if output looks like a transient network failure. -retry_is_transient() { - local text="$1" - local pat='(Temporary failure|Could not resolve|Connection (timed out|reset|refused)|network is unreachable|503 |502 |504 |failed to fetch|EOF occurred|timed out|Try again later)' - [[ $text =~ $pat ]] -} diff --git a/src/lib/run.sh b/src/lib/run.sh deleted file mode 100644 index d032a16..0000000 --- a/src/lib/run.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env bash -# Command runner: dry-run aware, live-log monitor, retry on transient errors, -# one-line collapsed summary on success. - -: "${DRY_RUN:=0}" -: "${UI_VERBOSE:=0}" -: "${RETRY_MAX:=2}" - -run_cmd() { - local label="$1"; shift - if (( DRY_RUN )); then - local joined; joined=$(IFS=' '; printf '%s' "$*") - ui_sub "[dry-run] $joined" - return 0 - fi - local rc=0 - if (( UI_VERBOSE )); then - ui_sub "$label" - "$@" - rc=$? - if (( rc == 0 )); then - return 0 - else - ui_fail "$label" "$rc" - log_error "$label: rc=$rc" - return "$rc" - fi - fi - - local tmp; tmp=$(mktemp -t emerger.XXXXXX) - local attempt=1 - while :; do - : >"$tmp" - ui_monitor_start "$label" "$tmp" - "$@" >"$tmp" 2>&1 - rc=$? - ui_monitor_stop - if (( rc == 0 )); then - local stat="" - stat=$(progress_summarize "${_PKG_CURRENT:-}" "$tmp") - if [[ -n $stat ]]; then - ui_done "$label" "$stat" - else - ui_done "$label" - fi - rm -f "$tmp" - return 0 - fi - local out; out=$(cat "$tmp" 2>/dev/null || true) - if retry_is_transient "$out" && (( attempt < RETRY_MAX )); then - ui_warn "$label: transient failure, retrying ($attempt/$RETRY_MAX)" - log_warn "$label: retry $attempt (rc=$rc)" - attempt=$(( attempt + 1 )) - sleep $(( attempt * 2 )) - continue - fi - ui_fail "$label" "$rc" - log_error "$label: rc=$rc" - tail -n 20 "$tmp" | progress_highlight >&2 - log_error "$(tail -n 50 "$tmp")" - rm -f "$tmp" - return "$rc" - done -} diff --git a/src/lib/run/command.sh b/src/lib/run/command.sh new file mode 100644 index 0000000..ba776b0 --- /dev/null +++ b/src/lib/run/command.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# Command runner: dry-run aware, live-log monitor, retry on transient errors, +# one-line collapsed summary on success. + +: "${DRY_RUN:=0}" +: "${UI_VERBOSE:=0}" +: "${RETRY_ATTEMPTS:=2}" +# Seconds before the first retry, the n-th retry waits n times as long. +: "${RETRY_DELAY:=3}" +# Seconds one command may run before it is stopped, 0 for no limit. +: "${MANAGER_TIMEOUT:=0}" + +# Capture file of the command running now, removed by run_cmd_cleanup. +_RUN_TMP="" + +# Set _RUN_TIMEOUT_PREFIX to the prefix that bounds a command by MANAGER_TIMEOUT (empty +# when there is no limit or no `timeout`, which is warned about once). Probed +# once per run: call it in the current shell, never in a subshell. +_run_timeout_prefix() { + _RUN_TIMEOUT_PREFIX=() + (( MANAGER_TIMEOUT > 0 )) || return 0 + if [[ -z ${_RUN_TIMEOUT_MODE:-} ]]; then + _RUN_TIMEOUT_MODE=none + if command -v timeout >/dev/null 2>&1; then + # --foreground keeps a sudo password prompt on the terminal. + if timeout --foreground 5 true 2>/dev/null; then + _RUN_TIMEOUT_MODE="fg" + else + _RUN_TIMEOUT_MODE="plain" + fi + else + ui_warn "MANAGER_TIMEOUT=$MANAGER_TIMEOUT is not applied: no timeout command found" + fi + fi + case $_RUN_TIMEOUT_MODE in + fg) _RUN_TIMEOUT_PREFIX=(timeout --foreground -k 10 "$MANAGER_TIMEOUT") ;; + plain) _RUN_TIMEOUT_PREFIX=(timeout "$MANAGER_TIMEOUT") ;; + esac + return 0 +} + +# Remove the capture file of an interrupted run_cmd. Called by the exit trap. +run_cmd_cleanup() { + [[ -n $_RUN_TMP ]] && rm -f "$_RUN_TMP" + _RUN_TMP="" + return 0 +} + +# Strip terminal control sequences from stdin: CSI and OSC sequences whole, +# C0 controls except tab and newline, invalid UTF-8 and C1 controls. With $1 +# set to `log` the text is bound for a file and keeps valid UTF-8; otherwise +# it is bound for the terminal and loses bytes above 0x7F on one outside UTF-8. +run_sanitize() { + local target="${1:-terminal}" + # Escape sequences, then control bytes, then invalid UTF-8 (iconv -c), so + # the C1 pairs left are whole characters: removing them in one pass cannot + # join the halves of another, since 0xC2 only ever starts a character. + LC_ALL=C sed -E -e $'s/\x1b\\[[0-9;?]*[a-zA-Z]//g' -e $'s/\x1b\\][^\x07\x1b]*(\x07|\x1b\\\\)?//g' \ + | LC_ALL=C tr -d '\000-\010\013-\037\177' \ + | _run_valid_utf8 \ + | LC_ALL=C sed -e $'s/\xc2[\x80-\x9f]//g' \ + | if [[ $target == log ]]; then cat; else ui_terminal_bytes; fi +} + + +# Copy stdin to stdout without invalid UTF-8. Without iconv, drop every byte +# in 0x80-0x9F instead: no C1 control survives, at the cost of the non-ASCII +# characters holding such a byte. +_run_valid_utf8() { + if command -v iconv >/dev/null 2>&1; then + iconv -c -f UTF-8 -t UTF-8 2>/dev/null || true + else + LC_ALL=C tr -d '\200-\237' + fi +} + +# Return 0 when command output $1 reads as a transient network failure, +# which run_cmd retries. +retry_is_transient() { + local text="$1" + local pattern='(Temporary failure|Could not resolve|Connection (timed out|reset|refused)|network is unreachable|503 |502 |504 |failed to fetch|EOF occurred|timed out|Try again later)' + [[ $text =~ $pattern ]] +} + +# Run command "$@" under label $1: dry-run aware, retried on transient +# errors, bounded by MANAGER_TIMEOUT. Return the command's exit code (124 +# on timeout). The command never inherits the lock fd 9. +run_cmd() { + local label="$1"; shift + if (( DRY_RUN )); then + local joined; joined=$(IFS=' '; printf '%s' "$*") + ui_sub "[dry-run] $joined" + return 0 + fi + if (( UI_VERBOSE )); then + _run_cmd_verbose "$label" "$@" + return + fi + _run_cmd_captured "$label" "$@" +} + +# Run command $2... under label $1 for run_cmd under -v: output straight to +# the terminal (stderr under --json), no retry. +_run_cmd_verbose() { + local label="$1"; shift + local rc=0 + ui_sub "$label" + local -a timeout_prefix=() + declare -F "$1" >/dev/null || { _run_timeout_prefix; timeout_prefix=(${_RUN_TIMEOUT_PREFIX[@]+"${_RUN_TIMEOUT_PREFIX[@]}"}); } + # Under --json, stdout carries the JSON object alone. + local out_fd=1 + (( ${ARG_JSON:-0} )) && out_fd=2 + ${timeout_prefix[@]+"${timeout_prefix[@]}"} "$@" 9>&- >&"$out_fd" + rc=$? + (( rc == 124 && ${#timeout_prefix[@]} > 0 )) && ui_warn "$label: timed out after ${MANAGER_TIMEOUT}s" + if (( rc == 0 )); then + return 0 + else + ui_fail "$label" "$rc" + log_error "$label: rc=$rc" + return "$rc" + fi +} + +# Run command $2... under label $1 for run_cmd without -v: output captured +# under the live monitor, retried on transient failures, its tail shown on failure. +_run_cmd_captured() { + local label="$1"; shift + local rc=0 + local capture + if ! capture=$(mktemp -t emerger.XXXXXX 2>/dev/null); then + # Read by ui_done. + # shellcheck disable=SC2034 + UI_LAST_ELAPSED="" + ui_fail "$label" 1 + ui_err "$label: cannot create a temp file in ${TMPDIR:-/tmp}" + log_error "$label: cannot create a temp file in ${TMPDIR:-/tmp}" + return 1 + fi + _RUN_TMP=$capture + local -a timeout_prefix=() + # `timeout` runs programs only: a shell function runs unbounded. + declare -F "$1" >/dev/null || { _run_timeout_prefix; timeout_prefix=(${_RUN_TIMEOUT_PREFIX[@]+"${_RUN_TIMEOUT_PREFIX[@]}"}); } + local attempt=1 + while :; do + : >"$capture" + ui_monitor_start "$label" "$capture" + ${timeout_prefix[@]+"${timeout_prefix[@]}"} "$@" >"$capture" 2>&1 9>&- + rc=$? + ui_monitor_stop + if (( rc == 124 && ${#timeout_prefix[@]} > 0 )); then + ui_warn "$label: timed out after ${MANAGER_TIMEOUT}s" + log_error "$label: timed out after ${MANAGER_TIMEOUT}s" + fi + if (( rc == 0 )); then + local summary="" + summary=$(progress_summarize "${_PKG_CURRENT:-}" "$capture") + if [[ -n $summary ]]; then + ui_done "$label" "$summary" + else + ui_done "$label" + fi + rm -f "$capture"; _RUN_TMP="" + return 0 + fi + local output; output=$(cat "$capture" 2>/dev/null || true) + if retry_is_transient "$output" && (( attempt < RETRY_ATTEMPTS )); then + ui_warn "$label: transient failure, retrying ($attempt/$RETRY_ATTEMPTS)" + log_warn "$label: retry $attempt (rc=$rc)" + sleep $(( RETRY_DELAY * attempt )) + attempt=$(( attempt + 1 )) + continue + fi + ui_fail "$label" "$rc" + log_error "$label: rc=$rc" + tail -n 20 "$capture" | run_sanitize | ui_highlight | sed "s/^/ ${C_DIM}${C_GRAY}$(ui_glyph v)${C_RESET} /" >&2 + # No escape and no "|" in the log: output cannot forge a log line. + log_error "$(tail -n 50 "$capture" | run_sanitize log | tr '|' '/')" + rm -f "$capture"; _RUN_TMP="" + return "$rc" + done +} diff --git a/src/lib/run/parallel.sh b/src/lib/run/parallel.sh new file mode 100644 index 0000000..9e65676 --- /dev/null +++ b/src/lib/run/parallel.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# --parallel: the managers that can run side by side, as one step. + +# PIDs of the --parallel managers still running. +_PARALLEL_PIDS=() + +# Run managers $3... side by side as step $1 of $2, each logging to +# $EMERGER_STATE/parallel-.log, then record each result. The +# interrupt handler stops the PIDs in _PARALLEL_PIDS. +run_parallel() { + local step="$1" total="$2"; shift 2 + local -a parallel=("$@") + local manager + ui_step "$step" "$total" + local joined; printf -v joined '%s ' "${parallel[@]}" + ui_title "parallel: ${joined% }" + local pids=() names=() logs=() exit_codes=() + for manager in "${parallel[@]}"; do + local log_file="$EMERGER_STATE/parallel-$manager.log" + # `||` keeps errexit off inside pkg_run, as in a serial run, so a + # failing step is retried and logged instead of ending the subshell. + # Its own capture file is removed when the run is interrupted. + ( trap 'run_cmd_cleanup; exit 1' INT TERM + # Read by the ui functions in this subshell. + # shellcheck disable=SC2034 + UI_IS_TTY=0; start=$SECONDS; rc=0 + pkg_run "$manager" >"$log_file" 2>&1 || rc=$? + printf '%d\n' $(( SECONDS - start )) >"$log_file.secs" + exit "$rc" ) 9>&- & + pids+=($!); names+=("$manager"); logs+=("$log_file") + done + _PARALLEL_PIDS=("${pids[@]}") + ui_monitor_start "running ${#parallel[@]} managers" "${logs[0]}" + local i secs + for i in "${!pids[@]}"; do + if wait "${pids[i]}"; then exit_codes[i]=0; else exit_codes[i]=$?; fi + done + _PARALLEL_PIDS=() + ui_monitor_stop + # Read by ui_done. + # shellcheck disable=SC2034 + UI_LAST_ELAPSED="" + for i in "${!pids[@]}"; do + secs=$(cat "${logs[i]}.secs" 2>/dev/null || true) + [[ $secs =~ ^[0-9]+$ ]] || secs=0 + rm -f "${logs[i]}.secs" + if (( exit_codes[i] == 0 )); then + summary_add "${names[i]}" ok "$secs" + ui_done "${names[i]}" + resume_mark "${names[i]}" + else + summary_add "${names[i]}" fail "$secs" + ui_fail "${names[i]}" "${exit_codes[i]}" + tail -n 10 "${logs[i]}" | run_sanitize | ui_highlight >&2 || true + fi + done +} diff --git a/src/lib/run/select.sh b/src/lib/run/select.sh new file mode 100644 index 0000000..3adf07f --- /dev/null +++ b/src/lib/run/select.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Manager selection: which detected managers this run updates. + +# Set RUN_SKIP_REASON to why detected manager $1 stays out of this run: dev, +# firmware, resume, only, except, security or download. Empty means it runs. +run_skip_reason() { + local manager="$1" + RUN_SKIP_REASON="" + if pkg_is_dev "$manager" && (( ! ${ARG_DEV:-0} )); then + RUN_SKIP_REASON=dev + elif [[ $manager == fwupd ]] && { (( ${ARG_NO_FIRMWARE:-0} )) || (( ! ${ARG_FIRMWARE:-0} )); }; then + RUN_SKIP_REASON=firmware + # Pi bootloader: always checked, flashed only with --firmware. + elif [[ $manager == rpi-eeprom ]] && (( ${ARG_NO_FIRMWARE:-0} )); then + RUN_SKIP_REASON=firmware + elif (( ${ARG_RESUME:-0} )) && resume_has "$manager"; then + RUN_SKIP_REASON=resume + elif [[ -n ${ARG_ONLY:-} ]] && ! args_list_has "$ARG_ONLY" "$manager"; then + RUN_SKIP_REASON=only + elif [[ -n ${ARG_EXCEPT:-} ]] && args_list_has "$ARG_EXCEPT" "$manager"; then + RUN_SKIP_REASON=except + elif (( ${ARG_SECURITY:-0} )) && ! pkg_has_security "$manager"; then + RUN_SKIP_REASON=security + elif (( ${ARG_DOWNLOAD_ONLY:-0} )) && ! pkg_has_download_only "$manager"; then + RUN_SKIP_REASON=download + fi + return 0 +} + +# Return 0 if a manager selected for this run, or --deep-clean, needs sudo. +# Same selection as the run loop (run_skip_reason). +run_needs_sudo() { + local manager + for manager in "${PKG_MANAGERS[@]}"; do + pkg_detect "$manager" || continue + run_skip_reason "$manager" + [[ -n $RUN_SKIP_REASON ]] && continue + if pkg_needs_sudo "$manager"; then return 0; fi + done + (( ${ARG_DEEP_CLEAN:-0} )) +} + +# Append each detected manager this run updates to the caller's arrays: +# `detected`, and `parallel` (under --parallel, when it can run beside others) +# or `serial`. A skipped manager is reported unless it is skipped silently. +run_select() { + local manager + for manager in "${PKG_MANAGERS[@]}"; do + pkg_detect "$manager" || continue + run_skip_reason "$manager" + case $RUN_SKIP_REASON in + resume) ui_muted "skip $manager (resume)"; continue ;; + except) ui_muted "skip $manager (--except)"; continue ;; + security) + ui_warn "skip $manager: no security-only updates, --security never runs a full upgrade" + [[ $manager == apt ]] && ui_warn "install the unattended-upgrades package to get security-only updates with apt" + log_warn "$manager skipped: no security channel" + continue + ;; + download) + ui_muted "skip $manager (no download-only mode)" + log_warn "$manager skipped: no download-only mode" + continue + ;; + ?*) continue ;; + esac + detected+=("$manager") + if (( ARG_PARALLEL )) && pkg_is_parallelizable "$manager"; then + parallel+=("$manager") + else + serial+=("$manager") + fi + done +} diff --git a/src/lib/run/sudo.sh b/src/lib/run/sudo.sh new file mode 100644 index 0000000..517c6fd --- /dev/null +++ b/src/lib/run/sudo.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# sudo timestamp keep-alive for the length of the run. + +# Start the background loop that refreshes the sudo timestamp every $1 +# seconds (default 60), its PID in SUDO_KEEPALIVE_PID. The loop holds no +# terminal or pipe open, ends with its parent (checked by parent PID, so a +# reused PID does not keep it alive) and takes its sleep with it on TERM. +run_sudo_keepalive() { + local interval="${1:-60}" + ( + exec /dev/null 2>&1 + sleep_pid=0 + trap 'kill "$sleep_pid" 2>/dev/null; exit 0' TERM + while sys_is_parent_alive "$$"; do + sudo -n true + sleep "$interval" & sleep_pid=$! + wait "$sleep_pid" + done + ) 9>&- & + SUDO_KEEPALIVE_PID=$! + disown "$SUDO_KEEPALIVE_PID" 2>/dev/null || true +} diff --git a/src/lib/selfupdate.sh b/src/lib/selfupdate.sh new file mode 100644 index 0000000..d0d67dc --- /dev/null +++ b/src/lib/selfupdate.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Self-update of a git checkout (git pull --ff-only). + +# Fast-forward the git checkout at $1 and print the commits pulled. Return 1 +# when it is not a checkout, git is missing, or the fetch or pull fails. +self_update() { + local root="$1" + ui_title "Self-update" + if [[ ! -d "$root/.git" ]]; then + ui_err "Not a git checkout. Re-clone: git clone https://github.com/MasterCruelty/eMerger" + return 1 + fi + if ! sys_has git; then + ui_err "git not installed" + return 1 + fi + local branch before after + branch=$(git -C "$root" rev-parse --abbrev-ref HEAD) + ui_info "Branch: $branch" + if (( DRY_RUN )); then + ui_sub "[dry-run] git -C $root pull --ff-only" + return 0 + fi + before=$(git -C "$root" rev-parse HEAD) + if ! git -C "$root" fetch --quiet 9>&-; then + ui_err "git fetch failed" + return 1 + fi + if ! git -C "$root" pull --ff-only --quiet 9>&-; then + ui_err "git pull failed (non fast-forward?)" + return 1 + fi + after=$(git -C "$root" rev-parse HEAD) + if [[ $before == "$after" ]]; then + ui_ok "Already up to date." + else + ui_ok "Updated ${before:0:7}..${after:0:7}" + git -C "$root" log --oneline "$before..$after" | sed "s/^/ $(ui_glyph dot) /" + fi +} diff --git a/src/lib/snapshot.sh b/src/lib/snapshot.sh deleted file mode 100644 index 993e950..0000000 --- a/src/lib/snapshot.sh +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env bash -# Pre-update filesystem snapshot via snapper, timeshift or btrfs. - -snapshot_create() { - ui_title "Snapshot" - local desc="eMerger pre-update $(date -u +%Y-%m-%dT%H:%M:%SZ)" - if (( DRY_RUN )); then - ui_sub "[dry-run] would create snapshot: $desc" - return 0 - fi - if sys_has snapper && snapper list-configs 2>/dev/null | grep -q '^root'; then - if sudo snapper -c root create --description "$desc" --type single --cleanup-algorithm number; then - ui_ok "snapper snapshot created" - return 0 - fi - fi - if sys_has timeshift; then - if sudo timeshift --create --comments "$desc" --tags D >/dev/null 2>&1; then - ui_ok "timeshift snapshot created" - return 0 - fi - fi - if sys_has btrfs && mount | grep -q 'on / type btrfs'; then - local snap_dir="/.snapshots/emerger" - sudo mkdir -p "$snap_dir" 2>/dev/null || true - local name="$snap_dir/$(date +%Y-%m-%dT%H-%M-%S)" - if sudo btrfs subvolume snapshot -r / "$name" >/dev/null 2>&1; then - ui_ok "btrfs snapshot: $name" - return 0 - fi - fi - ui_warn "No snapshot tool available (snapper/timeshift/btrfs); continuing without." - return 1 -} - -# Roll back to the most recent eMerger-created snapshot. -# Supports snapper (native rollback) and timeshift (--restore). -# For raw btrfs snapshots the user must swap subvolumes manually - we print -# the path of the latest one and refuse to touch /. -snapshot_rollback() { - ui_title "Rollback" - if sys_has snapper && snapper list-configs 2>/dev/null | grep -q '^root'; then - local last - last=$(snapper -c root list 2>/dev/null | awk -F'|' '/eMerger pre-update/ {gsub(/ /,"",$2); last=$2} END{print last}') - if [[ -n $last ]]; then - ui_muted "Rolling back to snapper snapshot #$last" - if (( DRY_RUN )); then - ui_sub "[dry-run] would run: snapper -c root rollback $last" - return 0 - fi - if sudo snapper -c root rollback "$last"; then - ui_ok "Rollback queued. Reboot to apply." - return 0 - fi - ui_err "snapper rollback failed"; return 1 - fi - ui_warn "No eMerger snapper snapshot found." - fi - if sys_has timeshift; then - if (( DRY_RUN )); then - ui_sub "[dry-run] would run: timeshift --restore (interactive)" - return 0 - fi - ui_muted "Launching timeshift --restore" - sudo timeshift --restore - return $? - fi - if sys_has btrfs && mount | grep -q 'on / type btrfs'; then - local snap_dir="/.snapshots/emerger" latest - if [[ -d $snap_dir ]]; then - latest=$(ls -1t "$snap_dir" 2>/dev/null | head -n1) - if [[ -n $latest ]]; then - ui_warn "Latest btrfs snapshot: $snap_dir/$latest" - ui_warn "Automatic btrfs rollback is not performed - swap subvolumes manually." - return 1 - fi - fi - fi - ui_err "No rollback mechanism available." - return 1 -} diff --git a/src/lib/state/diff.sh b/src/lib/state/diff.sh new file mode 100644 index 0000000..cb7d816 --- /dev/null +++ b/src/lib/state/diff.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# Package lists before and after a run, and the diff between them. + +# Read by the entry point. +# shellcheck disable=SC2034 +DIFF_BEFORE="$EMERGER_STATE/pkgs.before" +DIFF_AFTER="$EMERGER_STATE/pkgs.after" +DIFF_LAST="$EMERGER_STATE/pkgs.diff" + +# Write every installed package to file $1, sorted, as "sourcename +# version" lines, source being apt (dpkg), pacman, rpm, flatpak, snap or brew. +# The tools run without the lock fd. +diff_snapshot() { + local out="$1" + : >"$out" + { + if sys_has dpkg-query; then + dpkg-query -W -f='apt\t${Package}\t${Version}\n' 2>/dev/null >>"$out" + fi + if sys_has pacman; then + pacman -Q 2>/dev/null | awk '{print "pacman\t"$1"\t"$2}' >>"$out" + fi + if sys_has rpm; then + rpm -qa --qf 'rpm\t%{NAME}\t%{VERSION}-%{RELEASE}\n' 2>/dev/null >>"$out" + fi + if sys_has flatpak; then + flatpak list --columns=application,version 2>/dev/null | awk -F'\t' 'NR>1 || tolower($1) !~ /^application$/ {if ($1!="") print "flatpak\t"$1"\t"$2}' >>"$out" + fi + if sys_has snap; then + snap list 2>/dev/null | tail -n +2 | awk '{print "snap\t"$1"\t"$2}' >>"$out" + fi + if sys_has brew; then + brew list --versions 2>/dev/null | awk '{print "brew\t"$1"\t"$2}' >>"$out" + fi + } 9>&- + sort -o "$out" "$out" 2>/dev/null || true +} + +# Write the changes from snapshot $1 to snapshot $2 into $3, one line per +# change: "+" added, "-" removed, "~" upgraded ("old -> new"). Versions are +# compared as sets per manager and name, so a package installed in several +# versions (rpm kernels) yields only the versions that came or went, and "~" +# only when exactly one version left and one arrived. +diff_compute() { + local before="$1" after="$2" out="$3" + : >"$out" + [[ -f $before && -f $after ]] || return 0 + # Read the before file in BEGIN: an NR == FNR test would also hold for + # the after file when the before file is empty. + _DIFF_BEFORE="$before" awk -F'\t' -v OFS='\t' ' + BEGIN { + src = ENVIRON["_DIFF_BEFORE"] + while ((getline line < src) > 0) { + split(line, f, "\t") + if (f[2] == "") continue + k = f[1] OFS f[2]; e = k OFS f[3] + if (!(e in b)) { b[e] = 1; bl[k] = bl[k] "\037" f[3] } + } + close(src) + } + $2 == "" { next } + { k = $1 OFS $2; e = k OFS $3 } + !(e in a) { a[e] = 1; al[k] = al[k] "\037" $3 } + END { + for (k in bl) if (!(k in al)) al[k] = "" + for (k in al) { + nr = 0; na = 0 + n = split(substr(bl[k], 2), v, "\037") + for (i = 1; i <= n; i++) if (!((k OFS v[i]) in a)) rv[++nr] = v[i] + n = split(substr(al[k], 2), v, "\037") + for (i = 1; i <= n; i++) if (!((k OFS v[i]) in b)) av[++na] = v[i] + if (nr == 1 && na == 1) { print 3, "~", k, rv[1] " -> " av[1]; continue } + for (i = 1; i <= na; i++) print 1, "+", k, av[i] + for (i = 1; i <= nr; i++) print 2, "-", k, rv[i] + } + }' "$after" | LC_ALL=C sort -t$'\t' -k1,1n -k3,3 -k4,4 -k5,5 | cut -f2- >>"$out" +} + +# Print the added, removed and upgraded counts of diff file $1 (default +# DIFF_LAST), then each change, or that none is recorded. Package names and +# versions come from outside and are stripped of terminal controls. +diff_show() { + local file="${1:-$DIFF_LAST}" + if [[ ! -s $file ]]; then + ui_muted "No package changes recorded." + return + fi + ui_title "Package changes" + local added removed upgraded + added=$(grep -c '^+' "$file" || true) + removed=$(grep -c '^-' "$file" || true) + upgraded=$(grep -c '^~' "$file" || true) + printf ' %s+%s %d added %s-%s %d removed %s~%s %d upgraded\n\n' \ + "$C_GREEN" "$C_RESET" "${added:-0}" \ + "$C_RED" "$C_RESET" "${removed:-0}" \ + "$C_YELLOW" "$C_RESET" "${upgraded:-0}" + run_sanitize <"$file" | awk -F'\t' ' + $1=="~"{printf " \033[33m~\033[0m %-10s %-30s %s\n", $2, $3, $4} + $1=="+"{printf " \033[32m+\033[0m %-10s %-30s %s\n", $2, $3, $4} + $1=="-"{printf " \033[31m-\033[0m %-10s %-30s %s\n", $2, $3, $4} + ' +} + +# Print the number of changes in diff file $1 (default DIFF_LAST), 0 when +# it is missing or empty. +diff_count_changed() { + local file="${1:-$DIFF_LAST}" + [[ -s $file ]] || { echo 0; return; } + wc -l <"$file" +} diff --git a/src/lib/state/estimate.sh b/src/lib/state/estimate.sh new file mode 100644 index 0000000..c279da9 --- /dev/null +++ b/src/lib/state/estimate.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Estimate step duration based on recent history.jsonl entries. + +# Print the average time manager $1 took over the last 10 runs, as "~42s" or +# "~9m30s", from each run's per-manager "secs". Print nothing without data. +estimate_for() { + local manager="$1" + local history="$EMERGER_STATE/history.jsonl" + [[ -f $history ]] || return 0 + tail -n 10 "$history" 2>/dev/null | awk -v key="\"name\":\"$manager\"," ' + { + line = $0 + while ((p = index(line, key)) > 0) { + line = substr(line, p + length(key)) + obj = substr(line, 1, index(line "}", "}") - 1) + if (match(obj, /"secs":[0-9]+/)) { + d = substr(obj, RSTART + 7, RLENGTH - 7) + 0 + if (d > 0) { sum += d; n += 1 } + } + } + } + END { + if (n == 0) exit + avg = int(sum / n + 0.5) + if (avg < 60) printf "~%ds", avg + else printf "~%dm%02ds", int(avg / 60), avg % 60 + } + ' +} diff --git a/src/lib/state/history.sh b/src/lib/state/history.sh new file mode 100644 index 0000000..116ee73 --- /dev/null +++ b/src/lib/state/history.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Run history in $EMERGER_STATE/history.jsonl: append and show. + +# Append JSON line $1 to history.jsonl, keeping the last 500 lines. +history_append() { + printf '%s\n' "$1" >>"$EMERGER_STATE/history.jsonl" 2>/dev/null || true + + local history="$EMERGER_STATE/history.jsonl" + if [[ -f $history ]] && [[ $(wc -l <"$history") -gt 500 ]]; then + tail -n 500 "$history" >"$history.tmp" && mv "$history.tmp" "$history" + fi +} + +# Print the last 10 runs of history.jsonl, one line each: time, duration, +# error count and a reboot tag. +history_show() { + local history="$EMERGER_STATE/history.jsonl" + if [[ ! -f $history ]]; then + ui_muted "No history yet." + return + fi + ui_title "Recent runs" + tail -n 10 "$history" | while IFS= read -r line; do + local timestamp duration errors reboot + timestamp=$(history_text "$line" ts) + duration=$(history_field "$line" duration) + errors=$(history_field "$line" errors) + reboot=$(history_field "$line" reboot) + local tag="" + [[ ${reboot:-0} -gt 0 ]] && tag=" ${C_YELLOW}reboot${C_RESET}" + if [[ ${errors:-0} -gt 0 ]]; then + printf ' %s%s%s %s %ss %serrors=%s%s%s\n' "$C_RED" "$(ui_glyph cross)" "$C_RESET" "$timestamp" "$duration" "$C_YELLOW" "$errors" "$C_RESET" "$tag" + else + printf ' %s%s%s %s %ss%s\n' "$C_GREEN" "$(ui_glyph check)" "$C_RESET" "$timestamp" "$duration" "$tag" + fi + done +} + +# Print number field $2 of history line $1 ("duration", "errors", ...), +# empty when the line has none. +history_field() { + printf '%s' "$1" | sed -n "s/.*\"$2\":\([0-9]*\).*/\1/p" +} + +# Print string field $2 of history line $1 ("ts", "name", "result"), empty +# when the line has none. +history_text() { + printf '%s' "$1" | sed -n "s/.*\"$2\":\"\([^\"]*\)\".*/\1/p" +} diff --git a/src/lib/state/lock.sh b/src/lib/state/lock.sh new file mode 100644 index 0000000..09b053f --- /dev/null +++ b/src/lib/state/lock.sh @@ -0,0 +1,111 @@ +#!/usr/bin/env bash +# Global lock: prevent two concurrent eMerger runs from stepping on each other. +# One path per user, independent of the session environment, so a cron or +# timer run and an interactive run see the same lock. + +# 1 while this process holds the mkdir fallback lock. +_LOCK_DIR_IS_HELD=0 +# PID last read from the mkdir fallback lock, empty when none was written. +_LOCK_DIR_PID="" + +# Take the lock "$EMERGER_STATE/emerger.lock", path kept in EMERGER_LOCK: flock on +# fd 9 when flock exists, else an atomic mkdir of "$EMERGER_LOCK.d". Return 1 +# with a message when another run holds it or the lock path cannot be opened. +# Children must not inherit fd 9 (`9>&-`). +lock_acquire() { + EMERGER_LOCK="$EMERGER_STATE/emerger.lock" + if ! command -v flock >/dev/null 2>&1; then + _lock_acquire_dir + return + fi + # Append mode: a refused run must not truncate the holder's PID line. + # Keep the braces: a bare `exec 9>>x 2>/dev/null` silences stderr for good. + if ! { exec 9>>"$EMERGER_LOCK"; } 2>/dev/null; then + ui_err "Cannot open the lock file $EMERGER_LOCK." + return 1 + fi + if ! flock -n 9; then + _lock_refused "$(cat "$EMERGER_LOCK" 2>/dev/null)" + { exec 9>&-; } 2>/dev/null || true + return 1 + fi + : >"$EMERGER_LOCK" + printf '%d\n' "$$" >&9 + return 0 +} + +# Take the mkdir fallback lock, replacing it if its holder is gone. The +# replacement runs under a second mkdir lock ("$dir.break") and checks the +# holder again there, so two runs finding the same dead holder never both +# take over. +_lock_acquire_dir() { + local dir="$EMERGER_LOCK.d" break_dir="$EMERGER_LOCK.d.break" rc=1 + if mkdir "$dir" 2>/dev/null; then + _lock_dir_own "$dir" + return 0 + fi + if [[ ! -d $dir ]]; then + ui_err "Cannot create the lock directory $dir." + return 1 + fi + if _lock_dir_is_live "$dir"; then + _lock_refused "$_LOCK_DIR_PID" + return 1 + fi + if ! mkdir "$break_dir" 2>/dev/null; then + # Clear a break lock left by a crash for the next run. + _lock_dir_is_fresh "$break_dir" || rm -rf "$break_dir" + _lock_refused "$_LOCK_DIR_PID" + return 1 + fi + if ! _lock_dir_is_live "$dir"; then + rm -rf "$dir" + mkdir "$dir" 2>/dev/null && _lock_dir_own "$dir" && rc=0 + fi + rm -rf "$break_dir" + (( rc == 0 )) || _lock_refused "$_LOCK_DIR_PID" + return "$rc" +} + +# Write this process's PID into lock directory $1 and mark the lock held. +_lock_dir_own() { + printf '%d\n' "$$" >"$1/pid" + _LOCK_DIR_IS_HELD=1 +} + +# Return 0 when lock directory $1 has a live holder: its PID answers +# `kill -0`, or no PID is written yet and the directory is fresh (the holder +# may be between its mkdir and its write). Set _LOCK_DIR_PID to the PID read. +_lock_dir_is_live() { + _LOCK_DIR_PID=$(cat "$1/pid" 2>/dev/null || true) + if [[ $_LOCK_DIR_PID =~ ^[0-9]+$ ]] && kill -0 "$_LOCK_DIR_PID" 2>/dev/null; then + return 0 + fi + [[ -z $_LOCK_DIR_PID ]] && _lock_dir_is_fresh "$1" +} + +# Return 0 if directory $1 was modified less than 10 seconds ago. An +# unreadable age counts as old, so a lock left by a crash is still taken over. +_lock_dir_is_fresh() { + local mtime now + mtime=$(stat -c %Y -- "$1" 2>/dev/null || stat -f %m -- "$1" 2>/dev/null) || return 1 + now=$(date +%s 2>/dev/null) || return 1 + [[ $mtime =~ ^[0-9]+$ && $now =~ ^[0-9]+$ ]] || return 1 + (( now - mtime < 10 )) +} + +# Report that the run holding the lock (PID $1, may be empty) blocks this one. +_lock_refused() { + local pid="${1//[!0-9]/}" + ui_err "Another eMerger run is in progress (PID ${pid:-unknown}, lock: $EMERGER_LOCK)." + ui_muted "Wait for it to finish, or stop that process. Deleting the lock file does not release the lock." +} + +# Release the lock if this process holds it. +lock_release() { + { exec 9>&-; } 2>/dev/null || true + if (( _LOCK_DIR_IS_HELD )); then + rm -rf "$EMERGER_LOCK.d" + _LOCK_DIR_IS_HELD=0 + fi +} diff --git a/src/lib/state/metrics.sh b/src/lib/state/metrics.sh new file mode 100644 index 0000000..636e10a --- /dev/null +++ b/src/lib/state/metrics.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# Prometheus textfile-collector export. +# Reads the most recent entry of history.jsonl and renders a .prom file. + +# Write the last history.jsonl run as Prometheus textfile gauges to path $1, +# replaced atomically and readable by all. Return 1 without history or when the file cannot be written. +metrics_export() { + local out="$1" + local history="$EMERGER_STATE/history.jsonl" + if [[ ! -f $history ]]; then + ui_err "No history yet ($history missing)" + return 1 + fi + local last + last=$(tail -n 1 "$history") + [[ -z $last ]] && { ui_err "history.jsonl is empty"; return 1; } + + local timestamp duration freed errors reboot + timestamp=$(history_text "$last" ts) + duration=$(history_field "$last" duration) + freed=$(history_field "$last" freed_kb) + errors=$(history_field "$last" errors) + reboot=$(history_field "$last" reboot) + + # Epoch seconds: GNU date first, then the BSD form macOS ships. + local epoch=0 + if [[ -n $timestamp ]]; then + epoch=$(date -d "$timestamp" +%s 2>/dev/null \ + || date -j -u -f '%Y-%m-%dT%H:%M:%SZ' "$timestamp" +%s 2>/dev/null \ + || echo 0) + fi + + # Fresh random name beside the target, so nothing planted there is followed. + local tmp + tmp=$(mktemp "$out.XXXXXX") || { ui_err "cannot write beside $out"; return 1; } + _metrics_render >"$tmp" + # Textfile collectors usually run as another user: keep the file readable. + chmod 0644 "$tmp" + mv "$tmp" "$out" + ui_ok "metrics written to $out" +} + +# Print the textfile-collector gauges of metrics_export's locals: epoch, duration, +# freed (KiB), errors, reboot and the history line last for the per-manager +# results. +_metrics_render() { + printf '# HELP emerger_last_run_timestamp_seconds Unix timestamp of the last eMerger run\n' + printf '# TYPE emerger_last_run_timestamp_seconds gauge\n' + printf 'emerger_last_run_timestamp_seconds %s\n' "${epoch:-0}" + printf '# HELP emerger_last_run_duration_seconds Duration of the last run\n' + printf '# TYPE emerger_last_run_duration_seconds gauge\n' + printf 'emerger_last_run_duration_seconds %s\n' "${duration:-0}" + printf '# HELP emerger_last_run_freed_bytes Bytes freed by the last run\n' + printf '# TYPE emerger_last_run_freed_bytes gauge\n' + printf 'emerger_last_run_freed_bytes %s\n' "$(( ${freed:-0} * 1024 ))" + printf '# HELP emerger_last_run_errors Manager failures in the last run\n' + printf '# TYPE emerger_last_run_errors gauge\n' + printf 'emerger_last_run_errors %s\n' "${errors:-0}" + printf '# HELP emerger_reboot_required Whether a reboot is pending (0/1)\n' + printf '# TYPE emerger_reboot_required gauge\n' + printf 'emerger_reboot_required %s\n' "${reboot:-0}" + + # Per-manager success flag. + printf '# HELP emerger_manager_ok Per-manager success in the last run (1=ok,0=fail)\n' + printf '# TYPE emerger_manager_ok gauge\n' + # No managers means no match: grep exits 1, which is not an error here. + printf '%s\n' "$last" | { grep -oE '"name":"[^"]*","result":"[^"]*"' || true; } | \ + while IFS= read -r pair; do + local name result value + name=$(history_text "$pair" name) + result=$(history_text "$pair" result) + value=0 + [[ $result == ok ]] && value=1 + printf 'emerger_manager_ok{manager="%s"} %s\n' "$name" "$value" + done +} diff --git a/src/lib/state/resume.sh b/src/lib/state/resume.sh new file mode 100644 index 0000000..d741a3f --- /dev/null +++ b/src/lib/state/resume.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# Resume support: remember completed managers so an interrupted run can continue. + +RESUME_FILE="$EMERGER_STATE/resume" + +# Fill RESUME_DONE with the managers listed in RESUME_FILE, empty when it is +# missing. +resume_load() { + RESUME_DONE=() + [[ -f $RESUME_FILE ]] || return 0 + local line + while IFS= read -r line || [[ -n $line ]]; do + RESUME_DONE+=("$line") + done <"$RESUME_FILE" +} + +# Return 0 if manager $1 is in RESUME_DONE. +resume_has() { + local manager="$1" entry + for entry in "${RESUME_DONE[@]:-}"; do + [[ $entry == "$manager" ]] && return 0 + done + return 1 +} + +# Record manager $1 as done. A dry run leaves the cursor of real runs alone. +resume_mark() { + local manager="$1" + (( ${DRY_RUN:-0} )) && return 0 + printf '%s\n' "$manager" >>"$RESUME_FILE" +} + +# Forget every completed manager (not on a dry run). +resume_clear() { + (( ${DRY_RUN:-0} )) && return 0 + rm -f "$RESUME_FILE" +} diff --git a/src/lib/summary.sh b/src/lib/summary.sh index 167415c..334f2a6 100644 --- a/src/lib/summary.sh +++ b/src/lib/summary.sh @@ -1,12 +1,17 @@ #!/usr/bin/env bash # Final summary: box banner, reboot advisory, optional package diff summary. -: "${SUMMARY_FREED:=0}" +# Run state, never read from the environment. +SUMMARY_FREED_KB=0 SUMMARY_MANAGERS=() SUMMARY_RESULTS=() +# Wall-clock seconds per manager, read back by estimate_for. +SUMMARY_SECONDS=() SUMMARY_ERRORS=0 -_fmt_bytes() { +# Print KiB count $1 through numfmt in IEC units, one decimal and a B +# suffix ("1.5GB"), else as " KiB" when numfmt is missing or fails. +_summary_format_bytes() { local kb="$1" if sys_has numfmt; then numfmt --to=iec --suffix=B --format='%.1f' $(( kb * 1024 )) 2>/dev/null && return @@ -14,32 +19,45 @@ _fmt_bytes() { printf '%s KiB' "$kb" } +# Record manager $1 with result $2 (ok or fail) after $3 seconds. +summary_add() { + SUMMARY_MANAGERS+=("$1"); SUMMARY_RESULTS+=("$2"); SUMMARY_SECONDS+=("${3:-0}") + [[ $2 == ok ]] || SUMMARY_ERRORS=$(( SUMMARY_ERRORS + 1 )) + return 0 +} + +# Print the run as one JSON line: the --json output and the history.jsonl entry. summary_json() { local duration="$1" - local i first=1 + local i is_first=1 printf '{"ts":"%s","duration":%d,"freed_kb":%d,"errors":%d,"reboot":%d,"managers":[' \ - "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$duration" "$SUMMARY_FREED" "$SUMMARY_ERRORS" "${REBOOT_NEEDED:-0}" + "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$duration" "$SUMMARY_FREED_KB" "$SUMMARY_ERRORS" "${REBOOT_IS_NEEDED:-0}" for i in "${!SUMMARY_MANAGERS[@]}"; do - (( first )) || printf ',' - first=0 - printf '{"name":"%s","result":"%s"}' "${SUMMARY_MANAGERS[i]}" "${SUMMARY_RESULTS[i]}" + (( is_first )) || printf ',' + is_first=0 + printf '{"name":"%s","result":"%s","secs":%d}' "${SUMMARY_MANAGERS[i]}" "${SUMMARY_RESULTS[i]}" "${SUMMARY_SECONDS[i]:-0}" done printf ']}\n' } +# Close the run: check for a pending reboot, append the history line (not on +# a dry run), then print what the quiet level allows: the JSON line, a +# one-line tally (-qq), nothing (-qqq) or the summary box. summary_print() { - local duration="$1" + local duration="$1" line + + reboot_check + line=$(summary_json "$duration") + (( DRY_RUN )) || history_append "$line" if (( ARG_JSON )); then - reboot_check - summary_json "$duration" - _persist_history "$duration" + printf '%s\n' "$line" return fi (( QUIET_LEVEL >= 3 )) && return - local min=$(( duration / 60 )) s=$(( duration % 60 )) + local min=$(( duration / 60 )) seconds=$(( duration % 60 )) local ok_count=0 fail_count=0 i for i in "${!SUMMARY_MANAGERS[@]}"; do if [[ ${SUMMARY_RESULTS[i]} == ok ]]; then @@ -49,112 +67,67 @@ summary_print() { fi done - local mgr_list="" - if (( ${#SUMMARY_MANAGERS[@]} > 0 )); then - for i in "${!SUMMARY_MANAGERS[@]}"; do - if [[ ${SUMMARY_RESULTS[i]} == ok ]]; then - mgr_list+="${C_GREEN}$(ui_glyph check)${C_RESET} ${SUMMARY_MANAGERS[i]} " - else - mgr_list+="${C_RED}$(ui_glyph cross)${C_RESET} ${SUMMARY_MANAGERS[i]} " - fi - done - fi - - local dur_line="duration: ${min}m${s}s" - local freed_line="" - (( SUMMARY_FREED > 0 )) && freed_line="freed: $(_fmt_bytes "$SUMMARY_FREED")" - local changed_line="" - local changed_n; changed_n=$(diff_count_changed 2>/dev/null || echo 0) - (( changed_n > 0 )) && changed_line="pkg diff: ${changed_n} changes (up --changed)" - local err_line - if (( SUMMARY_ERRORS > 0 )); then - err_line="${C_YELLOW}${SUMMARY_ERRORS} error(s) - up --errors${C_RESET}" - else - err_line="${C_GREEN}no errors${C_RESET}" - fi + _summary_lines "$min" "$seconds" if (( QUIET_LEVEL >= 2 )); then if (( SUMMARY_ERRORS > 0 )); then printf '%s/%s managers ok, %s error(s), %dm%02ds\n' \ - "$ok_count" "$(( ok_count + fail_count ))" "$SUMMARY_ERRORS" "$min" "$s" + "$ok_count" "$(( ok_count + fail_count ))" "$SUMMARY_ERRORS" "$min" "$seconds" else - printf '%s managers ok, %dm%02ds\n' "$ok_count" "$min" "$s" + printf '%s managers ok, %dm%02ds\n' "$ok_count" "$min" "$seconds" fi - _persist_history "$duration" - reboot_check; reboot_advisory + reboot_advisory return fi - local lines=("$dur_line") - [[ -n $freed_line ]] && lines+=("$freed_line") - [[ -n $changed_line ]] && lines+=("$changed_line") - lines+=("$err_line") - [[ -n $mgr_list ]] && lines=("$mgr_list" "" "${lines[@]}") - - ui_box "eMerger summary" "${lines[@]}" + local UI_BOX_COLOR="$C_GREEN" + # Read by ui_box. + # shellcheck disable=SC2034 + (( SUMMARY_ERRORS > 0 )) && UI_BOX_COLOR="$C_YELLOW" + ui_box "eMerger summary" "${_SUMMARY_LINES[@]}" - reboot_check reboot_advisory - - _persist_history "$duration" } -_persist_history() { - local duration="$1" - { - printf '{"ts":"%s","duration":%d,"freed_kb":%d,"errors":%d,"reboot":%d,"managers":[' \ - "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$duration" "$SUMMARY_FREED" "$SUMMARY_ERRORS" "${REBOOT_NEEDED:-0}" - local first=1 i +# Set _SUMMARY_LINES to the summary box lines (managers, time $1 minutes $2 +# seconds, freed space, changed packages, status). Reads the package diff +# unless this is a dry run. +_summary_lines() { + local min="$1" seconds="$2" i + local manager_list="" + if (( ${#SUMMARY_MANAGERS[@]} > 0 )); then for i in "${!SUMMARY_MANAGERS[@]}"; do - (( first )) || printf ',' - first=0 - printf '{"name":"%s","result":"%s"}' "${SUMMARY_MANAGERS[i]}" "${SUMMARY_RESULTS[i]}" + if [[ ${SUMMARY_RESULTS[i]} == ok ]]; then + manager_list+="${C_GREEN}$(ui_glyph check)${C_RESET} ${SUMMARY_MANAGERS[i]} " + else + manager_list+="${C_RED}$(ui_glyph cross)${C_RESET} ${C_RED}${SUMMARY_MANAGERS[i]}${C_RESET} " + fi done - printf ']}\n' - } >>"$EMERGER_STATE/history.jsonl" 2>/dev/null || true - - local hist="$EMERGER_STATE/history.jsonl" - if [[ -f $hist ]] && [[ $(wc -l <"$hist") -gt 500 ]]; then - tail -n 500 "$hist" >"$hist.tmp" && mv "$hist.tmp" "$hist" + manager_list=${manager_list% } fi -} -show_errors() { - local log="$EMERGER_LOG" - if [[ ! -f $log ]]; then - ui_ok "No log yet." - return 0 - fi - local count - count=$(grep -c '|ERROR|' "$log" 2>/dev/null || true) - : "${count:=0}" - if (( count == 0 )); then - ui_ok "No errors logged." + local key_color="${C_DIM}${C_GRAY}" + local time_line + printf -v time_line '%s%-9s%s %s%dm%02ds%s' "$key_color" "time" "$C_RESET" "$C_BOLD" "$min" "$seconds" "$C_RESET" + local freed_line="" + (( SUMMARY_FREED_KB > 0 )) && printf -v freed_line '%s%-9s%s %s%s%s' "$key_color" "freed" "$C_RESET" "$C_CYAN" "$(_summary_format_bytes "$SUMMARY_FREED_KB")" "$C_RESET" + local changed_line="" + # Dry runs compute no diff: the file holds the last real run's. + local changed_count=0 + (( DRY_RUN )) || changed_count=$(diff_count_changed 2>/dev/null || echo 0) + (( changed_count > 0 )) && printf -v changed_line '%s%-9s%s %s packages %s(up --changed)%s' "$key_color" "changed" "$C_RESET" "$changed_count" "$key_color" "$C_RESET" + local err_line + if (( SUMMARY_ERRORS > 0 )); then + printf -v err_line '%s%-9s%s %s%s %s error(s)%s %s(up --errors)%s' "$key_color" "status" "$C_RESET" "$C_YELLOW$C_BOLD" "$(ui_glyph warn)" "$SUMMARY_ERRORS" "$C_RESET" "$key_color" "$C_RESET" else - ui_warn "$count error line(s) in $log:" - grep '|ERROR|' "$log" | tail -n 30 | progress_highlight | sed 's/^/ /' + printf -v err_line '%s%-9s%s %s%s all good%s' "$key_color" "status" "$C_RESET" "$C_GREEN$C_BOLD" "$(ui_glyph check)" "$C_RESET" fi -} -show_history() { - local hist="$EMERGER_STATE/history.jsonl" - if [[ ! -f $hist ]]; then - ui_muted "No history yet." - return - fi - ui_title "Recent runs" - tail -n 10 "$hist" | while IFS= read -r line; do - local ts dur err reboot - ts=$(printf '%s' "$line" | sed -n 's/.*"ts":"\([^"]*\)".*/\1/p') - dur=$(printf '%s' "$line" | sed -n 's/.*"duration":\([0-9]*\).*/\1/p') - err=$(printf '%s' "$line" | sed -n 's/.*"errors":\([0-9]*\).*/\1/p') - reboot=$(printf '%s' "$line" | sed -n 's/.*"reboot":\([0-9]*\).*/\1/p') - local tag="" - [[ ${reboot:-0} -gt 0 ]] && tag=" ${C_YELLOW}reboot${C_RESET}" - if [[ ${err:-0} -gt 0 ]]; then - printf ' %s%s%s %s %ss %serrors=%s%s%s\n' "$C_RED" "$(ui_glyph cross)" "$C_RESET" "$ts" "$dur" "$C_YELLOW" "$err" "$C_RESET" "$tag" - else - printf ' %s%s%s %s %ss%s\n' "$C_GREEN" "$(ui_glyph check)" "$C_RESET" "$ts" "$dur" "$tag" - fi - done + local lines=() + [[ -n $manager_list ]] && lines+=("$(printf '%s%-9s%s %s' "$key_color" "managers" "$C_RESET" "$manager_list")") + lines+=("$time_line") + [[ -n $freed_line ]] && lines+=("$freed_line") + [[ -n $changed_line ]] && lines+=("$changed_line") + lines+=("$err_line") + _SUMMARY_LINES=("${lines[@]}") } diff --git a/src/lib/sys.sh b/src/lib/sys.sh index 9f504ca..6d6f733 100644 --- a/src/lib/sys.sh +++ b/src/lib/sys.sh @@ -1,21 +1,16 @@ #!/usr/bin/env bash # System detection helpers. +# Return 0 if command $1 is on PATH. sys_has() { command -v "$1" >/dev/null 2>&1; } +# Return 0 on macOS. sys_is_macos() { [[ $(uname -s) == Darwin ]]; } -sys_is_linux() { [[ $(uname -s) == Linux ]]; } +# Print Homebrew's prefix, returning 1 when brew is missing or fails. sys_brew_prefix() { command -v brew >/dev/null 2>&1 && brew --prefix 2>/dev/null; } -sys_os() { - case "$(uname -s)" in - Linux) echo linux ;; - Darwin) echo macos ;; - MINGW*|MSYS*|CYGWIN*) echo windows ;; - *) echo unknown ;; - esac -} - -sys_distro() { +# Print the distribution name from /etc/os-release (PRETTY_NAME, else NAME), +# else the kernel name and release. Sourcing the file leaves its variables set. +sys_read_distro() { if [[ -f /etc/os-release ]]; then # shellcheck disable=SC1091 . /etc/os-release @@ -25,35 +20,51 @@ sys_distro() { fi } +# Print the start-up file of the user's SHELL: ~/.bashrc, $ZDOTDIR/.zshrc, +# fish's config.fish, else ~/.rc. sys_shell_rc() { - local sh - sh=$(basename "${SHELL:-bash}") - case "$sh" in + local shell + shell=$(basename "${SHELL:-bash}") + case "$shell" in bash) echo "$HOME/.bashrc" ;; zsh) echo "${ZDOTDIR:-$HOME}/.zshrc" ;; fish) echo "$HOME/.config/fish/config.fish" ;; - *) echo "$HOME/.${sh}rc" ;; + *) echo "$HOME/.${shell}rc" ;; esac } -sys_on_battery() { - [[ -d /sys/class/power_supply ]] || return 1 - local ac found=0 - for ac in /sys/class/power_supply/A{C,DP,C0,DP0}*/online; do - [[ -f $ac ]] || continue - found=1 - [[ $(cat "$ac" 2>/dev/null) == 1 ]] && return 1 - done - (( found )) && return 0 - return 1 +# Print the free space of the file system holding path $2 in df block size +# $1 (k for KiB, m for MiB), empty when df fails. +sys_free_space() { + { df -P"$1" "$2" 2>/dev/null || true; } | awk 'NR==2{print $4}' } -sys_battery_percent() { - local cap - for cap in /sys/class/power_supply/BAT*/capacity; do - [[ -f $cap ]] && { cat "$cap"; return; } - done - echo 100 +# Return 0 when the effective uid is 0. +sys_is_root() { [[ ${EUID:-$(id -u)} -eq 0 ]]; } + +# Print the privilege prefix for a root-only command: nothing as root (a +# container or CI image may have no sudo), `sudo` otherwise. +sys_sudo_prefix() { + sys_is_root || printf 'sudo' + return 0 } -sys_is_root() { [[ ${EUID:-$(id -u)} -eq 0 ]]; } +# Run command $@ as root: directly as root, through sudo otherwise. The lock +# fd stays out of it, so a daemon the command leaves behind cannot hold the lock. +sys_as_root() { + local prefix + prefix=$(sys_sudo_prefix) + ${prefix:+"$prefix"} "$@" 9>&- +} + +# Return 0 while the calling subshell's parent is still process $1. An +# orphan is re-parented, so a PID reused after the parent died does not count. +# Without ps, fall back to `kill -0`. +sys_is_parent_alive() { + # Read BASHPID here: inside $(...) it names the substitution's subshell. + local parent self="${BASHPID:-$$}" + parent=$(ps -o ppid= -p "$self" 2>/dev/null) || { kill -0 "$1" 2>/dev/null; return; } + parent=${parent//[!0-9]/} + [[ -z $parent ]] && { kill -0 "$1" 2>/dev/null; return; } + [[ $parent == "$1" ]] +} diff --git a/src/lib/system/mirrors.sh b/src/lib/system/mirrors.sh new file mode 100644 index 0000000..f0c3263 --- /dev/null +++ b/src/lib/system/mirrors.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Mirror ranking and refresh for the managers that support it. + +# Print the os-release text. Tests replace this function. +_mirrors_os_release() { + cat /etc/os-release 2>/dev/null || true +} + +# Print the running Debian release codename, or nothing on any other +# distribution (netselect-apt only knows Debian's own suites) and on testing +# or sid, which carry no VERSION_ID and share one codename. +_mirrors_debian_suite() { + local text id version codename + text=$(_mirrors_os_release) + id=$(sed -n 's/^ID="\{0,1\}\([^"]*\)"\{0,1\}$/\1/p' <<<"$text") + version=$(sed -n 's/^VERSION_ID="\{0,1\}\([^"]*\)"\{0,1\}$/\1/p' <<<"$text") + codename=$(sed -n 's/^VERSION_CODENAME="\{0,1\}\([^"]*\)"\{0,1\}$/\1/p' <<<"$text") + [[ $id == debian && -n $version && $codename =~ ^[a-z]+$ ]] && printf '%s' "$codename" + return 0 +} + +# Return 0 when root-owned file $1 holds only "deb"/"deb-src" lines with an +# http(s) URL, a suite and components, no [options] such as trusted=yes, and +# comments or blanks. +_mirrors_list_is_plain() { + local line content + content=$(sys_as_root cat -- "$1") || return 1 + while IFS= read -r line; do + [[ -z $line || $line == "#"* ]] && continue + [[ $line =~ ^deb(-src)?\ +https?://[A-Za-z0-9._~:/%+-]+\ +[A-Za-z0-9._/-]+(\ +[A-Za-z0-9._-]+)+\ *$ ]] || return 1 + done <<<"$content" + return 0 +} + +# Rank mirrors with the tools present and write the result as root. +mirrors_refresh() { + ui_title "Refresh mirrors" + if (( DRY_RUN )); then + ui_sub "[dry-run] would refresh mirrors" + return 0 + fi + local is_refreshed=0 + if sys_has reflector; then + if sys_as_root reflector --latest 20 --sort rate --protocol https --save /etc/pacman.d/mirrorlist >/dev/null 2>&1; then + ui_ok "reflector: pacman mirrorlist updated" + is_refreshed=1 + else + ui_warn "reflector failed" + fi + fi + local suite + if sys_has netselect-apt && suite=$(_mirrors_debian_suite) && [[ -n $suite ]]; then + # Root owns the list from creation to install: a user-owned file could be + # rewritten in between and plant an apt source. + local tmp + if ! tmp=$(sys_as_root mktemp -t emerger.XXXXXX); then + ui_warn "netselect-apt: could not create a temp file as root" + elif sys_as_root netselect-apt -o "$tmp" "$suite" >/dev/null 2>&1 && [[ -s $tmp ]]; then + if ! _mirrors_list_is_plain "$tmp"; then + ui_warn "netselect-apt: output is not a plain http(s) source list, not installed" + elif sys_as_root install -m 0644 "$tmp" /etc/apt/sources.list.d/netselect.list; then + ui_ok "netselect-apt: wrote /etc/apt/sources.list.d/netselect.list" + is_refreshed=1 + else + ui_warn "netselect-apt: could not install /etc/apt/sources.list.d/netselect.list" + fi + fi + [[ -n ${tmp:-} ]] && sys_as_root rm -f "$tmp" + fi + if sys_has dnf && dnf config-manager --help >/dev/null 2>&1; then + ui_muted "dnf: the fastestmirror plugin ranks mirrors when enabled" + fi + (( is_refreshed )) || ui_muted "No mirror tool available; install 'reflector' (arch) or 'netselect-apt' (debian)." +} diff --git a/src/lib/system/notify.sh b/src/lib/system/notify.sh new file mode 100644 index 0000000..d4839f9 --- /dev/null +++ b/src/lib/system/notify.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Optional desktop notification at end of run. + +# Show the run's outcome as a desktop notification: notify-send on a Linux +# graphical session, osascript on macOS. Silent when neither applies. +notify_send_result() { + local message urgency=normal icon=emblem-default + if (( SUMMARY_ERRORS > 0 )); then + urgency=critical; icon=dialog-error + message="Finished with $SUMMARY_ERRORS error(s)." + else + message="${#SUMMARY_MANAGERS[@]} manager(s) updated." + fi + if sys_has notify-send && [[ -n ${DISPLAY:-} || -n ${WAYLAND_DISPLAY:-} ]]; then + notify-send -a eMerger -u "$urgency" -i "$icon" "eMerger" "$message" 2>/dev/null 9>&- || true + elif sys_is_macos && sys_has osascript; then + # msg is built above from counts only, never from outside text. + osascript -e "display notification \"$message\" with title \"eMerger\"" >/dev/null 2>&1 9>&- || true + fi + return 0 +} diff --git a/src/lib/system/preflight.sh b/src/lib/system/preflight.sh new file mode 100644 index 0000000..0fb6a85 --- /dev/null +++ b/src/lib/system/preflight.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Pre-flight checks: disk space and battery charge. + +: "${DISK_MIN_FREE_MB:=1024}" +: "${BATTERY_MIN_PCT:=20}" + +# Power-supply directory read on Linux. Tests reassign it after sourcing, +# the environment never sets it. +SYS_POWER_DIR=/sys/class/power_supply + +# Return 0 when running on battery: Linux AC adapters under SYS_POWER_DIR, +# else `pmset -g batt` on macOS. Unknown reads as "not on battery". +sys_is_on_battery() { + if [[ -d $SYS_POWER_DIR ]]; then + local adapter has_adapter=0 + for adapter in "$SYS_POWER_DIR"/A{C,DP,C0,DP0}*/online; do + [[ -f $adapter ]] || continue + has_adapter=1 + [[ $(cat "$adapter" 2>/dev/null) == 1 ]] && return 1 + done + (( has_adapter )) && return 0 + return 1 + fi + sys_has pmset || return 1 + local out; out=$(pmset -g batt 2>/dev/null || true) + [[ $out == *"'Battery Power'"* ]] +} + +# Print the battery charge in percent as decimal digits: first BAT* under +# SYS_POWER_DIR holding a number, else the first "N%" of `pmset -g batt`, +# else 100. +sys_battery_percent() { + local capacity_file value + for capacity_file in "$SYS_POWER_DIR"/BAT*/capacity; do + [[ -f $capacity_file ]] || continue + value=$(cat "$capacity_file" 2>/dev/null || true) + [[ $value =~ ^[0-9]{1,3}$ ]] && { echo "$(( 10#$value ))"; return; } + done + if sys_has pmset; then + local out; out=$(pmset -g batt 2>/dev/null || true) + if [[ $out =~ [[:space:]]([0-9]+)%\; ]]; then + echo "${BASH_REMATCH[1]}"; return + fi + fi + echo 100 +} + +# Print the free MiB of the file system holding path $1 (default /), nothing +# when df fails. +disk_free_mb() { + local path="${1:-/}" + { df -Pm "$path" 2>/dev/null || true; } | awk 'NR==2{print $4}' +} + +# Warn when / has less than DISK_MIN_FREE_MB free and, unless -y, exit 1 +# when the user declines to continue. An unreadable figure skips the check. +disk_precheck() { + local free; free=$(disk_free_mb /) + [[ -z $free ]] && return 0 + if (( free < DISK_MIN_FREE_MB )); then + ui_warn "Low disk space on / (${free}MB free, threshold ${DISK_MIN_FREE_MB}MB)." + if (( ARG_YES == 0 )); then + ui_confirm "Continue anyway?" n || { ui_muted "Aborted by user."; exit 1; } + fi + else + log_info "disk precheck ok: ${free}MB free on /" + fi +} + +# Ask before updating on battery below BATTERY_MIN_PCT, unless -y. +battery_precheck() { + sys_is_on_battery || return 0 + local percent; percent=$(sys_battery_percent) + if (( percent < BATTERY_MIN_PCT )) && (( ! ARG_YES )); then + ui_warn "On battery at ${percent}%. Updates are I/O heavy." + ui_confirm "Continue anyway?" n || { ui_muted "Aborted."; exit 1; } + fi +} diff --git a/src/lib/system/reboot.sh b/src/lib/system/reboot.sh new file mode 100644 index 0000000..e431fe1 --- /dev/null +++ b/src/lib/system/reboot.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# Detect whether the system needs a reboot after updates. + +REBOOT_IS_NEEDED=0 +REBOOT_REASON="" +# Flag file Debian-family packages drop when a reboot is due. Tests reassign +# it after sourcing, the environment never sets it. +REBOOT_REQUIRED_FILE=/var/run/reboot-required + +# Set REBOOT_IS_NEEDED and REBOOT_REASON. needs-restarting exits 1 when a +# reboot is due: any other failure (missing plugin, error) is unknown and +# claims nothing. +reboot_check() { + REBOOT_IS_NEEDED=0; REBOOT_REASON="" + if (( ${RPI_EEPROM_IS_PENDING:-0} )); then + REBOOT_IS_NEEDED=1 + REBOOT_REASON="Raspberry Pi bootloader update staged" + return 0 + fi + if [[ -f $REBOOT_REQUIRED_FILE ]]; then + REBOOT_IS_NEEDED=1 + REBOOT_REASON="$REBOOT_REQUIRED_FILE exists" + if [[ -f $REBOOT_REQUIRED_FILE.pkgs ]]; then + REBOOT_REASON+=" ($(wc -l <"$REBOOT_REQUIRED_FILE.pkgs") pkg(s))" + fi + return 0 + fi + local rc + if sys_has needs-restarting; then + rc=0; needs-restarting -r >/dev/null 2>&1 || rc=$? + if (( rc == 1 )); then + REBOOT_IS_NEEDED=1 + REBOOT_REASON="needs-restarting -r says so" + return 0 + fi + fi + if sys_has dnf; then + rc=0; dnf -q needs-restarting -r >/dev/null 2>&1 || rc=$? + if (( rc == 1 )); then + REBOOT_IS_NEEDED=1; REBOOT_REASON="dnf needs-restarting" + fi + fi + return 0 +} + +# Reboot now as root. Under --dry-run print the command and return 0, +# otherwise replace the shell and never return. +reboot_now() { + local prefix + prefix=$(sys_sudo_prefix) + if (( DRY_RUN )); then + ui_sub "[dry-run] would reboot: ${prefix:+$prefix }reboot ($REBOOT_REASON)" + return 0 + fi + ui_warn "Rebooting now." + exec ${prefix:+"$prefix"} reboot +} + +# Print the pending-reboot notice with the command that applies it. +reboot_advisory() { + (( REBOOT_IS_NEEDED )) || return 0 + local prefix + prefix=$(sys_sudo_prefix) + printf '\n %s%s Reboot recommended%s %s%s%s\n' \ + "$C_YELLOW$C_BOLD" "$(ui_glyph warn)" "$C_RESET" \ + "$C_DIM$C_GRAY" "$REBOOT_REASON" "$C_RESET" + printf ' %srun%s %s%sreboot%s %sor%s %sup --reboot%s\n' \ + "$C_DIM$C_GRAY" "$C_RESET" "$C_BOLD" "${prefix:+$prefix }" "$C_RESET" "$C_DIM$C_GRAY" "$C_RESET" "$C_BOLD" "$C_RESET" +} diff --git a/src/lib/system/rpi.sh b/src/lib/system/rpi.sh new file mode 100644 index 0000000..9f9d607 --- /dev/null +++ b/src/lib/system/rpi.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# Raspberry Pi board probes: model, EEPROM presence, power and thermal +# pre-flight. + +# 1 = abort on under-voltage, even with -y. +: "${RPI_ABORT_ON_UNDERVOLTAGE:=0}" +: "${RPI_TEMP_WARN:=80}" # ยฐC + +: "${RPI_MODEL_FILE:=/proc/device-tree/model}" + +# Print the board model from RPI_MODEL_FILE without NUL bytes, empty when +# the file is unreadable. +rpi_model() { + local model="" + [[ -r $RPI_MODEL_FILE ]] && model=$(tr -d '\0' <"$RPI_MODEL_FILE" 2>/dev/null) + printf '%s' "$model" +} + +# Return 0 on a Raspberry Pi. +rpi_is_pi() { [[ $(rpi_model) == "Raspberry Pi"* ]]; } + +# Return 0 on a board that boots from an SPI EEPROM: Pi 4, 400, 5, 500, +# CM4 or CM5. +rpi_has_eeprom() { + local model; model=$(rpi_model) + [[ $model =~ Raspberry\ Pi\ (4|400|5|500|Compute\ Module\ (4|5)) ]] +} + +# Print the Pi's model, temperature and power state and warn about +# under-voltage and heat. Exit 1 on under-voltage with +# RPI_ABORT_ON_UNDERVOLTAGE=1 or a declined prompt. Return 0 off a Pi. +# vcgencmd get_throttled bits: 0 under-voltage, 1 freq capped, 2 throttled, +# 3 soft temp limit. Bits 16+ are the same, "since boot". +rpi_health_check() { + rpi_is_pi || return 0 + sys_has vcgencmd || return 0 + local raw throttled temp="" temp_tenths=0 + raw=$(vcgencmd get_throttled 2>/dev/null) || return 0 + [[ $raw =~ throttled=(0x[0-9a-fA-F]+) ]] || return 0 + throttled=$(( BASH_REMATCH[1] )) + if [[ $(vcgencmd measure_temp 2>/dev/null) =~ temp=([0-9]+)\.?([0-9]?) ]]; then + temp="${BASH_REMATCH[1]}.${BASH_REMATCH[2]:-0}" + temp_tenths=$(( BASH_REMATCH[1] * 10 + ${BASH_REMATCH[2]:-0} )) + fi + + local power="power ok" + (( throttled & 0x10000 )) && power="under-voltage since boot" + (( throttled & 0x1 )) && power="UNDER-VOLTAGE" + ui_muted "$(rpi_model) $(ui_glyph dot) ${temp:-?}ยฐC $(ui_glyph dot) $power" + log_info "rpi: throttled=$(printf '0x%x' "$throttled") temp=${temp:-?}" + + if (( throttled & 0x1 )); then + ui_warn "The Pi is under-voltage right now, the power supply can't keep up." + ui_muted "A brown-out while dpkg is writing can corrupt the SD card. Use the official PSU." + if (( RPI_ABORT_ON_UNDERVOLTAGE )); then + ui_err "Aborting (RPI_ABORT_ON_UNDERVOLTAGE=1)."; exit 1 + fi + if (( ! ARG_YES )); then + ui_confirm "Update anyway?" n || { ui_muted "Aborted."; exit 1; } + fi + elif (( throttled & 0x10000 )); then + ui_warn "Under-voltage happened since boot; check the power supply and cable." + fi + if (( throttled & 0x4 )) || (( temp_tenths >= RPI_TEMP_WARN * 10 )); then + ui_warn "SoC is hot (${temp:-?}ยฐC) and may throttle; updates will be slower." + fi + return 0 +} diff --git a/src/lib/system/snapshot.sh b/src/lib/system/snapshot.sh new file mode 100644 index 0000000..947fbc3 --- /dev/null +++ b/src/lib/system/snapshot.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# Pre-update filesystem snapshot via snapper, timeshift or btrfs. + +# Take a pre-update snapshot with the first tool that works: snapper (root +# config), timeshift, then a read-only btrfs snapshot of /. Return 1 when +# none worked, after naming each tool that failed and its exit code. +snapshot_create() { + ui_title "Snapshot" + local description + description="eMerger pre-update $(date -u +%Y-%m-%dT%H:%M:%SZ)" + if (( DRY_RUN )); then + ui_sub "[dry-run] would create snapshot: $description" + return 0 + fi + local has_tried=0 rc + if sys_has snapper && { snapper list-configs 2>/dev/null || true; } | grep -q '^root'; then + has_tried=1; rc=0 + sys_as_root snapper -c root create --description "$description" --type single --cleanup-algorithm number || rc=$? + if (( rc == 0 )); then + ui_ok "snapper snapshot created" + return 0 + fi + ui_warn "snapper create failed (exit $rc)" + fi + if sys_has timeshift; then + has_tried=1; rc=0 + sys_as_root timeshift --create --comments "$description" --tags D >/dev/null 2>&1 || rc=$? + if (( rc == 0 )); then + ui_ok "timeshift snapshot created" + return 0 + fi + ui_warn "timeshift --create failed (exit $rc)" + fi + if sys_has btrfs && { mount 2>/dev/null || true; } | grep -q 'on / type btrfs'; then + has_tried=1; rc=0 + local snap_dir="/.snapshots/emerger" + sys_as_root mkdir -p "$snap_dir" 2>/dev/null || true + local name + name="$snap_dir/$(date +%Y-%m-%dT%H-%M-%S)" + sys_as_root btrfs subvolume snapshot -r / "$name" >/dev/null 2>&1 || rc=$? + if (( rc == 0 )); then + ui_ok "btrfs snapshot: $name" + return 0 + fi + ui_warn "btrfs subvolume snapshot failed (exit $rc)" + fi + (( has_tried )) || ui_err "No snapshot tool available (snapper/timeshift/btrfs)." + return 1 +} + +# Roll back to the most recent eMerger snapshot with snapper (rollback) or +# timeshift (--restore). A raw btrfs snapshot needs a manual subvolume swap: +# print the path of the latest one and leave / untouched. +snapshot_rollback() { + ui_title "Rollback" + if sys_has snapper && { snapper list-configs 2>/dev/null || true; } | grep -q '^root'; then + local last + # Column 1 is "#", the number: keep its digits (snapper appends + # markers such as "*" or "-"). Newer snapper draws "โ”‚" between columns. + last=$({ snapper -c root list 2>/dev/null || true; } | sed 's/โ”‚/|/g' \ + | awk -F'|' '/eMerger pre-update/ {n = $1; gsub(/[^0-9]/, "", n); if (n != "") last = n} END{print last}') + if [[ -n $last ]]; then + ui_muted "Rolling back to snapper snapshot #$last" + if (( DRY_RUN )); then + ui_sub "[dry-run] would run: snapper -c root rollback $last" + return 0 + fi + if sys_as_root snapper -c root rollback "$last"; then + ui_ok "Rollback queued. Reboot to apply." + return 0 + fi + ui_err "snapper rollback failed"; return 1 + fi + ui_warn "No eMerger snapper snapshot found." + fi + if sys_has timeshift; then + if (( DRY_RUN )); then + ui_sub "[dry-run] would run: timeshift --restore (interactive)" + return 0 + fi + ui_muted "Launching timeshift --restore" + sys_as_root timeshift --restore + return $? + fi + if sys_has btrfs && { mount 2>/dev/null || true; } | grep -q 'on / type btrfs'; then + local snap_dir="/.snapshots/emerger" latest + if [[ -d $snap_dir ]]; then + latest=$(ls -1t "$snap_dir" 2>/dev/null | head -n1) + if [[ -n $latest ]]; then + ui_warn "Latest btrfs snapshot: $snap_dir/$latest" + ui_warn "Automatic btrfs rollback is not performed - swap subvolumes manually." + return 1 + fi + fi + fi + ui_err "No rollback mechanism available." + return 1 +} diff --git a/src/lib/trust.sh b/src/lib/trust.sh new file mode 100644 index 0000000..0282300 --- /dev/null +++ b/src/lib/trust.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Ownership and mode checks for the user files eMerger sources or runs. + +# Return 0 if file $1 and the directories holding it (the link's and, for a +# symlink, the target's) are owned by the effective uid and not writable by +# group or other: whoever can write the directory can swap the file. Write by +# the user's private group (named after the user, as a umask of 002 +# produces) is accepted: no one else is in it. Otherwise print why with +# ui_warn and return 1. +trust_file() { + local file="$1" target + _trust_path "$file" || return 1 + _trust_path "$(dirname -- "$file")" || return 1 + if [[ -L $file ]]; then + target=$(readlink -f -- "$file" 2>/dev/null) || target="" + [[ -z $target ]] || _trust_path "$(dirname -- "$target")" || return 1 + fi + return 0 +} + +# Check one path (symlinks followed) for trust_file: owner and write bits. +_trust_path() { + local path="$1" stat_line uid gid mode euid="${EUID:-$(id -u)}" write_mask=8#022 + stat_line=$(stat -L -c '%u %g %a' -- "$path" 2>/dev/null || stat -L -f '%u %g %Lp' -- "$path" 2>/dev/null) || { + ui_warn "$path: cannot read its owner and mode, not loaded" + return 1 + } + IFS=' ' read -r uid gid mode <<<"$stat_line" + if [[ ! $uid =~ ^[0-9]+$ || ! $gid =~ ^[0-9]+$ || ! $mode =~ ^[0-7]+$ ]]; then + ui_warn "$path: cannot read its owner and mode, not loaded" + return 1 + fi + if [[ $uid != "$euid" ]]; then + ui_warn "$path is not owned by you (uid $uid, you are $euid), not loaded" + return 1 + fi + if [[ $gid == "$(id -g)" && $(id -gn) == "$(id -un)" ]]; then + write_mask=8#002 + fi + if (( 8#$mode & write_mask )); then + ui_warn "$path is writable by group or other (mode $mode), not loaded. Fix: chmod go-w '$path'" + return 1 + fi + return 0 +} + +# Return 0 unless running as root with a HOME owned by another user (as +# `sudo -E` leaves it), in which case print why with ui_err and return 1. +trust_home() { + sys_is_root || return 0 + local uid + uid=$(stat -L -c %u -- "$HOME" 2>/dev/null || stat -L -f %u -- "$HOME" 2>/dev/null) || return 0 + [[ $uid == 0 ]] && return 0 + ui_err "Running as root with HOME=$HOME, owned by uid $uid." + ui_muted "Its config, profiles, plugins and hooks would run as root. Run up as that user, or use sudo -H." + return 1 +} diff --git a/src/lib/tui.sh b/src/lib/tui.sh deleted file mode 100644 index 13cdb8c..0000000 --- a/src/lib/tui.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env bash -# Interactive TUI using gum or whiptail, falling back to a simple read loop. - -tui_menu() { - local choice - if sys_has gum; then - choice=$(gum choose --header="eMerger" \ - "Update all" \ - "Dry run" \ - "Security updates only" \ - "Include dev tools (rust/npm/pip...)" \ - "Show errors" \ - "Show history" \ - "Self-update" \ - "Quit") || return 0 - elif sys_has whiptail; then - choice=$(whiptail --title "eMerger" --menu "Choose an action" 18 60 8 \ - "Update all" "full system update" \ - "Dry run" "simulate without changes" \ - "Security updates only" "apt/dnf/zypper security" \ - "Include dev tools (rust/npm/pip...)" "also update toolchains" \ - "Show errors" "read log errors" \ - "Show history" "last 10 runs" \ - "Self-update" "git pull eMerger" \ - "Quit" "exit" \ - 3>&1 1>&2 2>&3) || return 0 - else - printf '\n Install "gum" or "whiptail" for a nicer menu.\n\n' - printf ' 1) Update all\n 2) Dry run\n 3) Security only\n 4) + dev tools\n 5) Errors\n 6) History\n 7) Self-update\n q) Quit\n\n' - local pick - read -r -p " > " pick - case "$pick" in - 1) choice="Update all" ;; - 2) choice="Dry run" ;; - 3) choice="Security updates only" ;; - 4) choice="Include dev tools (rust/npm/pip...)" ;; - 5) choice="Show errors" ;; - 6) choice="Show history" ;; - 7) choice="Self-update" ;; - *) return 0 ;; - esac - fi - - case "$choice" in - "Update all") ARG_YES=1 ;; - "Dry run") ARG_DRY=1; DRY_RUN=1 ;; - "Security updates only") ARG_SECURITY=1; ARG_YES=1 ;; - "Include dev tools"*) ARG_DEV=1; ARG_YES=1 ;; - "Show errors") show_errors; exit 0 ;; - "Show history") show_history; exit 0 ;; - "Self-update") self_update "$EMERGER_ROOT"; exit $? ;; - *) exit 0 ;; - esac -} diff --git a/src/lib/ui.sh b/src/lib/ui.sh deleted file mode 100644 index 7fc9228..0000000 --- a/src/lib/ui.sh +++ /dev/null @@ -1,220 +0,0 @@ -#!/usr/bin/env bash -# UI primitives: colors, glyphs, boxes, steps, live log monitor, box banner. - -: "${ARG_NO_EMOJI:=0}" -: "${QUIET_LEVEL:=0}" - -_ui_detect_light_bg() { - # Parse COLORFGBG="fg;bg". A low bg value (0-6) = dark theme, 7+ = light. - [[ -z ${COLORFGBG:-} ]] && { UI_LIGHT_BG=0; return; } - local bg="${COLORFGBG##*;}" - if [[ $bg =~ ^[0-9]+$ ]] && (( bg >= 7 )); then - UI_LIGHT_BG=1 - else - UI_LIGHT_BG=0 - fi -} - -_ui_init() { - local colors=0 - _ui_detect_light_bg - if [[ -n ${NO_COLOR:-} ]] || [[ ${TERM:-} == dumb ]] || ! [[ -t 1 ]]; then - C_RESET="" C_BOLD="" C_DIM="" - C_RED="" C_GREEN="" C_YELLOW="" C_BLUE="" C_MAGENTA="" C_CYAN="" C_GRAY="" - UI_TTY=0 - else - command -v tput >/dev/null 2>&1 && colors=$(tput colors 2>/dev/null || echo 0) - C_RESET=$'\e[0m'; C_BOLD=$'\e[1m'; C_DIM=$'\e[2m' - if (( colors >= 256 )); then - if (( UI_LIGHT_BG )); then - C_RED=$'\e[38;5;160m'; C_GREEN=$'\e[38;5;28m'; C_YELLOW=$'\e[38;5;136m' - C_BLUE=$'\e[38;5;26m'; C_MAGENTA=$'\e[38;5;90m'; C_CYAN=$'\e[38;5;30m' - C_GRAY=$'\e[38;5;240m' - else - C_RED=$'\e[38;5;203m'; C_GREEN=$'\e[38;5;114m'; C_YELLOW=$'\e[38;5;221m' - C_BLUE=$'\e[38;5;39m'; C_MAGENTA=$'\e[38;5;176m'; C_CYAN=$'\e[38;5;81m' - C_GRAY=$'\e[38;5;245m' - fi - else - C_RED=$'\e[31m'; C_GREEN=$'\e[32m'; C_YELLOW=$'\e[33m' - C_BLUE=$'\e[34m'; C_MAGENTA=$'\e[35m'; C_CYAN=$'\e[36m'; C_GRAY=$'\e[37m' - fi - UI_TTY=1 - fi - if (( ARG_NO_EMOJI )); then - UI_UNICODE=0 - elif [[ ${LANG:-} =~ [Uu][Tt][Ff]-?8 ]] || [[ ${LC_ALL:-} =~ [Uu][Tt][Ff]-?8 ]] || [[ ${LC_CTYPE:-} =~ [Uu][Tt][Ff]-?8 ]]; then - UI_UNICODE=1 - else - UI_UNICODE=0 - fi -} -_ui_init - -ui_reinit() { _ui_init; } - -ui_glyph() { - if (( UI_UNICODE )); then - case "$1" in - check) printf '\xe2\x9c\x94' ;; - cross) printf '\xe2\x9c\x96' ;; - arrow) printf '\xe2\x96\xb6' ;; - info) printf '\xe2\x84\xb9' ;; - warn) printf '\xe2\x9a\xa0' ;; - bullet) printf '\xe2\x80\xa2' ;; - hline) printf '\xe2\x94\x80' ;; - dot) printf '\xc2\xb7' ;; - tl) printf '\xe2\x95\xad' ;; - tr) printf '\xe2\x95\xae' ;; - bl) printf '\xe2\x95\xb0' ;; - br) printf '\xe2\x95\xaf' ;; - v) printf '\xe2\x94\x82' ;; - esac - else - case "$1" in - check) printf '[OK]' ;; - cross) printf '[X]' ;; - arrow) printf '>' ;; - info) printf 'i' ;; - warn) printf '!' ;; - bullet) printf '*' ;; - hline) printf '-' ;; - dot) printf '.' ;; - tl|tr|bl|br) printf '+' ;; - v) printf '|' ;; - esac - fi -} - -ui_width() { - local w - w=$(tput cols 2>/dev/null || echo 80) - (( w > 0 )) || w=80 - printf '%d' "$w" -} - -ui_hr() { - (( QUIET_LEVEL >= 2 )) && return - local w ch line - w=$(ui_width); (( w > 80 )) && w=80 - ch=$(ui_glyph hline) - printf -v line '%*s' "$w" '' - printf '%s%s%s\n' "$C_GRAY" "${line// /$ch}" "$C_RESET" -} - -ui_title() { (( QUIET_LEVEL >= 2 )) && return; printf '\n%s%s %s%s\n' "$C_CYAN$C_BOLD" "$(ui_glyph arrow)" "$*" "$C_RESET"; ui_hr; } -ui_info() { (( QUIET_LEVEL >= 2 )) && return; printf ' %s%s%s %s\n' "$C_BLUE" "$(ui_glyph info)" "$C_RESET" "$*"; } -ui_ok() { (( QUIET_LEVEL >= 2 )) && return; printf ' %s%s%s %s\n' "$C_GREEN" "$(ui_glyph check)" "$C_RESET" "$*"; } -ui_warn() { printf ' %s%s%s %s\n' "$C_YELLOW" "$(ui_glyph warn)" "$C_RESET" "$*"; } -ui_err() { printf ' %s%s%s %s\n' "$C_RED$C_BOLD" "$(ui_glyph cross)" "$C_RESET" "$*" >&2; } -ui_muted() { (( QUIET_LEVEL >= 1 )) && return; printf ' %s%s%s\n' "$C_DIM$C_GRAY" "$*" "$C_RESET"; } -ui_step() { (( QUIET_LEVEL >= 2 )) && return; printf '\n%s[%d/%d]%s %s %s%s%s\n' "$C_MAGENTA" "$1" "$2" "$C_RESET" "$(ui_glyph arrow)" "$C_BOLD" "$3" "$C_RESET"; } -ui_sub() { (( QUIET_LEVEL >= 1 )) && return; printf ' %s%s%s %s\n' "$C_GRAY" "$(ui_glyph dot)" "$C_RESET" "$*"; } - -# Collapsed summary line for a finished step. -ui_done() { - local label="$1" stat="${2:-}" - (( QUIET_LEVEL >= 2 )) && return - if [[ -n $stat ]]; then - printf ' %s%s%s %s %s\xe2\x80\x94%s %s%s%s\n' \ - "$C_GREEN" "$(ui_glyph check)" "$C_RESET" "$label" \ - "$C_DIM$C_GRAY" "$C_RESET" "$C_GRAY" "$stat" "$C_RESET" - else - printf ' %s%s%s %s\n' "$C_GREEN" "$(ui_glyph check)" "$C_RESET" "$label" - fi -} - -ui_fail() { - local label="$1" rc="${2:-1}" - printf ' %s%s%s %s %s(rc=%s)%s\n' \ - "$C_RED$C_BOLD" "$(ui_glyph cross)" "$C_RESET" "$label" "$C_DIM$C_GRAY" "$rc" "$C_RESET" >&2 -} - -# Live log monitor: follow $file, print spinner frame plus last tail line. -# Replaces the old blind spinner. -_MON_PID=0 -ui_monitor_start() { - (( QUIET_LEVEL >= 2 )) && return - (( ${UI_VERBOSE:-0} )) && { ui_sub "$1"; return; } - (( UI_TTY )) || { ui_sub "$1"; return; } - local label="$1" file="$2" hint="${3:-}" - ( - local frames - if (( UI_UNICODE )); then - frames=($'\xe2\xa0\x8b' $'\xe2\xa0\x99' $'\xe2\xa0\xb9' $'\xe2\xa0\xb8' $'\xe2\xa0\xbc' $'\xe2\xa0\xb4' $'\xe2\xa0\xa6' $'\xe2\xa0\xa7' $'\xe2\xa0\x87' $'\xe2\xa0\x8f') - else - frames=('|' '/' '-' '\\') - fi - local i=0 - trap 'exit 0' TERM - while :; do - local last="" w max - w=$(tput cols 2>/dev/null || echo 80) - max=$(( w - 10 - ${#label} - ${#hint} )) - (( max < 10 )) && max=10 - if [[ -f $file ]]; then - last=$(tail -n 1 "$file" 2>/dev/null | tr -d '\r' | sed -E 's/\x1b\[[0-9;]*[a-zA-Z]//g') - last=${last:0:max} - fi - printf "\r\033[K %s%s%s %s%s %s%s%s" \ - "$C_CYAN" "${frames[i]}" "$C_RESET" \ - "$label" \ - "$( [[ -n $hint ]] && printf ' %s(%s)%s' "$C_DIM$C_GRAY" "$hint" "$C_RESET" )" \ - "$C_DIM$C_GRAY" "$last" "$C_RESET" - i=$(( (i+1) % ${#frames[@]} )) - sleep 0.12 - done - ) & - _MON_PID=$! - disown "$_MON_PID" 2>/dev/null || true -} - -ui_monitor_stop() { - if (( _MON_PID > 0 )) 2>/dev/null; then - kill "$_MON_PID" 2>/dev/null || true - wait "$_MON_PID" 2>/dev/null || true - _MON_PID=0 - (( UI_TTY )) && printf '\r\033[K' - fi -} - -# Back-compat aliases used elsewhere. -ui_spinner_start() { ui_monitor_start "$1" /dev/null; } -ui_spinner_stop() { ui_monitor_stop; } - -ui_print_logo() { - local logo="$1" - [[ -f $logo ]] || return 0 - (( QUIET_LEVEL >= 1 )) && return - local w; w=$(ui_width) - (( w < 60 )) && return 0 - printf '%s' "$C_GREEN$C_BOLD" - cat "$logo" - printf '%s\n' "$C_RESET" -} - -# Pretty banner box used for the final summary. -ui_box() { - local title="$1"; shift - local lines=("$@") - local tl tr bl br v h - tl=$(ui_glyph tl); tr=$(ui_glyph tr); bl=$(ui_glyph bl); br=$(ui_glyph br) - v=$(ui_glyph v); h=$(ui_glyph hline) - local maxlen=${#title} - local l - for l in "${lines[@]}"; do - local stripped; stripped=$(printf '%s' "$l" | sed -E 's/\x1b\[[0-9;]*[a-zA-Z]//g') - (( ${#stripped} > maxlen )) && maxlen=${#stripped} - done - (( maxlen < 30 )) && maxlen=30 - local bar; printf -v bar '%*s' "$((maxlen+2))" ''; bar=${bar// /$h} - printf '\n %s%s%s%s%s\n' "$C_CYAN" "$tl" "$bar" "$tr" "$C_RESET" - printf ' %s%s%s %s%-*s%s %s%s%s\n' "$C_CYAN" "$v" "$C_RESET" "$C_BOLD" "$maxlen" "$title" "$C_RESET" "$C_CYAN" "$v" "$C_RESET" - printf ' %s%s%s%s%s\n' "$C_CYAN" "$v" "$bar" "$v" "$C_RESET" - for l in "${lines[@]}"; do - local stripped; stripped=$(printf '%s' "$l" | sed -E 's/\x1b\[[0-9;]*[a-zA-Z]//g') - local pad=$(( maxlen - ${#stripped} )) - printf ' %s%s%s %s%*s %s%s%s\n' "$C_CYAN" "$v" "$C_RESET" "$l" "$pad" "" "$C_CYAN" "$v" "$C_RESET" - done - printf ' %s%s%s%s%s\n' "$C_CYAN" "$bl" "$bar" "$br" "$C_RESET" -} diff --git a/src/lib/ui/monitor.sh b/src/lib/ui/monitor.sh new file mode 100644 index 0000000..ea5886d --- /dev/null +++ b/src/lib/ui/monitor.sh @@ -0,0 +1,193 @@ +#!/usr/bin/env bash +# Live log monitor shown while a command runs. + +: "${EMERGER_SPINNER:=}" # braille, dots, pulse or line + +# Print microsecond count $1 as 4.2s, 42s or 1m03s. +_ui_format_us() { + local us="$1" seconds + seconds=$(( us / 1000000 )) + if (( seconds < 10 )); then + printf '%d.%ds' "$seconds" $(( (us / 100000) % 10 )) + elif (( seconds < 60 )); then + printf '%ds' "$seconds" + else + printf '%dm%02ds' $(( seconds / 60 )) $(( seconds % 60 )) + fi +} + +# Print the wall clock in microseconds (whole seconds padded with zeros +# when EPOCHREALTIME is missing). +_ui_now_us() { + if [[ -n ${EPOCHREALTIME:-} ]]; then + printf '%s' "${EPOCHREALTIME/[.,]/}" + else + printf '%s000000' "$(date +%s)" + fi +} + +# Set _UI_FRAMES to the EMERGER_SPINNER style: braille by default and for an +# unknown name, pulse in ASCII mode unless the style is line. +_ui_spinner_frames() { + local style="${EMERGER_SPINNER:-}" + if [[ -z $style ]]; then + if (( UI_HAS_UNICODE )); then style=braille; else style=pulse; fi + fi + (( UI_HAS_UNICODE )) || [[ $style == line ]] || style=pulse + case "$style" in + dots) _UI_FRAMES=(โ  โ ˆ โ  โ   โข€ โก€ โ „ โ ‚) ;; + line) _UI_FRAMES=('|' '/' '-' '\') ;; + pulse) _UI_FRAMES=('. ' '.. ' '.:.' ':::' ' ::' ' :' ' ' ' .' ' ..' '.:.' ':::' ':: ' ': ' ' ') ;; + *) _UI_FRAMES=(โ ‰ โ ˜ โ ฐ โข  โฃ€ โก„ โ † โ ƒ) ;; + esac +} + +# Set _UI_WAVE to ".:::." bouncing across 8 columns, for steps with no +# known progress. +_ui_wave_frames() { + local track=8 shape='.:::.' position line frames=() j column k + for (( position=-${#shape}+1; position= 0 && column < track )) && line="${line:0:column}${shape:j:1}${line:column+1}" + done + frames+=("$line") + done + for (( k=${#frames[@]}-2; k>0; k-- )); do frames+=("${frames[k]}"); done + _UI_WAVE=("${frames[@]}") +} + +# PID of the running monitor subshell, 0 when none runs. +_MONITOR_PID=0 +# Microsecond clock at the last ui_monitor_start, 0 once ui_monitor_stop read it. +_MONITOR_START_US=0 + +# Show step label $1 live while a command writes log file $2, with hint $3: +# spinner, progress bar (or wave), elapsed time and last output line. Under +# -qq nothing is shown, under -v or off a terminal one plain line. Reads the +# log through an fd, no forks per frame except a parent check every 16 +# frames. A line without a newline (a prompt waiting for input) is shown once +# no output came for 2 s (20 frames). +ui_monitor_start() { + _MONITOR_START_US=$(_ui_now_us) + (( QUIET_LEVEL >= 2 )) && return + (( ${UI_VERBOSE:-0} )) && { ui_sub "$1"; return; } + (( UI_IS_TTY )) || { ui_sub "$1"; return; } + local label="$1" file="$2" hint="${3:-}" + _ui_spinner_frames + _ui_wave_frames + ui_cursor_hide + ( + local frames=("${_UI_FRAMES[@]}") wave=("${_UI_WAVE[@]}") + local frame_count=${#frames[@]} wave_count=${#wave[@]} grad=("${UI_GRADIENT[@]}") gradient_count=${#UI_GRADIENT[@]} + local tick=0 width=80 start=$SECONDS elapsed last="" line carry="" max spinner_color read_fd="" n + local manager="${_PKG_CURRENT:-}" anim progress_text shown idle=0 parent=$$ + local hint_colored="" + + progress_reset + [[ -n $hint ]] && hint_colored=" $C_DIM$C_GRAY($hint)$C_RESET" + trap 'exit 0' TERM + while :; do + if (( tick % 16 == 0 )); then + sys_is_parent_alive "$parent" || exit 0 + width=$(tput cols 2>/dev/null || echo 80); (( width > 0 )) || width=80 + fi + elapsed=$(( SECONDS - start )) + _ui_monitor_read + _ui_monitor_frame + tick=$(( tick + 1 )) + sleep 0.1 + done + ) 9>&- & + # Not disowned: ui_monitor_stop waits for it, so no frame lands after the + # line is cleared. + _MONITOR_PID=$! +} + +# Record the elapsed time of the last ui_monitor_start in UI_LAST_ELAPSED, +# stop the monitor, wait for it, clear its line and show the cursor. +ui_monitor_stop() { + if (( _MONITOR_START_US > 0 )); then + # Read by ui_done. + # shellcheck disable=SC2034 + UI_LAST_ELAPSED=$(_ui_format_us $(( $(_ui_now_us) - _MONITOR_START_US ))) + _MONITOR_START_US=0 + fi + if (( _MONITOR_PID > 0 )) 2>/dev/null; then + kill "$_MONITOR_PID" 2>/dev/null || true + wait "$_MONITOR_PID" 2>/dev/null || true + _MONITOR_PID=0 + (( UI_IS_TTY )) && printf '\r\e[K' + ui_cursor_show + fi + return 0 +} + +# Monitor helpers, run inside ui_monitor_start's subshell on its locals. + +# Open the log once it exists, then read at most 400 new lines into last +# (the newest line, or its progress message), feeding each to progress_feed. +# Keep a partial line in carry and show it after 20 idle frames. +_ui_monitor_read() { + if [[ -z $read_fd && -f $file && $file != /dev/null ]]; then + exec {read_fd}<"$file" || read_fd="" + fi + if [[ -n $read_fd ]]; then + # At most 400 lines per frame, so a burst cannot freeze the spinner. + idle=$(( idle + 1 )) + for (( n=0; n<400; n++ )); do + if IFS= read -r -u "$read_fd" line; then + line="$carry$line"; carry=""; idle=0 + else + [[ -n $line ]] && idle=0 + carry+="$line" # partial line, finish it next frame + break + fi + _ui_clean_line "$line"; line=$_UI_CLEANED + [[ -z $line ]] && continue + PROGRESS_MESSAGE="" + progress_feed "$manager" "$line" + last=${PROGRESS_MESSAGE:-$line} + done + if (( idle == 20 )) && [[ -n $carry ]]; then + _ui_clean_line "$carry" + [[ -n $_UI_CLEANED ]] && last=$_UI_CLEANED + fi + last=${last//$'\t'/ } + last=${last#"${last%%[![:space:]]*}"} + fi +} + +# Draw one frame on the current line: spinner, label, hint, progress bar or +# wave, elapsed time and as much of last as fits the width w. +_ui_monitor_frame() { + progress_text="" + if (( PROGRESS_TOTAL > 0 )); then + ui_bar $(( PROGRESS_CURRENT * 100 / PROGRESS_TOTAL )); anim=$_UI_BAR + progress_text="${PROGRESS_CURRENT}/${PROGRESS_TOTAL}" + elif (( PROGRESS_PERCENT >= 0 )); then + ui_bar "$PROGRESS_PERCENT"; anim=$_UI_BAR + progress_text="${PROGRESS_PERCENT}%" + else + anim="${C_CYAN}${wave[tick % wave_count]} ${C_RESET}" + (( PROGRESS_CURRENT > 0 )) && progress_text="#${PROGRESS_CURRENT}" + fi + + # 35 = indent, bar, counter, clock and the gaps between them. + max=$(( width - 35 - ${#frames[0]} - ${#label} - ${#hint} )) + (( max < 0 )) && max=0 + shown=${last:0:max} + if (( gradient_count > 0 )); then + spinner_color=$'\e[38;5;'"${grad[(tick / 2) % gradient_count]}"'m' + else + spinner_color=$C_CYAN + fi + printf '\r\e[K %s%s%s %s%s%s%s %s %s%-7s%s %s%d:%02d%s %s%s%s' \ + "$spinner_color$C_BOLD" "${frames[tick % frame_count]}" "$C_RESET" \ + "$C_BOLD" "$label" "$C_RESET" \ + "$hint_colored" \ + "$anim" "$C_BOLD" "$progress_text" "$C_RESET" \ + "$C_GRAY" $(( elapsed / 60 )) $(( elapsed % 60 )) "$C_RESET" \ + "$C_DIM$C_GRAY" "$shown" "$C_RESET" +} diff --git a/src/lib/ui/print.sh b/src/lib/ui/print.sh new file mode 100644 index 0000000..3f87cb3 --- /dev/null +++ b/src/lib/ui/print.sh @@ -0,0 +1,171 @@ +#!/usr/bin/env bash +# Message printers: section headers, status lines, results, logo, header +# line and box. + +: "${QUIET_LEVEL:=0}" + +# Print a dim horizontal rule across the header width. Hidden from -qq. +ui_rule() { + (( QUIET_LEVEL >= 2 )) && return + local width; width=$(_ui_columns) + _ui_repeat "$(ui_glyph hline)" $(( width - 2 )) + printf ' %s%s%s\n' "$C_DIM$C_GRAY" "$_UI_REPEATED" "$C_RESET" +} + +# Step counter, shown by the next section header. +_UI_STEP_INDEX=0; _UI_STEP_TOTAL=0 +# Set the step counter, $1 of $2, which the next ui_section shows and clears. +ui_step() { + _UI_STEP_INDEX=$1; _UI_STEP_TOTAL=$2 + return 0 +} + +# Print section header for name $2 with icon $1 (arrow when empty) and dim +# note $3, ruled to the header width, with the ui_step counter when set: +# โ—† apt ~42s โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ–ฐโ–ฐโ–ฑ 1/3 +# Hidden from -qq. The bar is drawn for 12 steps or fewer. +ui_section() { + (( QUIET_LEVEL >= 2 )) && return + local icon="${1:-}" name="$2" note="${3:-}" + [[ -z $icon ]] && icon=$(ui_glyph arrow) + local width left right="" right_c="" fill + width=$(_ui_columns) + + left=" $icon $name" + [[ -n $note ]] && left+=" $note" + + if (( _UI_STEP_TOTAL > 0 )); then + local bar="" step + if (( _UI_STEP_TOTAL <= 12 )); then + for (( step=1; step<=_UI_STEP_TOTAL; step++ )); do + if (( step <= _UI_STEP_INDEX )); then bar+=$(ui_glyph pfull); else bar+=$(ui_glyph pempty); fi + done + bar+=" " + fi + right=" ${bar}${_UI_STEP_INDEX}/${_UI_STEP_TOTAL}" + right_c=" ${C_MAGENTA}${bar}${C_BOLD}${_UI_STEP_INDEX}/${_UI_STEP_TOTAL}${C_RESET}" + _UI_STEP_INDEX=0; _UI_STEP_TOTAL=0 + fi + + _ui_visible_width "$left"; local left_width=$_UI_WIDTH + _ui_visible_width "$right"; local right_width=$_UI_WIDTH + fill=$(( width - left_width - right_width - 2 )) + (( fill < 3 )) && fill=3 + _ui_repeat "$(ui_glyph hline)" "$fill" + + printf '\n %s%s%s %s%s%s' "$C_CYAN$C_BOLD" "$icon" "$C_RESET" "$C_BOLD" "$name" "$C_RESET" + [[ -n $note ]] && printf ' %s%s%s' "$C_DIM$C_GRAY" "$note" "$C_RESET" + printf ' %s%s%s%s\n' "$C_DIM$C_GRAY" "$_UI_REPEATED" "$C_RESET" "$right_c" +} + +# Print a section header with the arrow glyph and title $*. +ui_title() { ui_section "" "$*"; } +# Print message $* on one indented status line with its glyph: info and ok +# hidden from -qq, muted and sub from -q, warn and err always shown, on stderr. +ui_info() { (( QUIET_LEVEL >= 2 )) && return; printf ' %s%s%s %s\n' "$C_BLUE" "$(ui_glyph info)" "$C_RESET" "$*"; } +ui_ok() { (( QUIET_LEVEL >= 2 )) && return; printf ' %s%s%s %s\n' "$C_GREEN" "$(ui_glyph check)" "$C_RESET" "$*"; } +ui_warn() { printf ' %s%s%s %s\n' "$C_YELLOW" "$(ui_glyph warn)" "$C_RESET" "$*" >&2; } +ui_err() { printf ' %s%s%s %s\n' "$C_RED$C_BOLD" "$(ui_glyph cross)" "$C_RESET" "$*" >&2; } +ui_muted() { (( QUIET_LEVEL >= 1 )) && return; printf ' %s%s%s\n' "$C_DIM$C_GRAY" "$*" "$C_RESET"; } +ui_sub() { (( QUIET_LEVEL >= 1 )) && return; printf ' %s%s%s %s\n' "$C_GRAY" "$(ui_glyph dot)" "$C_RESET" "$*"; } + +# Set by ui_monitor_stop, printed by the next ui_done/ui_fail. +UI_LAST_ELAPSED="" + +# Set _UI_REPEATED to the dot leader that pads label $1 to column 26, at +# least two dots, so the results line up. +_ui_leader() { + local label="$1" column=26 count + _ui_visible_width "$label" + count=$(( column - _UI_WIDTH )) + (( count < 2 )) && count=2 + _ui_repeat "$(ui_glyph dot)" "$count" +} + +# Print the success line of step $1 with dot leader, the elapsed time from +# ui_monitor_stop and optional stat $2. Hidden from -qq. +ui_done() { + local label="$1" status="${2:-}" elapsed="$UI_LAST_ELAPSED" + UI_LAST_ELAPSED="" + (( QUIET_LEVEL >= 2 )) && return + _ui_leader "$label" + printf ' %s%s%s %s %s%s%s' "$C_GREEN" "$(ui_glyph check)" "$C_RESET" "$label" "$C_DIM$C_GRAY" "$_UI_REPEATED" "$C_RESET" + [[ -n $elapsed ]] && printf ' %s%6s%s' "$C_GRAY" "$elapsed" "$C_RESET" + [[ -n $status ]] && printf ' %s%s%s' "$C_CYAN" "$status" "$C_RESET" + printf '\n' +} + +# Print the failure line of step $1 with the elapsed time and exit code $2 +# (default 1) on stderr. +ui_fail() { + local label="$1" rc="${2:-1}" elapsed="$UI_LAST_ELAPSED" + UI_LAST_ELAPSED="" + _ui_leader "$label" + { + printf ' %s%s%s %s%s%s %s%s%s' "$C_RED$C_BOLD" "$(ui_glyph cross)" "$C_RESET" "$C_RED" "$label" "$C_RESET" "$C_DIM$C_GRAY" "$_UI_REPEATED" "$C_RESET" + [[ -n $elapsed ]] && printf ' %s%6s%s' "$C_GRAY" "$elapsed" "$C_RESET" + printf ' %sexit %s%s\n' "$C_RED" "$rc" "$C_RESET" + } >&2 +} + +# Print logo file $1 line by line in the gradient colours. Skipped when the +# file is missing, under -q, or on a terminal narrower than 64 columns. +ui_print_logo() { + local logo="$1" + [[ -f $logo ]] || return 0 + (( QUIET_LEVEL >= 1 )) && return + local width; width=$(ui_width) + (( width < 64 )) && return 0 + local line i=0 gradient_count=${#UI_GRADIENT[@]} + printf '\n' + while IFS= read -r line || [[ -n $line ]]; do + if (( gradient_count > 0 )); then + printf ' \e[38;5;%sm%s%s%s\n' "${UI_GRADIENT[i % gradient_count]}" "$C_BOLD" "$line" "$C_RESET" + else + printf ' %s%s%s\n' "$C_GREEN$C_BOLD" "$line" "$C_RESET" + fi + i=$(( i + 1 )) + done <"$logo" + printf '\n' + return 0 +} + +# Print the system info line under the logo: items $@ separated by dots, +# empty ones skipped. Hidden from -q. +ui_header() { + (( QUIET_LEVEL >= 1 )) && return + local sep out="" item + sep=" ${C_DIM}${C_GRAY}$(ui_glyph dot)${C_RESET} " + for item in "$@"; do + [[ -z $item ]] && continue + [[ -n $out ]] && out+="$sep" + out+="$item" + done + printf ' %s%s%s %s\n' "$C_CYAN" "$(ui_glyph diamond)" "$C_RESET" "$out" +} + +# Print a box with title $1 in its top border around lines $2..., at least +# 44 columns wide, border colour from UI_BOX_COLOR (cyan by default). +ui_box() { + local title="$1"; shift + local lines=("$@") + local border_color="${UI_BOX_COLOR:-$C_CYAN}" + local tl tr bl br v h line + tl=$(ui_glyph tl); tr=$(ui_glyph tr); bl=$(ui_glyph bl); br=$(ui_glyph br) + v=$(ui_glyph v); h=$(ui_glyph hline) + local inner=$(( ${#title} + 4 )) + for line in "${lines[@]}"; do + _ui_visible_width "$line" + (( _UI_WIDTH + 2 > inner )) && inner=$(( _UI_WIDTH + 2 )) + done + (( inner < 44 )) && inner=44 + _ui_repeat "$h" $(( inner - ${#title} - 3 )) + printf '\n %s%s%s %s%s%s %s%s%s%s\n' "$border_color" "$tl" "$h" "$C_RESET$C_BOLD" "$title" "$C_RESET" "$border_color" "$_UI_REPEATED" "$tr" "$C_RESET" + for line in "${lines[@]}"; do + _ui_visible_width "$line" + local pad=$(( inner - 2 - _UI_WIDTH )) + printf ' %s%s%s %s%*s %s%s%s\n' "$border_color" "$v" "$C_RESET" "$line" "$pad" "" "$border_color" "$v" "$C_RESET" + done + _ui_repeat "$h" "$inner" + printf ' %s%s%s%s%s\n' "$border_color" "$bl" "$_UI_REPEATED" "$br" "$C_RESET" +} diff --git a/src/lib/ui/prompt.sh b/src/lib/ui/prompt.sh new file mode 100644 index 0000000..cbd99f6 --- /dev/null +++ b/src/lib/ui/prompt.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Prompts on the terminal: free answer and yes/no. + +: "${EMERGER_PROMPT_TIMEOUT:=60}" # seconds, 0 waits forever + +# Ask prompt $1 with hint $2 and detail $3 on /dev/tty, which works with stdin +# or stderr redirected. Set UI_ANSWER and return 1 when nothing was read (no +# tty, EOF, EMERGER_PROMPT_TIMEOUT), so the caller tells a default from an answer. +ui_ask() { + local prompt="$1" hint="${2:-}" detail="${3:-}" fd timeout="${EMERGER_PROMPT_TIMEOUT:-60}" + [[ $timeout =~ ^[0-9]{1,9}$ ]] && timeout=$(( 10#$timeout )) || timeout=60 + UI_ANSWER="" + if ! { exec {fd}<>/dev/tty; } 2>/dev/null; then + ui_muted "no terminal for \"$prompt\", using the default" + return 1 + fi + printf ' %s%s%s %s%s%s' "$C_MAGENTA$C_BOLD" "$(ui_glyph ask)" "$C_RESET" "$C_BOLD" "$prompt" "$C_RESET" >&"$fd" + [[ -n $detail ]] && printf ' %s%s%s' "$C_DIM$C_GRAY" "$detail" "$C_RESET" >&"$fd" + [[ -n $hint ]] && printf ' %s[%s]%s' "$C_GRAY" "$hint" "$C_RESET" >&"$fd" + printf ' ' >&"$fd" + local rc=0 + if (( timeout > 0 )); then + read -r -t "$timeout" -u "$fd" UI_ANSWER || rc=$? + else + read -r -u "$fd" UI_ANSWER || rc=$? + fi + if (( rc != 0 )); then + printf '\n' >&"$fd" + UI_ANSWER="" + # read -t exits >128 on timeout, 1 on EOF. + if (( rc > 128 )); then + ui_muted "no answer after ${timeout}s, using the default" + else + ui_muted "no input, using the default" + fi + rc=1 + fi + exec {fd}>&- + return "$rc" +} + +# Ask y/N question $1 (default answer $2, detail $3) and return 0 for yes. +# -y says yes without asking. +ui_confirm() { + local prompt="$1" default="${2:-n}" detail="${3:-}" + if (( ${ARG_YES:-0} )); then return 0; fi + local hint="y/N"; [[ $default == [yY]* ]] && hint="Y/n" + ui_ask "$prompt" "$hint" "$detail" || true + local answer=${UI_ANSWER:-$default} + [[ $answer == [yY]* ]] +} diff --git a/src/lib/ui/term.sh b/src/lib/ui/term.sh new file mode 100644 index 0000000..2499378 --- /dev/null +++ b/src/lib/ui/term.sh @@ -0,0 +1,155 @@ +#!/usr/bin/env bash +# Terminal capabilities: colour, UTF-8 and emoji detection, glyphs, width, +# cursor. +# UI_* are read by the other ui modules. +# shellcheck disable=SC2034 + +: "${ARG_ASCII:=0}" +: "${EMERGER_EMOJI:=auto}" # auto, 1 or 0 + +# Set UI_IS_LIGHT_BG to 1 when COLORFGBG names a background colour of 7 or +# more, else 0. +_ui_detect_light_bg() { + # COLORFGBG is "fg;bg": a background of 0 to 6 is a dark theme, 7 or more a light one. + [[ -z ${COLORFGBG:-} ]] && { UI_IS_LIGHT_BG=0; return; } + local background="${COLORFGBG##*;}" + if [[ $background =~ ^[0-9]+$ ]] && (( background >= 7 )); then + UI_IS_LIGHT_BG=1 + else + UI_IS_LIGHT_BG=0 + fi +} + +# Set UI_HAS_EMOJI: EMERGER_EMOJI when it says yes or no, else 1 on macOS, over +# SSH or with a colour-emoji font installed. Always 0 without UTF-8, where +# emoji would show as empty boxes. +_ui_detect_emoji() { + UI_HAS_EMOJI=0 + (( UI_HAS_UNICODE )) || return 0 + case "${EMERGER_EMOJI,,}" in + 1|yes|on|true) UI_HAS_EMOJI=1; return 0 ;; + 0|no|off|false) return 0 ;; + esac + [[ ${TERM:-} == linux ]] && return 0 + [[ ${OSTYPE:-} == darwin* ]] && { UI_HAS_EMOJI=1; return 0; } + # Over SSH the client's fonts matter. + [[ -n ${SSH_CONNECTION:-} ]] && { UI_HAS_EMOJI=1; return 0; } + if command -v fc-list >/dev/null 2>&1; then + [[ -n $(fc-list ':charset=1f4e6' family 2>/dev/null | head -n 1) ]] && UI_HAS_EMOJI=1 + fi + return 0 +} + +# Set the colour codes, gradient and UI_IS_TTY from the terminal, NO_COLOR +# and TERM, then UI_HAS_UNICODE from --ascii and the locale, and UI_HAS_EMOJI. +_ui_init() { + local colors=0 + _ui_detect_light_bg + if [[ -n ${NO_COLOR:-} ]] || [[ ${TERM:-} == dumb ]] || ! [[ -t 1 ]]; then + C_RESET="" C_BOLD="" C_DIM="" + C_RED="" C_GREEN="" C_YELLOW="" C_BLUE="" C_MAGENTA="" C_CYAN="" C_GRAY="" + UI_GRADIENT=() + UI_IS_TTY=0 + else + command -v tput >/dev/null 2>&1 && colors=$(tput colors 2>/dev/null || echo 0) + C_RESET=$'\e[0m'; C_BOLD=$'\e[1m'; C_DIM=$'\e[2m' + if (( colors >= 256 )); then + if (( UI_IS_LIGHT_BG )); then + C_RED=$'\e[38;5;160m'; C_GREEN=$'\e[38;5;28m'; C_YELLOW=$'\e[38;5;136m' + C_BLUE=$'\e[38;5;26m'; C_MAGENTA=$'\e[38;5;90m'; C_CYAN=$'\e[38;5;30m' + C_GRAY=$'\e[38;5;240m' + UI_GRADIENT=(35 35 29 29 29 22 22) + else + C_RED=$'\e[38;5;203m'; C_GREEN=$'\e[38;5;114m'; C_YELLOW=$'\e[38;5;221m' + C_BLUE=$'\e[38;5;39m'; C_MAGENTA=$'\e[38;5;176m'; C_CYAN=$'\e[38;5;81m' + C_GRAY=$'\e[38;5;245m' + UI_GRADIENT=(121 84 48 42 35 29 29) + fi + else + C_RED=$'\e[31m'; C_GREEN=$'\e[32m'; C_YELLOW=$'\e[33m' + C_BLUE=$'\e[34m'; C_MAGENTA=$'\e[35m'; C_CYAN=$'\e[36m'; C_GRAY=$'\e[37m' + UI_GRADIENT=() + fi + UI_IS_TTY=1 + fi + # Read as text: the value may come from the environment, where arithmetic + # would run it as code. + if [[ ${ARG_ASCII:-0} =~ ^[0-9]{1,15}$ ]] && (( 10#$ARG_ASCII )); then + UI_HAS_UNICODE=0 + # The first set of LC_ALL, LC_CTYPE and LANG decides the character set. + elif [[ ${LC_ALL:-${LC_CTYPE:-${LANG:-}}} =~ [Uu][Tt][Ff]-?8 ]]; then + UI_HAS_UNICODE=1 + else + UI_HAS_UNICODE=0 + fi + _ui_detect_emoji +} +_ui_init + +# Detect the terminal again, after a flag, config or profile changed what +# _ui_init reads. +ui_reinit() { _ui_init; } + +# Print glyph name $1 (check, cross, arrow, box corners...) as Unicode, or +# its ASCII stand-in when UI_HAS_UNICODE is 0. Unknown names print nothing. +ui_glyph() { + if (( UI_HAS_UNICODE )); then + case "$1" in + check) printf '\xe2\x9c\x94' ;; + cross) printf '\xe2\x9c\x96' ;; + arrow) printf '\xe2\x96\xb8' ;; + info) printf '\xe2\x97\x8f' ;; + warn) printf '\xe2\x96\xb2' ;; + ask) printf '\xe2\x9d\xaf' ;; + bullet) printf '\xe2\x80\xa2' ;; + hline) printf '\xe2\x94\x80' ;; + dot) printf '\xc2\xb7' ;; + diamond) printf '\xe2\x97\x86' ;; + pfull) printf '\xe2\x96\xb0' ;; + pempty) printf '\xe2\x96\xb1' ;; + tl) printf '\xe2\x95\xad' ;; + tr) printf '\xe2\x95\xae' ;; + bl) printf '\xe2\x95\xb0' ;; + br) printf '\xe2\x95\xaf' ;; + v) printf '\xe2\x94\x82' ;; + esac + else + case "$1" in + check) printf '[OK]' ;; + cross) printf '[X]' ;; + arrow) printf '>' ;; + info) printf 'i' ;; + warn) printf '!' ;; + ask) printf '?' ;; + bullet) printf '*' ;; + hline) printf '-' ;; + dot) printf '.' ;; + diamond) printf '*' ;; + pfull) printf '#' ;; + pempty) printf '.' ;; + tl|tr|bl|br) printf '+' ;; + v) printf '|' ;; + esac + fi +} + +# Print the terminal width in columns, 80 when tput cannot tell. +ui_width() { + local width + width=$(tput cols 2>/dev/null || echo 80) + (( width > 0 )) || width=80 + printf '%d' "$width" +} + +# Print the width for headers and boxes: the terminal width held between 40 +# and 78 columns. +_ui_columns() { + local width; width=$(ui_width) + (( width > 78 )) && width=78 + (( width < 40 )) && width=40 + printf '%d' "$width" +} + +# Hide or show the cursor on a terminal. Always return 0. +ui_cursor_hide() { (( UI_IS_TTY )) && printf '\e[?25l'; return 0; } +ui_cursor_show() { (( UI_IS_TTY )) && printf '\e[?25h'; return 0; } diff --git a/src/lib/ui/text.sh b/src/lib/ui/text.sh new file mode 100644 index 0000000..c0d6689 --- /dev/null +++ b/src/lib/ui/text.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# Text measurement and filtering: escape stripping, visible width, repeat, +# percentage bar, stream highlighting. + +# Helpers named _ui_* return through globals to avoid subshells. + +# Set _UI_STRIPPED to text $1 without its CSI escape sequences. +_ui_strip() { + local text="$1" re=$'\e''\[[0-9;?]*[a-zA-Z]' + while [[ $text =~ $re ]]; do text=${text/"${BASH_REMATCH[0]}"/}; done + _UI_STRIPPED="$text" +} + +# Set _UI_WIDTH to the visible width of $1, escapes stripped, emoji counted +# as two columns. +_ui_visible_width() { + _ui_strip "$1" + local text="$_UI_STRIPPED" width=${#_UI_STRIPPED} i char + if (( UI_HAS_EMOJI )); then + for (( i=0; i<${#text}; i++ )); do + char=${text:i:1} + [[ $char == [[:ascii:]] ]] && continue + (( $(printf '%d' "'$char") >= 0x1F000 )) && width=$(( width + 1 )) + done + fi + _UI_WIDTH=$width +} + +# Set _UI_REPEATED to string $1 repeated $2 times. +_ui_repeat() { + local line; printf -v line '%*s' "$2" '' + _UI_REPEATED=${line// /$1} +} + +# Set _UI_BAR to a 10-column coloured bar for percentage $1, clamped to +# 0 to 100. Unicode fills in eighths of a cell. +ui_bar() { + local percent="$1" width=10 full=0 remainder=0 i bar="" empty="" fill='#' pad='-' + (( percent < 0 )) && percent=0 + (( percent > 100 )) && percent=100 + if (( UI_HAS_UNICODE )); then + local parts=('' 'โ–' 'โ–Ž' 'โ–' 'โ–Œ' 'โ–‹' 'โ–Š' 'โ–‰') + fill='โ–ˆ'; pad='โ–‘' + full=$(( percent * width * 8 / 100 / 8 )); remainder=$(( percent * width * 8 / 100 % 8 )) + for (( i=0; i 0 && full < width )) && { bar+=${parts[remainder]}; full=$(( full + 1 )); } + else + full=$(( percent * width / 100 )) + for (( i=0; i 4096 )) && line=${line: -4096} + line=${line##*$'\r'} + line=${line:0:1024} + LC_ALL=C # byte-wise from here, so the C1 pair matches whatever the locale + while [[ $line =~ $re_csi ]]; do line=${line/"${BASH_REMATCH[0]}"/}; done + # OSC (title, clipboard, hyperlink) and stray controls never reach the terminal. + while [[ $line =~ $re_osc ]]; do line=${line/"${BASH_REMATCH[0]}"/}; done + line=${line//$re_control/} + # Removing one C1 pair or control byte can join the halves of another: repeat. + while [[ $line == *$'\xc2'[$'\x80'-$'\x9f']* ]]; do + line=${line//$'\xc2'[$'\x80'-$'\x9f']/} + done + # A terminal outside UTF-8 reads a byte in 0x80-0x9F as a C1 control. + (( ${UI_HAS_UNICODE:-0} )) || line=${line//[$'\x80'-$'\xff']/} + _UI_CLEANED=$line +} + +# Copy stdin to stdout with error words in red and warning words in yellow, +# apt "E:" and "W:" lines whole. With colours off (NO_COLOR, dumb terminal, +# no tty) the stream is copied unchanged. +ui_highlight() { + [[ -n ${C_RED:-} ]] || { cat; return; } + sed -E \ + -e "s/(ERROR|Error|error)/$(printf '\033[31m')\1$(printf '\033[0m')/g" \ + -e "s/(WARNING|Warning|warning|WARN)/$(printf '\033[33m')\1$(printf '\033[0m')/g" \ + -e "s/^(E: .*)/$(printf '\033[31m')\1$(printf '\033[0m')/g" \ + -e "s/^(W: .*)/$(printf '\033[33m')\1$(printf '\033[0m')/g" +} + +# Copy stdin to stdout, dropping every byte above 0x7F when the terminal is +# not UTF-8: such a terminal reads 0x80-0x9F as C1 controls. +ui_terminal_bytes() { + if (( ${UI_HAS_UNICODE:-0} )); then + cat + else + LC_ALL=C tr -d '\200-\377' + fi +} diff --git a/src/lib/update.sh b/src/lib/update.sh deleted file mode 100644 index 190f361..0000000 --- a/src/lib/update.sh +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env bash -# Self-update (git pull) and auto-update scheduling (systemd user timer or cron). - -self_update() { - local root="$1" - ui_title "Self-update" - if [[ ! -d "$root/.git" ]]; then - ui_err "Not a git checkout. Re-clone: git clone https://github.com/MasterCruelty/eMerger" - return 1 - fi - if ! sys_has git; then - ui_err "git not installed" - return 1 - fi - local branch before after - branch=$(git -C "$root" rev-parse --abbrev-ref HEAD) - ui_info "Branch: $branch" - if (( DRY_RUN )); then - ui_sub "[dry-run] git -C $root pull --ff-only" - return 0 - fi - before=$(git -C "$root" rev-parse HEAD) - if ! git -C "$root" fetch --quiet; then - ui_err "git fetch failed" - return 1 - fi - if ! git -C "$root" pull --ff-only --quiet; then - ui_err "git pull failed (non fast-forward?)" - return 1 - fi - after=$(git -C "$root" rev-parse HEAD) - if [[ $before == "$after" ]]; then - ui_ok "Already up to date." - else - ui_ok "Updated ${before:0:7}..${after:0:7}" - git -C "$root" log --oneline "$before..$after" | sed "s/^/ $(ui_glyph dot) /" - fi -} - -setup_cron() { - local root="$1" - ui_title "Enable auto-update" - if sys_has systemctl && [[ -d /run/systemd/system ]] || sys_has systemctl && systemctl --user show-environment >/dev/null 2>&1; then - local unit_dir="$HOME/.config/systemd/user" - mkdir -p "$unit_dir" - cat >"$unit_dir/emerger.service" <"$unit_dir/emerger.timer" </dev/null | grep -v "emerger.sh" || true; echo "$cronline" ) | crontab - - ui_ok "Weekly cronjob installed (Sunday 10:00)" - else - ui_err "Neither systemd --user nor crontab available." - return 1 - fi -} diff --git a/src/lib/wizard.sh b/src/lib/wizard.sh deleted file mode 100644 index dbf0e06..0000000 --- a/src/lib/wizard.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env bash -# First-run wizard: ask 3 questions, seed config.sh. - -wizard_maybe_run() { - local cfg="$EMERGER_CONFIG/config.sh" - local flag="$EMERGER_CONFIG/.wizard-done" - [[ -f $flag ]] && return 0 - [[ ! -t 0 ]] && return 0 - (( ARG_QUIET )) && return 0 - - ui_title "First-run setup" - ui_muted "Quick 3-question setup. Skip with Ctrl-C at any time." - mkdir -p "$EMERGER_CONFIG" - - local a1 a2 a3 - read -r -p " Include dev toolchains (rust/npm/pip...) by default? [y/N]: " a1 || a1=n - read -r -p " Show weather line? [y/N]: " a2 || a2=n - read -r -p " Install weekly auto-update timer? [y/N]: " a3 || a3=n - - { - printf '# eMerger user config - generated by the wizard %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" - printf '# Edit freely; it is sourced before argument parsing.\n\n' - [[ $a1 == [yY]* ]] && printf 'ARG_DEV=1\n' - [[ $a2 == [yY]* ]] && printf 'ARG_WEATHER=1\n' - } >"$cfg" - - touch "$flag" - ui_ok "Wrote $cfg" - if [[ $a3 == [yY]* ]]; then - setup_cron "$EMERGER_ROOT" || true - fi -} diff --git a/src/logo/README.md b/src/logo/README.md index f900a3b..77ac1cf 100644 --- a/src/logo/README.md +++ b/src/logo/README.md @@ -1 +1,20 @@ -Logos are created using inkscape and GIMP. \ No newline at end of file +`big_name.svg` is the source: four blades turning around a hub with an +upward arrow, and the name below. The name is converted to outlines (Inter +Display ExtraBold, SIL Open Font License 1.1), so the file does not depend +on installed fonts. `big_name.png` is a 512 px wide export: + +``` +inkscape big_name.svg --export-type=png --export-width=512 --export-filename=big_name.png +``` + +Colors: + +| part | colors | +|---|---| +| blades | `#BBF7D0`, `#4ADE80`, `#16A34A`, `#166534` | +| arrow and name | `#22C55E` to `#15803D` | + +The terminal logo uses the nearest 256-color greens (`UI_GRADIENT` in +`src/lib/ui/term.sh` and `src/pslib/ui/Term.ps1`). + +`logo.txt` is the terminal logo, drawn by hand in block characters for this project. diff --git a/src/logo/big_name.png b/src/logo/big_name.png index 8b5c3e2..658961e 100644 Binary files a/src/logo/big_name.png and b/src/logo/big_name.png differ diff --git a/src/logo/big_name.svg b/src/logo/big_name.svg index 4153f9b..6819995 100644 --- a/src/logo/big_name.svg +++ b/src/logo/big_name.svg @@ -1,40 +1,53 @@ - - - - - - - - - - - - - - - - - - - + + eMerger + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - eMerger - diff --git a/src/logo/logo.txt b/src/logo/logo.txt index 8092204..b3048f4 100644 --- a/src/logo/logo.txt +++ b/src/logo/logo.txt @@ -1,6 +1,6 @@ -โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— -โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ• โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•— -โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•”โ–ˆโ–ˆโ–ˆโ–ˆโ•”โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• -โ–ˆโ–ˆโ•”โ•โ•โ• โ–ˆโ–ˆโ•‘โ•šโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ• โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ• โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•— -โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ•šโ•โ• โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ -โ•šโ•โ•โ•โ•โ•โ•โ•โ•šโ•โ• โ•šโ•โ•โ•šโ•โ•โ•โ•โ•โ•โ•โ•šโ•โ• โ•šโ•โ• โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ•โ•โ•โ•โ•โ•โ•šโ•โ• โ•šโ•โ• + โ–ˆโ–ˆโ–ˆโ–„ โ–„โ–ˆโ–ˆโ–ˆ +โ–„โ–ˆโ–ˆโ–€โ–€โ–ˆโ–ˆโ–„ โ–ˆโ–ˆโ–€โ–ˆโ–ˆโ–„โ–„โ–ˆโ–ˆโ–€โ–ˆโ–ˆ โ–„โ–ˆโ–ˆโ–€โ–€โ–ˆโ–ˆโ–„ โ–ˆโ–ˆโ–„โ–ˆโ–ˆโ–€ โ–„โ–ˆโ–ˆโ–€โ–€โ–ˆโ–ˆโ–ˆ โ–„โ–ˆโ–ˆโ–€โ–€โ–ˆโ–ˆโ–„ โ–ˆโ–ˆโ–„โ–ˆโ–ˆโ–€ +โ–ˆโ–ˆโ–„โ–„โ–„โ–„โ–ˆโ–ˆ โ–ˆโ–ˆ โ–€โ–ˆโ–ˆโ–€ โ–ˆโ–ˆ โ–ˆโ–ˆโ–„โ–„โ–„โ–„โ–ˆโ–ˆ โ–ˆโ–ˆโ–ˆโ–€ โ–ˆโ–ˆ โ–ˆโ–ˆ โ–ˆโ–ˆโ–„โ–„โ–„โ–„โ–ˆโ–ˆ โ–ˆโ–ˆโ–ˆโ–€ +โ–ˆโ–ˆโ–€โ–€โ–€โ–€โ–€โ–€ โ–ˆโ–ˆ โ–ˆโ–ˆ โ–ˆโ–ˆโ–€โ–€โ–€โ–€โ–€โ–€ โ–ˆโ–ˆ โ–€โ–ˆโ–ˆโ–„โ–„โ–ˆโ–ˆโ–ˆ โ–ˆโ–ˆโ–€โ–€โ–€โ–€โ–€โ–€ โ–ˆโ–ˆ +โ–€โ–ˆโ–ˆโ–„โ–„โ–„โ–ˆโ–€ โ–ˆโ–ˆ โ–ˆโ–ˆ โ–€โ–ˆโ–ˆโ–„โ–„โ–„โ–ˆโ–€ โ–ˆโ–ˆ โ–€โ–€โ–€ โ–ˆโ–ˆ โ–€โ–ˆโ–ˆโ–„โ–„โ–„โ–ˆโ–€ โ–ˆโ–ˆ + โ–€โ–ˆโ–ˆโ–„โ–„โ–ˆโ–ˆโ–€ diff --git a/src/pslib/Args.ps1 b/src/pslib/Args.ps1 index 8fb8de7..f9bf11b 100644 --- a/src/pslib/Args.ps1 +++ b/src/pslib/Args.ps1 @@ -1,107 +1,165 @@ # Argument parser. Returns a PSCustomObject with booleans / strings. -function Parse-Args { - param([string[]]$Argv) - $o = [pscustomobject]@{ +# Parse command line $Argv into the options object, onto -Into when given. +# Exit 2 on an unknown argument or a value flag without a value. +function Args-Parse { + # -Into: start from the object config.ps1 and the profile already set. + param([string[]]$Argv, $Into = $null) + if ($Into) { $options = $Into } else { $options = _Args-Defaults } + # Actions and queries come from the command line only: set in config.ps1 + # or a profile they would run on every run (a self-update among them). + foreach ($field in @('Help', 'Version', 'SelfUpdate', 'AutoUpdate', 'Errors', 'RebuildCache', 'History', + 'Doctor', 'ListProfiles', 'Changed', 'Rollback', 'Reboot')) { $options.$field = $false } + $options.Changelog = ''; $options.Metrics = '' + if (-not $Argv) { return $options } + $Argv = _Args-Expand-Bundles $Argv + $i = 0 + while ($i -lt $Argv.Count) { + $word = [string]$Argv[$i] + switch -Regex -CaseSensitive ($word) { + '^(-h|--help)$' { $options.Help = $true } + '^(-V|--version)$' { $options.Version = $true } + '^(-n|--dry-run)$' { $options.DryRun = $true } + '^(-v|--verbose)$' { $script:UI_VERBOSE = $true } + '^(-q|--quiet)$' { $script:QUIET_LEVEL++ } + '^-qq$' { $script:QUIET_LEVEL = 2 } + '^-qqq$' { $script:QUIET_LEVEL = 3 } + '^(-y|--yes)$' { $options.Yes = $true } + '^--dev$' { $options.Dev = $true } + '^--security$' { $options.Security = $true } + '^--firmware$' { $options.Firmware = $true } + '^(-nl|--no-logo)$' { $options.NoLogo = $true } + '^(-ni|--no-info)$' { $options.NoInfo = $true } + '^(-nc|--keep-cache)$' { $options.KeepCache = $true } + '^(-nt|--keep-trash)$' { $options.KeepTrash = $true } + '^(-err|--errors)$' { $options.Errors = $true } + '^--history$' { $options.History = $true } + '^--doctor$' { $options.Doctor = $true } + '^(-up|--self-update)$' { $options.SelfUpdate = $true } + '^(-au|--auto-update)$' { $options.AutoUpdate = $true } + '^(-rc|--rebuild-cache)$' { $options.RebuildCache = $true } + '^--snapshot$' { $options.Snapshot = $true } + '^--reboot$' { $options.Reboot = $true } + '^--list-profiles$' { $options.ListProfiles = $true } + '^--ascii$' { $options.Ascii = $true; $script:UI_IS_ASCII = $true; $script:UI_HAS_UNICODE = $false; $script:UI_HAS_EMOJI = $false } + '^--parallel$' { $options.Parallel = $true } + '^--changed$' { $options.Changed = $true } + '^--resume$' { $options.Resume = $true } + '^--json$' { $options.Json = $true } + '^(-w|--weather)$' { $options.Weather = $true } + '^--reboot-exit$' { $options.RebootExit = $true } + '^--download-only$' { $options.DownloadOnly = $true } + '^--accept-licenses$' { $options.AcceptLicenses = $true } + '^--deep-clean$' { $options.DeepClean = $true } + '^--no-firmware$' { $options.NoFirmware = $true } + '^--refresh-mirrors$' { $options.RefreshMirrors = $true } + '^--rollback$' { $options.Rollback = $true } + # End of options: the words after it are ignored. + '^--$' { $i = $Argv.Count } + '^--(only|except|metrics|profile|changelog)(=|$)' { + $flag = $Matches[1] + if ($Matches[2] -eq '=') { $value = $word.Substring($flag.Length + 3) } + else { $i++; $value = if ($i -lt $Argv.Count) { [string]$Argv[$i] } else { '' } } + $value = _Args-Need-Value "--$flag" $value + switch ($flag) { + # --except appends to the list from config.ps1 or the profile. + 'except' { $options.Except = (@($options.Except, $value) | Where-Object { $_ }) -join ',' } + 'only' { $options.Only = $value } + 'metrics' { $options.Metrics = $value } + # Args-Prescan-Profile already loaded the profile. + 'profile' { } + 'changelog' { $options.Changelog = $value } + } + } + default { + [Console]::Error.WriteLine("Unknown argument: $word (try `"up --help`")") + exit 2 + } + } + $i++ + } + return $options +} + +# Return every option at its default: the object config.ps1 and the profile +# write into. +function _Args-Defaults { + return [pscustomobject]@{ Help=$false; Version=$false - DryRun=$false; Verbose=$false; Yes=$false + DryRun=$false; Yes=$false Dev=$false; Security=$false; Firmware=$false - NoLogo=$false; NoInfo=$false; NoCache=$false; NoTrash=$false + NoLogo=$false; NoInfo=$false; KeepCache=$false; KeepTrash=$false Errors=$false; History=$false; Doctor=$false SelfUpdate=$false; AutoUpdate=$false; RebuildCache=$false Snapshot=$false; Reboot=$false - Profile=''; Changelog=''; Report='' - ListProfiles=$false; NoEmoji=$false; Interactive=$false + Changelog='' + ListProfiles=$false; Ascii=$false Parallel=$false; Changed=$false; Resume=$false - Json=$false; RebootExit=$false; DownloadOnly=$false + Json=$false; Weather=$false; RebootExit=$false; DownloadOnly=$false; AcceptLicenses=$false + DeepClean=$false; NoFirmware=$false; RefreshMirrors=$false; Rollback=$false Only=''; Except=''; Metrics='' } - if (-not $Argv) { return $o } - # Expand short-flag bundles: "-nv" -> "-n -v". - $allowed = 'hVnvqyiw'.ToCharArray() - $keep = @('-up','-au','-err','-rc','-nl','-ni','-nc','-nt','-qq','-qqq','-xyzzy', - '-h','-V','-n','-v','-q','-y','-i','-w') - $expanded = New-Object System.Collections.Generic.List[string] - foreach ($a in $Argv) { - $s = [string]$a - if ($keep -contains $s -or $s.StartsWith('--')) { [void]$expanded.Add($s); continue } - if ($s -match '^-[A-Za-z]{2,}$') { - $letters = $s.Substring(1).ToCharArray() - $all = $true - foreach ($c in $letters) { if ($allowed -notcontains $c) { $all = $false; break } } - if ($all) { - foreach ($c in $letters) { [void]$expanded.Add("-$c") } +} + +# Expand short-flag bundles: "-nv" -> "-n -v". A word with a letter outside +# the bundle set, a multi-letter short flag and a long flag stay whole. +function _Args-Expand-Bundles { + param([string[]]$Argv) + $allowed = 'hVnvqyw'.ToCharArray() + $keep = @('-up','-au','-err','-rc','-nl','-ni','-nc','-nt','-qq','-qqq', + '-h','-V','-n','-v','-q','-y','-w') + $words = New-Object System.Collections.Generic.List[string] + foreach ($item in $Argv) { + $word = [string]$item + if ($keep -contains $word -or $word.StartsWith('--')) { [void]$words.Add($word); continue } + if ($word -match '^-[A-Za-z]{2,}$') { + $letters = $word.Substring(1).ToCharArray() + $isBundle = $true + foreach ($letter in $letters) { if ($allowed -notcontains $letter) { $isBundle = $false; break } } + if ($isBundle) { + foreach ($letter in $letters) { [void]$words.Add("-$letter") } continue } } - [void]$expanded.Add($s) + [void]$words.Add($word) } - $Argv = $expanded.ToArray() - $i = 0 - while ($i -lt $Argv.Count) { - $a = [string]$Argv[$i] - switch -Regex -CaseSensitive ($a) { - '^(-h|--help|-help)$' { $o.Help = $true } - '^(-V|--version)$' { $o.Version = $true } - '^(-n|--dry-run)$' { $o.DryRun = $true } - '^(-v|--verbose)$' { $o.Verbose = $true; $script:UI_VERBOSE = $true } - '^(-q|--quiet)$' { $script:QUIET_LEVEL++ } - '^-qq$' { $script:QUIET_LEVEL = 2 } - '^-qqq$' { $script:QUIET_LEVEL = 3 } - '^(-y|--yes)$' { $o.Yes = $true } - '^--dev$' { $o.Dev = $true } - '^--security$' { $o.Security = $true } - '^--firmware$' { $o.Firmware = $true } - '^(-nl|--no-logo)$' { $o.NoLogo = $true } - '^(-ni|--no-info)$' { $o.NoInfo = $true } - '^(-nc|--no-cache)$' { $o.NoCache = $true } - '^(-nt|--no-trash)$' { $o.NoTrash = $true } - '^(-err|--errors)$' { $o.Errors = $true } - '^--history$' { $o.History = $true } - '^--doctor$' { $o.Doctor = $true } - '^(-up|--self-update)$' { $o.SelfUpdate = $true } - '^(-au|--auto-update)$' { $o.AutoUpdate = $true } - '^(-rc|--rebuild-cache)$' { $o.RebuildCache = $true } - '^--snapshot$' { $o.Snapshot = $true } - '^--reboot$' { $o.Reboot = $true } - '^--list-profiles$' { $o.ListProfiles = $true } - '^--no-emoji$' { $o.NoEmoji = $true; $script:UI_UNICODE = $false } - '^(-i|--interactive)$' { $o.Interactive = $true } - '^--parallel$' { $o.Parallel = $true } - '^--changed$' { $o.Changed = $true } - '^--resume$' { $o.Resume = $true } - '^--json$' { $o.Json = $true } - '^--reboot-exit$' { $o.RebootExit = $true } - '^(--download-only|--offline)$' { $o.DownloadOnly = $true } - '^--only$' { $i++; $o.Only = [string]$Argv[$i] } - '^--only=' { $o.Only = $a -replace '^--only=','' } - '^--except$' { $i++; $o.Except = [string]$Argv[$i] } - '^--except=' { $o.Except = $a -replace '^--except=','' } - '^--metrics$' { $i++; $o.Metrics = [string]$Argv[$i] } - '^--metrics=' { $o.Metrics = $a -replace '^--metrics=','' } - '^--profile$' { $i++; $o.Profile = [string]$Argv[$i] } - '^--profile=' { $o.Profile = $a -replace '^--profile=','' } - '^--changelog$' { $i++; $o.Changelog = [string]$Argv[$i] } - '^--changelog=' { $o.Changelog = $a -replace '^--changelog=','' } - '^--report$' { $i++; $o.Report = [string]$Argv[$i] } - '^--report=' { $o.Report = $a -replace '^--report=','' } - default { - [Console]::Error.WriteLine("Unknown argument: $a (try 'up --help')") - exit 2 - } - } - $i++ - } - return $o + return ,$words.ToArray() +} + +# Return $Value, or exit 2 with "Missing value for $Flag" when it is empty +# (the flag was the last word, or its value is ""). +function _Args-Need-Value { + param([string]$Flag, [string]$Value) + if ($Value -ne '') { return $Value } + [Console]::Error.WriteLine("Missing value for $Flag") + exit 2 } +# Return the profile named on the command line, the last --profile winning +# as in Args-Parse, so the profile can set defaults before the CLI flags. function Args-Prescan-Profile { param([string[]]$Argv) if (-not $Argv) { return '' } + $name = '' for ($i = 0; $i -lt $Argv.Count; $i++) { - $a = [string]$Argv[$i] - if ($a -eq '--profile' -and ($i + 1) -lt $Argv.Count) { return [string]$Argv[$i+1] } - if ($a -match '^--profile=') { return ($a -replace '^--profile=','') } + $word = [string]$Argv[$i] + if ($word -eq '--') { break } + if ($word -eq '--profile' -and ($i + 1) -lt $Argv.Count) { $name = [string]$Argv[$i+1]; $i++ } + elseif ($word -match '^--profile=') { $name = ($word -replace '^--profile=','') } + } + return $name +} + +# Warn about each Unix-only flag set in $script:ArgsGlobal that changes how a +# run goes: Windows ignores it. The Unix-only queries and actions (--changed, +# --changelog, --rollback) exit in the entry point instead. +function Args-Warn-Unsupported { + $unsupported = [ordered]@{ + Firmware = '--firmware'; NoFirmware = '--no-firmware'; Snapshot = '--snapshot' + Parallel = '--parallel'; Resume = '--resume'; DownloadOnly = '--download-only' + DeepClean = '--deep-clean'; RefreshMirrors = '--refresh-mirrors' + } + foreach ($field in $unsupported.Keys) { + if ($script:ArgsGlobal.$field) { UI-Warn "$($unsupported[$field]) is not supported on Windows, ignored." } } - return '' } diff --git a/src/pslib/Update.ps1 b/src/pslib/AutoUpdate.ps1 similarity index 50% rename from src/pslib/Update.ps1 rename to src/pslib/AutoUpdate.ps1 index c31badc..54748d2 100644 --- a/src/pslib/Update.ps1 +++ b/src/pslib/AutoUpdate.ps1 @@ -1,39 +1,17 @@ -# Self-update (git) and auto-update (Task Scheduler). +# Weekly auto-update through Task Scheduler (--auto-update). -function Self-Update { - param([string]$Root) - UI-Title 'Self-update' - if (-not (Test-Path (Join-Path $Root '.git'))) { - UI-Err 'Not a git checkout. Re-clone from https://github.com/MasterCruelty/eMerger' - return 1 - } - if (-not (Sys-Has git)) { UI-Err 'git not installed'; return 1 } - if ($script:ArgsGlobal.DryRun) { UI-Sub "[dry-run] git -C `"$Root`" pull --ff-only"; return 0 } - $before = (& git -C $Root rev-parse HEAD 2>$null).Trim() - & git -C $Root fetch --quiet 2>$null - & git -C $Root pull --ff-only --quiet 2>$null - if ($LASTEXITCODE -ne 0) { - UI-Err 'git pull failed (non fast-forward?)' - return 1 - } - $after = (& git -C $Root rev-parse HEAD 2>$null).Trim() - if ($before -eq $after) { - UI-Ok 'Already up to date.' - } else { - UI-Ok ("Updated {0}..{1}" -f $before.Substring(0, [math]::Min(7,$before.Length)), $after.Substring(0, [math]::Min(7,$after.Length))) - & git -C $Root log --oneline "$before..$after" | ForEach-Object { Write-Host " $(UI-Color gray (UI-Glyph dot)) $_" } - } - return 0 -} - -function Setup-Task { +# Register the weekly 'eMerger' scheduled task for the running PowerShell +# host (--auto-update). Return 0, or 1 when registration fails. +function AutoUpdate-Register { param([string]$Root) UI-Title 'Auto-update (Task Scheduler)' if ($script:ArgsGlobal.DryRun) { UI-Sub '[dry-run] would register scheduled task'; return 0 } $entry = Join-Path $Root 'src\emerger.ps1' try { + # Host running now (pwsh 7 or Windows PowerShell 5.1), not + # whichever 'powershell' is on PATH. $action = New-ScheduledTaskAction ` - -Execute 'powershell' ` + -Execute (Run-PowerShell-Path) ` -Argument "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$entry`" -y -q -nl -ni" $trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At '10:00' $settings = New-ScheduledTaskSettingsSet ` @@ -44,7 +22,7 @@ function Setup-Task { $principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive Register-ScheduledTask -TaskName 'eMerger' -Action $action -Trigger $trigger -Settings $settings -Principal $principal ` -Description 'Weekly eMerger update' -Force | Out-Null - UI-Ok "Scheduled task 'eMerger' created (weekly, Sunday 10:00, ยฑ1h delay)" + UI-Ok "Scheduled task 'eMerger' created (weekly, Sunday 10:00, +/-1h delay)" UI-Muted "Manage with: Get-ScheduledTask eMerger | Select-Object State,LastRunTime" return 0 } catch { diff --git a/src/pslib/Clean.ps1 b/src/pslib/Clean.ps1 deleted file mode 100644 index 594caa5..0000000 --- a/src/pslib/Clean.ps1 +++ /dev/null @@ -1,54 +0,0 @@ -# Clean %TEMP% folders and the Recycle Bin. - -function _Clean-Confirm { - param([string]$Prompt) - if ($script:ArgsGlobal.Yes) { return $true } - $a = Read-Host " $Prompt [y/N]" - return $a -match '^[Yy]' -} - -function _Folder-Size-MB { - param([string]$Path) - if (-not (Test-Path $Path)) { return 0 } - try { - $sum = (Get-ChildItem $Path -Recurse -Force -ErrorAction SilentlyContinue | - Measure-Object Length -Sum).Sum - if (-not $sum) { return 0 } - return [math]::Round($sum / 1MB, 1) - } catch { return 0 } -} - -function Clean-Temp { - UI-Title 'Temp folders' - $paths = @($env:TEMP, (Join-Path $env:LOCALAPPDATA 'Temp'), (Join-Path $env:SystemRoot 'Temp')) | - Where-Object { $_ } | Select-Object -Unique - $before = 0 - foreach ($p in $paths) { $before += (_Folder-Size-MB $p) } - UI-Muted ("Paths: {0} Size: {1} MB" -f ($paths -join ', '), $before) - - if ($script:ArgsGlobal.DryRun) { UI-Sub '[dry-run] would clean temp folders'; return } - if (-not (_Clean-Confirm 'Clean temp folders?')) { UI-Muted 'skipped'; return } - - foreach ($p in $paths) { - if (-not (Test-Path $p)) { continue } - Get-ChildItem $p -Force -ErrorAction SilentlyContinue | ForEach-Object { - try { Remove-Item $_.FullName -Recurse -Force -ErrorAction Stop } catch {} - } - } - $after = 0 - foreach ($p in $paths) { $after += (_Folder-Size-MB $p) } - $script:SUMMARY_FREED_MB += [math]::Max(0, $before - $after) - UI-Ok ("temp cleaned ({0} MB)" -f [math]::Max(0, $before - $after)) -} - -function Clean-RecycleBin { - UI-Title 'Recycle bin' - if ($script:ArgsGlobal.DryRun) { UI-Sub '[dry-run] would empty recycle bin'; return } - if (-not (_Clean-Confirm 'Empty recycle bin?')) { UI-Muted 'skipped'; return } - try { - Clear-RecycleBin -Force -ErrorAction Stop - UI-Ok 'recycle bin emptied' - } catch { - UI-Warn "could not empty recycle bin: $($_.Exception.Message)" - } -} diff --git a/src/pslib/Doctor.ps1 b/src/pslib/Doctor.ps1 index 34f204f..83e4dcf 100644 --- a/src/pslib/Doctor.ps1 +++ b/src/pslib/Doctor.ps1 @@ -1,5 +1,7 @@ # Environment health check. +# Check the environment (PowerShell, admin, disk, network, execution +# policy, managers, pending reboot) for --doctor. Return 0, or 1 on any issue. function Doctor-Run { UI-Title 'eMerger doctor (Windows)' $issues = 0 @@ -9,33 +11,38 @@ function Doctor-Run { if (Sys-IsAdmin) { UI-Ok 'running as administrator' } else { UI-Info 'not admin (elevation prompted when needed)' } - $free = Sys-Disk-Free-GB 'C' - if ($free -lt 2) { UI-Warn "low disk space on C: ($free GB)"; $issues++ } - else { UI-Ok "disk: $free GB free on C:" } + # Same threshold as the run's disk precheck. + $threshold = 1024 + if ("$($script:DISK_MIN_FREE_MB)" -match '^\d{1,9}$') { $threshold = [int]$script:DISK_MIN_FREE_MB } + $drive = "$env:SystemDrive".TrimEnd(':'); if (-not $drive) { $drive = 'C' } + $freeMb = Preflight-Disk-Free-MB + if ($freeMb -lt 0) { UI-Info "disk: free space on ${drive}: unknown" } + elseif ($freeMb -lt $threshold) { UI-Warn "low disk space on ${drive}: (${freeMb}MB free, threshold ${threshold}MB)"; $issues++ } + else { UI-Ok "disk: ${freeMb}MB free on ${drive}:" } + # HTTPS: github.com drops ICMP, so a ping proves nothing. try { - if (Test-Connection -ComputerName 'github.com' -Count 1 -Quiet -ErrorAction Stop) { - UI-Ok 'network: github reachable' - } else { UI-Warn 'network: github unreachable'; $issues++ } - } catch { UI-Warn 'network: check failed'; $issues++ } + Invoke-WebRequest -Uri 'https://github.com' -Method Head -TimeoutSec 4 -UseBasicParsing | Out-Null + UI-Ok 'network: reachable' + } catch { UI-Warn 'network: github.com unreachable'; $issues++ } - $ep = Get-ExecutionPolicy -Scope CurrentUser - if ($ep -eq 'Restricted') { UI-Warn "ExecutionPolicy=$ep (run setup.ps1 to fix)"; $issues++ } - else { UI-Ok "ExecutionPolicy: $ep" } + $policy = Get-ExecutionPolicy -Scope CurrentUser + if ($policy -eq 'Restricted') { UI-Warn "ExecutionPolicy=$policy (run install.ps1 to fix)"; $issues++ } + else { UI-Ok "ExecutionPolicy: $policy" } - foreach ($m in $script:PKG_MANAGERS) { - if (Pkg-Detect $m) { UI-Ok "$m: detected" } + foreach ($manager in $script:PKG_MANAGERS) { + if (Pkg-Detect $manager) { UI-Ok "${manager}: detected" } } if (Reboot-Pending) { UI-Warn 'reboot pending from a previous operation' } if ($script:ArgsGlobal.Dev) { - foreach ($m in $script:PKG_DEV) { - if (Pkg-Detect $m) { UI-Ok "$m (dev): detected" } + foreach ($manager in $script:PKG_DEV) { + if (Pkg-Detect $manager) { UI-Ok "$manager (dev): detected" } } } - UI-Hr + UI-Rule if ($issues -eq 0) { UI-Ok 'all clear' return 0 diff --git a/src/pslib/Elevated.ps1 b/src/pslib/Elevated.ps1 new file mode 100644 index 0000000..2b67fb3 --- /dev/null +++ b/src/pslib/Elevated.ps1 @@ -0,0 +1,320 @@ +# Elevation for the admin managers only. The caller stays unelevated and +# keeps config.ps1, the profile and the hooks. One elevated child runs the +# admin managers and loads none of those: settings reach it as validated +# arguments, never as code. Results come back through a file the child +# creates, the caller replays them on its own console. + +# Flags of the caller the child may receive, all plain switches. +$script:ELEVATED_FLAGS = @('-v', '-y', '--security', '--ascii', '--accept-licenses') + +# Return the folders that only administrators can write: Windows, System32, +# Program Files (both). Windows takes them from the API, never from variables +# a user can override; elsewhere (tests) from the variables. +function _Elevated-Admin-Roots { + if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { + $roots = @([Environment]::GetFolderPath('Windows'), [Environment]::GetFolderPath('System'), + [Environment]::GetFolderPath('ProgramFiles'), [Environment]::GetFolderPath('ProgramFilesX86')) + } else { + $roots = @("$env:SystemRoot", [IO.Path]::Combine("$env:SystemRoot", 'System32'), "$env:ProgramFiles") + } + return @($roots | Where-Object { $_ -and [IO.Path]::IsPathRooted($_) }) +} + +# Return the machine-scope value of environment variable $Name, or $null. +# Only Windows has a machine scope; elsewhere nothing is trusted. +function _Elevated-Machine-Env { + param([string]$Name) + if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { return $null } + return [Environment]::GetEnvironmentVariable($Name, 'Machine') +} + +# Variables that make the .NET runtime, the CLR profiler API or PowerShell +# load or trust attacker code, cleared in the elevated child by name or prefix. +$script:ELEVATED_CLEAR_NAMES = @('PSExecutionPolicyPreference', 'PSModuleAnalysisCachePath', '__PSLockdownPolicy', 'ChocolateyToolsLocation') +$script:ELEVATED_CLEAR_PREFIXES = @('DOTNET_', 'COR_', 'CORECLR_', 'COMPlus_') + +# Narrow the environment of the elevated child so nothing a user can set +# changes what runs as administrator: PATH and PSModulePath cut to system +# locations, ComSpec and PATHEXT reset, ChocolateyInstall taken from the +# machine scope, and the runtime hook variables (DOTNET_STARTUP_HOOKS, COR_*, +# CORECLR_*, COMPlus_*, PSExecutionPolicyPreference) removed for the managers +# it starts. They have already acted on this PowerShell process itself. +function Elevated-Restrict-Env { + $sep = [IO.Path]::PathSeparator + if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { + $windows = [Environment]::GetFolderPath('Windows'); $system = [Environment]::GetFolderPath('System') + $data = [Environment]::GetFolderPath('CommonApplicationData'); $programs = [Environment]::GetFolderPath('ProgramFiles') + } else { + $windows = "$env:SystemRoot"; $system = [IO.Path]::Combine($windows, 'System32') + $data = "$env:ProgramData"; $programs = "$env:ProgramFiles" + } + $shell = [IO.Path]::Combine($system, 'WindowsPowerShell', 'v1.0') + $paths = @($system, $windows, [IO.Path]::Combine($system, 'Wbem'), $shell, [IO.Path]::Combine($data, 'chocolatey', 'bin')) + $modules = @((Join-Path $PSHOME 'Modules'), [IO.Path]::Combine($programs, 'WindowsPowerShell', 'Modules'), [IO.Path]::Combine($shell, 'Modules')) + $env:PATH = ($paths | Where-Object { [IO.Path]::IsPathRooted($_) }) -join $sep + $env:PSModulePath = ($modules | Where-Object { [IO.Path]::IsPathRooted($_) }) -join $sep + foreach ($entry in @(Get-ChildItem env:)) { + $name = $entry.Name + $isPrefixed = @($script:ELEVATED_CLEAR_PREFIXES | Where-Object { $name.StartsWith($_, [StringComparison]::OrdinalIgnoreCase) }).Count -gt 0 + if ($isPrefixed -or ($script:ELEVATED_CLEAR_NAMES -contains $name)) { Remove-Item -LiteralPath "env:$name" -ErrorAction SilentlyContinue } + } + $env:ComSpec = [IO.Path]::Combine($system, 'cmd.exe') + $env:PATHEXT = '.COM;.EXE;.BAT;.CMD' + $choco = _Elevated-Machine-Env 'ChocolateyInstall' + if ($choco -and [IO.Path]::IsPathRooted($choco)) { $env:ChocolateyInstall = $choco } else { Remove-Item -LiteralPath 'env:ChocolateyInstall' -ErrorAction SilentlyContinue } +} + +# Return $true when a standard user can write to, or has taken ownership of, +# $Path or an ancestor up to the ProgramData chocolatey folder: an ACL entry +# for Users, Authenticated Users or Everyone with a write right, or an owner +# other than Administrators, SYSTEM and TrustedInstaller. An unreadable ACL +# counts as writable. Always $false off Windows, where there is no ACL. +function _Elevated-Users-Can-Write { + param([string]$Path) + if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { return $false } + $writeMask = 0x000D0046 + $everyone = @('S-1-1-0', 'S-1-5-11', 'S-1-5-32-545') + $owners = @('S-1-5-32-544', 'S-1-5-18', 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464') + try { + $stop = [IO.Path]::Combine([Environment]::GetFolderPath('CommonApplicationData'), 'chocolatey').TrimEnd('\') + $dir = $Path + while ($dir) { + $acl = Get-Acl -LiteralPath $dir -ErrorAction Stop + $ownerSid = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value + if ($owners -notcontains $ownerSid) { return $true } + foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) { + if ($rule.AccessControlType -eq 'Allow' -and ($everyone -contains $rule.IdentityReference.Value) -and (([int]$rule.FileSystemRights -band $writeMask) -ne 0)) { return $true } + } + if ($dir.TrimEnd('\') -ieq $stop) { break } + $dir = Split-Path -Parent $dir + } + return $false + } catch { return $true } +} + +# Return a refusal message when the executable of admin manager $Manager, +# found on the child's PATH, is outside the locations only administrators can +# write (Windows, System32, Program Files, or ProgramData\chocolatey while +# its ACL denies standard users), else an empty string. A manager with no +# executable on PATH is not refused here: it is simply not found. +function Elevated-Exe-Refusal { + param([string]$Manager) + $exe = switch ($Manager) { 'choco' { 'choco' } 'wsl' { 'wsl' } default { '' } } + if (-not $exe) { return '' } + $app = Get-Command $exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 + if (-not $app) { return '' } + $path = $app.Source + if (-not $path) { $path = $app.Path } + $full = [IO.Path]::GetFullPath($path) + $sep = [string][IO.Path]::DirectorySeparatorChar + $inside = { param($Root) $Root -and $full.StartsWith($Root.TrimEnd('\', '/') + $sep, [StringComparison]::OrdinalIgnoreCase) } + foreach ($root in (_Elevated-Admin-Roots)) { + if (& $inside $root) { return '' } + } + $choco = [IO.Path]::Combine($(if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { [Environment]::GetFolderPath('CommonApplicationData') } else { "$env:ProgramData" }), 'chocolatey') + if ($Manager -eq 'choco' -and (& $inside $choco) -and -not (_Elevated-Users-Can-Write (Split-Path -Parent $full))) { return '' } + return "$exe is outside the administrator-only locations ($full), not run elevated" +} + +# Build the child's arguments after the script path: the result file, the +# managers, the numeric settings, then the switches that change how the +# admin managers run. +function Elevated-Args { + param([string]$ResultFile, [string[]]$Managers) + $out = @('--elevated-child', $ResultFile, ($Managers -join ','), + [string][int]$script:RETRY_ATTEMPTS, [string][int]$script:RETRY_DELAY, + [string][int]$script:MANAGER_TIMEOUT, [string][int]$script:QUIET_LEVEL) + if ($script:UI_VERBOSE) { $out += '-v' } + if ($script:ArgsGlobal.Yes) { $out += '-y' } + if ($script:ArgsGlobal.Security) { $out += '--security' } + if ($script:ArgsGlobal.Ascii) { $out += '--ascii' } + if ($script:ArgsGlobal.AcceptLicenses) { $out += '--accept-licenses' } + return ,$out +} + +# Return the failed result of manager $Name the child did not report on, +# with $Why as its only output line. +function _Elevated-Missing-Result { + param([string]$Name, [string]$Why) + return [pscustomobject]@{ + name = $Name; result = 'fail'; secs = 0; changed = 0 + steps = @([pscustomobject]@{ label = $Name; ok = $false; rc = '1'; stat = ''; tail = @($Why) }) + } +} + +# Run $ScriptPath under the current PowerShell host with a UAC prompt, wait, +# and return its exit code. Throws when the prompt is declined. +function Elevated-Start { + param([string]$ScriptPath, [string[]]$Arguments) + $words = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $ScriptPath) + @($Arguments) + $commandLine = ($words | ForEach-Object { Run-Quote $_ }) -join ' ' + $process = Start-Process -FilePath (Run-PowerShell-Path) -ArgumentList $commandLine -Verb RunAs -Wait -PassThru + return [int]$process.ExitCode +} + +# Run $Managers in one elevated child (one UAC prompt) and wait. Return a +# hashtable name -> result (result, secs, changed, steps). A declined +# prompt, a crash or a missing result file fails every manager it covers. +function Elevated-Run { + param([string[]]$Managers) + $file = Join-Path ([IO.Path]::GetTempPath()) ("emerger-" + [guid]::NewGuid().ToString('N') + '.json') + $results = @{} + $why = '' + $rc = $null + try { + $rc = Elevated-Start (Join-Path $script:EMERGER_SRC 'emerger.ps1') (Elevated-Args $file $Managers) + } catch { + $why = "elevation failed: $($_.Exception.Message)" + } + # Child writes with CreateNew and exits 0 or 3 only after that write + # succeeded: any other code means the file, if any, is not its own. + if (-not $why -and @(0, 3) -notcontains $rc) { + $why = "elevated child exited with rc=$rc and wrote no result" + } + if (-not $why) { + try { + $payload = Get-Content -LiteralPath $file -Raw -ErrorAction Stop | ConvertFrom-Json + foreach ($entry in @($payload.managers)) { + if ($Managers -contains $entry.name) { $results[[string]$entry.name] = $entry } + } + foreach ($line in @($payload.log)) { if ($line -is [string]) { Log-Append-Raw $line } } + } catch { + $why = "elevated child exited with rc=$rc and wrote no result" + } + } + Remove-Item -LiteralPath $file -Force -ErrorAction SilentlyContinue + if ($why) { + UI-Warn $why + Log-Error $why + } + foreach ($manager in $Managers) { + if (-not $results.ContainsKey($manager)) { + if (-not $why) { $why = "elevated child exited with rc=$rc without a result for $manager" } + $results[$manager] = _Elevated-Missing-Result $manager $why + } + } + return $results +} + +# Print elevated result $Result of manager $Name the way an in-process run +# prints it. +function Elevated-Show { + param([string]$Name, $Result) + UI-Section (Pkg-Icon $Name) $Name (Estimate-Read $Name) + foreach ($step in @($Result.steps)) { + if ($step.ok) { UI-Done ([string]$step.label) ([string]$step.stat); continue } + UI-Fail ([string]$step.label) ([string]$step.rc) + $tail = @($step.tail | ForEach-Object { [string]$_ }) + if ($tail.Count -gt 0) { UI-Fail-Tail $tail } + } + # Child prints its own hint on its console, it is not replayed. + if ($Name -eq 'PSWindowsUpdate' -and -not $script:ArgsGlobal.AcceptLicenses) { + UI-Muted 'updates not installed: they may need licence agreement, run with --accept-licenses' + } + $script:PKG_CHANGED += [int]$Result.changed +} + +# Write $Text to a file that must not exist yet (CreateNew), so the elevated +# child never writes through a link planted at that path. +function _Elevated-Write-New { + param([string]$Path, [string]$Text) + $stream = [IO.File]::Open($Path, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) + try { + $bytes = (New-Object System.Text.UTF8Encoding $false).GetBytes($Text) + $stream.Write($bytes, 0, $bytes.Length) + } finally { $stream.Dispose() } +} + +# Return $true when $Path is a result file Elevated-Run would name: a rooted +# path on a local disk (no UNC or device path) whose leaf is emerger-<32 hex>.json. +function _Elevated-Is-Result-Path { + param([string]$Path) + if (-not [IO.Path]::IsPathRooted($Path)) { return $false } + if ($Path -match '^[\\/]{2}') { return $false } + return ((Split-Path -Leaf $Path) -cmatch '^emerger-[0-9a-f]{32}\.json$') +} + +# Child side: validate $Argv (as built by Elevated-Args), hold the elevated +# lock, run the managers, write the result file. Return 0 when all +# succeeded, 3 on a failure, 2 on invalid arguments, 1 when another elevated +# child holds the lock or the result cannot be written. +function Elevated-Child { + param([string[]]$Argv) + $script:QUIET_LEVEL = 0 + $script:ArgsGlobal = Args-Parse @() + if ($Argv.Count -lt 7) { [Console]::Error.WriteLine('elevated child: missing arguments'); return 2 } + $file = [string]$Argv[1] + $managers = @(([string]$Argv[2]) -split ',' | Where-Object { $_ }) + $numbers = @($Argv[3..6] | ForEach-Object { [string]$_ }) + $flags = @(if ($Argv.Count -gt 7) { $Argv[7..($Argv.Count - 1)] }) + $invalid = @($managers | Where-Object { -not (Pkg-Need-Admin $_) }) + + @($numbers | Where-Object { $_ -notmatch '^\d{1,9}$' }) + + @($flags | Where-Object { $script:ELEVATED_FLAGS -notcontains $_ }) + if (-not (_Elevated-Is-Result-Path $file) -or $managers.Count -eq 0 -or $invalid.Count -gt 0) { + [Console]::Error.WriteLine("elevated child: invalid arguments: $($invalid -join ' ')") + return 2 + } + $script:RETRY_ATTEMPTS = [int]$numbers[0]; $script:RETRY_DELAY = [int]$numbers[1] + $script:MANAGER_TIMEOUT = [int]$numbers[2] + $script:ArgsGlobal = Args-Parse $flags -Into $script:ArgsGlobal + $script:QUIET_LEVEL = [int]$numbers[3] + UI-Init + # No log file: the caller writes these lines to its own log. + $script:LOG_BUFFER = New-Object System.Collections.Generic.List[string] + # Caller's run lock dies with an interrupted caller, this one lives + # as long as the managers run. Without a lock the child does not run: + # the state directory of the account it runs under is created for it. + $lock = $null + try { + [void][IO.Directory]::CreateDirectory($script:EMERGER_STATE) + $lock = Lock-Open (Lock-Elevated-Path) + } catch { + [Console]::Error.WriteLine("elevated child: cannot take the elevated lock: $($_.Exception.Message)") + return 1 + } + if ($null -eq $lock) { + [Console]::Error.WriteLine('elevated child: another elevated run is in progress') + return 1 + } + try { + return (_Elevated-Child-Run $file $managers) + } finally { + Lock-Release $lock + } +} + +# Run $Managers in the child and write their results to $File. Return 0, 3 +# when a manager failed, or 1 when the result cannot be written. +function _Elevated-Child-Run { + param([string]$File, [string[]]$Managers) + $out = @() + $failCount = 0 + foreach ($manager in $Managers) { + $script:RUN_STEPS = New-Object System.Collections.Generic.List[object] + $before = $script:PKG_CHANGED + $started = [DateTime]::UtcNow + $refusal = Elevated-Exe-Refusal $manager + if ($refusal) { + Log-Error $refusal + $script:RUN_STEPS.Add([pscustomobject]@{ label = $manager; ok = $false; rc = '1'; stat = ''; tail = @($refusal) }) + $isOk = $false + } else { + $isOk = Pkg-Run $manager + } + if (-not $isOk) { $failCount++ } + $out += [pscustomobject]@{ + name = $manager; result = $(if ($isOk) { 'ok' } else { 'fail' }) + secs = Sys-Elapsed-Seconds $started + changed = [int]($script:PKG_CHANGED - $before) + steps = $script:RUN_STEPS.ToArray() + } + } + $script:RUN_STEPS = $null + $json = [pscustomobject]@{ managers = $out; log = $script:LOG_BUFFER.ToArray() } | ConvertTo-Json -Depth 6 -Compress + try { _Elevated-Write-New $file $json } catch { + [Console]::Error.WriteLine("elevated child: cannot write ${file}: $($_.Exception.Message)") + return 1 + } + if ($failCount -gt 0) { return 3 } + return 0 +} diff --git a/src/pslib/Help.txt b/src/pslib/Help.txt index c2fe0cd..3141440 100644 --- a/src/pslib/Help.txt +++ b/src/pslib/Help.txt @@ -1,7 +1,10 @@ eMerger (Windows) - one-command system updater +Lists every flag of up on Windows, the variables config.ps1 and the +environment set, the config and state files and the exit codes. The options +object config.ps1 can also set: doc/documentation.pdf. USAGE - up [options] + up [options] [--] GENERAL -h, --help Show this help @@ -11,45 +14,62 @@ GENERAL EXECUTION -n, --dry-run Show what would be done, do nothing -v, --verbose Stream pkg-manager output live - -q / -qq / -qqq Quieter (titles / summary only / exit code only) + -q, --quiet Quieter by one level per use: no info lines + -qq, -qqq Summary line only, exit code only -y, --yes Assume "yes" on prompts --json Machine-readable run summary on stdout - Short single-letter flags bundle: -nv == -n -v + --reboot Reboot if the system requires it + --reboot-exit Exit 4 instead of 0 when a reboot is required + -- End of options: the words after it are ignored + Short flags from the set h V n v q y w bundle: -nv == -n -v + A value flag also takes --flag=VALUE: --only=winget,scoop SELECTION - --security Prefer security-only where supported + --security Security updates only: Windows Update; every other + manager has no security channel and is skipped + --accept-licenses Let winget, choco and Windows Update accept licence + agreements; without it they only list updates --dev Include dev toolchains (rustup, cargo, npm, pnpm, pip, gem) - --profile NAME Load a profile (share\profiles\.ps1) + --only LIST Comma-separated managers to keep (e.g. winget,scoop) + --except LIST Comma-separated managers to skip (adds to the profile's list) + --profile NAME Load profiles.d\NAME.ps1, else the shipped share\profiles\NAME.ps1 --list-profiles List available profiles - --no-emoji ASCII glyphs only DISPLAY -nl, --no-logo Hide logo -ni, --no-info Hide system info line - -nc, --no-cache Skip %TEMP% cleaning - -nt, --no-trash Skip recycle bin + --ascii ASCII glyphs only + -w, --weather Show weather line via wttr.in + (env) EMERGER_EMOJI=auto|1|0, EMERGER_SPINNER=braille|dots|pulse|line, + EMERGER_PROMPT_TIMEOUT=60 (seconds), NO_COLOR, COLORFGBG + +CLEANING + -nc, --keep-cache Skip %TEMP% cleaning + -nt, --keep-trash Skip recycle bin INSPECTION --history Last runs -err, --errors Tail of logged errors - --reboot Reboot if the system requires it - --reboot-exit Exit 4 instead of 0 when a reboot is required - --download-only Download packages, do not install (where supported) - --offline Alias for --download-only - --only LIST Comma-separated managers to keep - --except LIST Comma-separated managers to skip --metrics FILE Export last run as Prometheus textfile MAINTENANCE -up, --self-update Update eMerger via git (fast-forward) -au, --auto-update Register weekly Task Scheduler entry - -rc, --rebuild-cache Clear detection cache (no-op stub) + -rc, --rebuild-cache Accepted; Windows keeps no detection cache + +NOT AVAILABLE ON WINDOWS + --changed --changelog --rollback + Print a warning and exit 0, nothing is updated + --firmware --no-firmware --snapshot --parallel --resume --download-only + --deep-clean --refresh-mirrors + Print a warning, the run goes on without them EXAMPLES - up # normal run (elevates if needed) + up # normal run (UAC prompt for choco/wsl/Windows Update) up -n # preview - up --security -y # unattended security + up --security -y --accept-licenses # unattended, security-only Windows Update up --dev # include rustup/npm/pip/gem + up --only winget,scoop # limit to specific managers up --profile work # named profile CONFIG @@ -57,14 +77,21 @@ CONFIG %APPDATA%\emerger\profiles.d\*.ps1 User profiles %APPDATA%\emerger\hooks\pre.d\*.ps1 Pre-update hooks %APPDATA%\emerger\hooks\post.d\*.ps1 Post-update hooks + Thresholds in config.ps1: $script:DISK_MIN_FREE_MB (1024), + $script:BATTERY_MIN_PCT (20), $script:RETRY_ATTEMPTS (2), + $script:RETRY_DELAY (3), + $script:MANAGER_TIMEOUT (0; seconds per manager step, 0 = no limit), + $script:UI_VERBOSE ($false, as -v), $script:QUIET_LEVEL (0, as -q) STATE %LOCALAPPDATA%\emerger\state\emerger.log Log %LOCALAPPDATA%\emerger\state\history.jsonl Run history + %LOCALAPPDATA%\emerger\state\run.lock Run lock, one run at a time + %LOCALAPPDATA%\emerger\state\elevated.lock Lock the elevated child holds EXIT CODES 0 success - 1 runtime failure + 1 runtime failure or aborted (a declined safety prompt) 2 argument parsing error 3 one or more package managers failed 4 reboot required (only with --reboot-exit) diff --git a/src/pslib/Hooks.ps1 b/src/pslib/Hooks.ps1 index 1faf9dc..943a28a 100644 --- a/src/pslib/Hooks.ps1 +++ b/src/pslib/Hooks.ps1 @@ -1,18 +1,31 @@ # User hook runner: *.ps1 scripts under hooks/{pre,post}.d/ +# Run each *.ps1 hook of $Phase (pre or post) in name order. A failing hook is a +# warning and the next one runs. Under --dry-run hooks are listed only. function Hooks-Run { param([string]$Phase) $dir = Join-Path $script:EMERGER_CONFIG "hooks\$Phase.d" - if (-not (Test-Path $dir)) { return } - $scripts = @(Get-ChildItem $dir -Filter '*.ps1' -ErrorAction SilentlyContinue) + if (-not (Test-Path -LiteralPath $dir)) { return } + $scripts = @(Get-ChildItem -LiteralPath $dir -Filter '*.ps1' -ErrorAction SilentlyContinue | Sort-Object Name) if ($scripts.Count -eq 0) { return } UI-Title "Hooks ($Phase)" - foreach ($s in $scripts) { - UI-Sub $s.Name + foreach ($hook in $scripts) { + UI-Sub $hook.Name if ($script:ArgsGlobal.DryRun) { continue } - try { & $s.FullName } catch { - UI-Warn "hook $($s.Name) failed: $($_.Exception.Message)" - Log-Warn "hook $Phase/$($s.Name) failed" + $global:LASTEXITCODE = 0 + try { + # Under --json stdout carries the JSON object alone. + if ($script:ArgsGlobal.Json) { & $hook.FullName *>&1 | ForEach-Object { [Console]::Error.WriteLine("$_") } } + else { & $hook.FullName } + } catch { + UI-Warn "hook $($hook.Name) failed: $($_.Exception.Message)" + Log-Warn "hook $Phase/$($hook.Name) failed" + continue + } + # `exit N` in a hook, or its last native command, sets the code. + if ($global:LASTEXITCODE -ne 0) { + UI-Warn "hook $($hook.Name) failed (exit $global:LASTEXITCODE)" + Log-Warn "hook $Phase/$($hook.Name) failed" } } } diff --git a/src/pslib/Log.ps1 b/src/pslib/Log.ps1 index 19d115d..4b853b2 100644 --- a/src/pslib/Log.ps1 +++ b/src/pslib/Log.ps1 @@ -1,25 +1,59 @@ -# Structured logging to $EMERGER_LOG. +# Structured logging to $EMERGER_LOG, and the --errors viewer. +# Set EMERGER_LOG, create the state directory and the log file when +# missing, and keep the log to its last 2000 lines. function Log-Init { $script:EMERGER_LOG = Join-Path $script:EMERGER_STATE 'emerger.log' - if (-not (Test-Path $script:EMERGER_STATE)) { - New-Item -ItemType Directory -Path $script:EMERGER_STATE -Force | Out-Null + if (-not (Test-Path -LiteralPath $script:EMERGER_STATE)) { + [void][IO.Directory]::CreateDirectory($script:EMERGER_STATE) } - if (-not (Test-Path $script:EMERGER_LOG)) { - New-Item -ItemType File -Path $script:EMERGER_LOG -Force | Out-Null + if (-not (Test-Path -LiteralPath $script:EMERGER_LOG)) { + [IO.File]::Open($script:EMERGER_LOG, [IO.FileMode]::OpenOrCreate).Dispose() } - # Rotate at 2000 lines. - $count = (Get-Content $script:EMERGER_LOG -ErrorAction SilentlyContinue | Measure-Object).Count + # Rotate at 2000 lines. The parentheses finish the read before the + # write: 5.1 refuses to rewrite a file still open in the same pipeline. + $count = (Get-Content -LiteralPath $script:EMERGER_LOG -ErrorAction SilentlyContinue | Measure-Object).Count if ($count -gt 2000) { - Get-Content $script:EMERGER_LOG -Tail 2000 | Set-Content $script:EMERGER_LOG + (Get-Content -LiteralPath $script:EMERGER_LOG -Tail 2000) | Set-Content -LiteralPath $script:EMERGER_LOG } } +# Lines kept in memory instead of the log file when set (the elevated child). +$script:LOG_BUFFER = $null + +# Return the current UTC time as 2026-01-31T12:00:00Z. Invariant culture: a +# custom format's ':' is the culture's time separator, '.' in some locales. +function Log-Timestamp { + return (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ', [Globalization.CultureInfo]::InvariantCulture) +} + +# Write $Message at $Level as one "ts|LEVEL|message" line to the log, or to +# LOG_BUFFER when set. A pipe becomes '/' and a line break a space, so text +# from a manager cannot forge a "ts|ERROR|" line. function Log-Write { - param([string]$Level, [string]$Msg) - $ts = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') - try { Add-Content -Path $script:EMERGER_LOG -Value "$ts|$Level|$Msg" -ErrorAction Stop } catch {} + param([string]$Level, [string]$Message) + $Message = ($Message -replace '\|', '/') -replace '\r?\n|\r', ' ' + $timestamp = Log-Timestamp + if ($null -ne $script:LOG_BUFFER) { $script:LOG_BUFFER.Add("$timestamp|$Level|$Message"); return } + Log-Append-Raw "$timestamp|$Level|$Message" +} + +# Append one already formatted line to the log file, errors ignored. +function Log-Append-Raw { + param([string]$Line) + try { Add-Content -LiteralPath $script:EMERGER_LOG -Value $Line -ErrorAction Stop } catch {} +} +# Log $Message at INFO, WARN or ERROR level. +function Log-Info { param([string]$Message) Log-Write 'INFO' $Message } +function Log-Warn { param([string]$Message) Log-Write 'WARN' $Message } +function Log-Error { param([string]$Message) Log-Write 'ERROR' $Message } + +# Print the last 30 ERROR lines of the log and their count (--errors). +function Log-Show-Errors { + $log = Join-Path $script:EMERGER_STATE 'emerger.log' + if (-not (Test-Path -LiteralPath $log)) { UI-Ok 'No log yet.'; return } + $errorLines = @(Select-String -LiteralPath $log -Pattern '\|ERROR\|' -ErrorAction SilentlyContinue) + if ($errorLines.Count -eq 0) { UI-Ok 'No errors logged.'; return } + UI-Warn "$($errorLines.Count) error line(s) in ${log}:" + $errorLines | Select-Object -Last 30 | ForEach-Object { Write-Host (" " + ($_.Line -replace '\|ERROR\|', ('|' + (UI-Color red 'ERROR') + '|'))) } } -function Log-Info { param([string]$M) Log-Write 'INFO' $M } -function Log-Warn { param([string]$M) Log-Write 'WARN' $M } -function Log-Error { param([string]$M) Log-Write 'ERROR' $M } diff --git a/src/pslib/Packages.ps1 b/src/pslib/Packages.ps1 deleted file mode 100644 index 2a9ff91..0000000 --- a/src/pslib/Packages.ps1 +++ /dev/null @@ -1,148 +0,0 @@ -# Windows package manager registry and dispatcher. - -$script:PKG_MANAGERS = @( - 'winget','scoop','choco','wsl','PSWindowsUpdate' -) -$script:PKG_DEV = @('rustup','cargo','npm','pnpm','pip','gem') - -function Pkg-Need-Admin { - param([string]$M) - return @('choco','PSWindowsUpdate','wsl') -contains $M -} - -function Pkg-Detect { - param([string]$M) - switch ($M) { - 'winget' { return (Sys-Has winget) } - 'scoop' { return (Sys-Has scoop) } - 'choco' { return (Sys-Has choco) } - 'wsl' { return (Sys-Has wsl) } - 'PSWindowsUpdate' { return [bool](Get-Module -ListAvailable PSWindowsUpdate -ErrorAction SilentlyContinue) } - 'rustup' { return (Sys-Has rustup) } - 'cargo' { return (Sys-Has cargo) -and (Sys-Has cargo-install-update) } - 'npm' { return (Sys-Has npm) } - 'pnpm' { return (Sys-Has pnpm) } - 'pip' { return (Sys-Has pip) } - 'gem' { return (Sys-Has gem) } - default { return $false } - } -} - -function Pkg-Detect-All { - param([switch]$IncludeDev) - $out = @() - foreach ($m in $script:PKG_MANAGERS) { if (Pkg-Detect $m) { $out += $m } } - if ($IncludeDev) { foreach ($m in $script:PKG_DEV) { if (Pkg-Detect $m) { $out += $m } } } - return ,$out -} - -function Pkg-Need-Admin-Any { - param([switch]$IncludeDev) - $detected = Pkg-Detect-All -IncludeDev:$IncludeDev - foreach ($m in $detected) { if (Pkg-Need-Admin $m) { return $true } } - return $false -} - -function Pkg-Icon { - param([string]$M) - if (-not $script:UI_UNICODE) { return '*' } - switch ($M) { - 'winget' { '๐Ÿ“ฆ' } - 'scoop' { '๐Ÿฅ„' } - 'choco' { '๐Ÿซ' } - 'wsl' { '๐Ÿง' } - 'PSWindowsUpdate' { '๐ŸชŸ' } - 'rustup' { '๐Ÿฆ€' } - 'cargo' { '๐Ÿฆ€' } - 'npm' { '๐Ÿ“—' } - 'pnpm' { '๐Ÿ“—' } - 'pip' { '๐Ÿ' } - 'gem' { '๐Ÿ’Ž' } - default { '*' } - } -} - -function Run-Cmd { - param([string]$Label, [scriptblock]$Block) - if ($script:ArgsGlobal.DryRun) { - UI-Sub "[dry-run] $Label" - return $true - } - if ($script:UI_VERBOSE) { - UI-Sub $Label - try { & $Block } catch { UI-Fail $Label 1; Log-Error "$Label : $_"; return $false } - if ($LASTEXITCODE -and $LASTEXITCODE -ne 0) { UI-Fail $Label $LASTEXITCODE; Log-Error "$Label rc=$LASTEXITCODE"; return $false } - UI-Done $Label - return $true - } - $tmp = [IO.Path]::GetTempFileName() - try { - & $Block *>$tmp - $rc = $LASTEXITCODE - if (-not $rc) { $rc = 0 } - } catch { - $rc = 1 - $_ | Out-File $tmp -Append - } - if ($rc -ne 0) { - UI-Fail $Label $rc - Log-Error "$Label rc=$rc" - Get-Content $tmp -Tail 15 -ErrorAction SilentlyContinue | ForEach-Object { - [Console]::Error.WriteLine(" $_") - } - Remove-Item $tmp -Force -ErrorAction SilentlyContinue - return $false - } - UI-Done $Label - Remove-Item $tmp -Force -ErrorAction SilentlyContinue - return $true -} - -function Pkg-Run { - param([string]$M) - $script:PKG_CURRENT = $M - $icon = Pkg-Icon $M - UI-Title "$icon $M" - Log-Info "starting $M" - $ok = $true - switch ($M) { - 'winget' { - $ok = (Run-Cmd 'winget source update' { winget source update --disable-interactivity *>$null; $global:LASTEXITCODE = 0 }) -and $ok - $ok = (Run-Cmd 'winget upgrade --all' { - winget upgrade --all --include-unknown --accept-package-agreements --accept-source-agreements --silent --disable-interactivity - if (-not $LASTEXITCODE) { $global:LASTEXITCODE = 0 } - }) -and $ok - } - 'scoop' { - $ok = (Run-Cmd 'scoop update' { scoop update }) -and $ok - $ok = (Run-Cmd 'scoop update *' { scoop update * }) -and $ok - $ok = (Run-Cmd 'scoop cleanup *' { scoop cleanup * }) -and $ok - $ok = (Run-Cmd 'scoop cache rm *' { scoop cache rm * }) -and $ok - } - 'choco' { - $ok = (Run-Cmd 'choco upgrade all' { choco upgrade all -y --limit-output }) -and $ok - } - 'wsl' { - $ok = (Run-Cmd 'wsl --update' { wsl --update }) -and $ok - } - 'PSWindowsUpdate' { - $ok = (Run-Cmd 'Windows Update' { - Import-Module PSWindowsUpdate -ErrorAction Stop - Get-WindowsUpdate -AcceptAll -Install -IgnoreReboot -Confirm:$false - }) -and $ok - } - 'rustup' { $ok = (Run-Cmd 'rustup update' { rustup update }) -and $ok } - 'cargo' { $ok = (Run-Cmd 'cargo install-update -a' { cargo install-update -a }) -and $ok } - 'npm' { $ok = (Run-Cmd 'npm -g update' { npm update -g }) -and $ok } - 'pnpm' { $ok = (Run-Cmd 'pnpm -g update' { pnpm -g update }) -and $ok } - 'pip' { $ok = (Run-Cmd 'pip upgrade outdated' { - pip list --outdated --format=json 2>$null | - ConvertFrom-Json | - ForEach-Object { pip install --user -U $_.name 2>$null } - }) -and $ok } - 'gem' { $ok = (Run-Cmd 'gem update' { gem update }) -and $ok } - } - $script:PKG_CURRENT = '' - if ($ok) { Log-Info "$M ok" } else { Log-Error "$M failed" } - return $ok -} diff --git a/src/pslib/Profiles.ps1 b/src/pslib/Profiles.ps1 index 368dba0..2f14d3b 100644 --- a/src/pslib/Profiles.ps1 +++ b/src/pslib/Profiles.ps1 @@ -3,7 +3,9 @@ # 1) $EMERGER_CONFIG\profiles.d\.ps1 (user) # 2) $EMERGER_ROOT\share\profiles\.ps1 (shipped) -function Load-Profile { +# Dot-source profile $Name from the user's profiles.d, else the shipped +# ones. Exit 2 for an invalid name or a profile that does not exist. +function Profiles-Load { param([string]$Name) if (-not $Name) { return } if ($Name -notmatch '^[A-Za-z0-9._-]+$') { @@ -14,10 +16,10 @@ function Load-Profile { (Join-Path $script:EMERGER_CONFIG "profiles.d\$Name.ps1"), (Join-Path $script:EMERGER_ROOT "share\profiles\$Name.ps1") ) - foreach ($f in $candidates) { - if (Test-Path -LiteralPath $f) { - . $f - Log-Info "profile loaded: $Name ($f)" + foreach ($candidate in $candidates) { + if (Test-Path -LiteralPath $candidate) { + . $candidate + Log-Info "profile loaded: $Name ($candidate)" return } } @@ -26,20 +28,22 @@ function Load-Profile { exit 2 } -function List-Profiles { +# Print every profile with its description in name order, a user profile +# hiding a shipped one of the same name (--list-profiles). +function Profiles-List { UI-Title 'Available profiles' $seen = @{} - foreach ($d in @((Join-Path $script:EMERGER_CONFIG 'profiles.d'), + foreach ($dir in @((Join-Path $script:EMERGER_CONFIG 'profiles.d'), (Join-Path $script:EMERGER_ROOT 'share\profiles'))) { - if (-not (Test-Path $d)) { continue } - Get-ChildItem $d -Filter '*.ps1' -ErrorAction SilentlyContinue | ForEach-Object { - $n = $_.BaseName - if ($seen.ContainsKey($n)) { return } - $seen[$n] = $true + if (-not (Test-Path -LiteralPath $dir)) { continue } + Get-ChildItem -LiteralPath $dir -Filter '*.ps1' -ErrorAction SilentlyContinue | Sort-Object Name | ForEach-Object { + $name = $_.BaseName + if ($seen.ContainsKey($name)) { return } + $seen[$name] = $true $descLine = Select-String -Path $_.FullName -Pattern '^# description:' -ErrorAction SilentlyContinue | Select-Object -First 1 - $desc = '' - if ($descLine) { $desc = $descLine.Line -replace '^# description:\s*','' } - Write-Host " $(UI-Color cyan $n) $(UI-Color gray $desc)" + $description = '' + if ($descLine) { $description = $descLine.Line -replace '^# description:\s*','' } + Write-Host " $(UI-Color cyan $name) $(UI-Color gray $description)" } } } diff --git a/src/pslib/Run.ps1 b/src/pslib/Run.ps1 new file mode 100644 index 0000000..5e9153c --- /dev/null +++ b/src/pslib/Run.ps1 @@ -0,0 +1,374 @@ +# Run one manager step: command resolution, child process, live monitor, +# timeout and retry. + +# Quote $Argument for a Windows command line (CommandLineToArgvW rules). +function Run-Quote { + param([string]$Argument) + if ($Argument -and $Argument -notmatch '[\s"]') { return $Argument } + $escaped = [regex]::Replace($Argument, '(\\*)"', '$1$1\"') + $escaped = [regex]::Replace($escaped, '(\\+)$', '$1$1') + return '"' + $escaped + '"' +} + +# Escape a command line for cmd.exe: outside quotes caret-escape & | ^ < > %, +# inside quotes (where a caret is literal) step out to escape % as "^%". +function _Run-Escape-CmdExe { + param([string]$Line) + $builder = New-Object System.Text.StringBuilder + $isInQuotes = $false + foreach ($char in $Line.ToCharArray()) { + if ($char -eq '"') { $isInQuotes = -not $isInQuotes; [void]$builder.Append($char); continue } + if ($isInQuotes) { + if ($char -eq '%') { [void]$builder.Append('"^%"') } else { [void]$builder.Append($char) } + continue + } + if ('&|^<>%'.IndexOf($char) -ge 0) { [void]$builder.Append('^') } + [void]$builder.Append($char) + } + return $builder.ToString() +} + +# Return the path of the running edition's console host in $PSHOME (pwsh or +# powershell), not the process image, which is powershell_ise.exe under the ISE. +function Run-PowerShell-Path { + $name = if ($PSVersionTable.PSEdition -eq 'Core') { 'pwsh' } else { 'powershell' } + foreach ($leaf in @("$name.exe", $name)) { + $exe = Join-Path $PSHOME $leaf + if (Test-Path -LiteralPath $exe -PathType Leaf) { return $exe } + } + return "$name.exe" +} + +# Return the arguments of a child PowerShell running $Body, which exits with +# the last native exit code, or 1 on a terminating error. +function _Run-PowerShell-Args { + param([string]$Body) + $script = @" +`$ProgressPreference = 'SilentlyContinue' +`$ErrorActionPreference = 'Continue' +try { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding `$false } catch {} +`$global:LASTEXITCODE = 0 +try { & { $Body } } catch { [Console]::Error.WriteLine("ERROR: " + `$_); exit 1 } +exit [int]`$global:LASTEXITCODE +"@ + $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($script)) + return "-NoProfile -NonInteractive -ExecutionPolicy Bypass -OutputFormat Text -EncodedCommand $encoded" +} + +# Resolve $Exe with $ArgList, or $Block, to the {File, Args} to start: an .exe +# directly, a .cmd or .bat through cmd.exe, a .ps1 shim (scoop, npm) and a +# script block through a child PowerShell. +function _Run-Resolve { + param([string]$Exe, [string[]]$ArgList, [scriptblock]$Block) + if ($Block) { return @{ File = (Run-PowerShell-Path); Args = (_Run-PowerShell-Args $Block.ToString()) } } + $joined = ($ArgList | ForEach-Object { Run-Quote $_ }) -join ' ' + $app = Get-Command $Exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($app) { + $path = $app.Source + if (-not $path) { $path = $app.Path } + if ($path -match '\.(cmd|bat)$') { + $comSpec = $env:ComSpec + if (-not $comSpec) { $comSpec = 'cmd.exe' } + return @{ File = $comSpec; Args = "/d /s /c `"$(_Run-Escape-CmdExe "$(Run-Quote $path) $joined")`"" } + } + return @{ File = $path; Args = $joined } + } + $shim = Get-Command $Exe -CommandType ExternalScript -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($shim) { + $quoted = ($ArgList | ForEach-Object { "'" + ($_ -replace "'", "''") + "'" }) -join ' ' + return @{ File = (Run-PowerShell-Path); Args = (_Run-PowerShell-Args "& '$($shim.Source -replace "'", "''")' $quoted") } + } + return @{ File = $Exe; Args = $joined } +} + +# Longest line, in characters, that reaches the progress parsers and the +# monitor: a longer one is cut, so one unterminated feed cannot grow the carry +# or make a parser scan more than this. +$script:RUN_MAX_LINE = 1024 + +# Append output $Chunk to $State.Log and feed its complete lines (CR or LF), +# sanitised and cut to RUN_MAX_LINE, to the progress parser and the monitor, +# the rest kept (cut the same way) in $State.Carry. +function _Run-Consume { + param($State, [string]$Chunk) + if ($Chunk.IndexOf([char]0) -ge 0) { $Chunk = $Chunk.Replace([string][char]0, '') } # UTF-16 from old wsl.exe + [void]$State.Log.Append($Chunk) + if ($State.Log.Length -gt 2MB) { [void]$State.Log.Remove(0, $State.Log.Length - 1MB) } + $parts = [regex]::Split($State.Carry + $Chunk, '\r\n|\r|\n') + $State.Carry = $parts[$parts.Count - 1] + if ($State.Carry.Length -gt $script:RUN_MAX_LINE) { $State.Carry = $State.Carry.Substring(0, $script:RUN_MAX_LINE) } + for ($i = 0; $i -lt $parts.Count - 1; $i++) { + $segment = $parts[$i] + if ($segment.Length -gt $script:RUN_MAX_LINE) { $segment = $segment.Substring(0, $script:RUN_MAX_LINE) } + $segment = UI-Sanitize $segment + if (-not $segment.Trim()) { continue } + # Parser errors must never reach _Run-Process, whose finally kills the child. + $message = '' + try { $message = Progress-Feed $segment } catch { $message = '' } + if ($message -eq ' ') { continue } + if ($message) { UI-Monitor-Text $message } else { UI-Monitor-Text $segment } + } +} + +# Kill $Process and every process it started. Kill($true) needs .NET Core 3 +# or later, 5.1 falls back to taskkill /T, then to a plain Kill(). +function _Run-Kill-Tree { + param([Diagnostics.Process]$Process) + try { if ($Process.HasExited) { return } } catch { return } + try { $Process.Kill($true); return } catch {} + try { & taskkill.exe /PID $Process.Id /T /F 2>&1 | Out-Null; if ($Process.WaitForExit(2000)) { return } } catch {} + try { $Process.Kill() } catch {} +} + +# Return the deadline of one step from $script:MANAGER_TIMEOUT seconds, or +# $null when it is 0 or unset (no timeout). +function _Run-Deadline { + $seconds = 0 + if ("$($script:MANAGER_TIMEOUT)" -match '^\d{1,9}$') { $seconds = [int]$script:MANAGER_TIMEOUT } + if ($seconds -le 0) { return $null } + return [DateTime]::UtcNow.AddSeconds($seconds) +} + +# Exit code reported for a step killed by MANAGER_TIMEOUT, as the timeout command does. +$script:RUN_TIMEOUT_RC = 124 + +# Build the start info of resolved target $Target ({File, Args}), run without +# the shell. +function _Run-New-StartInfo { + param([hashtable]$Target) + $startInfo = New-Object System.Diagnostics.ProcessStartInfo + $startInfo.FileName = $Target.File + $startInfo.Arguments = $Target.Args + $startInfo.UseShellExecute = $false + return $startInfo +} + +# Run resolved target $Target, its stdout and stderr read asynchronously into +# $State and the monitor redrawn in between (no threads or events, so 5.1 and +# 7 behave the same). Return the exit code, or RUN_TIMEOUT_RC with +# $State.HasTimedOut set when MANAGER_TIMEOUT expired. +function _Run-Process { + param([hashtable]$Target, $State) + $startInfo = _Run-New-StartInfo $Target + $startInfo.RedirectStandardOutput = $true + $startInfo.RedirectStandardError = $true + $startInfo.RedirectStandardInput = $true + $startInfo.CreateNoWindow = $false + $encoding = New-Object System.Text.UTF8Encoding $false + $startInfo.StandardOutputEncoding = $encoding + $startInfo.StandardErrorEncoding = $encoding + $startInfo.EnvironmentVariables['WSL_UTF8'] = '1' + $startInfo.EnvironmentVariables['PYTHONIOENCODING'] = 'utf-8' + + $process = [Diagnostics.Process]::Start($startInfo) + $isFinished = $false + try { + try { $process.StandardInput.Close() } catch {} + $outBuffer = New-Object char[] 8192 + $errBuffer = New-Object char[] 8192 + $outRead = $process.StandardOutput.ReadAsync($outBuffer, 0, $outBuffer.Length) + $errRead = $process.StandardError.ReadAsync($errBuffer, 0, $errBuffer.Length) + $next = [DateTime]::UtcNow + $deadline = _Run-Deadline + while ($outRead -or $errRead) { + if ($deadline -and [DateTime]::UtcNow -ge $deadline) { + _Run-Kill-Tree $process + $State.HasTimedOut = $true + [void]$State.Log.AppendLine("timed out after $($script:MANAGER_TIMEOUT)s (MANAGER_TIMEOUT), process tree killed") + [void]$process.WaitForExit(5000) + $isFinished = $true + return $script:RUN_TIMEOUT_RC + } + $pending = @() + if ($outRead) { $pending += $outRead } + if ($errRead) { $pending += $errRead } + $wait = [int][math]::Max(0, ($next - [DateTime]::UtcNow).TotalMilliseconds) + if ($deadline) { $wait = [int][math]::Min([double]$wait, [math]::Max(0.0, ($deadline - [DateTime]::UtcNow).TotalMilliseconds)) } + [void][Threading.Tasks.Task]::WaitAny([Threading.Tasks.Task[]]$pending, $wait) + if ($outRead -and $outRead.IsCompleted) { + $count = $outRead.Result + if ($count -gt 0) { _Run-Consume $State ([string]::new($outBuffer, 0, $count)); $outRead = $process.StandardOutput.ReadAsync($outBuffer, 0, $outBuffer.Length) } + else { $outRead = $null } + } + if ($errRead -and $errRead.IsCompleted) { + $count = $errRead.Result + if ($count -gt 0) { _Run-Consume $State ([string]::new($errBuffer, 0, $count)); $errRead = $process.StandardError.ReadAsync($errBuffer, 0, $errBuffer.Length) } + else { $errRead = $null } + } + if ([DateTime]::UtcNow -ge $next) { + UI-Monitor-Frame + $next = [DateTime]::UtcNow.AddMilliseconds(100) + } + } + if ($State.Carry) { _Run-Consume $State "`n" } + $process.WaitForExit() + $isFinished = $true + return $process.ExitCode + } finally { + # Ctrl-C: don't leave the child or anything it started running. + if (-not $isFinished) { + _Run-Kill-Tree $process + UI-Monitor-Stop + } + $process.Dispose() + } +} + +# Show verbose output lines from the pipeline: on the host, or on stderr +# under --json, where stdout carries the JSON object alone. +function _Run-Show { + process { + if ($script:ArgsGlobal.Json) { [Console]::Error.WriteLine("$_") } else { $_ | Out-Host } + } +} + +# Run a resolved target with the console inherited (verbose mode) under the +# MANAGER_TIMEOUT deadline, its stdout copied to stderr under --json. Return +# its exit code, or RUN_TIMEOUT_RC after killing the process tree. +function _Run-Inline { + param([hashtable]$Target) + $startInfo = _Run-New-StartInfo $Target + $isToStderr = [bool]$script:ArgsGlobal.Json + $startInfo.RedirectStandardOutput = $isToStderr + $process = [Diagnostics.Process]::Start($startInfo) + $copy = $null + if ($isToStderr) { $copy = $process.StandardOutput.BaseStream.CopyToAsync([Console]::OpenStandardError()) } + try { + $deadline = _Run-Deadline + # WaitForExit takes an int of milliseconds: wait in slices that fit. + while (-not $process.WaitForExit([int][math]::Min([double][int]::MaxValue, [math]::Max(0.0, ($deadline - [DateTime]::UtcNow).TotalMilliseconds)))) { + if ([DateTime]::UtcNow -lt $deadline) { continue } + _Run-Kill-Tree $process + [void]$process.WaitForExit(5000) + return $script:RUN_TIMEOUT_RC + } + $process.WaitForExit() + return $process.ExitCode + } finally { + if (-not $process.HasExited) { _Run-Kill-Tree $process } + if ($copy) { try { [void]$copy.Wait(2000) } catch {} } + $process.Dispose() + } +} + +# Return $true when step output $Text shows a transient network failure, +# matched against the retry patterns. +function _Run-Is-Transient { + param([string]$Text) + return $Text -match '(Temporary failure|Could not resolve|Connection (timed out|reset|refused)|network is unreachable|503 |502 |504 |failed to fetch|EOF occurred|timed out|Try again later|0x80072EE2|0x80072EFD)' +} + +# Steps of the current manager, recorded when set (the elevated child sends +# them to the caller, which replays them). +$script:RUN_STEPS = $null + +# Record one finished step in RUN_STEPS when recording is on. +function _Run-Record { + param([string]$Label, [bool]$IsOk, [string]$Rc = '0', [string]$Stat = '', [string[]]$Tail = @()) + if ($null -eq $script:RUN_STEPS) { return } + $script:RUN_STEPS.Add([pscustomobject]@{ label = $Label; ok = $IsOk; rc = $Rc; stat = $Stat; tail = @($Tail) }) +} + +# Run one step under the live monitor, either -Exe/-ArgList or a script +# block (in a child PowerShell). -OkCodes: more exit codes that mean +# success. -AnyExit: ignore the exit code. +function Run-Cmd { + param( + [Parameter(Position = 0)][string]$Label, + [Parameter(Position = 1)][scriptblock]$Block, + [string]$Exe, + [string[]]$ArgList = @(), + [int[]]$OkCodes = @(), + [switch]$AnyExit, + [int]$Total = 0, + [string]$Parser + ) + if (-not $Parser) { $Parser = $script:PKG_CURRENT } + $shown = if ($Exe) { (@($Exe) + $ArgList) -join ' ' } else { $Label } + if ($script:ArgsGlobal.DryRun) { + UI-Sub "[dry-run] $shown" + return $true + } + if ($script:UI_VERBOSE) { + return (_Run-Cmd-Verbose -Label $Label -Block $Block -Exe $Exe -ArgList $ArgList -OkCodes $OkCodes -AnyExit:$AnyExit) + } + return (_Run-Cmd-Monitored -Label $Label -Block $Block -Exe $Exe -ArgList $ArgList -OkCodes $OkCodes -AnyExit:$AnyExit ` + -Total $Total -Parser $Parser) +} + +# Verbose path of Run-Cmd: output on the console, no monitor and no retry. +# Return $true on success. +function _Run-Cmd-Verbose { + param([string]$Label, [scriptblock]$Block, [string]$Exe, [string[]]$ArgList, [int[]]$OkCodes, [switch]$AnyExit) + UI-Sub $Label + # In-process native calls: stderr and exit codes are judged by $rc, + # never raised as errors (5.1 turns redirected stderr into one under Stop). + $ErrorActionPreference = 'Continue' + $PSNativeCommandUseErrorActionPreference = $false + $rc = 0 + try { + $global:LASTEXITCODE = 0 + if (_Run-Deadline) { + # Child process, so MANAGER_TIMEOUT can stop it, on the same console. + $rc = _Run-Inline (_Run-Resolve $Exe $ArgList $Block) + if ($rc -eq $script:RUN_TIMEOUT_RC) { UI-Err "${Label}: timed out after $($script:MANAGER_TIMEOUT)s (MANAGER_TIMEOUT), process tree killed" } + } else { + # _Run-Show, or the output ends up in this function's return value. + if ($Exe) { & $Exe @ArgList | _Run-Show } else { & $Block *>&1 | _Run-Show } + $rc = [int]$global:LASTEXITCODE + } + } catch { UI-Err "$_"; $rc = 1 } + if ($rc -eq 0 -or $AnyExit -or $OkCodes -contains $rc) { UI-Done $Label; _Run-Record $Label $true; return $true } + UI-Fail $Label $rc + Log-Error "$Label rc=$rc" + _Run-Record $Label $false "$rc" + return $false +} + +# Monitored path of Run-Cmd: output parsed under the live monitor, a transient +# failure retried up to RETRY_ATTEMPTS times. Return $true on success. +function _Run-Cmd-Monitored { + param([string]$Label, [scriptblock]$Block, [string]$Exe, [string[]]$ArgList, [int[]]$OkCodes, [switch]$AnyExit, + [int]$Total, [string]$Parser) + $attempt = 1 + while ($true) { + Progress-Reset $Parser $Total + $state = @{ Log = (New-Object System.Text.StringBuilder); Carry = ''; HasTimedOut = $false } + UI-Monitor-Start $Label + $rc = 0 + try { + $rc = _Run-Process (_Run-Resolve $Exe $ArgList $Block) $state + } catch { + [void]$state.Log.AppendLine("$_") + $rc = 1 + } + UI-Monitor-Stop + + if ($rc -eq 0 -or $AnyExit -or $OkCodes -contains $rc) { + $script:PKG_CHANGED += (Progress-Changed) + $stat = Progress-Summarize + UI-Done $Label $stat + _Run-Record $Label $true '0' $stat + return $true + } + # Timeouts are final: retrying a stalled step only doubles the wait. + if (-not $state.HasTimedOut -and (_Run-Is-Transient $state.Log.ToString()) -and $attempt -lt $script:RETRY_ATTEMPTS) { + UI-Warn "${Label}: transient failure, retrying ($attempt/$($script:RETRY_ATTEMPTS))" + Log-Warn "${Label}: retry $attempt (rc=$rc)" + Start-Sleep -Seconds ($script:RETRY_DELAY * $attempt) + $attempt++ + continue + } + break + } + $script:PKG_CHANGED += (Progress-Changed) + UI-Fail $Label $rc + Log-Error "$Label rc=$rc" + # Keep only what's left after the last CR, like the terminal shows it. + $lines = @(($state.Log.ToString() -split '\r?\n') | ForEach-Object { UI-Sanitize (($_ -split '\r')[-1]) } | Where-Object { $_.Trim() }) + $tail = @($lines | Select-Object -Last 20) + UI-Fail-Tail $tail + Log-Error (($lines | Select-Object -Last 50) -join "`n") + _Run-Record $Label $false "$rc" '' $tail + return $false +} diff --git a/src/pslib/SelfUpdate.ps1 b/src/pslib/SelfUpdate.ps1 new file mode 100644 index 0000000..f7dba28 --- /dev/null +++ b/src/pslib/SelfUpdate.ps1 @@ -0,0 +1,36 @@ +# Self-update from git (--self-update). + +# Fast-forward the git checkout at $Root (--self-update) and list the new +# commits. Return 0, or 1 when it is not a checkout or git fails. +function SelfUpdate-Run { + param([string]$Root) + UI-Title 'Self-update' + if (-not (Test-Path (Join-Path $Root '.git'))) { + UI-Err 'Not a git checkout. Re-clone from https://github.com/MasterCruelty/eMerger' + return 1 + } + if (-not (Sys-Has git)) { UI-Err 'git not installed'; return 1 } + if ($script:ArgsGlobal.DryRun) { UI-Sub "[dry-run] git -C `"$Root`" pull --ff-only"; return 0 } + # Native stderr must not turn into a terminating error (5.1 under Stop): + # each step is judged by its exit code. + $ErrorActionPreference = 'Continue' + $before = "$(& git -C $Root rev-parse HEAD 2>$null)".Trim() + & git -C $Root fetch --quiet 2>$null + if ($LASTEXITCODE -ne 0) { + UI-Err 'git fetch failed' + return 1 + } + & git -C $Root pull --ff-only --quiet 2>$null + if ($LASTEXITCODE -ne 0) { + UI-Err 'git pull failed (non fast-forward?)' + return 1 + } + $after = "$(& git -C $Root rev-parse HEAD 2>$null)".Trim() + if ($before -eq $after) { + UI-Ok 'Already up to date.' + } else { + UI-Ok ("Updated {0}..{1}" -f $before.Substring(0, [math]::Min(7,$before.Length)), $after.Substring(0, [math]::Min(7,$after.Length))) + & git -C $Root log --oneline "$before..$after" | ForEach-Object { Write-Host " $(UI-Color gray (UI-Glyph dot)) $_" } + } + return 0 +} diff --git a/src/pslib/Summary.ps1 b/src/pslib/Summary.ps1 index f50b0a6..ab33dc6 100644 --- a/src/pslib/Summary.ps1 +++ b/src/pslib/Summary.ps1 @@ -1,130 +1,81 @@ -# Final summary box, history persistence, errors/history viewers. +# Final summary: the run as one JSON line, and the summary box. -$script:SUMMARY_FREED_MB = 0 +# KiB freed by the cache and trash cleaning of this run. +$script:SUMMARY_FREED_KB = 0 +# Count the managers that failed in this run. +function Summary-Fail-Count { + return @($script:Summary | Where-Object { $_.Result -eq 'fail' }).Count +} + +# Return the run of $Duration seconds as one JSON line: the --json output and +# the history.jsonl entry. Estimate-Read reads back its per-manager secs. function Summary-Json { param([int]$Duration) - $obj = [pscustomobject]@{ - ts = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + $run = [pscustomobject]@{ + ts = Log-Timestamp duration = $Duration - errors = @($script:Summary | Where-Object { $_.Result -eq 'fail' }).Count - freed_mb = $script:SUMMARY_FREED_MB + errors = Summary-Fail-Count + freed_kb = [int64]$script:SUMMARY_FREED_KB reboot = [int](Reboot-Pending) - managers = @($script:Summary | ForEach-Object { [pscustomobject]@{ name = $_.Name; result = $_.Result } }) + managers = @($script:Summary | ForEach-Object { [pscustomobject]@{ name = $_.Name; result = $_.Result; secs = [int]$_.Secs } }) } - $obj | ConvertTo-Json -Compress -Depth 5 + $run | ConvertTo-Json -Compress -Depth 5 } +# Close the run of $Duration seconds: append the history line (not on a dry +# run), then print what +# the quiet level allows: the JSON line, a one-line tally (-qq), nothing +# (-qqq) or the summary box. function Summary-Print { param([int]$Duration) + $line = Summary-Json $Duration + if (-not ($script:ArgsGlobal -and $script:ArgsGlobal.DryRun)) { History-Append $line } if ($script:ArgsGlobal -and $script:ArgsGlobal.Json) { - Summary-Json $Duration - _Persist-History $Duration + $line return } if ($script:QUIET_LEVEL -ge 3) { return } - $min = [int]($Duration / 60) - $sec = $Duration % 60 + $minutes = [int][math]::Floor($Duration / 60) + $seconds = $Duration % 60 $okCount = @($script:Summary | Where-Object { $_.Result -eq 'ok' }).Count - $failCount = @($script:Summary | Where-Object { $_.Result -eq 'fail' }).Count + $failCount = Summary-Fail-Count if ($script:QUIET_LEVEL -ge 2) { if ($failCount -gt 0) { - Write-Host "$okCount/$($okCount+$failCount) managers ok, $failCount error(s), ${min}m${sec}s" + Write-Host ("{0}/{1} managers ok, {2} error(s), {3}m{4:00}s" -f $okCount, ($okCount + $failCount), $failCount, $minutes, $seconds) } else { - Write-Host "$okCount managers ok, ${min}m${sec}s" + Write-Host ("{0} managers ok, {1}m{2:00}s" -f $okCount, $minutes, $seconds) } - _Persist-History $Duration + Reboot-Advisory return } - $mgrLine = '' - foreach ($r in $script:Summary) { - if ($r.Result -eq 'ok') { $mgrLine += "$(UI-Color green (UI-Glyph check)) $($r.Name) " } - else { $mgrLine += "$(UI-Color red (UI-Glyph cross)) $($r.Name) " } + $keyLabel = { param($name) UI-Color 'dim gray' ($name.PadRight(9)) } + $managerParts = @() + foreach ($entry in $script:Summary) { + if ($entry.Result -eq 'ok') { $managerParts += ((UI-Color green (UI-Glyph check)) + " $($entry.Name)") } + else { $managerParts += ((UI-Color red (UI-Glyph cross)) + ' ' + (UI-Color red $entry.Name)) } } $lines = @() - if ($mgrLine) { $lines += $mgrLine; $lines += '' } - $lines += "duration: ${min}m${sec}s" - if ($script:SUMMARY_FREED_MB -gt 0) { - $lines += ("freed: {0} MB" -f $script:SUMMARY_FREED_MB) + if ($managerParts.Count -gt 0) { $lines += ((& $keyLabel 'managers') + ' ' + ($managerParts -join ' ')) } + $lines += ((& $keyLabel 'time') + ' ' + (UI-Color bold ('{0}m{1:00}s' -f $minutes, $seconds))) + if ($script:SUMMARY_FREED_KB -gt 0) { + $lines += ((& $keyLabel 'freed') + ' ' + (UI-Color cyan (Size-Format-KB $script:SUMMARY_FREED_KB))) + } + if ($script:PKG_CHANGED -gt 0) { + $lines += ((& $keyLabel 'changed') + " $($script:PKG_CHANGED) packages") } if ($failCount -gt 0) { - $lines += (UI-Color yellow "$failCount error(s) - up --errors") + $lines += ((& $keyLabel 'status') + ' ' + (UI-Color 'bold yellow' "$(UI-Glyph warn) $failCount error(s)") + ' ' + (UI-Color 'dim gray' '(up --errors)')) } else { - $lines += (UI-Color green 'no errors') + $lines += ((& $keyLabel 'status') + ' ' + (UI-Color 'bold green' "$(UI-Glyph check) all good")) } - UI-Box 'eMerger summary' $lines - _Persist-History $Duration + $boxColor = if ($failCount -gt 0) { 'yellow' } else { 'green' } + UI-Box 'eMerger summary' $lines $boxColor Reboot-Advisory } - -function _Persist-History { - param([int]$Duration) - $hist = Join-Path $script:EMERGER_STATE 'history.jsonl' - $obj = [pscustomobject]@{ - ts = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') - duration = $Duration - errors = @($script:Summary | Where-Object { $_.Result -eq 'fail' }).Count - freed_mb = $script:SUMMARY_FREED_MB - reboot = [int](Reboot-Pending) - managers = @($script:Summary | ForEach-Object { [pscustomobject]@{ name = $_.Name; result = $_.Result } }) - } - try { - $line = $obj | ConvertTo-Json -Compress -Depth 5 - Add-Content -Path $hist -Value $line -ErrorAction Stop - # rotate - $count = (Get-Content $hist | Measure-Object).Count - if ($count -gt 500) { Get-Content $hist -Tail 500 | Set-Content $hist } - } catch {} -} - -function Reboot-Pending { - # Several signals can indicate a pending reboot on Windows. - $keys = @( - 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending', - 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired', - 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations' - ) - foreach ($k in $keys) { - if (Test-Path $k) { return $true } - } - return $false -} - -function Reboot-Advisory { - if (Reboot-Pending) { - Write-Host ("`n $(UI-Color yellow (UI-Glyph warn)) $(UI-Color yellow 'REBOOT RECOMMENDED') $(UI-Color gray '(pending updates require restart)')") - Write-Host (" $(UI-Color gray 'run:') Restart-Computer") - } -} - -function Show-Errors { - $log = Join-Path $script:EMERGER_STATE 'emerger.log' - if (-not (Test-Path $log)) { UI-Ok 'no log yet'; return } - $errs = @(Select-String -Path $log -Pattern '\|ERROR\|' -ErrorAction SilentlyContinue) - if ($errs.Count -eq 0) { UI-Ok 'no errors logged'; return } - UI-Warn "$($errs.Count) error line(s):" - $errs | Select-Object -Last 30 | ForEach-Object { Write-Host " $($_.Line)" } -} - -function Show-History { - $hist = Join-Path $script:EMERGER_STATE 'history.jsonl' - if (-not (Test-Path $hist)) { UI-Muted 'no history yet'; return } - UI-Title 'Recent runs' - Get-Content $hist -Tail 10 | ForEach-Object { - try { - $o = $_ | ConvertFrom-Json - $reboot = if ($o.reboot -eq 1) { ' ' + (UI-Color yellow 'reboot') } else { '' } - if ($o.errors -gt 0) { - Write-Host " $(UI-Color red (UI-Glyph cross)) $($o.ts) $($o.duration)s $(UI-Color yellow "errors=$($o.errors)")$reboot" - } else { - Write-Host " $(UI-Color green (UI-Glyph check)) $($o.ts) $($o.duration)s$reboot" - } - } catch {} - } -} diff --git a/src/pslib/Sys.ps1 b/src/pslib/Sys.ps1 index 5cf0d5e..a8fc854 100644 --- a/src/pslib/Sys.ps1 +++ b/src/pslib/Sys.ps1 @@ -1,55 +1,70 @@ # Platform helpers. +# Return $true when $Command resolves to a command. function Sys-Has { - param([string]$Cmd) - return [bool](Get-Command $Cmd -ErrorAction SilentlyContinue) + param([string]$Command) + return [bool](Get-Command $Command -ErrorAction SilentlyContinue) } +# Return the Windows edition and release, such as "Windows 11 Pro 23H2", read +# from the registry because CIM is slow. function Sys-OS { + try { + $currentVersion = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction Stop + $name = [string]$currentVersion.ProductName + # ProductName still says "Windows 10" on Windows 11 (build 22000+). + if ([int]$currentVersion.CurrentBuild -ge 22000) { $name = $name -replace 'Windows 10', 'Windows 11' } + if ($currentVersion.DisplayVersion) { $name += " $($currentVersion.DisplayVersion)" } + if ($name.Trim()) { return $name.Trim() } + } catch {} + try { return [Runtime.InteropServices.RuntimeInformation]::OSDescription.Trim() } catch {} $os = [Environment]::OSVersion "Windows $($os.Version)" } -function Sys-Arch { return $env:PROCESSOR_ARCHITECTURE } +# Return the processor architecture, '' when unknown. +function Sys-Architecture { + if ($env:PROCESSOR_ARCHITECTURE) { return $env:PROCESSOR_ARCHITECTURE } + try { return [string][Runtime.InteropServices.RuntimeInformation]::OSArchitecture } catch {} + return '' +} +# Return $true when the process runs as Administrator, $false off Windows. function Sys-IsAdmin { try { - $id = [Security.Principal.WindowsIdentity]::GetCurrent() - $p = [Security.Principal.WindowsPrincipal]::new($id) - return $p.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = [Security.Principal.WindowsPrincipal]::new($identity) + return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } catch { return $false } } -function Sys-Start-Elevated { - param([string]$ScriptPath, [string[]]$Arguments) - $argStr = ($Arguments | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }) -join ' ' - Start-Process -FilePath 'powershell' ` - -ArgumentList "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "`"$ScriptPath`"", $argStr ` - -Verb RunAs -Wait -} - -function Sys-On-Battery { - try { - $b = Get-CimInstance -ClassName Win32_Battery -ErrorAction SilentlyContinue - if ($b -and $b.BatteryStatus -eq 1) { return $true } - } catch {} - return $false +# Normalise numeric knob $Name (a script variable) to a whole number, or set +# it to $Default with a warning when it holds anything else. Empty means the +# default. Values past 999999999 are capped there, so every [int] cast holds. +function Sys-Knob-Int { + param([string]$Name, [int]$Default) + $value = "$(Get-Variable -Name $Name -Scope Script -ValueOnly -ErrorAction SilentlyContinue)" + if ($value -match '^[0-9]{1,15}$') { + Set-Variable -Name $Name -Scope Script -Value ([int][math]::Min([int64]$value, 999999999)) + return + } + if ($value) { UI-Warn "$Name=`"$value`" is not a whole number, using $Default" } + Set-Variable -Name $Name -Scope Script -Value $Default } -function Sys-Battery-Percent { - try { - $b = Get-CimInstance -ClassName Win32_Battery -ErrorAction SilentlyContinue - if ($b) { return [int]$b.EstimatedChargeRemaining } - } catch {} - return 100 +# Return the whole seconds from $From to $To (default now), truncated. +function Sys-Elapsed-Seconds { + param([DateTime]$From, [DateTime]$To = [DateTime]::UtcNow) + return [int][math]::Floor(($To - $From).TotalSeconds) } -function Sys-Disk-Free-GB { - param([string]$Drive = 'C') +# Fetch the one-line weather report from wttr.in (3 s timeout), sanitized, +# newlines joined with spaces. Return '' on any failure. +function Sys-Fetch-Weather { try { - $d = Get-PSDrive $Drive -ErrorAction Stop - return [math]::Round($d.Free / 1GB, 1) - } catch { return 0 } + $response = Invoke-WebRequest -Uri 'https://wttr.in/?format=%l:+%c+%t+%w+%m' -TimeoutSec 3 -UseBasicParsing + return ((UI-Sanitize ([string]$response.Content)) -replace '\s*\n\s*', ' ').Trim() + } catch { return '' } } diff --git a/src/pslib/UI.ps1 b/src/pslib/UI.ps1 deleted file mode 100644 index a91c985..0000000 --- a/src/pslib/UI.ps1 +++ /dev/null @@ -1,115 +0,0 @@ -# eMerger Windows UI helpers: colors, glyphs, box, step, spinner. -# Stays in script scope; all state is kept on $script:. - -$script:UI_COLOR = $true -if ($env:NO_COLOR) { $script:UI_COLOR = $false } -try { if ([Console]::IsOutputRedirected) { $script:UI_COLOR = $false } } catch {} - -$script:UI_UNICODE = -not [bool]$env:EMERGER_NO_EMOJI -$script:QUIET_LEVEL = 0 -$script:UI_VERBOSE = $false - -function UI-Color { - param([string]$Color, [string]$Text) - if (-not $script:UI_COLOR) { return $Text } - $esc = [char]27 - $map = @{ red=91; green=92; yellow=93; blue=94; magenta=95; cyan=96; gray=90; bold=1; dim=2 } - $c = $map[$Color] - if (-not $c) { return $Text } - return "$esc[${c}m$Text$esc[0m" -} - -function UI-Glyph { - param([string]$Name) - if ($script:UI_UNICODE) { - switch ($Name) { - 'check' { 'โœ”' } - 'cross' { 'โœ–' } - 'arrow' { 'โ–ถ' } - 'info' { 'โ„น' } - 'warn' { 'โš ' } - 'dot' { 'ยท' } - 'bullet' { 'โ€ข' } - default { '*' } - } - } else { - switch ($Name) { - 'check' { '[OK]' } - 'cross' { '[X]' } - 'arrow' { '>' } - 'info' { 'i' } - 'warn' { '!' } - 'dot' { '.' } - 'bullet' { '*' } - default { '*' } - } - } -} - -function UI-Width { - try { $w = [Console]::WindowWidth } catch { $w = 80 } - if ($w -lt 20) { $w = 80 } - if ($w -gt 80) { return 80 } - return $w -} - -function UI-Hr { - if ($script:QUIET_LEVEL -ge 2) { return } - $w = UI-Width - Write-Host (UI-Color gray ('โ”€' * $w)) -} - -function UI-Title { - param([string]$Text) - if ($script:QUIET_LEVEL -ge 2) { return } - Write-Host "" - Write-Host ("$(UI-Color cyan (UI-Glyph arrow)) $(UI-Color cyan (UI-Color bold $Text))") - UI-Hr -} - -function UI-Info { param([string]$T) if ($script:QUIET_LEVEL -lt 2) { Write-Host " $(UI-Color blue (UI-Glyph info)) $T" } } -function UI-Ok { param([string]$T) if ($script:QUIET_LEVEL -lt 2) { Write-Host " $(UI-Color green (UI-Glyph check)) $T" } } -function UI-Warn { param([string]$T) Write-Host " $(UI-Color yellow (UI-Glyph warn)) $T" } -function UI-Err { param([string]$T) [Console]::Error.WriteLine(" $(UI-Color red (UI-Glyph cross)) $T") } -function UI-Muted { param([string]$T) if ($script:QUIET_LEVEL -lt 1) { Write-Host (UI-Color gray " $T") } } -function UI-Sub { param([string]$T) if ($script:QUIET_LEVEL -lt 1) { Write-Host " $(UI-Color gray (UI-Glyph dot)) $T" } } -function UI-Done { param([string]$T) if ($script:QUIET_LEVEL -lt 2) { Write-Host " $(UI-Color green (UI-Glyph check)) $T" } } -function UI-Fail { param([string]$T,[int]$Rc=1) Write-Host " $(UI-Color red (UI-Glyph cross)) $T $(UI-Color gray "(rc=$Rc)")" } - -function UI-Step { - param([int]$I,[int]$N,[string]$Text) - if ($script:QUIET_LEVEL -ge 2) { return } - Write-Host "" - Write-Host "$(UI-Color magenta "[$I/$N]") $(UI-Color bold $Text)" -} - -function UI-Logo { - param([string]$Path) - if ($script:QUIET_LEVEL -ge 1) { return } - if (-not (Test-Path $Path)) { return } - if ((UI-Width) -lt 60) { return } - Write-Host (UI-Color cyan (Get-Content $Path -Raw)) -} - -function UI-Box { - param([string]$Title, [string[]]$Lines) - if ($script:QUIET_LEVEL -ge 3) { return } - $strip = { param($s) [regex]::Replace($s, "`e\[[0-9;]*[a-zA-Z]", '') } - $maxlen = $Title.Length - foreach ($l in $Lines) { - $len = (& $strip $l).Length - if ($len -gt $maxlen) { $maxlen = $len } - } - if ($maxlen -lt 30) { $maxlen = 30 } - $bar = 'โ”€' * ($maxlen + 2) - Write-Host "" - Write-Host " $(UI-Color cyan "โ•ญ$barโ•ฎ")" - Write-Host (" $(UI-Color cyan 'โ”‚') " + (UI-Color bold ($Title.PadRight($maxlen))) + " $(UI-Color cyan 'โ”‚')") - Write-Host " $(UI-Color cyan "โ”‚$barโ”‚")" - foreach ($l in $Lines) { - $stripped = & $strip $l - $pad = ' ' * ($maxlen - $stripped.Length) - Write-Host (" $(UI-Color cyan 'โ”‚') $l$pad $(UI-Color cyan 'โ”‚')") - } - Write-Host " $(UI-Color cyan "โ•ฐ$barโ•ฏ")" -} diff --git a/src/pslib/clean/RecycleBin.ps1 b/src/pslib/clean/RecycleBin.ps1 new file mode 100644 index 0000000..2e1f7d7 --- /dev/null +++ b/src/pslib/clean/RecycleBin.ps1 @@ -0,0 +1,38 @@ +# Empty the Recycle Bin. Prompts unless -y. + +# Return the Recycle Bin's item count and size ({Count, KB}, size in KiB), or +# $null when the shell does not report them. +function _RecycleBin-Info { + try { + $shell = New-Object -ComObject Shell.Application + $items = @($shell.NameSpace(10).Items()) + $size = 0 + foreach ($item in $items) { try { $size += [double]$item.ExtendedProperty('Size') } catch {} } + return @{ Count = $items.Count; KB = [int64][math]::Round($size / 1KB) } + } catch { return $null } +} + +# Empty the Recycle Bin after a prompt (-y says yes) and add its size to +# SUMMARY_FREED_KB. A failure is a warning, never an error. +function Clean-RecycleBin { + UI-Title 'Recycle bin' + $info = _RecycleBin-Info + $detail = '' + if ($info) { + if ($info.Count -eq 0) { UI-Ok 'empty'; return } + $detail = "($(Size-Format-KB $info.KB), $($info.Count) items)" + } + if (-not (UI-Confirm 'Empty recycle bin?' 'n' $detail)) { UI-Muted 'skipped'; return } + if ($script:ArgsGlobal.DryRun) { UI-Sub '[dry-run] would empty recycle bin'; return } + try { + $stopwatch = [Diagnostics.Stopwatch]::StartNew() + Clear-RecycleBin -Force -ErrorAction Stop + if ($info) { $script:SUMMARY_FREED_KB += $info.KB } + $script:UI_LAST_ELAPSED = UI-Format-Elapsed $stopwatch.Elapsed + $stat = '' + if ($info) { $stat = Size-Format-KB $info.KB } + UI-Done 'recycle bin emptied' $stat + } catch { + UI-Warn "could not empty recycle bin: $($_.Exception.Message)" + } +} diff --git a/src/pslib/clean/Size.ps1 b/src/pslib/clean/Size.ps1 new file mode 100644 index 0000000..5619ee3 --- /dev/null +++ b/src/pslib/clean/Size.ps1 @@ -0,0 +1,9 @@ +# Size formatting shared by the cleaning steps and the summary. + +# Format size $Kibibytes, in KiB, as 812.0MB or 1.2GB. +function Size-Format-KB { + param([double]$Kibibytes) + $mebibytes = $Kibibytes / 1024 + if ($mebibytes -ge 1024) { return ('{0:0.0}GB' -f ($mebibytes / 1024)).Replace(',', '.') } + return ('{0:0.0}MB' -f $mebibytes).Replace(',', '.') +} diff --git a/src/pslib/clean/Temp.ps1 b/src/pslib/clean/Temp.ps1 new file mode 100644 index 0000000..55c9a80 --- /dev/null +++ b/src/pslib/clean/Temp.ps1 @@ -0,0 +1,147 @@ +# Clean the %TEMP% folders without following reparse points. Prompts +# unless -y. + +# Return $true when the file system entry at $Path is a junction, symlink or +# other reparse point, read now (never the attributes cached by an earlier +# enumeration). A path that cannot be read counts as a link. +function _Temp-Is-Link-Now { + param([string]$Path) + try { return (([int][IO.File]::GetAttributes($Path)) -band [int][IO.FileAttributes]::ReparsePoint) -ne 0 } catch { return $true } +} + +# Return $true when $Item is a reparse point, never descended into so an admin +# run cannot be steered outside the temp folder. +function _Temp-Is-Reparse { + param($Item) + return (_Temp-Is-Link-Now $Item.FullName) +} + +# Return the size of the regular files under $Path in whole KiB, not following +# reparse points. +function _Temp-Folder-Size-KB { + param([string]$Path) + if (-not (Test-Path -LiteralPath $Path)) { return 0 } + try { + $totalBytes = 0.0 + $stack = New-Object System.Collections.Generic.Stack[string] + $stack.Push($Path) + while ($stack.Count -gt 0) { + foreach ($item in @(Get-ChildItem -LiteralPath $stack.Pop() -Force -ErrorAction SilentlyContinue)) { + if (_Temp-Is-Reparse $item) { continue } + if ($item.PSIsContainer) { $stack.Push($item.FullName) } else { $totalBytes += $item.Length } + } + } + return [int64][math]::Round($totalBytes / 1KB) + } catch { return 0 } +} + +# Open directory $Path with reparse-point semantics and return a handle that +# denies other processes the right to rename or delete it while held, after +# checking the reparse attribute on that same handle. Return $null when it is +# a link or cannot be opened. Off Windows (no such sharing mode) the result is +# $true for a plain directory. +function _Temp-Open-Dir { + param([string]$Path) + if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { + if (_Temp-Is-Link-Now $Path) { return $null } + return $true + } + if (-not ('EmergerDirHandle' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; +public static class EmergerDirHandle { + [StructLayout(LayoutKind.Sequential)] + struct FileTime { public uint Low; public uint High; } + [StructLayout(LayoutKind.Sequential)] + struct ByHandleInfo { + public uint Attributes; public FileTime Created; public FileTime Accessed; public FileTime Written; + public uint Volume; public uint SizeHigh; public uint SizeLow; public uint Links; public uint IndexHigh; public uint IndexLow; + } + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + static extern SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template); + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool GetFileInformationByHandle(SafeFileHandle handle, out ByHandleInfo info); + public static SafeFileHandle Open(string path) { + // List and read attributes; share read and write but not delete, so the directory cannot be renamed or replaced while held. + SafeFileHandle handle = CreateFileW(path, 0x81, 3, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero); + if (handle.IsInvalid) return null; + ByHandleInfo info; + if (!GetFileInformationByHandle(handle, out info) || (info.Attributes & 0x400) != 0 || (info.Attributes & 0x10) == 0) { handle.Dispose(); return null; } + return handle; + } +} +'@ + } + try { return [EmergerDirHandle]::Open($Path) } catch { return $null } +} + +# Delete $Item. A reparse point loses only the link itself. A directory is +# pinned by a handle opened without delete sharing and checked for the reparse +# attribute on that handle, so it cannot be swapped for a link while its +# entries are enumerated and removed; the handle is released just before the +# final delete of the then empty directory (a link there is removed, never +# followed). Throws on the first failure. +function _Temp-Remove-NoFollow { + param($Item) + $path = $Item.FullName + if (_Temp-Is-Link-Now $path) { + if ($Item.PSIsContainer) { + try { [IO.Directory]::Delete($path, $false); return } catch {} + } + [IO.File]::Delete($path) + return + } + if ($Item.PSIsContainer) { + $handle = _Temp-Open-Dir $path + if ($null -eq $handle) { throw "$path is a link or cannot be pinned" } + try { + foreach ($child in @(Get-ChildItem -LiteralPath $path -Force -ErrorAction SilentlyContinue)) { + if (_Temp-Is-Link-Now $path) { throw "$path became a link" } + try { _Temp-Remove-NoFollow $child } catch {} + } + } finally { + if ($handle -is [IDisposable]) { $handle.Dispose() } + } + if (_Temp-Is-Link-Now $path) { throw "$path became a link" } + [IO.Directory]::Delete($path, $false) + return + } + # File APIs act on the name given and never follow a link swapped in for it. + $attributes = [IO.File]::GetAttributes($path) + if ($attributes -band [IO.FileAttributes]::ReadOnly) { + [IO.File]::SetAttributes($path, ($attributes -band (-bnot [IO.FileAttributes]::ReadOnly))) + } + [IO.File]::Delete($path) +} + +# Empty the temp folders after a prompt (-y says yes) and add what was freed +# to SUMMARY_FREED_KB. Entries that cannot be removed are skipped. +function Clean-Temp { + UI-Title 'Temp folders' + $paths = @($env:TEMP, (Join-Path $env:LOCALAPPDATA 'Temp'), (Join-Path $env:SystemRoot 'Temp')) | + Where-Object { $_ } | Select-Object -Unique + $before = 0 + foreach ($path in $paths) { $before += (_Temp-Folder-Size-KB $path) } + # Below 52 KiB the size prints as 0.0MB. + if ($before -lt 52) { UI-Ok 'already clean'; return } + UI-Muted ($paths -join ', ') + + if (-not (UI-Confirm 'Clean temp folders?' 'n' "($(Size-Format-KB $before))")) { UI-Muted 'skipped'; return } + if ($script:ArgsGlobal.DryRun) { UI-Sub '[dry-run] would clean temp folders'; return } + + $stopwatch = [Diagnostics.Stopwatch]::StartNew() + foreach ($path in $paths) { + if (-not (Test-Path -LiteralPath $path)) { continue } + foreach ($item in @(Get-ChildItem -LiteralPath $path -Force -ErrorAction SilentlyContinue)) { + try { _Temp-Remove-NoFollow $item } catch {} + } + } + $after = 0 + foreach ($path in $paths) { $after += (_Temp-Folder-Size-KB $path) } + $freed = [math]::Max([int64]0, [int64]($before - $after)) + $script:SUMMARY_FREED_KB += $freed + $script:UI_LAST_ELAPSED = UI-Format-Elapsed $stopwatch.Elapsed + UI-Done 'temp cleaned' (Size-Format-KB $freed) +} diff --git a/src/pslib/managers/Packages.ps1 b/src/pslib/managers/Packages.ps1 new file mode 100644 index 0000000..66b7723 --- /dev/null +++ b/src/pslib/managers/Packages.ps1 @@ -0,0 +1,213 @@ +# Windows package manager registry and dispatcher. + +# System managers in run order. +$script:PKG_MANAGERS = @( + 'winget','scoop','choco','wsl','PSWindowsUpdate' +) +# Dev toolchains, run after the system managers with --dev. +$script:PKG_DEV = @('rustup','cargo','npm','pnpm','pip','gem') + +# Return $true when manager $Manager needs an elevated process. +function Pkg-Need-Admin { + param([string]$Manager) + return @('choco','PSWindowsUpdate','wsl') -contains $Manager +} + +# Return $true when manager $Manager can install security updates alone, which +# is what --security runs. Only PSWindowsUpdate can, every other manager is skipped. +function Pkg-Has-Security { + param([string]$Manager) + return $Manager -eq 'PSWindowsUpdate' +} + +# Return $true when manager $Manager is installed (cargo also needs +# cargo-install-update). +function Pkg-Detect { + param([string]$Manager) + switch ($Manager) { + 'winget' { return (Sys-Has winget) } + 'scoop' { return (Sys-Has scoop) } + 'choco' { return (Sys-Has choco) } + 'wsl' { return (Sys-Has wsl) } + 'PSWindowsUpdate' { return [bool](Get-Module -ListAvailable PSWindowsUpdate -ErrorAction SilentlyContinue) } + 'rustup' { return (Sys-Has rustup) } + 'cargo' { return (Sys-Has cargo) -and (Sys-Has cargo-install-update) } + 'npm' { return (Sys-Has npm) } + 'pnpm' { return (Sys-Has pnpm) } + 'pip' { return (Sys-Has pip) } + 'gem' { return (Sys-Has gem) } + default { return $false } + } +} + +# Return the detected managers in run order, the dev toolchains too with +# -IncludeDev. +function Pkg-Detect-All { + param([switch]$IncludeDev) + $out = @() + foreach ($manager in $script:PKG_MANAGERS) { if (Pkg-Detect $manager) { $out += $manager } } + if ($IncludeDev) { foreach ($manager in $script:PKG_DEV) { if (Pkg-Detect $manager) { $out += $manager } } } + return ,$out +} + +# Return the section icon of manager $Manager: an emoji, a Unicode mark or an +# ASCII bullet, as the console allows. +function Pkg-Icon { + param([string]$Manager) + if ($script:UI_HAS_EMOJI) { + $codePoint = switch ($Manager) { + 'winget' { 0x1F4E6 } + 'scoop' { 0x1F944 } + 'choco' { 0x1F36B } + 'wsl' { 0x1F427 } + 'PSWindowsUpdate' { 0x1FA9F } + 'rustup' { 0x1F980 } + 'cargo' { 0x1F980 } + 'npm' { 0x1F4D7 } + 'pnpm' { 0x1F4D7 } + 'pip' { 0x1F40D } + 'gem' { 0x1F48E } + default { 0x2022 } + } + return [char]::ConvertFromUtf32($codePoint) + } + if ($script:UI_HAS_UNICODE) { + if (@('winget','msstore','scoop') -contains $Manager) { return [string][char]0x25A3 } + if ($script:PKG_DEV -contains $Manager) { return [string][char]0x03BB } + return [string][char]0x25C6 + } + return (UI-Glyph bullet) +} + +# Return the managers of $Detected this run updates, in order: --only and --except +# applied (case-sensitive) and, under --security, only those with a security +# channel. Each skip is reported. +function Pkg-Select { + param([string[]]$Detected) + $onlyNames = @(); if ($script:ArgsGlobal.Only) { $onlyNames = $script:ArgsGlobal.Only -split ',' | ForEach-Object { $_.Trim() } } + $exceptNames = @(); if ($script:ArgsGlobal.Except) { $exceptNames = $script:ArgsGlobal.Except -split ',' | ForEach-Object { $_.Trim() } } + + $filtered = @() + foreach ($manager in $Detected) { + if ($onlyNames.Count -gt 0 -and ($onlyNames -cnotcontains $manager)) { continue } + if ($exceptNames.Count -gt 0 -and ($exceptNames -ccontains $manager)) { UI-Muted "skip $manager (--except)"; continue } + if ($script:ArgsGlobal.Security -and -not (Pkg-Has-Security $manager)) { + UI-Warn "skip ${manager}: no security-only updates, --security never runs a full upgrade" + Log-Warn "$manager skipped: no security channel" + continue + } + $filtered += $manager + } + return ,$filtered +} + +# Count the installed choco packages, the total for "choco upgrade all". +function _Pkg-Choco-Count { + $root = $env:ChocolateyInstall + if (-not $root -and $env:ProgramData) { $root = Join-Path $env:ProgramData 'chocolatey' } + if (-not $root) { return 0 } + $lib = Join-Path $root 'lib' + if (-not (Test-Path $lib)) { return 0 } + return @(Get-ChildItem $lib -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -notmatch '\.(lock|bkp)$|^\.' }).Count +} + +# Run Windows Update through PSWindowsUpdate, security updates alone under +# --security. Installs and accepts each update's EULA only with +# --accept-licenses, otherwise lists them. Return $true on success. +function _Pkg-Run-WindowsUpdate { + # Child process runs the block, so build it as text. + $label = 'Windows Update' + $category = '' + if ($script:ArgsGlobal.Security) { $label = 'Windows Update (security)'; $category = " -Category 'Security Updates'" } + # -AcceptAll accepts each update's EULA: only on request, else list. + $install = '' + if ($script:ArgsGlobal.AcceptLicenses) { $install = ' -AcceptAll -Install -IgnoreReboot' } + $updateBlock = [scriptblock]::Create( + "Import-Module PSWindowsUpdate -ErrorAction Stop`n" + + "`$errorsBefore = `$Error.Count`n" + + "Get-WindowsUpdate$install -Confirm:`$false -Verbose$category`n" + + # Failed updates are non-terminating errors, the exit code stays 0. + "if (`$Error.Count -gt `$errorsBefore) { `$global:LASTEXITCODE = 1 }") + $isOk = Run-Cmd $label $updateBlock + if (-not $script:ArgsGlobal.AcceptLicenses) { + UI-Muted 'updates not installed: they may need licence agreement, run with --accept-licenses' + } + return $isOk +} + +# Upgrade each outdated pip package for the user, in a child PowerShell. A +# failing package fails the step without stopping the others. +function _Pkg-Run-Pip { + return (Run-Cmd 'pip upgrade outdated' { + $raw = (pip list --outdated --format=json 2>$null) -join '' + $outdated = @() + if ($raw) { $outdated = @($raw | ConvertFrom-Json) } + if ($outdated.Count -eq 0) { 'nothing to upgrade'; return } + $i = 0; $failCount = 0 + foreach ($package in $outdated) { + $i++ + "[$i/$($outdated.Count)] $($package.name)" + pip install --user -U $package.name 2>&1 | ForEach-Object { "$_" } + if ($LASTEXITCODE -ne 0) { $failCount++ } + } + $global:LASTEXITCODE = [int]($failCount -gt 0) + }) +} + +# Packages changed so far in this run, for the summary. +$script:PKG_CHANGED = 0 + +# Run every step of manager $Manager under its section header and log the +# result. Return $true when all steps succeeded. +function Pkg-Run { + param([string]$Manager) + $script:PKG_CURRENT = $Manager + UI-Section (Pkg-Icon $Manager) $Manager (Estimate-Read $Manager) + Log-Info "starting $Manager" + $isOk = $true + switch ($Manager) { + 'winget' { + $isOk = (Run-Cmd 'winget source update' -Exe winget -ArgList @('source','update','--disable-interactivity') -AnyExit) -and $isOk + # Upgrading can mean agreeing to package and source licences: only on request. + if ($script:ArgsGlobal.AcceptLicenses) { + # 0x8A15002B: no applicable upgrade. + $isOk = (Run-Cmd 'winget upgrade --all' -Exe winget -OkCodes @(-1978335189) -ArgList @( + 'upgrade','--all','--include-unknown','--accept-package-agreements', + '--accept-source-agreements','--silent','--disable-interactivity')) -and $isOk + } else { + $isOk = (Run-Cmd 'winget upgrade' -Exe winget -AnyExit -ArgList @('upgrade','--include-unknown','--disable-interactivity')) -and $isOk + UI-Muted 'upgrades not installed: they may need licence agreement, run with --accept-licenses' + } + } + 'scoop' { + $isOk = (Run-Cmd 'scoop update' -Exe scoop -ArgList @('update')) -and $isOk + $isOk = (Run-Cmd 'scoop update *' -Exe scoop -ArgList @('update','*')) -and $isOk + $isOk = (Run-Cmd 'scoop cleanup *' -Exe scoop -ArgList @('cleanup','*')) -and $isOk + $isOk = (Run-Cmd 'scoop cache rm *' -Exe scoop -ArgList @('cache','rm','*')) -and $isOk + } + 'choco' { + # -y accepts package licences: upgrade only on request. No --limit-output, + # it hides the lines the progress parser counts. + if ($script:ArgsGlobal.AcceptLicenses) { + $isOk = (Run-Cmd 'choco upgrade all' -Exe choco -ArgList @('upgrade','all','-y') -Total (_Pkg-Choco-Count)) -and $isOk + } else { + # Exit code 2: outdated packages found. + $isOk = (Run-Cmd 'choco outdated' -Exe choco -OkCodes @(2) -ArgList @('outdated')) -and $isOk + UI-Muted 'upgrades not installed: they may need licence agreement, run with --accept-licenses' + } + } + 'wsl' { + $isOk = (Run-Cmd 'wsl --update' -Exe wsl -ArgList @('--update')) -and $isOk + } + 'PSWindowsUpdate' { $isOk = (_Pkg-Run-WindowsUpdate) -and $isOk } + 'rustup' { $isOk = (Run-Cmd 'rustup update' -Exe rustup -ArgList @('update')) -and $isOk } + 'cargo' { $isOk = (Run-Cmd 'cargo install-update -a' -Exe cargo -ArgList @('install-update','-a')) -and $isOk } + 'npm' { $isOk = (Run-Cmd 'npm -g update' -Exe npm -ArgList @('update','-g')) -and $isOk } + 'pnpm' { $isOk = (Run-Cmd 'pnpm -g update' -Exe pnpm -ArgList @('-g','update')) -and $isOk } + 'pip' { $isOk = (_Pkg-Run-Pip) -and $isOk } + 'gem' { $isOk = (Run-Cmd 'gem update' -Exe gem -ArgList @('update')) -and $isOk } + } + $script:PKG_CURRENT = '' + if ($isOk) { Log-Info "$Manager ok" } else { Log-Error "$Manager failed" } + return $isOk +} diff --git a/src/pslib/managers/Progress.ps1 b/src/pslib/managers/Progress.ps1 new file mode 100644 index 0000000..5f2f384 --- /dev/null +++ b/src/pslib/managers/Progress.ps1 @@ -0,0 +1,246 @@ +# Progress parsers for the Windows managers. Run-Cmd +# passes every output line (ANSI stripped) to Progress-Feed. Counters match at +# most 9 digits so every [int] cast fits: a longer one leaves the line unparsed. + +# Progress of the current or last step, $null before the first. Current of Total is +# the item counter, Percent the current item's percent (-1 unknown), Fraction +# the overall fraction when a parser knows better (-1 otherwise). +$script:PROGRESS_STATE = $null + +# Start progress tracking for manager $Manager, $Total items when known (0 if not). +function Progress-Reset { + param([string]$Manager, [int]$Total = 0) + $script:PROGRESS_STATE = @{ + Manager = $Manager; Total = $Total; Current = 0; Percent = -1; Fraction = -1 + Name = ''; DoneCount = 0; FailedCount = 0; DownloadedCount = 0; FinalText = ''; IsUpToDate = $false; HasAcceptedTotal = $false + } +} + +# Convert $Number in $Unit ("12.3" "MB", "58" "MiB") to bytes, 0 when $Number +# is not a number. +function _Progress-Bytes { + param([string]$Number, [string]$Unit) + $value = 0.0 + if (-not [double]::TryParse(($Number -replace ',', '.'), [Globalization.NumberStyles]::Float, [Globalization.CultureInfo]::InvariantCulture, [ref]$value)) { return 0 } + switch -Regex ($Unit) { + '^T' { return $value * 1TB } + '^G' { return $value * 1GB } + '^M' { return $value * 1MB } + '^K' { return $value * 1KB } + default { return $value } + } +} + +# Patterns of a "cur / max" byte pair, a percentage, a choco "Progress: N%" +# line and an "(i/N)" counter. A lookbehind keeps a number from starting inside +# a longer run, an atomic group stops the backtracking: all linear. +$script:PROGRESS_RX_BYTES = '(?[^\s.]+))[^%]*?)?(\d{1,3})%' +$script:PROGRESS_RX_COUNTER = '[\[(]\s*(\d{1,9})\s*/\s*(\d{1,9})\s*[\])]' + +# Return the percent done that $Line shows, from a "cur / max" byte pair or +# the last "N%": whole number 0 to 100, -1 when the line has neither. +function _Progress-Percent { + param([string]$Line) + if ($Line -match $script:PROGRESS_RX_BYTES) { + $current = _Progress-Bytes $Matches[1] $Matches[2] + $maximum = _Progress-Bytes $Matches[3] $Matches[4] + if ($maximum -gt 0) { return [math]::Min(100, [math]::Floor($current * 100 / $maximum)) } + } + $percents = [regex]::Matches($Line, $script:PROGRESS_RX_PERCENT) + if ($percents.Count -gt 0) { + $value = 0.0 + if ([double]::TryParse(($percents[$percents.Count - 1].Groups[1].Value -replace ',', '.'), [Globalization.NumberStyles]::Float, [Globalization.CultureInfo]::InvariantCulture, [ref]$value)) { + if ($value -le 100) { return [math]::Floor($value) } + } + } + return -1 +} + +# Update $Progress from winget line $Line ("N upgrades available.", "(i/N) +# Found Name [Id]", "12.0 MB / 58.3 MB"). Return what Progress-Feed returns. +function _Progress-Feed-Winget { + param($Progress, [string]$Line) + if ($Line -match '^\s*(\d{1,9}) upgrades? available') { $Progress.Total = [int]$Matches[1]; return '' } + if ($Line -match '^\s*(?:\((\d{1,9})/(\d{1,9})\)\s*)?Found (.+?) \[([^\]]+)\]') { + if ($Matches[1]) { $Progress.Current = [int]$Matches[1]; $Progress.Total = [int]$Matches[2] } + elseif ($Progress.Total -gt 0) { $Progress.Current = [math]::Min($Progress.Total, $Progress.Current + 1) } + $Progress.Name = $Matches[3].Trim(); $Progress.Percent = -1 + return $Progress.Name + } + if ($Line -match 'Successfully installed') { $Progress.DoneCount++; $Progress.Percent = 100; return "$($Progress.Name) installed" } + if ($Line -match 'Installer failed|failed with exit code|Installation failed') { $Progress.FailedCount++; return '' } + if ($Line -match 'Starting package install') { $Progress.Percent = 90; return "installing $($Progress.Name)" } + if ($Line -match '^\s*Downloading\s') { return "downloading $($Progress.Name)" } + if ($Line -match 'No (installed package found|available upgrade found|applicable upgrade)') { $Progress.IsUpToDate = $true; return '' } + $percent = _Progress-Percent $Line + if ($percent -ge 0) { + $Progress.Percent = $percent + if ($Progress.Name) { return "$($Progress.Name) $percent%" } + return '' + } + # winget's own spinner. + if ($Line -match '^\s*[-\\|/]\s*$') { return ' ' } + return '' +} + +# Update $Progress from choco line $Line ("You have X v1 installed. Version 2 +# is available", "Progress: 45%", "Chocolatey upgraded 2/45 packages."). Return +# what Progress-Feed returns. +function _Progress-Feed-Choco { + param($Progress, [string]$Line) + if ($Line -match 'You have (\S+) v(\S+) installed\. Version (\S+) is available') { + $Progress.Current++; $Progress.Name = $Matches[1]; $Progress.Percent = -1 + if ($Progress.Total -lt $Progress.Current) { $Progress.Total = $Progress.Current } + return "$($Matches[1]) $($Matches[2]) -> $($Matches[3])" + } + if ($Line -match '^\s*(\S+) v(\S+) is the latest version available') { + $Progress.Current++; $Progress.Percent = 100 + if ($Progress.Total -lt $Progress.Current) { $Progress.Total = $Progress.Current } + return "$($Matches[1]) up to date" + } + if ($Line -match $script:PROGRESS_RX_CHOCO) { + $Progress.Percent = [int]$Matches[2] + if ($Matches[1]) { $Progress.Name = $Matches[1] } + return "$($Progress.Name) $($Progress.Percent)%" + } + if ($Line -match 'The upgrade of (\S+) was successful') { $Progress.DoneCount++; $Progress.Percent = 100; return "$($Matches[1]) upgraded" } + if ($Line -match 'The upgrade of (\S+) was NOT successful') { $Progress.FailedCount++; return '' } + if ($Line -match 'Chocolatey upgraded (\d{1,9})/(\d{1,9}) packages') { + $Progress.DoneCount = [int]$Matches[1]; $Progress.Total = [int]$Matches[2]; $Progress.Current = $Progress.Total; $Progress.Percent = 100 + if ($Progress.DoneCount -gt 0) { $Progress.FinalText = "$($Progress.DoneCount) upgraded" } else { $Progress.FinalText = 'up to date' } + return '' + } + return '' +} + +# Update $Progress from scoop line $Line ("Updating N outdated apps:", +# "Updating 'x' (1 -> 2)", "'x' (2) was installed"). Return what Progress-Feed +# returns. +function _Progress-Feed-Scoop { + param($Progress, [string]$Line) + if ($Line -match 'Updating (\d{1,9}) outdated apps?') { $Progress.Total = [int]$Matches[1]; return '' } + if ($Line -match 'Updating one outdated app') { $Progress.Total = 1; return '' } + if ($Line -match "^\s*Updating '([^']+)' \(([^)]*)\)") { + $Progress.Name = $Matches[1]; $Progress.Percent = -1 + $Progress.Current++ + if ($Progress.Total -lt $Progress.Current) { $Progress.Total = $Progress.Current } + return "$($Matches[1]) $($Matches[2])" + } + if ($Line -match "^\s*Updating '([^']+)' bucket") { return "bucket $($Matches[1])" } + if ($Line -match "'([^']+)' \(([^)]*)\) was installed successfully") { $Progress.DoneCount++; $Progress.Percent = 100; return "$($Matches[1]) $($Matches[2]) installed" } + if ($Line -match 'Latest versions for all apps are installed') { $Progress.IsUpToDate = $true; return '' } + $percent = _Progress-Percent $Line + if ($percent -ge 0) { $Progress.Percent = $percent; if ($Progress.Name) { return "$($Progress.Name) $percent%" } } + return '' +} + +# Update $Progress from PSWindowsUpdate line $Line: rows "1 PC Accepted +# KB5000001 ...", then Downloaded and Installed, with -Verbose also "Accepted +# [N] Updates". Return what Progress-Feed returns. +function _Progress-Feed-WindowsUpdate { + param($Progress, [string]$Line) + if ($Line -match 'Accepted \[(\d{1,9})\]') { $Progress.Total = [int]$Matches[1]; $Progress.HasAcceptedTotal = $true; return '' } + if ($Line -match 'Found \[(\d{1,9})\] Updates? in post search') { if ($Progress.Total -eq 0) { $Progress.Total = [int]$Matches[1] }; return '' } + # Result rows: X ComputerName Result KB Size Title. + if ($Line -match '^\s*\d?\s*[^\s\[\]:]+\s+(Accepted|Downloaded|Installed|Failed)\s+(KB\d+)?') { + $article = $Matches[2] + switch ($Matches[1]) { + 'Accepted' { if (-not $Progress.HasAcceptedTotal) { $Progress.Total++ } } + 'Downloaded' { $Progress.DownloadedCount++ } + 'Installed' { $Progress.DoneCount++ } + 'Failed' { $Progress.FailedCount++ } + } + if ($Progress.Total -gt 0) { + $Progress.Current = [math]::Min($Progress.Total, $Progress.DoneCount + $Progress.FailedCount) + $Progress.Fraction = [math]::Min(1.0, ($Progress.DownloadedCount + $Progress.DoneCount + $Progress.FailedCount) / (2 * $Progress.Total)) + } + return "$($Matches[1].ToLower()) $article".Trim() + } + $percent = _Progress-Percent $Line + if ($percent -ge 0) { $Progress.Percent = $percent } + return '' +} + +# Update $Progress from line $Line of any other manager: "[i/N] name" from the +# pip loop, "(i/N)" counters, NN%. Return what Progress-Feed returns. +function _Progress-Feed-Generic { + param($Progress, [string]$Line) + if ($Line -match '^\s*\[(\d{1,9})/(\d{1,9})\]\s*(.*)$') { + $Progress.Current = [int]$Matches[1]; $Progress.Total = [int]$Matches[2]; $Progress.Percent = -1; $Progress.Name = $Matches[3] + return $Matches[3] + } + if ($Line -match $script:PROGRESS_RX_COUNTER -and [int]$Matches[2] -gt 0 -and [int]$Matches[1] -le [int]$Matches[2]) { + $Progress.Current = [int]$Matches[1]; $Progress.Total = [int]$Matches[2] + } + $percent = _Progress-Percent $Line + if ($percent -ge 0) { $Progress.Percent = $percent } + if ($Line -match 'nothing to upgrade|already up.to.date|up to date') { $Progress.IsUpToDate = $true } + return '' +} + +# Feed output line $Line to the current manager's parser. Return the text +# to show instead, '' for the raw line, ' ' to hide it. +function Progress-Feed { + param([string]$Line) + $progress = $script:PROGRESS_STATE + if (-not $progress) { return '' } + switch ($progress.Manager) { + 'winget' { return (_Progress-Feed-Winget $progress $Line) } + 'choco' { return (_Progress-Feed-Choco $progress $Line) } + 'scoop' { return (_Progress-Feed-Scoop $progress $Line) } + 'PSWindowsUpdate' { return (_Progress-Feed-WindowsUpdate $progress $Line) } + default { return (_Progress-Feed-Generic $progress $Line) } + } +} + +# Return the short stat of the step's result line, '' when there is none. +function Progress-Summarize { + $progress = $script:PROGRESS_STATE + if (-not $progress) { return '' } + if ($progress.FinalText) { return $progress.FinalText } + switch ($progress.Manager) { + 'winget' { + if ($progress.DoneCount -gt 0 -or $progress.FailedCount -gt 0) { + $stat = "$($progress.DoneCount) upgraded" + if ($progress.FailedCount -gt 0) { $stat += ", $($progress.FailedCount) failed" } + return $stat + } + if ($progress.IsUpToDate) { return 'up to date' } + } + 'scoop' { + if ($progress.DoneCount -gt 0) { return "$($progress.DoneCount) updated" } + if ($progress.IsUpToDate) { return 'up to date' } + } + 'PSWindowsUpdate' { + if ($progress.DoneCount -gt 0 -or $progress.FailedCount -gt 0) { + $stat = "$($progress.DoneCount) installed" + if ($progress.FailedCount -gt 0) { $stat += ", $($progress.FailedCount) failed" } + return $stat + } + } + 'pip' { + if ($progress.Total -gt 0) { return "$($progress.Total) upgraded" } + if ($progress.IsUpToDate) { return 'up to date' } + } + default { + if ($progress.IsUpToDate) { return 'up to date' } + } + } + return '' +} + +# Return the number of packages the step changed, for the summary. +function Progress-Changed { + $progress = $script:PROGRESS_STATE + if (-not $progress) { return 0 } + switch ($progress.Manager) { + 'winget' { return $progress.DoneCount } + 'choco' { return $progress.DoneCount } + 'scoop' { return $progress.DoneCount } + 'PSWindowsUpdate' { return $progress.DoneCount } + 'pip' { return $progress.Total } + default { return 0 } + } +} diff --git a/src/pslib/state/Estimate.ps1 b/src/pslib/state/Estimate.ps1 new file mode 100644 index 0000000..5a20c12 --- /dev/null +++ b/src/pslib/state/Estimate.ps1 @@ -0,0 +1,21 @@ +# Step duration estimate from recent history.jsonl entries. + +# Read the average duration of manager $Manager over the last 10 runs from +# history.jsonl as "~42s", for the section header. Return '' without data. +function Estimate-Read { + param([string]$Manager) + $historyPath = Join-Path $script:EMERGER_STATE 'history.jsonl' + if (-not (Test-Path -LiteralPath $historyPath)) { return '' } + $seconds = @() + foreach ($line in (Get-Content -LiteralPath $historyPath -Tail 10 -ErrorAction SilentlyContinue)) { + try { + $record = $line | ConvertFrom-Json + foreach ($entry in $record.managers) { if ($entry.name -eq $Manager -and $entry.secs -gt 0) { $seconds += [double]$entry.secs } } + } catch {} + } + if ($seconds.Count -eq 0) { return '' } + # Round half up: an [int] cast rounds a .5 to even. + $average = [int][math]::Round(($seconds | Measure-Object -Average).Average, [MidpointRounding]::AwayFromZero) + if ($average -lt 60) { return "~${average}s" } + return ('~{0}m{1:00}s' -f [int][math]::Floor($average / 60), ($average % 60)) +} diff --git a/src/pslib/state/History.ps1 b/src/pslib/state/History.ps1 new file mode 100644 index 0000000..f03a56f --- /dev/null +++ b/src/pslib/state/History.ps1 @@ -0,0 +1,31 @@ +# Run history: the history.jsonl append and the --history viewer. + +# Append JSON line $Line to history.jsonl, keeping the last 500 lines. +function History-Append { + param([string]$Line) + $historyPath = Join-Path $script:EMERGER_STATE 'history.jsonl' + try { + Add-Content -LiteralPath $historyPath -Value $Line -ErrorAction Stop + # Rotate at 500 lines, read finished before the write (see Log-Init). + $count = (Get-Content -LiteralPath $historyPath | Measure-Object).Count + if ($count -gt 500) { (Get-Content -LiteralPath $historyPath -Tail 500) | Set-Content -LiteralPath $historyPath } + } catch {} +} + +# Print the last 10 runs of history.jsonl (--history). +function History-Show { + $historyPath = Join-Path $script:EMERGER_STATE 'history.jsonl' + if (-not (Test-Path -LiteralPath $historyPath)) { UI-Muted 'No history yet.'; return } + UI-Title 'Recent runs' + Get-Content -LiteralPath $historyPath -Tail 10 | ForEach-Object { + try { + $record = $_ | ConvertFrom-Json + $reboot = if ($record.reboot -eq 1) { ' ' + (UI-Color yellow 'reboot') } else { '' } + if ($record.errors -gt 0) { + Write-Host " $(UI-Color red (UI-Glyph cross)) $($record.ts) $($record.duration)s $(UI-Color yellow "errors=$($record.errors)")$reboot" + } else { + Write-Host " $(UI-Color green (UI-Glyph check)) $($record.ts) $($record.duration)s$reboot" + } + } catch {} + } +} diff --git a/src/pslib/state/Lock.ps1 b/src/pslib/state/Lock.ps1 new file mode 100644 index 0000000..b19c9b6 --- /dev/null +++ b/src/pslib/state/Lock.ps1 @@ -0,0 +1,52 @@ +# Per-user run lock, and the lock the elevated child holds. + +# Return the path of the per-user run lock. It lives in the user's own state directory, +# so a scheduled task in session 0 and an interactive run of the same user +# share it, and no other account can create it first. +function Lock-Path { + return (Join-Path $script:EMERGER_STATE 'run.lock') +} + +# Return the path of the lock the elevated child holds while its managers +# run, so an interrupted caller's child still blocks the next run. +function Lock-Elevated-Path { + return (Join-Path $script:EMERGER_STATE 'elevated.lock') +} + +# Open lock file $Path for exclusive use, creating it when missing. Return +# the open stream, or $null when another process holds it. Any other failure +# (missing directory, access denied) throws. +function Lock-Open { + param([string]$Path) + try { + return [IO.File]::Open($Path, [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) + } catch { + # Busy: Windows reports ERROR_SHARING_VIOLATION or ERROR_LOCK_VIOLATION + # (0x80070020, 0x80070021), Unix the flock's EWOULDBLOCK (11, 35 on macOS). + $cause = $_.Exception.GetBaseException() + if ($cause -is [IO.IOException]) { + if (@(11, 35, -2147024864, -2147024863) -contains $cause.HResult) { return $null } + } + throw + } +} + +# Take the per-user run lock without waiting. Return the held lock, or $null +# when another run holds it or an elevated child of an earlier run is still +# working. The OS releases it when the process dies. +function Lock-Acquire { + $lock = Lock-Open (Lock-Path) + if (-not $lock) { return $null } + try { $child = Lock-Open (Lock-Elevated-Path) } catch { $lock.Dispose(); throw } + if (-not $child) { $lock.Dispose(); return $null } + $child.Dispose() + return $lock +} + +# Release a lock returned by Lock-Acquire or Lock-Open ($null is a +# no-op). The file stays: deleting it would race with the next run's open. +function Lock-Release { + param($Lock) + if (-not $Lock) { return } + $Lock.Dispose() +} diff --git a/src/pslib/state/Metrics.ps1 b/src/pslib/state/Metrics.ps1 new file mode 100644 index 0000000..757feeb --- /dev/null +++ b/src/pslib/state/Metrics.ps1 @@ -0,0 +1,45 @@ +# Prometheus textfile export of the last run (--metrics). + +# Write the last history.jsonl record to $Path in the Prometheus text format, +# through a temp file beside it. Return 0, or 1 with a message when there is +# no history or its last line is empty or not a record. +function Metrics-Export { + param([string]$Path) + $historyPath = Join-Path $script:EMERGER_STATE 'history.jsonl' + if (-not (Test-Path -LiteralPath $historyPath)) { UI-Err "No history yet ($historyPath missing)"; return 1 } + $lastLine = "$(Get-Content -LiteralPath $historyPath -Tail 1)" + if (-not $lastLine.Trim()) { UI-Err "history.jsonl is empty"; return 1 } + try { + $last = $lastLine | ConvertFrom-Json + $epoch = [int64](([DateTime]$last.ts).ToUniversalTime() - [DateTime]'1970-01-01').TotalSeconds + } catch { UI-Err "last line of $historyPath is not a valid record"; return 1 } + # Random name beside the target, so nothing can be planted at it. + $tempPath = "$($Path).$([guid]::NewGuid().ToString('N')).tmp" + $out = @() + $out += "# HELP emerger_last_run_timestamp_seconds Unix timestamp of the last eMerger run" + $out += "# TYPE emerger_last_run_timestamp_seconds gauge" + $out += "emerger_last_run_timestamp_seconds $epoch" + $out += "# HELP emerger_last_run_duration_seconds Duration of the last run" + $out += "# TYPE emerger_last_run_duration_seconds gauge" + # Missing fields read 0. + $out += "emerger_last_run_duration_seconds $([int64]$last.duration)" + $out += "# HELP emerger_last_run_freed_bytes Bytes freed by the last run" + $out += "# TYPE emerger_last_run_freed_bytes gauge" + $out += "emerger_last_run_freed_bytes $([int64]$last.freed_kb * 1024)" + $out += "# HELP emerger_last_run_errors Manager failures in the last run" + $out += "# TYPE emerger_last_run_errors gauge" + $out += "emerger_last_run_errors $([int64]$last.errors)" + $out += "# HELP emerger_reboot_required Whether a reboot is pending (0/1)" + $out += "# TYPE emerger_reboot_required gauge" + $out += "emerger_reboot_required $([int64]$last.reboot)" + $out += "# HELP emerger_manager_ok Per-manager success in the last run (1=ok,0=fail)" + $out += "# TYPE emerger_manager_ok gauge" + foreach ($manager in $last.managers) { + $value = if ($manager.result -eq 'ok') { 1 } else { 0 } + $out += "emerger_manager_ok{manager=`"$($manager.name)`"} $value" + } + $out | Set-Content -LiteralPath $tempPath + Move-Item -Force -LiteralPath $tempPath -Destination $Path + UI-Ok "metrics written to $Path" + return 0 +} diff --git a/src/pslib/Notify.ps1 b/src/pslib/system/Notify.ps1 similarity index 56% rename from src/pslib/Notify.ps1 rename to src/pslib/system/Notify.ps1 index 7fdbd31..1fdceb5 100644 --- a/src/pslib/Notify.ps1 +++ b/src/pslib/system/Notify.ps1 @@ -1,13 +1,15 @@ # Best-effort desktop notification. Uses BurntToast if installed, otherwise no-op. +# Show a desktop notification with the run's result when BurntToast is +# installed, errors ignored. function Notify-Send-Result { if (-not (Get-Module -ListAvailable -Name BurntToast -ErrorAction SilentlyContinue)) { return } try { Import-Module BurntToast -ErrorAction Stop - $errors = @($script:Summary | Where-Object { $_.Result -eq 'fail' }).Count + $errors = Summary-Fail-Count $total = @($script:Summary).Count - $msg = if ($errors -gt 0) { "Finished with $errors error(s)." } + $message = if ($errors -gt 0) { "Finished with $errors error(s)." } else { "$total manager(s) updated." } - New-BurntToastNotification -Text 'eMerger', $msg -ErrorAction SilentlyContinue + New-BurntToastNotification -Text 'eMerger', $message -ErrorAction SilentlyContinue } catch {} } diff --git a/src/pslib/system/Preflight.ps1 b/src/pslib/system/Preflight.ps1 new file mode 100644 index 0000000..ce6158a --- /dev/null +++ b/src/pslib/system/Preflight.ps1 @@ -0,0 +1,61 @@ +# Checks before a run: battery and free disk space. + +# Return $true when any battery reports BatteryStatus 1 (discharging). +function Preflight-Is-On-Battery { + try { + foreach ($battery in @(Get-CimInstance -ClassName Win32_Battery -ErrorAction SilentlyContinue)) { + if ($battery.BatteryStatus -eq 1) { return $true } + } + } catch {} + return $false +} + +# Return the charge in percent, the floor of the average over every battery, +# or 100 when there is none or the query fails. +function Preflight-Battery-Percent { + try { + $batteries = @(Get-CimInstance -ClassName Win32_Battery -ErrorAction SilentlyContinue) + if ($batteries.Count -gt 0) { + return [int][math]::Floor(($batteries | Measure-Object -Property EstimatedChargeRemaining -Average).Average) + } + } catch {} + return 100 +} + +# Return the free space of the system drive in whole MiB, -1 when unknown. +function Preflight-Disk-Free-MB { + $drive = "$env:SystemDrive".TrimEnd(':') + if (-not $drive) { $drive = 'C' } + try { + $psDrive = Get-PSDrive $drive -ErrorAction Stop + return [int][math]::Floor($psDrive.Free / 1MB) + } catch { return -1 } +} + +# Ask before a run on battery below BATTERY_MIN_PCT, unless -y. Return $false +# when the answer is no. +function Preflight-Battery { + if (Preflight-Is-On-Battery) { + $percent = Preflight-Battery-Percent + if ($percent -lt $script:BATTERY_MIN_PCT -and -not $script:ArgsGlobal.Yes) { + UI-Warn "On battery at ${percent}%. Updates are I/O heavy." + if (-not (UI-Confirm 'Continue anyway?' 'n' "(${percent}% battery)")) { UI-Muted 'Aborted.'; return $false } + } + } + return $true +} + +# Ask before a run with less than DISK_MIN_FREE_MB free on the system drive, +# unless -y. Return $false when the answer is no. An unknown free space passes. +function Preflight-Disk { + $freeMb = Preflight-Disk-Free-MB + if ($freeMb -ge 0 -and $freeMb -lt $script:DISK_MIN_FREE_MB) { + UI-Warn "Low disk space on the system drive (${freeMb}MB free, threshold $($script:DISK_MIN_FREE_MB)MB)." + if (-not $script:ArgsGlobal.Yes) { + if (-not (UI-Confirm 'Continue anyway?' 'n')) { UI-Muted 'Aborted by user.'; return $false } + } + } elseif ($freeMb -ge 0) { + Log-Info "disk precheck ok: ${freeMb}MB free" + } + return $true +} diff --git a/src/pslib/system/Reboot.ps1 b/src/pslib/system/Reboot.ps1 new file mode 100644 index 0000000..f7ec8a8 --- /dev/null +++ b/src/pslib/system/Reboot.ps1 @@ -0,0 +1,23 @@ +# Pending reboot detection and the reboot advisory. + +# Return $true when any registry key Windows sets for a pending reboot exists. +function Reboot-Pending { + # Several signals can indicate a pending reboot on Windows. + $keys = @( + 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending', + 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired', + 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations' + ) + foreach ($key in $keys) { + if (Test-Path $key) { return $true } + } + return $false +} + +# Print the reboot advice when a reboot is pending. +function Reboot-Advisory { + if (Reboot-Pending) { + Write-Host ("`n " + (UI-Color 'bold yellow' "$(UI-Glyph warn) Reboot recommended") + ' ' + (UI-Color 'dim gray' '(pending updates require restart)')) + Write-Host (" " + (UI-Color 'dim gray' 'run:') + ' Restart-Computer') + } +} diff --git a/src/pslib/ui/Monitor.ps1 b/src/pslib/ui/Monitor.ps1 new file mode 100644 index 0000000..4d3507d --- /dev/null +++ b/src/pslib/ui/Monitor.ps1 @@ -0,0 +1,157 @@ +# Live monitor of the Windows UI: spinner, wave, progress bar. +# Keep this file ASCII: PowerShell 5.1 reads BOM-less files as ANSI, so +# glyphs are built from code points. + +# Return the spinner frames of EMERGER_SPINNER (dots, line, pulse, braille), +# braille by default on a modern Unicode console, pulse otherwise. +function _UI-Spinner-Frames { + $style = "$env:EMERGER_SPINNER".ToLower() + if (-not $style) { + # conhost can't draw braille. + if ($script:UI_HAS_UNICODE -and $script:UI_IS_MODERN) { $style = 'braille' } else { $style = 'pulse' } + } + if (-not $script:UI_HAS_UNICODE -and $style -ne 'line') { $style = 'pulse' } + switch ($style) { + 'dots' { return @(0x2801, 0x2808, 0x2810, 0x2820, 0x2880, 0x2840, 0x2804, 0x2802 | ForEach-Object { _UI-Char $_ }) } + 'line' { return @('|', '/', '-', '\') } + 'pulse' { return @('. ', '.. ', '.:.', ':::', ' ::', ' :', ' ', ' .', ' ..', '.:.', ':::', ':: ', ': ', ' ') } + default { return @(0x2809, 0x2818, 0x2830, 0x28A0, 0x28C0, 0x2844, 0x2806, 0x2803 | ForEach-Object { _UI-Char $_ }) } + } +} + +# Return the frames of ".:::." bouncing across 8 columns, for steps with no +# known progress. +function _UI-Wave-Frames { + $track = 8; $shape = '.:::.' + $frames = New-Object System.Collections.Generic.List[string] + for ($position = - $shape.Length + 1; $position -lt $track; $position++) { + $line = (' ' * $track).ToCharArray() + for ($offset = 0; $offset -lt $shape.Length; $offset++) { + $column = $position + $offset + if ($column -ge 0 -and $column -lt $track) { $line[$column] = $shape[$offset] } + } + $frames.Add((-join $line)) + } + for ($i = $frames.Count - 2; $i -gt 0; $i--) { $frames.Add($frames[$i]) } + return $frames.ToArray() +} + +# Return the 10-column bar of $Fraction, clamped to 0..1. Unicode fills in +# eighths of a cell. +function UI-Bar { + param([double]$Fraction) + if ($Fraction -lt 0) { $Fraction = 0 } + if ($Fraction -gt 1) { $Fraction = 1 } + $width = 10 + if ($script:UI_HAS_UNICODE) { + $eighths = [int][math]::Floor($Fraction * $width * 8) + $full = [int][math]::Floor($eighths / 8); $remainder = $eighths % 8 + $bar = (_UI-Char 0x2588) * $full + $used = $full + if ($remainder -gt 0 -and $full -lt $width) { $bar += (_UI-Char (0x2590 - $remainder)); $used++ } + $empty = ' ' * ($width - $used) + return (UI-Color 'dim gray' (_UI-Char 0x2595)) + (UI-Color green $bar) + $empty + (UI-Color 'dim gray' (_UI-Char 0x258F)) + } + $full = [int][math]::Floor($Fraction * $width) + return (UI-Color 'dim gray' '[') + (UI-Color green ('#' * $full)) + (UI-Color 'dim gray' ('.' * ($width - $full))) + (UI-Color 'dim gray' ']') +} + +# State of the live monitor, $null when stopped. Run-Cmd calls +# UI-Monitor-Frame every ~100 ms while it polls the child process, progress +# comes from PROGRESS_STATE. +$script:UI_MONITOR = $null + +# Start the live monitor for step $Label, $Hint in parentheses after it. It +# draws only on a console, not quiet and not verbose, else prints the label once. +function UI-Monitor-Start { + param([string]$Label, [string]$Hint) + $stopwatch = [Diagnostics.Stopwatch]::StartNew() + $isLive = ($script:QUIET_LEVEL -lt 2) -and -not $script:UI_VERBOSE -and $script:UI_IS_TTY + $script:UI_MONITOR = @{ + Label = $Label; Hint = $Hint; Stopwatch = $stopwatch; FrameCount = 0; IsLive = $isLive; LastText = ''; Width = (UI-Width) + SpinnerFrames = (_UI-Spinner-Frames); WaveFrames = (_UI-Wave-Frames) + } + if ($script:QUIET_LEVEL -lt 2 -and -not $isLive) { UI-Sub $Label } + if ($isLive) { UI-Cursor-Hide } +} + +# Redraw the monitor line: spinner, label, progress bar or wave, counter, +# elapsed time and the last output text. +function UI-Monitor-Frame { + $monitor = $script:UI_MONITOR + if (-not $monitor -or -not $monitor.IsLive) { return } + if ($monitor.FrameCount % 16 -eq 0) { $monitor.Width = UI-Width } + $elapsed = [int][math]::Floor($monitor.Stopwatch.Elapsed.TotalSeconds) + $progress = $script:PROGRESS_STATE + + $progressText = '' + $fraction = -1 + if ($progress) { + if ($progress.Fraction -ge 0) { $fraction = $progress.Fraction } + elseif ($progress.Total -gt 0) { + # Cur is the item in progress, Pct its own percentage. + $doneItems = [math]::Max(0, $progress.Current - 1) + if ($progress.Percent -ge 0 -and $progress.Current -gt 0) { $doneItems += $progress.Percent / 100 } + $fraction = $doneItems / $progress.Total + } + elseif ($progress.Percent -ge 0) { $fraction = $progress.Percent / 100 } + if ($progress.Total -gt 0) { $progressText = "$($progress.Current)/$($progress.Total)" } + elseif ($progress.Percent -ge 0) { $progressText = "$([int]$progress.Percent)%" } + elseif ($fraction -ge 0) { $progressText = "$([int]($fraction * 100))%" } + } + if ($fraction -ge 0) { + $animation = (UI-Bar $fraction) + $animationWidth = 12 + } else { + $animation = UI-Color cyan $monitor.WaveFrames[$monitor.FrameCount % $monitor.WaveFrames.Count] + $animationWidth = 8 + } + + $frame = $monitor.SpinnerFrames[$monitor.FrameCount % $monitor.SpinnerFrames.Count] + if ($script:UI_GRADIENT.Count -gt 0) { + $spinColor = "$($script:UI_ESC)[38;5;$($script:UI_GRADIENT[[int][math]::Floor($monitor.FrameCount / 2) % $script:UI_GRADIENT.Count])m$($script:UI_PALETTE.bold)" + $spinner = "$spinColor$frame$($script:UI_PALETTE.reset)" + } else { $spinner = UI-Color 'bold cyan' $frame } + + $hintColored = '' + if ($monitor.Hint) { $hintColored = ' ' + (UI-Color 'dim gray' "($($monitor.Hint))") } + $time = '{0}:{1:00}' -f [int][math]::Floor($elapsed / 60), ($elapsed % 60) + $progressColored = '' + if ($progressText) { $progressColored = ' ' + (UI-Color bold $progressText) } + + $maxShown = $monitor.Width - 4 - $frame.Length - 1 - $monitor.Label.Length - (UI-Visible-Length $hintColored) - 2 - $animationWidth - (UI-Visible-Length $progressColored) - 2 - $time.Length - 2 - 1 + if ($maxShown -lt 0) { $maxShown = 0 } + $shown = $monitor.LastText + if ($shown.Length -gt $maxShown) { $shown = $shown.Substring(0, $maxShown) } + + $line = " $spinner " + (UI-Color bold $monitor.Label) + $hintColored + " $animation$progressColored " + (UI-Color gray $time) + ' ' + (UI-Color 'dim gray' $shown) + if ($script:UI_HAS_VT) { + [Console]::Write("`r$($script:UI_ESC)[K$line") + } else { + $plain = UI-Strip $line + if ($plain.Length -lt $monitor.Width - 1) { $plain = $plain.PadRight($monitor.Width - 1) } + [Console]::Write("`r$plain") + } + $monitor.FrameCount++ +} + +# Set the output text the monitor line shows next. +function UI-Monitor-Text { + param([string]$Text) + if ($script:UI_MONITOR) { $script:UI_MONITOR.LastText = ($Text -replace '\t', ' ').Trim() } +} + +# Stop the monitor, record its elapsed time for UI-Done or UI-Fail and clear +# the line. +function UI-Monitor-Stop { + $monitor = $script:UI_MONITOR + if (-not $monitor) { return } + $monitor.Stopwatch.Stop() + $script:UI_LAST_ELAPSED = UI-Format-Elapsed $monitor.Stopwatch.Elapsed + if ($monitor.IsLive) { + if ($script:UI_HAS_VT) { [Console]::Write("`r$($script:UI_ESC)[K") } + else { [Console]::Write("`r" + (' ' * ($monitor.Width - 1)) + "`r") } + UI-Cursor-Show + } + $script:UI_MONITOR = $null +} diff --git a/src/pslib/ui/Print.ps1 b/src/pslib/ui/Print.ps1 new file mode 100644 index 0000000..f5e7700 --- /dev/null +++ b/src/pslib/ui/Print.ps1 @@ -0,0 +1,165 @@ +# Message printers of the Windows UI: sections, status lines, logo, +# header, box. + +# Step counter the next section header shows, 0 for none. +$script:UI_STEP_INDEX = 0 +$script:UI_STEP_TOTAL = 0 + +# Print a horizontal rule at header width. +function UI-Rule { + if ($script:QUIET_LEVEL -ge 2) { return } + $width = _UI-Columns + Write-Host (" " + (UI-Color 'dim gray' ((UI-Glyph hline) * ($width - 2)))) +} + +# Set the step counter the next section header shows to $Index of $Total. +# $Text, the step's name, is not shown. +function UI-Step { + param([int]$Index, [int]$Total, [string]$Text) + $script:UI_STEP_INDEX = $Index + $script:UI_STEP_TOTAL = $Total +} + +# Print the header of section $Name with $Icon, $Note and the pending step +# counter: apt ~42s ---------------- ##. 1/3 +function UI-Section { + param([string]$Icon, [string]$Name, [string]$Note) + if ($script:QUIET_LEVEL -ge 2) { $script:UI_STEP_TOTAL = 0; return } + if (-not $Icon) { $Icon = UI-Glyph arrow } + $width = _UI-Columns + $left = " $Icon $Name" + if ($Note) { $left += " $Note" } + + $right = ''; $rightColored = '' + if ($script:UI_STEP_TOTAL -gt 0) { + $bar = '' + if ($script:UI_STEP_TOTAL -le 12) { + for ($i = 1; $i -le $script:UI_STEP_TOTAL; $i++) { + if ($i -le $script:UI_STEP_INDEX) { $bar += (UI-Glyph pfull) } else { $bar += (UI-Glyph pempty) } + } + $bar += ' ' + } + $counter = "$($script:UI_STEP_INDEX)/$($script:UI_STEP_TOTAL)" + $right = " $bar$counter" + $rightColored = ' ' + (UI-Color magenta $bar) + (UI-Color 'bold magenta' $counter) + $script:UI_STEP_INDEX = 0; $script:UI_STEP_TOTAL = 0 + } + + $fill = $width - (UI-Visible-Length $left) - (UI-Visible-Length $right) - 2 + if ($fill -lt 3) { $fill = 3 } + $out = "`n " + (UI-Color 'bold cyan' $Icon) + ' ' + (UI-Color bold $Name) + if ($Note) { $out += ' ' + (UI-Color 'dim gray' $Note) } + $out += ' ' + (UI-Color 'dim gray' ((UI-Glyph hline) * $fill)) + $rightColored + Write-Host $out +} + +# Print a section header with the default icon. +function UI-Title { param([string]$Text) UI-Section '' $Text } + +# Write $Line to stderr. +function _UI-Err-Line { param([string]$Line) [Console]::Error.WriteLine($Line) } + +# Print status line $Text. Info, Ok, Muted and Sub go to stdout and follow the +# quiet level, Warn and Err go to stderr and always show. +function UI-Info { param([string]$Text) if ($script:QUIET_LEVEL -lt 2) { Write-Host (" " + (UI-Color blue (UI-Glyph info)) + " $Text") } } +function UI-Ok { param([string]$Text) if ($script:QUIET_LEVEL -lt 2) { Write-Host (" " + (UI-Color green (UI-Glyph check)) + " $Text") } } +function UI-Warn { param([string]$Text) _UI-Err-Line (" " + (UI-Color yellow (UI-Glyph warn)) + " $Text") } +function UI-Err { param([string]$Text) _UI-Err-Line (" " + (UI-Color 'bold red' (UI-Glyph cross)) + " $Text") } +function UI-Muted { param([string]$Text) if ($script:QUIET_LEVEL -lt 1) { Write-Host (" " + (UI-Color 'dim gray' $Text)) } } +function UI-Sub { param([string]$Text) if ($script:QUIET_LEVEL -lt 1) { Write-Host (" " + (UI-Color gray (UI-Glyph dot)) + " $Text") } } + +# Return the dot leader after $Label, so the results line up. +function _UI-Leader { + param([string]$Label) + $count = 26 - (UI-Visible-Length $Label) + if ($count -lt 2) { $count = 2 } + return ((UI-Glyph dot) * $count) +} + +# Print the success line of step $Label: elapsed time of the last monitored +# step and $Stat after the dot leader. +function UI-Done { + param([string]$Label, [string]$Stat) + $elapsed = $script:UI_LAST_ELAPSED + $script:UI_LAST_ELAPSED = '' + if ($script:QUIET_LEVEL -ge 2) { return } + $out = " " + (UI-Color green (UI-Glyph check)) + " $Label " + (UI-Color 'dim gray' (_UI-Leader $Label)) + if ($elapsed) { $out += ' ' + (UI-Color gray ('{0,6}' -f $elapsed)) } + if ($Stat) { $out += ' ' + (UI-Color cyan $Stat) } + Write-Host $out +} + +# Print the failure line of step $Label with exit code $Rc to stderr. +function UI-Fail { + param([string]$Label, [string]$Rc = '1') + $elapsed = $script:UI_LAST_ELAPSED + $script:UI_LAST_ELAPSED = '' + $out = " " + (UI-Color 'bold red' (UI-Glyph cross)) + ' ' + (UI-Color red $Label) + ' ' + (UI-Color 'dim gray' (_UI-Leader $Label)) + if ($elapsed) { $out += ' ' + (UI-Color gray ('{0,6}' -f $elapsed)) } + $out += ' ' + (UI-Color red "exit $Rc") + _UI-Err-Line $out +} + +# Print output lines $Lines under a failed step, errors and warnings coloured. +function UI-Fail-Tail { + param([string[]]$Lines) + $bar = UI-Color 'dim gray' (UI-Glyph v) + foreach ($line in $Lines) { + $shown = $line + if ($script:UI_HAS_COLOR) { + $shown = [regex]::Replace($shown, '(ERROR|Error|error|FAILED|Failed|failed)', { param($match) (UI-Color red $match.Value) }) + $shown = [regex]::Replace($shown, '(WARNING|Warning|warning|WARN)', { param($match) (UI-Color yellow $match.Value) }) + } + _UI-Err-Line " $bar $shown" + } +} + +# Print the logo at $Path in the UI gradient. Skipped when quiet, narrower +# than 64 columns or without Unicode. +function UI-Logo { + param([string]$Path) + if ($script:QUIET_LEVEL -ge 1) { return } + if (-not (Test-Path -LiteralPath $Path)) { return } + if ((UI-Width) -lt 64) { return } + # Block characters, no point in ASCII mode. + if (-not $script:UI_HAS_UNICODE) { return } + $lines = [IO.File]::ReadAllLines($Path, [Text.Encoding]::UTF8) + $gradientCount = $script:UI_GRADIENT.Count + $out = New-Object System.Text.StringBuilder + [void]$out.Append("`n") + for ($i = 0; $i -lt $lines.Count; $i++) { + if ($gradientCount -gt 0) { + [void]$out.Append(" $($script:UI_ESC)[38;5;$($script:UI_GRADIENT[$i % $gradientCount])m$($script:UI_PALETTE.bold)$($lines[$i])$($script:UI_PALETTE.reset)`n") + } else { + [void]$out.Append(' ' + (UI-Color 'bold green' $lines[$i]) + "`n") + } + } + Write-Host $out.ToString() +} + +# Print the system info line under the logo, $Items separated by dots. +function UI-Header { + param([string[]]$Items) + if ($script:QUIET_LEVEL -ge 1) { return } + $separator = ' ' + (UI-Color 'dim gray' (UI-Glyph dot)) + ' ' + $parts = @($Items | Where-Object { $_ }) + Write-Host (' ' + (UI-Color cyan (UI-Glyph diamond)) + ' ' + ($parts -join $separator)) +} + +# Print $Lines in a rounded box of colour $Color, $Title in the top border. +function UI-Box { + param([string]$Title, [string[]]$Lines, [string]$Color = 'cyan') + if ($script:QUIET_LEVEL -ge 3) { return } + $hline = UI-Glyph hline; $vline = UI-Glyph v + $inner = $Title.Length + 4 + foreach ($line in $Lines) { $width = (UI-Visible-Length $line) + 2; if ($width -gt $inner) { $inner = $width } } + if ($inner -lt 44) { $inner = 44 } + $out = "`n " + (UI-Color $Color ((UI-Glyph tl) + $hline)) + ' ' + (UI-Color bold $Title) + ' ' + + (UI-Color $Color (($hline * ($inner - $Title.Length - 3)) + (UI-Glyph tr))) + "`n" + foreach ($line in $Lines) { + $padding = ' ' * ($inner - 2 - (UI-Visible-Length $line)) + $out += ' ' + (UI-Color $Color $vline) + " $line$padding " + (UI-Color $Color $vline) + "`n" + } + $out += ' ' + (UI-Color $Color ((UI-Glyph bl) + ($hline * $inner) + (UI-Glyph br))) + Write-Host $out +} diff --git a/src/pslib/ui/Prompt.ps1 b/src/pslib/ui/Prompt.ps1 new file mode 100644 index 0000000..3fa34fb --- /dev/null +++ b/src/pslib/ui/Prompt.ps1 @@ -0,0 +1,61 @@ +# Yes/no prompt of the Windows UI. + +# Ask yes/no question $Prompt, $Detail after it, and return $true for yes. -y +# says yes without asking. With no console $Default answers, otherwise it +# answers after EMERGER_PROMPT_TIMEOUT seconds (0 = forever). +function UI-Confirm { + param([string]$Prompt, [string]$Default = 'n', [string]$Detail) + if ($script:ArgsGlobal -and $script:ArgsGlobal.Yes) { return $true } + $isDefaultYes = $Default -match '^[Yy]' + $hint = if ($isDefaultYes) { 'Y/n' } else { 'y/N' } + + $isInteractive = $true + try { if ([Console]::IsInputRedirected) { $isInteractive = $false } } catch { $isInteractive = $false } + if ($isInteractive) { try { $null = [Console]::KeyAvailable } catch { $isInteractive = $false } } + if (-not $isInteractive) { + UI-Muted "no terminal for `"$Prompt`", using default ($Default)" + return $isDefaultYes + } + + $question = " " + (UI-Color 'bold magenta' (UI-Glyph ask)) + ' ' + (UI-Color bold $Prompt) + if ($Detail) { $question += ' ' + (UI-Color 'dim gray' $Detail) } + $question += ' ' + (UI-Color gray "[$hint]") + ' ' + Write-Host $question -NoNewline + + $timeout = 60 + if ("$env:EMERGER_PROMPT_TIMEOUT" -match '^\d+$') { $timeout = [int]$env:EMERGER_PROMPT_TIMEOUT } + $answer = '' + if ($timeout -le 0) { + $answer = [Console]::ReadLine() + if ($null -eq $answer) { $answer = '' } + } else { + $deadline = [DateTime]::UtcNow.AddSeconds($timeout) + $typed = New-Object System.Text.StringBuilder + $isDone = $false + while (-not $isDone) { + if ([Console]::KeyAvailable) { + $key = [Console]::ReadKey($true) + if ($key.Key -eq 'Enter') { $isDone = $true; break } + if ($key.Key -eq 'Backspace') { + if ($typed.Length -gt 0) { [void]$typed.Remove($typed.Length - 1, 1); [Console]::Write("`b `b") } + continue + } + if ([int]$key.KeyChar -ne 0 -and -not [char]::IsControl($key.KeyChar)) { + [void]$typed.Append($key.KeyChar); [Console]::Write($key.KeyChar) + } + continue + } + if ([DateTime]::UtcNow -ge $deadline) { + Write-Host '' + UI-Muted "no answer after ${timeout}s, using default ($Default)" + return $isDefaultYes + } + Start-Sleep -Milliseconds 50 + } + Write-Host '' + $answer = $typed.ToString() + } + $answer = $answer.Trim() + if (-not $answer) { return $isDefaultYes } + return ($answer -match '^[Yy]') +} diff --git a/src/pslib/ui/Term.ps1 b/src/pslib/ui/Term.ps1 new file mode 100644 index 0000000..377f425 --- /dev/null +++ b/src/pslib/ui/Term.ps1 @@ -0,0 +1,175 @@ +# Windows UI terminal setup (VT mode, colours, glyphs, width). +# Keep this file ASCII: PowerShell 5.1 reads BOM-less files as ANSI, so +# glyphs are built from code points. + +# Quiet level (0 to 3), the -v and --ascii switches, the elapsed time of the +# last monitored step, and the escape character. +$script:QUIET_LEVEL = 0 +$script:UI_VERBOSE = $false +$script:UI_IS_ASCII = $false +$script:UI_LAST_ELAPSED = '' +$script:UI_ESC = [string][char]27 + +# Return the character of code point $CodePoint as a string (two UTF-16 units +# above U+FFFF). +function _UI-Char { param([int]$CodePoint) [char]::ConvertFromUtf32($CodePoint) } + +# Return $true on Windows: always under 5.1, from $IsWindows under 6 and later. +function _UI-IsWindows { + if ($PSVersionTable.PSVersion.Major -lt 6) { return $true } + return [bool]$IsWindows +} + +# Enable ENABLE_VIRTUAL_TERMINAL_PROCESSING, which conhost needs for ANSI +# colours (PowerShell 7 and Windows Terminal set it, 5.1 may not). Return +# $true when both console handles take escape sequences. +function _UI-Enable-VT { + if (-not (_UI-IsWindows)) { return $true } + if ($PSVersionTable.PSVersion.Major -ge 7 -or $env:WT_SESSION) { return $true } + try { + if (-not ('Emerger.VT' -as [type])) { + Add-Type -Namespace 'Emerger' -Name 'VT' -MemberDefinition @' +[DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr GetStdHandle(int nStdHandle); +[DllImport("kernel32.dll", SetLastError = true)] public static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode); +[DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode); +'@ -ErrorAction Stop + } + $isOk = $true + foreach ($stdHandleId in @(-11, -12)) { + $handle = [Emerger.VT]::GetStdHandle($stdHandleId) + $mode = [uint32]0 + if ([Emerger.VT]::GetConsoleMode($handle, [ref]$mode)) { + if (-not [Emerger.VT]::SetConsoleMode($handle, ($mode -bor 4))) { $isOk = $false } + } + } + return $isOk + } catch { return $false } +} + +# Return $true when the console can draw emoji: EMERGER_EMOJI decides, else +# Windows Terminal and VS Code can and conhost, which draws boxes, cannot. +function _UI-Detect-Emoji { + if (-not $script:UI_HAS_UNICODE) { return $false } + switch -Regex (("$env:EMERGER_EMOJI").ToLower()) { + '^(1|yes|on|true)$' { return $true } + '^(0|no|off|false)$' { return $false } + } + if ($env:WT_SESSION) { return $true } + if ($env:TERM_PROGRAM -eq 'vscode') { return $true } + return $false +} + +# Return $true when the terminal background looks light: COLORFGBG first, then the +# console's own background colour. +function _UI-Detect-Light-Background { + # COLORFGBG="fg;bg": bg 7+ is a light theme. Otherwise trust the console. + if ($env:COLORFGBG) { + $background = ($env:COLORFGBG -split ';')[-1] + if ($background -match '^\d+$') { return ([int]$background -ge 7) } + return $false + } + try { + $color = [Console]::BackgroundColor + return @('White', 'Gray', 'Yellow') -contains "$color" + } catch { return $false } +} + +# Detect the console (redirection, UTF-8, emoji, VT) and set the colour +# palette and glyph table. Called at load and again after the flags are parsed. +function UI-Init { + # Ascii set by config.ps1 or a profile counts as the flag. + if ($script:ArgsGlobal -and $script:ArgsGlobal.Ascii) { $script:UI_IS_ASCII = $true } + $script:UI_IS_TTY = $true + try { if ([Console]::IsOutputRedirected) { $script:UI_IS_TTY = $false } } catch { $script:UI_IS_TTY = $false } + + # UTF-8 so glyphs and child process output survive. + try { + if ([Console]::OutputEncoding.CodePage -ne 65001) { + [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false + } + } catch {} + $isUtf8 = $false + try { $isUtf8 = ([Console]::OutputEncoding.CodePage -eq 65001) } catch {} + $script:UI_HAS_UNICODE = $isUtf8 -and -not $script:UI_IS_ASCII + $script:UI_HAS_EMOJI = _UI-Detect-Emoji + $script:UI_IS_MODERN = [bool]($env:WT_SESSION -or $env:TERM_PROGRAM -eq 'vscode' -or -not (_UI-IsWindows)) + + $script:UI_HAS_COLOR = $script:UI_IS_TTY -and -not $env:NO_COLOR -and ($env:TERM -ne 'dumb') + $script:UI_HAS_VT = $false + if ($script:UI_IS_TTY) { $script:UI_HAS_VT = _UI-Enable-VT } + if (-not $script:UI_HAS_VT) { $script:UI_HAS_COLOR = $false } + + $esc = $script:UI_ESC + $script:UI_PALETTE = @{} + foreach ($key in 'reset','bold','dim','red','green','yellow','blue','magenta','cyan','gray') { $script:UI_PALETTE[$key] = '' } + $script:UI_GRADIENT = @() + if ($script:UI_HAS_COLOR) { + $script:UI_PALETTE.reset = "$esc[0m"; $script:UI_PALETTE.bold = "$esc[1m"; $script:UI_PALETTE.dim = "$esc[2m" + if (_UI-Detect-Light-Background) { + $palette = @{ red=160; green=28; yellow=136; blue=26; magenta=90; cyan=30; gray=240 } + $script:UI_GRADIENT = @(35, 35, 29, 29, 29, 22, 22) + } else { + $palette = @{ red=203; green=114; yellow=221; blue=39; magenta=176; cyan=81; gray=245 } + $script:UI_GRADIENT = @(121, 84, 48, 42, 35, 29, 29) + } + foreach ($key in $palette.Keys) { $script:UI_PALETTE[$key] = "$esc[38;5;$($palette[$key])m" } + } + + if ($script:UI_HAS_UNICODE) { + $script:UI_GLYPHS = @{ + check = (_UI-Char 0x2714); cross = (_UI-Char 0x2716); arrow = (_UI-Char 0x25B8) + info = (_UI-Char 0x25CF); warn = (_UI-Char 0x25B2); ask = (_UI-Char 0x276F) + bullet = (_UI-Char 0x2022); hline = (_UI-Char 0x2500) + dot = (_UI-Char 0x00B7); diamond = (_UI-Char 0x25C6) + pfull = (_UI-Char 0x25B0); pempty = (_UI-Char 0x25B1) + tl = (_UI-Char 0x256D); tr = (_UI-Char 0x256E); bl = (_UI-Char 0x2570); br = (_UI-Char 0x256F) + v = (_UI-Char 0x2502) + } + } else { + $script:UI_GLYPHS = @{ + check = '[OK]'; cross = '[X]'; arrow = '>'; info = 'i'; warn = '!'; ask = '?' + bullet = '*'; hline = '-'; dot = '.'; diamond = '*' + pfull = '#'; pempty = '.'; tl = '+'; tr = '+'; bl = '+'; br = '+'; v = '|' + } + } +} + +# Return $Text in colour $Color, a list such as 'bold cyan', or plain when +# colour is off. +function UI-Color { + param([string]$Color, [string]$Text) + if (-not $script:UI_HAS_COLOR) { return $Text } + $prefix = '' + foreach ($name in ($Color -split '\s+')) { if ($script:UI_PALETTE.ContainsKey($name)) { $prefix += $script:UI_PALETTE[$name] } } + if (-not $prefix) { return $Text } + return "$prefix$Text$($script:UI_PALETTE.reset)" +} + +# Return glyph $Name from the current table, '*' for an unknown name. +function UI-Glyph { + param([string]$Name) + $glyph = $script:UI_GLYPHS[$Name] + if ($null -eq $glyph) { return '*' } + return $glyph +} + +# Return the console width in columns, 80 when unknown. +function UI-Width { + try { $width = [Console]::WindowWidth } catch { $width = 80 } + if ($width -le 0) { $width = 80 } + return $width +} + +# Return the width of headers and boxes: the console width within 40 to 78. +function _UI-Columns { + $width = UI-Width + if ($width -gt 78) { $width = 78 } + if ($width -lt 40) { $width = 40 } + return $width +} + +# Hide or show the cursor on a console, errors ignored. +function UI-Cursor-Hide { if ($script:UI_IS_TTY) { try { [Console]::CursorVisible = $false } catch {} } } +function UI-Cursor-Show { if ($script:UI_IS_TTY) { try { [Console]::CursorVisible = $true } catch {} } } + +UI-Init diff --git a/src/pslib/ui/Text.ps1 b/src/pslib/ui/Text.ps1 new file mode 100644 index 0000000..5b56e4b --- /dev/null +++ b/src/pslib/ui/Text.ps1 @@ -0,0 +1,33 @@ +# Text measurement and escape stripping for the Windows UI. + +# Remove CSI escape sequences from $Text. +function UI-Strip { + param([string]$Text) + return [regex]::Replace($Text, "$([char]27)\[[0-9;?]*[a-zA-Z]", '') +} + +# Remove CSI and OSC sequences, any other escape sequence (ESC, intermediate +# bytes, final byte), then every control character but tab and newline +# (C0, DEL and C1), from text that came from outside. +# Each pattern is linear in the length of $Text. +function UI-Sanitize { + param([string]$Text) + $esc = [char]27 + $stripped = [regex]::Replace($Text, "$esc\[[0-?]*[ -/]*[@-~]", '') + $stripped = [regex]::Replace($stripped, "$esc\][^\a$esc]*(\a|$esc\\)?", '') + $stripped = [regex]::Replace($stripped, "$esc[ -/]*[0-~]", '') + return [regex]::Replace($stripped, '[\x00-\x08\x0B-\x1F\x7F-\x9F]', '') +} + +# Return the length of $Text without escape sequences. Emoji are two UTF-16 +# units and two columns wide, so .Length counts columns. +function UI-Visible-Length { param([string]$Text) return (UI-Strip $Text).Length } + +# Format $Elapsed as 4.2s, 42s or 1m03s. +function UI-Format-Elapsed { + param([TimeSpan]$Elapsed) + $seconds = [int][math]::Floor($Elapsed.TotalSeconds) + if ($seconds -lt 10) { return ('{0}.{1}s' -f $seconds, ([int][math]::Floor($Elapsed.TotalMilliseconds / 100) % 10)) } + if ($seconds -lt 60) { return "${seconds}s" } + return ('{0}m{1:00}s' -f [int][math]::Floor($seconds / 60), ($seconds % 60)) +} diff --git a/tests/autoupdate.bats b/tests/autoupdate.bats new file mode 100644 index 0000000..2d21048 --- /dev/null +++ b/tests/autoupdate.bats @@ -0,0 +1,88 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_home +} + +teardown() { + teardown_home +} + +# Stub systemctl: the user bus answers, `enable` exits with $1. +stub_systemctl() { + cat >"$STUBS/systemctl" <>"\$HOME/systemctl.log" +[[ \$* == *enable* ]] && { echo "Failed to connect to bus: No medium found" >&2; exit $1; } +exit 0 +EOS + chmod +x "$STUBS/systemctl" +} + +# Run autoupdate_install with the stubs first on PATH. +run_setup_cron() { + bash -c 'PATH="$STUBS:$PATH"; source "$LIB/load.sh" ui log sys autoupdate + DRY_RUN=0; autoupdate_install "$1"' _ "$REPO_DIR" +} + +@test "auto-update: the systemd timer fires on Sunday at 10:00 like cron and Windows" { + stub_systemctl 0 + run run_setup_cron + [ "$status" -eq 0 ] + grep -qx 'OnCalendar=Sun \*-\*-\* 10:00:00' "$HOME/.config/systemd/user/emerger.timer" +} + +@test "auto-update: a failing enable explains itself, removes the units and exits 1" { + stub_systemctl 1 + run run_setup_cron + [ "$status" -eq 1 ] + [[ "$output" == *"loginctl enable-linger"* ]] + [ ! -e "$HOME/.config/systemd/user/emerger.timer" ] + [ ! -e "$HOME/.config/systemd/user/emerger.service" ] +} + +@test "auto-update: attack % and \$ in the install path, expected refused" { + stub crontab 'cat >>"$HOME/crontab-called"' + run lib "PATH=$STUBS:\$PATH; DRY_RUN=0; sys_has() { [[ \$1 != systemctl ]] && command -v \"\$1\" >/dev/null; } + autoupdate_install '$HOME/a%b'; echo rc=\$?; autoupdate_install '$HOME/a\$b'; echo rc=\$?" + [[ "$output" == *"rc=1"*"rc=1"* ]] + [ ! -e "$HOME/crontab-called" ] +} + +@test "auto-update: cron line quotes a path with a space" { + stub crontab '[ "$1" = "-l" ] && { echo "no crontab for u" >&2; exit 1; }; cat >>"$HOME/crontab-called"' + run lib "PATH=$STUBS:\$PATH; DRY_RUN=0; sys_has() { [[ \$1 != systemctl ]] && command -v \"\$1\" >/dev/null; } + autoupdate_install '$HOME/p q'; echo rc=\$?" + [[ "$output" == *"rc=0"* ]] + [ "$(cat "$HOME/crontab-called")" = "0 10 * * 0 bash \"$HOME/p q/src/emerger.sh\" -y -q -nl -ni" ] +} + +@test "auto-update: attack unreadable crontab, expected refusal without rewriting it" { + stub crontab '[ "$1" = "-l" ] && { echo "crontab: temporary read failure" >&2; exit 1; }; cat >>"$HOME/crontab-called"' + run lib "PATH=$STUBS:\$PATH; DRY_RUN=0; sys_has() { [[ \$1 != systemctl ]] && command -v \"\$1\" >/dev/null; } + autoupdate_install '$HOME/p'; echo rc=\$?" + [[ "$output" == *"rc=1"* ]] + [ ! -e "$HOME/crontab-called" ] +} + +@test "auto-update: cron install keeps unrelated lines and replaces only its own" { + printf '%s\n' '0 3 * * * /opt/backup/emerger.sh --sync' '0 10 * * 0 bash "/old/src/emerger.sh" -y -q -nl -ni' '5 5 * * * mine' >"$HOME/crontab-in" + stub crontab 'if [ "$1" = "-l" ]; then cat "$HOME/crontab-in"; else cat >"$HOME/crontab-called"; fi' + run lib "PATH=$STUBS:\$PATH; DRY_RUN=0; sys_has() { [[ \$1 != systemctl ]] && command -v \"\$1\" >/dev/null; } + autoupdate_install '$HOME/p'; echo rc=\$?" + [[ "$output" == *"rc=0"* ]] + [ "$(cat "$HOME/crontab-called")" = "$(printf '%s\n' '0 3 * * * /opt/backup/emerger.sh --sync' '5 5 * * * mine' "0 10 * * 0 bash \"$HOME/p/src/emerger.sh\" -y -q -nl -ni")" ] +} + +@test "install_path_check: attack each refused character alone, expected refusal; plain path accepted" { + local c + for c in "'" '"' '$' '`' '%' '\' $'\n'; do + export BAD_CHAR="$c" + run lib 'install_path_check "/opt/a${BAD_CHAR}b"' + [ "$status" -eq 1 ] + done + run lib 'install_path_check "/opt/a b-c_d.e"' + [ "$status" -eq 0 ] +} diff --git a/tests/changelog.bats b/tests/changelog.bats new file mode 100644 index 0000000..61a43d6 --- /dev/null +++ b/tests/changelog.bats @@ -0,0 +1,61 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +@test "changelog: long apt changelog is shown, not reported missing" { + stub apt '[ "$1" = changelog ] || exit 1; i=0; while [ $i -lt 5000 ]; do echo "line $i"; i=$((i+1)); done' + run sys_lib 'changelog_show foo; echo rc=$?' + [ "$status" -eq 0 ] + [[ "$output" == *"line 0"* ]] + [[ "$output" == *"line 59"* ]] + [[ "$output" != *"line 60"* ]] + [[ "$output" == *"rc=0" ]] +} + +@test "changelog: dnf falls back to updateinfo, nothing found exits 1" { + stub dnf 'case "$1" in changelog) exit 1 ;; updateinfo) echo "Update ID: FEDORA-1" ;; esac' + run sys_lib 'changelog_show foo; echo rc=$?' + [[ "$output" == *"Update ID: FEDORA-1"* ]] + [[ "$output" == *"rc=0" ]] + rm "$STUBS/dnf" + run sys_lib 'changelog_show foo' + [ "$status" -eq 1 ] + [[ "$output" == *"No supported package manager with changelog info found."* ]] +} + +@test "changelog: pacman output is labelled package info" { + stub pacman '[ "$1" = "-Qi" ] && echo "Name : foo"' + run sys_lib 'changelog_show foo' + [ "$status" -eq 0 ] + [[ "$output" == *"package info (pacman has no changelog)"* ]] + [[ "$output" == *"Name : foo"* ]] +} + +@test "changelog: attack escapes in apt, dnf, pacman and brew text, expected stripped" { + esc='printf "pkg\n * x \033]52;c;ZXZpbA==\007 \033[31mred\n"' + stub apt "$esc" + run sys_lib 'changelog_show pkg' + [[ "$output" == *"red"* ]] + [[ "$output" != *$'\033'"]52"* && "$output" != *$'\033'"[31m"* ]] + rm "$STUBS/apt" + stub dnf "$esc" + run sys_lib 'changelog_show pkg' + [[ "$output" == *"red"* && "$output" != *$'\033'"]52"* ]] + rm "$STUBS/dnf" + stub pacman "$esc" + run sys_lib 'changelog_show pkg' + [[ "$output" == *"red"* && "$output" != *$'\033'"]52"* ]] + rm "$STUBS/pacman" + stub brew "$esc" + run sys_lib 'changelog_show pkg' + [[ "$output" == *"red"* && "$output" != *$'\033'"]52"* ]] +} diff --git a/tests/clean.bats b/tests/clean.bats new file mode 100644 index 0000000..98e4ee2 --- /dev/null +++ b/tests/clean.bats @@ -0,0 +1,175 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +@test "clean_cache: du partial failure continues cleaning" { + mkdir -p "$HOME/.cache/junk" + head -c 200000 /dev/zero >"$HOME/.cache/junk/blob" + stub du 'for a; do case $a in -*) ;; *) printf "300\t%s\n" "$a" ;; esac; done; exit 1' + run sys_lib 'ARG_YES=1; clean_cache; echo "rc=$?"' + [ "$status" -eq 0 ] + [[ "$output" == *"cache cleaned"* ]] + [[ "$output" == *"rc=0"* ]] +} + +@test "clean_trash: du failure still empties the trash" { + mkdir -p "$HOME/.local/share/Trash/files" "$HOME/.local/share/Trash/info" + touch "$HOME/.local/share/Trash/files/old" + stub du 'echo "4 $3"; exit 1' + run sys_lib 'ARG_YES=1; clean_trash; echo "rc=$? freed=$SUMMARY_FREED_KB"' + [ "$status" -eq 0 ] + [[ "$output" == *"trash emptied"* ]] + [[ "$output" == *"rc=0 freed=0"* ]] + [ ! -e "$HOME/.local/share/Trash/files/old" ] +} + +@test "clean_trash: growing trash never makes freed negative" { + mkdir -p "$HOME/.local/share/Trash/files" + touch "$HOME/.local/share/Trash/files/old" + stub du 'n=$(cat "$HOME/du.n" 2>/dev/null || echo 0); n=$((n + 1)); echo $n >"$HOME/du.n"; echo "$((n * 100)) x"' + run sys_lib 'ARG_YES=1; SUMMARY_FREED_KB=5; clean_trash; echo "freed=$SUMMARY_FREED_KB"' + [ "$status" -eq 0 ] + [[ "$output" == *"freed=5"* ]] +} + +@test "clean_cache: CACHE_EXCLUDE glob is not expanded against the cwd" { + mkdir -p "$HOME/.cache/keepme" "$HOME/.cache/junk" "$HOME/cwd" + touch "$HOME/cwd/keepsake" + head -c 200000 /dev/zero >"$HOME/.cache/junk/blob" + head -c 200000 /dev/zero >"$HOME/.cache/keepme/blob" + run sys_lib 'cd "$HOME/cwd"; ARG_YES=1; CACHE_EXCLUDE="keep*"; clean_cache' + [ "$status" -eq 0 ] + [ -d "$HOME/.cache/keepme" ] + [ ! -e "$HOME/.cache/junk" ] +} + +@test "cache menu pick: leading zeros read as decimal" { + run sys_lib '_clean_parse_pick "010" 12; echo "${_CLEAN_PICK[@]}" + _clean_parse_pick "08 09-10" 12; echo "${_CLEAN_PICK[@]}"' + [ "$status" -eq 0 ] + [ "${lines[0]}" = "10" ] + [ "${lines[1]}" = "8 9 10" ] +} + +@test "cache menu pick: huge range is clamped, duplicates counted once" { + run timeout 10 bash -c "$(declare -f sys_lib); sys_lib '_clean_parse_pick \"1-999999999 2 2 3-1\" 3; echo \"\${_CLEAN_PICK[@]}\"'" + [ "$status" -eq 0 ] + [ "$output" = "1 2 3" ] +} + +@test "deep clean: zero-byte journal and failing probes skip the task, run continues" { + stub journalctl 'echo "Archived and active journals take up 0B in the file system."' + stub dnf 'exit 1' + stub go 'exit 1' + stub docker 'case "$1" in info) exit 0 ;; *) exit 1 ;; esac' + run sys_lib 'DRY_RUN=1; ARG_YES=1; clean_deep; echo "rc=$?"' + [ "$status" -eq 0 ] + [[ "$output" == *"rc=0"* ]] + [[ "$output" != *"vacuum-size"* ]] + [[ "$output" == *"image prune -f"*"_ docker"* ]] +} + +@test "deep clean: journal size in plain bytes is compared" { + stub journalctl 'echo "Archived and active journals take up 512B in the file system."' + run sys_lib 'DRY_RUN=1; ARG_YES=1; JOURNAL_MAX_SIZE=100; clean_deep; echo "rc=$?"' + [ "$status" -eq 0 ] + [[ "$output" == *"[dry-run] journalctl --vacuum-size=100"* ]] +} + +@test "deep clean: dry-run never calls sudo for the docker probe" { + stub docker 'exit 1' + stub sudo 'echo "$*" >>"$HOME/sudo.calls"; exit 0' + run sys_lib 'sys_is_root() { return 1; }; DRY_RUN=1; ARG_YES=1; clean_deep; echo "rc=$?"' + [ "$status" -eq 0 ] + [[ "$output" == *"rc=0"* ]] + [ ! -e "$HOME/sudo.calls" ] +} + +@test "clean_trash: macOS empties ~/.Trash" { + stub uname 'echo Darwin' + mkdir -p "$HOME/.Trash" + touch "$HOME/.Trash/old" + run sys_lib 'ARG_YES=1; clean_trash' + [ "$status" -eq 0 ] + [[ "$output" == *"trash emptied"* ]] + [ ! -e "$HOME/.Trash/old" ] +} + +@test "clean_trash: macOS Trash unreadable without Full Disk Access is reported, not called empty" { + stub uname 'echo Darwin' + mkdir -p "$HOME/.Trash" + touch "$HOME/.Trash/old" + stub find 'echo "find: $1: Operation not permitted" >&2; exit 1' + run sys_lib 'ARG_YES=1; clean_trash; echo "rc=$?"' + [ "$status" -eq 0 ] + [[ "$output" == *"cannot read the Trash (macOS privacy settings)"* ]] + [[ "$output" != *"empty"* ]] + [[ "$output" == *"rc=0"* ]] + [ -e "$HOME/.Trash/old" ] +} + +@test "clean_trash: an unreadable Linux Trash is reported, not called empty" { + mkdir -p "$HOME/.local/share/Trash/files" + stub find 'exit 1' + run sys_lib 'ARG_YES=1; clean_trash; echo "rc=$?"' + [ "$status" -eq 0 ] + [[ "$output" == *"cannot read the Trash"* ]] + [[ "$output" != *"privacy"* ]] + [[ "$output" != *"empty"* ]] +} + +@test "deep clean: DEEP_CLEAN_SKIP glob is not expanded against the cwd" { + mkdir -p "$HOME/cwd" && touch "$HOME/cwd/journal" + run sys_lib 'cd "$HOME/cwd"; DEEP_CLEAN_SKIP="jour*"; _deep_is_skipped journal && echo skip || echo run + DEEP_CLEAN_SKIP="docker, journal"; _deep_is_skipped journal && echo skip || echo run' + [ "$status" -eq 0 ] + [ "${lines[0]}" = run ] + [ "${lines[1]}" = skip ] +} + +@test "cache menu pick: ranges, commas and "a" select rows in order, empty selects none" { + run lib '_clean_parse_pick "1 3-4,9" 5; echo "${_CLEAN_PICK[@]}" + _clean_parse_pick a 3; echo "${_CLEAN_PICK[@]}" + _clean_parse_pick "" 3; echo "[${_CLEAN_PICK[*]}]"' + [ "${lines[0]}" = "1 3 4" ] + [ "${lines[1]}" = "1 2 3" ] + [ "${lines[2]}" = "[]" ] +} + +@test "clean_cache -y keeps emerger and CACHE_EXCLUDE" { + mkdir -p "$HOME/.cache/emerger" "$HOME/.cache/keepme" "$HOME/.cache/junk" + head -c 200000 /dev/zero >"$HOME/.cache/junk/blob" + head -c 200000 /dev/zero >"$HOME/.cache/keepme/blob" + run lib 'ARG_YES=1; DRY_RUN=0; SUMMARY_FREED_KB=0; CACHE_EXCLUDE="keep*"; clean_cache' + [ "$status" -eq 0 ] + [ -d "$HOME/.cache/emerger" ] + [ -d "$HOME/.cache/keepme" ] + [ ! -e "$HOME/.cache/junk" ] +} + +@test "clean_cache: entry named with the unit separator never deletes a CACHE_EXCLUDE entry" { + mkdir -p "$HOME/.cache/emerger" "$HOME/.cache/keepme" "$HOME/.cache/big" + head -c 300000 /dev/zero >"$HOME/.cache/big/blob" + head -c 200000 /dev/zero >"$HOME/.cache/keepme/blob" + head -c 100000 /dev/zero >"$HOME/.cache/a"$'\x1f'keepme + run lib 'ARG_YES=1; DRY_RUN=0; SUMMARY_FREED_KB=0; CACHE_MENU_ROWS=1; CACHE_EXCLUDE="keepme"; clean_cache' + [ "$status" -eq 0 ] + [ -d "$HOME/.cache/keepme" ] + [ ! -e "$HOME/.cache/big" ] + [ ! -e "$HOME/.cache/a"$'\x1f'keepme ] +} + +@test "--deep-clean under dry-run exits 0 and prints the Deep clean section" { + run $EMERGER -n -y -nl -nc -nt --deep-clean --only none + [ "$status" -eq 0 ] + [[ "$output" == *"Deep clean"* ]] +} diff --git a/tests/cli.bats b/tests/cli.bats new file mode 100644 index 0000000..f8851cc --- /dev/null +++ b/tests/cli.bats @@ -0,0 +1,122 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + # Managers the tests rely on, so detection does not depend on the host. + for m in apt snap; do printf '#!/bin/sh\nexit 0\n' >"$STUBS/$m"; chmod +x "$STUBS/$m"; done + printf '#!/bin/sh\necho "sudo $*" >>"$HOME/sudo.log"\n' >"$STUBS/sudo"; chmod +x "$STUBS/sudo" +} + +teardown() { + teardown_env +} + +# Assert that value flag $1 refuses an empty value in both spellings. +empty_value_refused() { + run $EMERGER -n -y "--$1" "" + [ "$status" -eq 2 ] + [[ "$output" == *"Missing value for --$1"* ]] + run $EMERGER -n -y "--$1=" + [ "$status" -eq 2 ] + [[ "$output" == *"Missing value for --$1"* ]] +} + +@test "help exits 0 and mentions USAGE" { + run $EMERGER --help + [ "$status" -eq 0 ] + [[ "$output" == *"USAGE"* ]] +} + +@test "version prints version string" { + run $EMERGER --version + [ "$status" -eq 0 ] + [[ "$output" == *"eMerger"* ]] +} + +@test "unknown flag fails with exit code 2" { + run $EMERGER --totally-bogus + [ "$status" -eq 2 ] +} + +@test "cli: --help -nl exits 0, -nl not read as a -n bundle" { + run $EMERGER --help -nl + [ "$status" -eq 0 ] +} + +@test "cli: --errors on an empty log exits 0" { + run $EMERGER --errors + [ "$status" -eq 0 ] +} + +@test "cli: bundled short flags -nv run as -n -v and exit 0" { + run $EMERGER -nv -y -nl -ni -nc -nt -q + [ "$status" -eq 0 ] +} + +@test "unknown long flag still fails with exit code 2" { + run $EMERGER --no-such-flag + [ "$status" -eq 2 ] +} + +@test "args: --flag=VALUE sets each value flag, the value kept whole after its first =" { + run bash -c "source '$REPO_DIR/src/lib/load.sh' args + args_parse --only=a=b --changelog=c --metrics=m --profile=p --except=e + echo \"\$ARG_ONLY|\$ARG_CHANGELOG|\$ARG_METRICS|\$ARG_EXCEPT\"" + [ "$status" -eq 0 ] + [ "$output" = "a=b|c|m|e" ] + run $EMERGER --json=1 + [ "$status" -eq 2 ] + [[ "$output" == *"Unknown argument: --json=1"* ]] +} + +@test "--only and --except trim spaces around names" { + plugin pa '' + plugin pb '' + plugin pc '' + run $EMERGER -y -nl -nc -nt --only "pa, pb" + [ "$status" -eq 0 ] + [ "$(sort "$HOME/ran" | tr '\n' ' ')" = "pa pb " ] + rm "$HOME/ran" + run $EMERGER -y -nl -nc -nt --only "pa,pb,pc" --except "pa, pb" + [ "$status" -eq 0 ] + [ "$(cat "$HOME/ran")" = "pc" ] +} + +@test "args: --only with an empty value exits 2" { empty_value_refused only; } + +@test "args: --except with an empty value exits 2" { empty_value_refused except; } + +@test "args: --changelog with an empty value exits 2" { empty_value_refused changelog; } + +@test "args: --metrics with an empty value exits 2" { empty_value_refused metrics; } + +@test "args: --profile with an empty value exits 2" { empty_value_refused profile; } + +@test "--except appends to the profile list" { + run bash -c "source '$LIB/load.sh' args; ARG_EXCEPT=yay,paru; args_parse --except snap --except=npm; echo \$ARG_EXCEPT" + [ "$output" = "yay,paru,snap,npm" ] +} + +@test "cli: --accept-licenses sets ARG_ACCEPT_LICENSES to 1" { + run bash -c "source '$LIB/load.sh' args; args_parse --accept-licenses; echo \$ARG_ACCEPT_LICENSES" + [ "$output" = "1" ] +} + +@test "args: --profile is read by the prescan only, no ARG_PROFILE is left behind" { + run bash -c "source '$REPO_DIR/src/lib/load.sh' args + args_parse --profile p; args_prescan_profile --profile p + echo \"[\${ARG_PROFILE-unset}] \$PROFILE_PRELOAD\"" + [ "$status" -eq 0 ] + [ "$output" = "[unset] p" ] +} + +@test "args: a newline inside a value never becomes an extra flag" { + run $EMERGER --changelog $'pkg\n--version' -nl -ni + [[ "$output" != *"eMerger $(cat "$REPO_DIR/VERSION")"* ]] + [[ "$output" != "$(cat "$REPO_DIR/VERSION")" ]] + run lib 'args_parse --only $'"'"'none\n--history'"'"'; echo "[${ARG_HISTORY}] [${ARG_ONLY}]"' + [ "$status" -eq 0 ] + [[ "${lines[0]}" == "[0] [none" ]] +} diff --git a/tests/completion.bats b/tests/completion.bats new file mode 100644 index 0000000..cce87b1 --- /dev/null +++ b/tests/completion.bats @@ -0,0 +1,137 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_home + export XDG_CONFIG_HOME="$HOME/.config" + mkdir -p "$XDG_CONFIG_HOME/emerger/profiles.d" +} + +teardown() { + teardown_home +} + +# Print the bash completions for the words given, one per line. +complete_words() { + (cd "$HOME" && bash -c 'source "$1/completions/up.bash" + alias up="bash \"$1/src/emerger.sh\"" + shift + COMP_WORDS=("$@"); COMP_CWORD=$(( $# - 1 )) + _up_completion + printf "%s\n" "${COMPREPLY[@]}"' _ "$REPO_DIR" "$@") +} + +@test "completion: --profile offers the shipped profiles" { + run complete_words up --profile "" + [ "$status" -eq 0 ] + [[ "$output" == *home*safe*server*work* ]] +} + +@test "completion: --profile treats a crafted file name as text, never runs it" { + touch "$XDG_CONFIG_HOME/emerger/profiles.d/\$(touch pwned).sh" + run complete_words up --profile "" + [ "$status" -eq 0 ] + [ ! -e "$HOME/pwned" ] + [[ "$output" == *'$(touch pwned)'* ]] +} + +@test "completion: --profile filters by the typed prefix" { + run complete_words up --profile se + [ "$output" = "server" ] +} + +@test "completion: zsh --profile offers the shipped profiles" { + command -v zsh >/dev/null || skip "zsh not installed" + mkdir -p "$HOME/.zsh/completions"; cp "$REPO_DIR/completions/_up" "$HOME/.zsh/completions/_up" + run zsh -fc 'compdef() { :; }; compadd() { [[ $1 == -- ]] && shift; print -l -- "$@"; } + source "$HOME/.zsh/completions/_up" + alias up="bash \"$1/src/emerger.sh\"" + _up_profiles' _ "$REPO_DIR" + [ "$status" -eq 0 ] + [[ "$output" == *home*safe*server*work* ]] +} + +@test "completion: zsh lets -q repeat" { + command -v zsh >/dev/null || skip "zsh not installed" + # Capture the option specs _up hands to _arguments. + run zsh -fc 'compdef() { :; }; _arguments() { print -l -- "$@"; } + source "$1/completions/_up"; _up' _ "$REPO_DIR" + [ "$status" -eq 0 ] + printf '%s\n' "$output" | grep -q '^\*-q\[' +} + +@test "completion: zsh treats a crafted profile name as text, never runs it" { + command -v zsh >/dev/null || skip "zsh not installed" + touch "$XDG_CONFIG_HOME/emerger/profiles.d/a:m:{touch pwned}.sh" + run zsh -fc 'compdef() { :; }; _values() { print -r -- "values $*"; }; compadd() { print -r -l -- "$@"; } + cd "$HOME"; source "$1/completions/_up"; _up_profiles' _ "$REPO_DIR" + [ "$status" -eq 0 ] + [ ! -e "$HOME/pwned" ] + [[ "$output" != *values* ]] + [[ "$output" == *'a:m:{touch pwned}'* ]] +} + +@test "completion: fish --profile offers the shipped profiles" { + command -v fish >/dev/null || skip "fish not installed" + mkdir -p "$HOME/.config/fish/completions"; cp "$REPO_DIR/completions/up.fish" "$HOME/.config/fish/completions/up.fish" + run fish --no-config -c "source '$HOME/.config/fish/completions/up.fish' + # What fish's alias builtin defines. + function up; bash \"$REPO_DIR/src/emerger.sh\" \$argv; end + __up_profiles" + [ "$status" -eq 0 ] + [[ "$output" == *home*safe*server*work* ]] +} + +@test "completion: fish finds the shipped profiles through an unquoted alias" { + command -v fish >/dev/null || skip "fish not installed" + run fish --no-config -c "source '$REPO_DIR/completions/up.fish' + function up; bash $REPO_DIR/src/emerger.sh \$argv; end + __up_profiles" + [[ "$output" == *home*safe*server*work* ]] +} + +@test "completion: fish offers the single-dash aliases" { + command -v fish >/dev/null || skip "fish not installed" + run fish --no-config -c "source '$REPO_DIR/completions/up.fish'; complete -C 'up -'" + for flag in -qq -qqq -up -au -rc -nl -err; do + printf '%s\n' "$output" | grep -q -- "^$flag"$'\t' || { echo "missing $flag"; false; } + done +} + +@test "completion: --metrics offers a file name with a space as one word" { + touch "$HOME/my metrics.prom" + run complete_words up --metrics my + [ "$status" -eq 0 ] + [ "$output" = "my metrics.prom" ] +} + +@test "completion: --profile lists a name once when the user and shipped directories both hold it" { + touch "$XDG_CONFIG_HOME/emerger/profiles.d/safe.sh" "$XDG_CONFIG_HOME/emerger/profiles.d/safeX.sh" + run complete_words up --profile saf + [ "$status" -eq 0 ] + [ "$(printf '%s\n' "$output" | grep -cx safe)" -eq 1 ] + [[ "$output" == *safeX* ]] +} + +@test "completion: the bash file uses no associative array, mapfile or readarray (bash 3.2)" { + run bash -c "grep -vE '^[[:space:]]*#' \"\$1\" | grep -nE 'local -A|declare -A|typeset -A|\\bmapfile\\b|\\breadarray\\b'" _ "$REPO_DIR/completions/up.bash" + [ "$status" -eq 1 ] +} + +@test "completion: --metrics keeps a backslash in a file name" { + touch "$HOME/a\\b.csv" + run complete_words up --metrics "a" + [ "$status" -eq 0 ] + [ "$output" = 'a\b.csv' ] +} + +@test "completion: --profile finds the shipped profiles without BASH_ALIASES, as on bash 3.2" { + run bash -c 'unset BASH_ALIASES; source "$1/completions/up.bash" + alias up="bash \"$1/src/emerger.sh\"" + COMP_WORDS=(up --profile ""); COMP_CWORD=2 + _up_completion + printf "%s\n" "${COMPREPLY[@]}"' _ "$REPO_DIR" + [ "$status" -eq 0 ] + [[ "$output" == *home*safe*server*work* ]] +} diff --git a/tests/config.bats b/tests/config.bats new file mode 100644 index 0000000..66926fa --- /dev/null +++ b/tests/config.bats @@ -0,0 +1,86 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +@test "config: ARG_ASCII=1 in config.sh gives ASCII glyphs" { + echo 'ARG_ASCII=1' >"$XDG_CONFIG_HOME/emerger/config.sh" + run env LANG=C.UTF-8 $EMERGER -n -y -nl --only none + [ "$status" -eq 0 ] + [[ "$output" == *"! No supported package managers"* ]] + [[ "$output" != *"โ–ฒ"* ]] +} + +@test "config: DRY_RUN=1 and UI_VERBOSE=1 in config.sh act as -n and -v" { + plugin pa 'run_cmd step echo noisy-manager' + run $EMERGER -y -nl -nc -nt --only pa + [ "$status" -eq 0 ] + [[ "$output" != *"noisy-manager"* ]] + echo 'UI_VERBOSE=1' >"$XDG_CONFIG_HOME/emerger/config.sh" + run $EMERGER -y -nl -nc -nt --only pa + [ "$status" -eq 0 ] + [[ "$output" == *"noisy-manager"* ]] + echo 'DRY_RUN=1' >"$XDG_CONFIG_HOME/emerger/config.sh" + run $EMERGER -y -nl -nc -nt --only pa + [ "$status" -eq 0 ] + [[ "$output" == *"[dry-run] echo noisy-manager"* ]] + [ "$(wc -l <"$EMERGER_STATE/history.jsonl")" -eq 2 ] + [ "$(wc -l <"$HOME/ran")" -eq 3 ] +} + +@test "quiet: -q and QUIET_LEVEL=1 in config.sh hide the logo" { + local mark; mark=$(sed -n 2p "$REPO_DIR/src/logo/logo.txt") + [ -n "$mark" ] + run $EMERGER -n -y --only none + [ "$status" -eq 0 ] + [[ "$output" == *"$mark"* ]] + run $EMERGER -n -y -q --only none + [ "$status" -eq 0 ] + [[ "$output" != *"$mark"* ]] + echo 'QUIET_LEVEL=1' >"$XDG_CONFIG_HOME/emerger/config.sh" + run $EMERGER -n -y --only none + [ "$status" -eq 0 ] + [[ "$output" != *"$mark"* ]] +} + +@test "config: action variables in config.sh are ignored, only the command line runs actions" { + mkdir -p "$STUBS"; printf '#!/bin/sh\necho "git $*" >>"$HOME/git.log"\n' >"$STUBS/git"; chmod +x "$STUBS/git" + for var in ARG_SELF_UPDATE ARG_ERRORS ARG_HISTORY ARG_REBUILD_CACHE ARG_DOCTOR ARG_LIST_PROFILES; do + echo "$var=1" >"$XDG_CONFIG_HOME/emerger/config.sh" + run env PATH="$STUBS:$PATH" $EMERGER -n -y -nl --only none --json + [ "$status" -eq 0 ] || { echo "$var: status $status"; false; } + [[ "${lines[-1]}" == \{*\"managers\":[]*\} ]] || { echo "$var: $output"; false; } + done + [ ! -e "$HOME/git.log" ] +} + +@test "config: the long-named action flags still run from the command line" { + run $EMERGER --errors + [ "$status" -eq 0 ] + run bash -c "source '$LIB/args.sh'; args_parse -up -au -err -rc; echo \$ARG_SELF_UPDATE\$ARG_AUTO_UPDATE\$ARG_ERRORS\$ARG_REBUILD_CACHE" + [ "$output" = "1111" ] +} + +@test "config: a config.sh whose last command fails (test && assignment) still runs the update" { + plugin pa '' + printf '%s\n' 'ARG_KEEP_CACHE=1' '[[ -f /nonexistent ]] && ARG_KEEP_TRASH=1' >"$XDG_CONFIG_HOME/emerger/config.sh" + run $EMERGER -y -nl -nt --only pa + [ "$status" -eq 0 ] + [ "$(cat "$HOME/ran")" = "pa" ] +} + +@test "config: a failing command in the middle of config.sh does not stop later lines" { + plugin pa '' + printf '%s\n' 'false' 'ARG_ONLY=pa' >"$XDG_CONFIG_HOME/emerger/config.sh" + plugin pb '' + run $EMERGER -y -nl -nc -nt + [ "$status" -eq 0 ] + [ "$(cat "$HOME/ran")" = "pa" ] +} diff --git a/tests/diff.bats b/tests/diff.bats new file mode 100644 index 0000000..2f0b367 --- /dev/null +++ b/tests/diff.bats @@ -0,0 +1,55 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +@test "diff_compute: underscores and multi-version packages give one line per version that came or went" { + printf 'apt\tgone\t2.0\npacman\tpython-typing_extensions\t4.1\napt\tfoo_bar\t1.0\nrpm\tlib\t1\nrpm\tkernel\t6.2\nrpm\tkernel\t6.3\napt\tgone\t2.0\napt\tsame\t1\n' | sort >"$HOME/b" + printf 'pacman\tpython-typing_extensions\t4.2\napt\tfoo_bar\t1.1\nrpm\tlib\t2\nrpm\tlib\t3\nrpm\tkernel\t6.2\nrpm\tkernel\t6.3\nrpm\tkernel\t6.4\napt\tnew\t0.1\napt\tsame\t1\n' | sort >"$HOME/a" + run sys_lib 'diff_compute "$HOME/b" "$HOME/a" "$HOME/d"; cat "$HOME/d"; echo "n=$(diff_count_changed "$HOME/d")"' + [ "$status" -eq 0 ] + [ "${lines[0]}" = "+ apt new 0.1" ] + [ "${lines[1]}" = "+ rpm kernel 6.4" ] + [ "${lines[2]}" = "+ rpm lib 2" ] + [ "${lines[3]}" = "+ rpm lib 3" ] + [ "${lines[4]}" = "- apt gone 2.0" ] + [ "${lines[5]}" = "- rpm lib 1" ] + [ "${lines[6]}" = "~ apt foo_bar 1.0 -> 1.1" ] + [ "${lines[7]}" = "~ pacman python-typing_extensions 4.1 -> 4.2" ] + [ "${lines[8]}" = "n=8" ] +} + +@test "diff_compute: missing snapshot gives an empty diff" { + run sys_lib 'echo x >"$HOME/d"; diff_compute "$HOME/none" "$HOME/none2" "$HOME/d"; wc -c <"$HOME/d"' + [ "$output" = "0" ] +} + +@test "diff_compute: empty before snapshot reads every package as added" { + : >"$HOME/b" + printf 'flatpak\torg.x\t1.0\n' >"$HOME/a" + run sys_lib 'diff_compute "$HOME/b" "$HOME/a" "$HOME/d"; cat "$HOME/d"' + [ "$status" -eq 0 ] + [ "$output" = "+ flatpak org.x 1.0" ] + printf 'flatpak\torg.x\t1.0\n' >"$HOME/b" + : >"$HOME/a" + run sys_lib 'diff_compute "$HOME/b" "$HOME/a" "$HOME/d"; cat "$HOME/d"' + [ "$output" = "- flatpak org.x 1.0" ] +} + +@test "diff_show: attack OSC 52, CSI and C1 introducers in a package name and version, expected stripped" { + printf '+\tflatpak\tapp\033]52;c;SGVsbG8=\007x\t1.0\xc2\x9d0;t\xc2\x9c\n~\tbrew\tfoo\t1\033[2J -> 2\n' >"$HOME/d" + run sys_lib 'diff_show "$HOME/d" >"$HOME/out"' + [ "$status" -eq 0 ] + [ "$(grep -c ']52' "$HOME/out" || true)" = "0" ] + [ "$(grep -c '\[2J' "$HOME/out" || true)" = "0" ] + [ "$(LC_ALL=C grep -c $'\xc2[\x80-\x9f]' "$HOME/out")" = "0" ] + grep -q 'appx' "$HOME/out" +} diff --git a/tests/doctor.bats b/tests/doctor.bats new file mode 100644 index 0000000..ee0c6ec --- /dev/null +++ b/tests/doctor.bats @@ -0,0 +1,46 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +@test "doctor: long dpkg --audit output is a warning" { + stub dpkg '[ "$1" = "--audit" ] || exit 0; i=0; while [ $i -lt 20000 ]; do echo "pkg$i half-configured"; i=$((i+1)); done' + run sys_lib '_doctor_pkg apt; echo "issues=$_DOCTOR_ISSUE_COUNT"' + [ "$status" -eq 0 ] + [[ "$output" == *"dpkg --audit reports issues"* ]] + [[ "$output" == *"issues=1" ]] + stub dpkg 'exit 0' + run sys_lib '_doctor_pkg apt; echo "issues=$_DOCTOR_ISSUE_COUNT"' + [[ "$output" == *"dpkg --audit clean"*"issues=0" ]] +} + +@test "doctor: failing dnf check warns, missing subcommand is informational" { + stub dnf '[ "$1" = check ] && { echo "Problem: foo-1 has missing requires of bar"; exit 1; }' + run sys_lib '_doctor_pkg dnf; echo "issues=$_DOCTOR_ISSUE_COUNT"' + [ "$status" -eq 0 ] + [[ "$output" == *"dnf: check reports problems"* ]] + [[ "$output" == *"issues=1" ]] + stub dnf '[ "$1" = check ] && { echo "Unknown argument \"check\" for command \"dnf5\"." >&2; exit 2; }' + run sys_lib '_doctor_pkg dnf; echo "issues=$_DOCTOR_ISSUE_COUNT"' + [[ "$output" == *"dnf: check not available"*"issues=0" ]] + stub dnf 'exit 0' + run sys_lib '_doctor_pkg dnf; echo "issues=$_DOCTOR_ISSUE_COUNT"' + [[ "$output" == *"dnf: check ok"*"issues=0" ]] +} + +@test "doctor: disk warning follows DISK_MIN_FREE_MB" { + stub df 'printf "Filesystem 1M-blocks Used Available Capacity Mounted\n/dev/x 9000 1000 1500 50%% /\n"' + stub sudo 'exit 1' + run sys_lib 'PKG_MANAGERS=(); DISK_MIN_FREE_MB=2048; doctor_run; echo rc=$?' + [[ "$output" == *"low disk space on / (1500MB free)"* ]] + run sys_lib 'PKG_MANAGERS=(); DISK_MIN_FREE_MB=1024; doctor_run; echo rc=$?' + [[ "$output" == *"disk: 1500MB free on /"* ]] +} diff --git a/tests/download_only.bats b/tests/download_only.bats new file mode 100644 index 0000000..ff80e6e --- /dev/null +++ b/tests/download_only.bats @@ -0,0 +1,103 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +# Run pkg_run for $1 in dry-run with the flags in $2 (shell assignments). +pkg_dry() { + sys_lib "DRY_RUN=1; ARG_SECURITY=0; ARG_DOWNLOAD_ONLY=0; ARG_DEV=0; ARG_ACCEPT_LICENSES=0; ARG_FIRMWARE=0 + ${2:-:}; pkg_run $1; echo rc=\$?" +} + +# Run a snippet with the package dispatcher sourced, in dry-run. +pkg() { + lib 'EMERGER_CONFIG=$HOME/.config/emerger + source "$LIB/load.sh" estimate ignore registry detect icon recipes + DRY_RUN=1; ARG_SECURITY=0; ARG_DOWNLOAD_ONLY=0; ARG_DEV=0 + '"$1" +} + +@test "--download-only: a manager without a download mode is skipped, not recorded" { + plugin pa '' + run $EMERGER -y -nl -nc -nt --download-only --only pa + [ "$status" -eq 0 ] + [[ "$output" == *"skip pa (no download-only mode)"* ]] + [ ! -e "$HOME/ran" ] + [[ "$(tail -n 1 "$EMERGER_STATE/history.jsonl")" != *'"pa"'* ]] + [ ! -e "$EMERGER_STATE/resume" ] +} + +@test "sudo check: --download-only leaves managers without a download mode out" { + stub snap 'exit 0' + run lib 'ARG_DOWNLOAD_ONLY=1; ARG_ONLY=snap + if run_needs_sudo; then echo sudo; else echo none; fi' + [ "$output" = "none" ] +} + +@test "download-only: managers without a download mode are skipped, never run" { + local m + for m in yay paru flatpak snap brew yum emerge npm; do + run pkg_dry "$m" 'ARG_DOWNLOAD_ONLY=1' + [ "$status" -eq 0 ] + [[ "$output" == *"skip $m: no download-only mode"* ]] + [[ "$output" != *"[dry-run]"* ]] + [[ "$output" == *"rc=0" ]] + done +} + +@test "download-only: pacman, apt, dnf, zypper only download" { + stub pacman 'exit 0' + run pkg_dry pacman 'ARG_DOWNLOAD_ONLY=1' + [[ "$output" == *"pacman -Syuw --noconfirm"* ]] + [[ "$output" != *"-Syu --noconfirm"* ]] + run pkg_dry dnf 'ARG_DOWNLOAD_ONLY=1' + [[ "$output" == *"dnf upgrade -y --downloadonly"* ]] + [[ "$output" != *"autoremove"* ]] + run pkg_dry zypper 'ARG_DOWNLOAD_ONLY=1' + [[ "$output" == *"zypper --non-interactive update --download-only"* ]] + [[ "$output" != *"zypper clean"* ]] + stub apt 'exit 0' + run pkg_dry apt 'ARG_DOWNLOAD_ONLY=1' + [[ "$output" == *"apt -o APT::Status-Fd=1 full-upgrade -y --download-only"* ]] + [[ "$output" != *"autoremove"* ]] +} + +@test "download-only off: yay still upgrades" { + run pkg_dry yay '' + [[ "$output" == *"[dry-run] yay -Syu --noconfirm"* ]] +} + +@test "download-only: apt fix-broken only downloads, never installs" { + stub apt 'exit 0' + run pkg_dry apt 'ARG_DOWNLOAD_ONLY=1' + [ "$status" -eq 0 ] + [[ "$output" == *"apt -o APT::Status-Fd=1 --fix-broken install -y --download-only"* ]] + run pkg_dry apt '' + [[ "$output" == *"apt -o APT::Status-Fd=1 --fix-broken install -y"* ]] + [[ "$output" != *"--fix-broken install -y --download-only"* ]] +} + +@test "download-only: softwareupdate with --security downloads only the recommended updates" { + run pkg_dry softwareupdate 'ARG_DOWNLOAD_ONLY=1; ARG_SECURITY=1' + [ "$status" -eq 0 ] + [[ "$output" == *"softwareupdate --download --recommended"* ]] + [[ "$output" != *"--all"* ]] + run pkg_dry softwareupdate 'ARG_DOWNLOAD_ONLY=1' + [[ "$output" == *"softwareupdate --download --all"* ]] +} + +@test "softwareupdate downloads without installing under --download-only" { + run pkg 'ARG_DOWNLOAD_ONLY=1; ARG_ACCEPT_LICENSES=0; pkg_run softwareupdate' + [ "$status" -eq 0 ] + [[ "$output" == *"softwareupdate --download --all"* ]] + [[ "$output" != *"--install"* ]] + [[ "$output" != *"skip softwareupdate"* ]] +} diff --git a/tests/dry_run.bats b/tests/dry_run.bats new file mode 100644 index 0000000..29cea82 --- /dev/null +++ b/tests/dry_run.bats @@ -0,0 +1,77 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + # Managers the tests rely on, so detection does not depend on the host. + for m in apt snap; do printf '#!/bin/sh\nexit 0\n' >"$STUBS/$m"; chmod +x "$STUBS/$m"; done + printf '#!/bin/sh\necho "sudo $*" >>"$HOME/sudo.log"\n' >"$STUBS/sudo"; chmod +x "$STUBS/sudo" +} + +teardown() { + teardown_env +} + +@test "dry-run completes without sudo" { + run $EMERGER -n -y -nl -ni -nc -nt -q + [ "$status" -eq 0 ] + [ ! -e "$HOME/sudo.log" ] +} + +@test "dry-run: no ibus restart, package diff and history untouched" { + stub pgrep 'exit 0' + mkdir -p "$EMERGER_STATE" + echo keep >"$EMERGER_STATE/pkgs.diff" + run $EMERGER -n -y -nl --only none + [ "$status" -eq 0 ] + [ ! -e "$HOME/ibus.log" ] + [ "$(cat "$EMERGER_STATE/pkgs.diff")" = "keep" ] + [ ! -e "$EMERGER_STATE/history.jsonl" ] +} + +@test "real run: ibus is restarted when its daemon runs" { + stub pgrep 'exit 0' + run $EMERGER -y -nl -nc -nt --only none + [ "$status" -eq 0 ] + [ "$(cat "$HOME/ibus.log")" = "ibus restart" ] +} + +@test "dry-run --reboot with a reboot pending: attack sudo reboot, expected only a message" { + stub needs-restarting 'exit 1' + stub sudo 'echo "$@" >"$HOME/sudo-called"' + run env PATH="$STUBS:$PATH" $EMERGER -n --reboot + [ "$status" -eq 0 ] + [[ "$output" == *"would reboot"* ]] + [ ! -e "$HOME/sudo-called" ] +} + +@test "dry-run -au: attack unit files and timer enabled, expected nothing written" { + stub systemctl 'echo "$@" >>"$HOME/systemctl-called"' + stub crontab 'echo "$@" >>"$HOME/crontab-called"' + run env PATH="$STUBS:$PATH" $EMERGER -n -au + [ "$status" -eq 0 ] + [[ "$output" == *"[dry-run]"* ]] + ! grep -q enable "$HOME/systemctl-called" 2>/dev/null || false + ! grep -q daemon-reload "$HOME/systemctl-called" 2>/dev/null || false + [ ! -e "$HOME/crontab-called" ] + [ ! -e "$HOME/.config/systemd/user/emerger.service" ] +} + +@test "dry-run -rc: attack detection cache deleted, expected cache kept" { + mkdir -p "$XDG_CACHE_HOME/emerger"; echo apt >"$XDG_CACHE_HOME/emerger/detected" + run $EMERGER -n -rc -y -nl -nc -nt --only none + [ "$status" -eq 0 ] + [[ "$output" == *"[dry-run]"* ]] + [ -f "$XDG_CACHE_HOME/emerger/detected" ] +} + +@test "real run: attack the ibus restart inheriting the lock fd, expected fd 9 closed" { + [ -e /proc/self/fd ] || skip "no /proc" + command -v flock >/dev/null || skip "flock not available" + stub pgrep 'exit 0' + stub ibus 'if [ -e /proc/self/fd/9 ]; then echo 1; else echo 0; fi >"$HOME/ibus.fd"' + run $EMERGER -y -nl -nc -nt --only none + [ "$status" -eq 0 ] + [ "$(cat "$HOME/ibus.fd")" = "0" ] +} diff --git a/tests/emerger.bats b/tests/emerger.bats deleted file mode 100644 index 50b9d26..0000000 --- a/tests/emerger.bats +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env bats - -setup() { - export REPO_DIR="${BATS_TEST_DIRNAME}/.." - export EMERGER="bash $REPO_DIR/src/emerger.sh" - export HOME_BAK="$HOME" - export HOME="$(mktemp -d)" - export XDG_CACHE_HOME="$HOME/.cache" - export XDG_CONFIG_HOME="$HOME/.config" - export XDG_STATE_HOME="$HOME/.local/state" - export NO_COLOR=1 - mkdir -p "$XDG_CACHE_HOME" "$XDG_CONFIG_HOME" "$XDG_STATE_HOME" -} - -teardown() { - rm -rf "$HOME" - export HOME="$HOME_BAK" -} - -@test "help exits 0 and mentions USAGE" { - run $EMERGER --help - [ "$status" -eq 0 ] - [[ "$output" == *"USAGE"* ]] -} - -@test "version prints version string" { - run $EMERGER --version - [ "$status" -eq 0 ] - [[ "$output" == *"eMerger"* ]] -} - -@test "unknown flag fails with exit code 2" { - run $EMERGER --totally-bogus - [ "$status" -eq 2 ] -} - -@test "short no-logo flag is parsed correctly (not as -n)" { - run $EMERGER --help -nl - [ "$status" -eq 0 ] -} - -@test "errors shows ok on empty log" { - run $EMERGER --errors - [ "$status" -eq 0 ] -} - -@test "history shows placeholder when empty" { - run $EMERGER --history - [ "$status" -eq 0 ] -} - -@test "dry-run completes without sudo" { - run $EMERGER -n -y -nl -ni -nc -nt -q - [ "$status" -eq 0 ] -} - -@test "short flag bundling: -nv is accepted" { - run $EMERGER -nv -y -nl -ni -nc -nt -q - [ "$status" -eq 0 ] -} - -@test "json mode emits a single json object on stdout" { - run $EMERGER -n -y --json - [ "$status" -eq 0 ] - [[ "$output" == *'"managers":'* ]] - [[ "$output" == *'"errors":'* ]] -} - -@test "--only filter restricts managers" { - run $EMERGER -n -y --json --only apt - [ "$status" -eq 0 ] - [[ "$output" == *'"apt"'* ]] - [[ "$output" != *'"snap"'* ]] -} - -@test "--except filter skips managers" { - run $EMERGER -n -y --json --except snap - [ "$status" -eq 0 ] - [[ "$output" != *'"snap"'* ]] -} - -@test "--metrics refuses with empty history" { - run $EMERGER --metrics "$HOME/out.prom" - # Either exits non-zero or writes the file; both behaviors are fine here. - [ "$status" -eq 0 ] || [ "$status" -eq 1 ] -} - -@test "unknown long flag still fails with exit code 2" { - run $EMERGER --no-such-flag - [ "$status" -eq 2 ] -} diff --git a/tests/history.bats b/tests/history.bats new file mode 100644 index 0000000..b0b5c1a --- /dev/null +++ b/tests/history.bats @@ -0,0 +1,70 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + # Managers the tests rely on, so detection does not depend on the host. + for m in apt snap; do printf '#!/bin/sh\nexit 0\n' >"$STUBS/$m"; chmod +x "$STUBS/$m"; done + printf '#!/bin/sh\necho "sudo $*" >>"$HOME/sudo.log"\n' >"$STUBS/sudo"; chmod +x "$STUBS/sudo" +} + +teardown() { + teardown_env +} + +@test "history shows placeholder when empty" { + run $EMERGER --history + [ "$status" -eq 0 ] +} + +@test "history lists each run with its time, duration, errors and reboot" { + mkdir -p "$XDG_STATE_HOME/emerger" + printf '%s\n' '{"ts":"2026-01-02T03:04:05Z","duration":42,"freed_kb":0,"errors":0,"reboot":0,"managers":[]}' \ + '{"ts":"2026-01-03T03:04:05Z","duration":7,"freed_kb":0,"errors":2,"reboot":1,"managers":[]}' \ + >"$XDG_STATE_HOME/emerger/history.jsonl" + run $EMERGER --history --ascii + [ "$status" -eq 0 ] + [ "${lines[1]}" = " [OK] 2026-01-02T03:04:05Z 42s" ] + [ "${lines[2]}" = " [X] 2026-01-03T03:04:05Z 7s errors=2 reboot" ] +} + +@test "--metrics refuses with empty history" { + run $EMERGER --metrics "$HOME/out.prom" + [ "$status" -eq 1 ] + [[ "$output" == *"No history yet"* ]] + [ ! -e "$HOME/out.prom" ] +} + +@test "estimate: per-manager seconds, not the whole-run duration" { + mkdir -p "$EMERGER_STATE" + echo '{"ts":"2026-01-01T00:00:00Z","duration":600,"freed_kb":0,"errors":0,"reboot":0,"managers":[{"name":"apt","result":"ok","secs":30},{"name":"flatpak","result":"ok","secs":570}]}' >"$EMERGER_STATE/history.jsonl" + run lib 'echo "[$(estimate_for apt)] [$(estimate_for flatpak)] [$(estimate_for ok)] [$(estimate_for snap)]"' + [ "$output" = "[~30s] [~9m30s] [] []" ] +} + +@test "estimate: averages the last runs and ignores lines without secs" { + mkdir -p "$EMERGER_STATE" + { + echo '{"duration":900,"managers":[{"name":"apt","result":"ok"}]}' + echo '{"duration":50,"managers":[{"name":"apt","result":"ok","secs":10}]}' + echo '{"duration":50,"managers":[{"name":"apt","result":"fail","secs":20}]}' + } >"$EMERGER_STATE/history.jsonl" + run lib 'estimate_for apt' + [ "$output" = "~15s" ] +} + +@test "history: each manager carries its seconds" { + plugin pa '' + run $EMERGER -y -nl -nc -nt --only pa + [ "$status" -eq 0 ] + [[ "$(tail -n 1 "$EMERGER_STATE/history.jsonl")" =~ \"name\":\"pa\",\"result\":\"ok\",\"secs\":[0-9]+ ]] +} + +@test "errors: a UTF-8 log line shown on a non-UTF-8 terminal loses its bytes above 0x7F" { + mkdir -p "$XDG_STATE_HOME/emerger" + printf '2026-01-01T00:00:00Z|ERROR|caf\xc3\x9b31m\n' >"$XDG_STATE_HOME/emerger/emerger.log" + run env LANG=C LC_ALL=C $EMERGER --errors + [ "$status" -eq 0 ] + [[ "$output" == *"caf31m"* ]] +} diff --git a/tests/install.bats b/tests/install.bats new file mode 100644 index 0000000..09c9257 --- /dev/null +++ b/tests/install.bats @@ -0,0 +1,112 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_home + export XDG_CONFIG_HOME="$HOME/.config" + export SHELL=/bin/bash + touch "$HOME/.bashrc" +} + +teardown() { + teardown_home +} + +@test "install adds the up alias when no up command exists" { + run env PATH="$STUBS:/usr/bin:/bin" bash "$REPO_DIR/install.sh" + [ "$status" -eq 0 ] + grep -q "^alias up=.*emerger.sh" "$HOME/.bashrc" +} + +@test "install refuses to shadow an existing up command" { + printf '#!/bin/sh\necho other\n' >"$STUBS/up"; chmod +x "$STUBS/up" + run env PATH="$STUBS:/usr/bin:/bin" bash "$REPO_DIR/install.sh" + [ "$status" -eq 1 ] + [[ "$output" == *"$STUBS/up"* ]] + ! grep -q "emerger.sh" "$HOME/.bashrc" +} + +@test "install refuses to shadow an up alias already in the rc file" { + echo "alias up='cd ..'" >>"$HOME/.bashrc" + run env PATH="$STUBS:/usr/bin:/bin" bash "$REPO_DIR/install.sh" + [ "$status" -eq 1 ] + [[ "$output" == *".bashrc"* ]] + ! grep -q "emerger.sh" "$HOME/.bashrc" +} + +# Run install.sh with $1 written to file $2 under HOME; print the exit status. +setup_with_definition() { + mkdir -p "$(dirname "$HOME/$2")" + printf '%s\n' "$1" >>"$HOME/$2" + run env PATH="$STUBS:/usr/bin:/bin" bash "$REPO_DIR/install.sh" +} + +@test "install refuses to shadow 'function up {' in the rc file" { + setup_with_definition 'function up { cd ..; }' .bashrc + [ "$status" -eq 1 ] +} + +@test "install refuses to shadow an up alias in ~/.bash_aliases" { + setup_with_definition "alias up='cd ..'" .bash_aliases + [ "$status" -eq 1 ] + [[ "$output" == *".bash_aliases"* ]] +} + +@test "install refuses to shadow a fish function named up" { + setup_with_definition 'function up; cd ..; end' .config/fish/functions/up.fish + [ "$status" -eq 1 ] +} + +@test "install refuses a user up() beside an old eMerger alias" { + printf "alias up='bash \"/old/src/emerger.sh\"'\n" >>"$HOME/.bashrc" + setup_with_definition 'up() { cd ..; }' .bashrc + [ "$status" -eq 1 ] +} + +@test "install run twice keeps one alias and succeeds" { + run env PATH="$STUBS:/usr/bin:/bin" bash "$REPO_DIR/install.sh" + [ "$status" -eq 0 ] + run env PATH="$STUBS:/usr/bin:/bin" bash "$REPO_DIR/install.sh" + [ "$status" -eq 0 ] + [ "$(grep -c 'emerger.sh' "$HOME/.bashrc")" -eq 1 ] +} + +@test "install: attack install path with \$(cmd), expected refused" { + local d="$HOME/x\$(touch \$HOME/M)y" + mkdir -p "$d/src/lib" + cp "$REPO_DIR/install.sh" "$d/"; cp -R "$LIB"/. "$d/src/lib/"; cp "$REPO_DIR/src/emerger.sh" "$d/src/" + touch "$HOME/.bashrc" + run env PATH="$STUBS:/usr/bin:/bin" SHELL=/bin/bash bash "$d/install.sh" + [ "$status" -eq 1 ] + [[ "$output" == *"install path"* ]] + ! grep -q emerger.sh "$HOME/.bashrc" || false + bash -c "source '$HOME/.bashrc'" || true + [ ! -e "$HOME/M" ] +} + +@test "install: install path with a space gives a working alias" { + local d="$HOME/my dir" + mkdir -p "$d/src/lib" + cp "$REPO_DIR/install.sh" "$d/"; cp -R "$LIB"/. "$d/src/lib/"; cp "$REPO_DIR/src/emerger.sh" "$d/src/" + touch "$HOME/.bashrc" + run env PATH="$STUBS:/usr/bin:/bin" SHELL=/bin/bash bash "$d/install.sh" + [ "$status" -eq 0 ] + run bash -c "shopt -s expand_aliases; source '$HOME/.bashrc'; alias up" + [ "$output" = "alias up='bash \"$d/src/emerger.sh\"'" ] +} + +@test "install and uninstall: attack arithmetic payload in QUIET_LEVEL and UI_VERBOSE, expected no code run" { + for script in install.sh uninstall.sh; do + run env PATH="$STUBS:/usr/bin:/bin" "QUIET_LEVEL=HOME[\$(touch $HOME/m-q)]" "UI_VERBOSE=HOME[\$(touch $HOME/m-v)]" bash "$REPO_DIR/$script" + [ ! -e "$HOME/m-q" ] + [ ! -e "$HOME/m-v" ] + done +} + +@test "install installs the man page so man up finds it" { + run env PATH="$STUBS:/usr/bin:/bin" bash "$REPO_DIR/install.sh" + [ "$status" -eq 0 ] + cmp "$REPO_DIR/man/up.1" "$HOME/.local/share/man/man1/up.1" + [ "$(stat -c %a "$HOME/.local/share/man/man1/up.1")" = 644 ] +} diff --git a/tests/interrupt.bats b/tests/interrupt.bats new file mode 100644 index 0000000..4091658 --- /dev/null +++ b/tests/interrupt.bats @@ -0,0 +1,51 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +@test "interrupt: TERM during a manager stops the run with exit 1" { + plugin pa 'kill -TERM $$' + plugin pb '' + run $EMERGER -y -nl -nc -nt --only pa,pb + [ "$status" -eq 1 ] + [ "$(cat "$HOME/ran")" = "pa" ] + [[ "$output" == *"Interrupted"* ]] +} + +@test "interrupt: TERM inside a command removes its capture file and skips the rest" { + stub killparent 'kill -TERM $PPID; sleep 1' + plugin pa 'run_cmd step killparent' + plugin pb '' + run $EMERGER -y -nl -nc -nt --only pa,pb + [ "$status" -eq 1 ] + [ "$(cat "$HOME/ran")" = "pa" ] + [ -z "$(ls "$TMPDIR")" ] +} + +@test "interrupt: Ctrl-C at a prompt exits 1, never takes the default" { + command -v script >/dev/null || skip "script not available" + run bash -c "(sleep 2; printf '\003'; sleep 2) | script -qfec \"env DISK_MIN_FREE_MB=999999999 $EMERGER -nl -nc -nt --only none\" /dev/null" + [ "$status" -eq 1 ] + [[ "$output" == *"Interrupted"* ]] + [[ "$output" != *"using the default"* ]] +} + +@test "interrupt: TERM during --parallel removes the parallel capture files" { + plugin pp 'export MAINPID=$$; run_cmd step sh -c "kill -TERM \$MAINPID; sleep 5"' 'pm_pp_parallel() { return 0; }' + run $EMERGER -y -nl -nc -nt --parallel --only pp + [ "$status" -eq 1 ] + sleep 1 + [ -z "$(ls "$TMPDIR")" ] +} + +@test "interrupt: pkill, which stops the --parallel managers, is listed as optional in README and manual" { + grep -q '`pkill`' "$REPO_DIR/README.md" + grep -q 'texttt{pkill}' "$REPO_DIR/doc/documentation.tex" +} diff --git a/tests/json.bats b/tests/json.bats new file mode 100644 index 0000000..f1ebab7 --- /dev/null +++ b/tests/json.bats @@ -0,0 +1,67 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + # Managers the tests rely on, so detection does not depend on the host. + for m in apt snap; do printf '#!/bin/sh\nexit 0\n' >"$STUBS/$m"; chmod +x "$STUBS/$m"; done + printf '#!/bin/sh\necho "sudo $*" >>"$HOME/sudo.log"\n' >"$STUBS/sudo"; chmod +x "$STUBS/sudo" +} + +teardown() { + teardown_env +} + +@test "json mode emits a single json object on stdout" { + run $EMERGER -n -y --json + [ "$status" -eq 0 ] + [[ "$output" == *'"managers":'* ]] + [[ "$output" == *'"errors":'* ]] +} + +@test "summary: --json prints the line appended to history" { + stub needs-restarting 'exit 1' + run bash -c "$EMERGER --json -y -nc -nt --only none 2>/dev/null" + [ "$status" -eq 0 ] + [[ "$output" == *'"reboot":1'* ]] + [ "$output" = "$(tail -n 1 "$EMERGER_STATE/history.jsonl")" ] +} + +@test "--json: hook stdout stays off stdout" { + mkdir -p "$XDG_CONFIG_HOME/emerger/hooks/pre.d" + echo 'echo hook-says-hi' >"$XDG_CONFIG_HOME/emerger/hooks/pre.d/h.sh" + run bash -c "$EMERGER --json -y -nc -nt --only none 2>/dev/null" + [ "$status" -eq 0 ] + [ "${#lines[@]}" -eq 1 ] + [[ "${lines[0]}" == \{*\} ]] +} + +@test "--json -v: manager output stays off stdout" { + plugin pa 'run_cmd step echo noisy-manager' + run bash -c "$EMERGER --json -v -y -nc -nt --only pa 2>/dev/null" + [ "$status" -eq 0 ] + [ "${#lines[@]}" -eq 1 ] + [[ "${lines[0]}" == \{*\} ]] +} + +@test "json: plugin stdout goes to stderr, stdout holds one JSON line" { + mkdir -p "$XDG_CONFIG_HOME/emerger/managers.d" + cat >"$XDG_CONFIG_HOME/emerger/managers.d/noisy.sh" <<'EOS' +PM_PLUGIN_SLUG=noisy +pm_noisy_detect() { return 0; } +pm_noisy_run() { echo "plugin chatter"; return 0; } +EOS + chmod 600 "$XDG_CONFIG_HOME/emerger/managers.d/noisy.sh" + run bash -c "$EMERGER --json -y --only noisy 2>/dev/null" + [ "$status" -eq 0 ] + [ "${#lines[@]}" -eq 1 ] + [[ "${lines[0]}" == \{*\"noisy\"*\} ]] +} + +@test "--json prints only one JSON line on stdout" { + run bash -c "$EMERGER --json -n -y --only none 2>/dev/null" + [ "$status" -eq 0 ] + [ "${#lines[@]}" -eq 1 ] + [[ "${lines[0]}" == \{*\} ]] +} diff --git a/tests/knobs.bats b/tests/knobs.bats new file mode 100644 index 0000000..43a69ce --- /dev/null +++ b/tests/knobs.bats @@ -0,0 +1,55 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +@test "safety switch: DRY_RUN=true in config.sh is refused with exit 2" { + plugin pa '' + echo 'DRY_RUN=true' >"$XDG_CONFIG_HOME/emerger/config.sh" + run $EMERGER -y -nl -nc -nt --only pa + [ "$status" -eq 2 ] + [[ "$output" == *'DRY_RUN="true"'* ]] + [ ! -e "$HOME/ran" ] +} + +@test "safety switch: RPI_ABORT_ON_UNDERVOLTAGE=yes is refused with exit 2" { + run env RPI_ABORT_ON_UNDERVOLTAGE=yes $EMERGER -n -y -nl --only none + [ "$status" -eq 2 ] + [[ "$output" == *'RPI_ABORT_ON_UNDERVOLTAGE="yes"'* ]] +} + +@test "ARG_ASCII: attack arithmetic injection from the environment, expected ignored" { + run env ARG_ASCII='BASH_VERSINFO[$(touch $HOME/pwned-emoji)]' $EMERGER -n -y -nl --only none + [ "$status" -eq 0 ] + [ ! -e "$HOME/pwned-emoji" ] +} + +@test "SUMMARY_FREED_KB: attack arithmetic injection from the environment, expected ignored" { + run env SUMMARY_FREED_KB='BASH_VERSINFO[$(touch $HOME/pwned-freed)]' $EMERGER -n -y -nl --only none + [ "$status" -eq 0 ] + [ ! -e "$HOME/pwned-freed" ] +} + +@test "numeric knob: attack arithmetic injection from the environment, expected default" { + run env DISK_MIN_FREE_MB='ARG_YES[$(touch $HOME/M)]' RETRY_ATTEMPTS='a[$(touch $HOME/N)]' \ + $EMERGER -n -y -nl -nc -nt --only none + [ "$status" -eq 0 ] + [ ! -e "$HOME/M" ] + [ ! -e "$HOME/N" ] + [[ "$output" == *"DISK_MIN_FREE_MB"*"1024"* ]] +} + +@test "numeric knob: 08 reads as 8, 1m falls back with a warning" { + run lib 'EMERGER_PROMPT_TIMEOUT=08; knob_int EMERGER_PROMPT_TIMEOUT 60; echo "$EMERGER_PROMPT_TIMEOUT" + EMERGER_PROMPT_TIMEOUT=1m; knob_int EMERGER_PROMPT_TIMEOUT 60 2>&1; echo "$EMERGER_PROMPT_TIMEOUT"' + [ "${lines[0]}" = "8" ] + [[ "${lines[1]}" == *"EMERGER_PROMPT_TIMEOUT"* ]] + [ "${lines[2]}" = "60" ] +} diff --git a/tests/lint.bats b/tests/lint.bats new file mode 100644 index 0000000..575986e --- /dev/null +++ b/tests/lint.bats @@ -0,0 +1,101 @@ +#!/usr/bin/env bats +# Static checks over the PowerShell sources, run through pwsh's own parser. + +@test "every PowerShell file parses without errors" { + command -v pwsh >/dev/null || skip "pwsh not installed" + ROOT="${BATS_TEST_DIRNAME}/.." run pwsh -NoProfile -NonInteractive -Command ' + $bad = 0 + foreach ($f in Get-ChildItem -Path $env:ROOT -Recurse -Filter *.ps1) { + $errors = $null + [void][System.Management.Automation.Language.Parser]::ParseFile($f.FullName, [ref]$null, [ref]$errors) + foreach ($e in $errors) { Write-Output "$($f.FullName):$($e.Extent.StartLineNumber): $($e.Message)"; $bad++ } + } + exit $bad' + echo "$output" + [ "$status" -eq 0 ] +} + +# List each node under directory $1 whose syntax Windows PowerShell 5.1 +# cannot parse (pwsh 7 only), one "file:line: kind" per line, and exit with +# their count. +ps51_check() { + ROOT="$1" pwsh -NoProfile -NonInteractive -Command ' + $bad = 0 + foreach ($f in Get-ChildItem -Path $env:ROOT -Recurse -Filter *.ps1) { + $ast = [System.Management.Automation.Language.Parser]::ParseFile($f.FullName, [ref]$null, [ref]$null) + $hits = $ast.FindAll({ + param($n) + $n -is [System.Management.Automation.Language.PipelineChainAst] -or + $n -is [System.Management.Automation.Language.TernaryExpressionAst] -or + ($n -is [System.Management.Automation.Language.BinaryExpressionAst] -and $n.Operator -eq "QuestionQuestion") -or + ($n -is [System.Management.Automation.Language.AssignmentStatementAst] -and $n.Operator -eq "QuestionQuestionEquals") -or + ($n -is [System.Management.Automation.Language.MemberExpressionAst] -and $n.NullConditional) -or + ($n -is [System.Management.Automation.Language.IndexExpressionAst] -and $n.NullConditional) + }, $true) + foreach ($h in $hits) { + $kind = $h.GetType().Name + if ($h.Operator) { $kind += " $($h.Operator)" } + if ($h.NullConditional) { $kind += " null-conditional" } + Write-Output "$($f.FullName):$($h.Extent.StartLineNumber): $kind" + $bad++ + } + } + exit $bad' +} + +@test "every PowerShell file uses only syntax Windows PowerShell 5.1 parses" { + command -v pwsh >/dev/null || skip "pwsh not installed" + run ps51_check "${BATS_TEST_DIRNAME}/.." + echo "$output" + [ "$status" -eq 0 ] + [ -z "$output" ] +} + +@test "the 5.1 syntax check flags each pwsh 7 only construct" { + command -v pwsh >/dev/null || skip "pwsh not installed" + local d + d="$(mktemp -d)" + printf '%s\n' 'a && b' 'a || b' '$x = $a ? 1 : 2' '$x = $a ?? 1' '$x ??= 1' '${a}?.B' '${a}?[0]' '$ok = $a -and $b' >"$d/s.ps1" + run ps51_check "$d" + rm -rf "$d" + echo "$output" + [ "$status" -eq 7 ] + [[ "$output" == *"s.ps1:1: PipelineChainAst"* ]] + [[ "$output" == *"s.ps1:2: PipelineChainAst"* ]] + [[ "$output" == *"s.ps1:3: TernaryExpressionAst"* ]] + [[ "$output" == *"s.ps1:4: BinaryExpressionAst QuestionQuestion"* ]] + [[ "$output" == *"s.ps1:5: AssignmentStatementAst QuestionQuestionEquals"* ]] + [[ "$output" == *"s.ps1:6: MemberExpressionAst null-conditional"* ]] + [[ "$output" == *"s.ps1:7: IndexExpressionAst null-conditional"* ]] + [[ "$output" != *"s.ps1:8:"* ]] +} + +@test "shell sources: CI error-level shellcheck list exits 0" { + command -v shellcheck >/dev/null || skip "shellcheck not installed" + cd "${BATS_TEST_DIRNAME}/.." + shopt -s globstar nullglob + run shellcheck -S error install.sh uninstall.sh \ + src/emerger.sh src/lib/**/*.sh share/plugins/*.sh share/profiles/*.sh completions/up.bash + echo "$output" + [ "$status" -eq 0 ] +} + +@test "shell sources: CI warning-level shellcheck list exits 0" { + command -v shellcheck >/dev/null || skip "shellcheck not installed" + cd "${BATS_TEST_DIRNAME}/.." + shopt -s globstar nullglob + run shellcheck -S warning install.sh uninstall.sh \ + src/emerger.sh src/lib/**/*.sh share/plugins/*.sh share/profiles/*.sh completions/up.bash + echo "$output" + [ "$status" -eq 0 ] +} + +@test "the CI warnings leg cannot pass on a failure: no || true after shellcheck" { + run awk '/Lint \(warnings\)/{w=1} w && /\|\| true/{exit 1}' "${BATS_TEST_DIRNAME}/../.github/workflows/ci.yml" + [ "$status" -eq 0 ] +} + +@test "the CI tests job fails when pwsh is missing, so tests/ps_*.bats cannot skip green" { + run awk '/^ tests:/{t=1} t && /command -v pwsh &&/{f=1} t && /run: bats tests\//{if(!f) exit 1; ok=1} END{exit !ok}' "${BATS_TEST_DIRNAME}/../.github/workflows/ci.yml" + [ "$status" -eq 0 ] +} diff --git a/tests/load.bats b/tests/load.bats new file mode 100644 index 0000000..35e683f --- /dev/null +++ b/tests/load.bats @@ -0,0 +1,50 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_home +} + +teardown() { + teardown_home +} + +@test "load.sh: all defines a function of every module" { + run bash -c 'source "$LIB/load.sh" all; declare -F ui_ok sys_has pkg_detect lock_acquire trust_home metrics_export | wc -l' + [ "$status" -eq 0 ] + [ "$output" -eq 6 ] +} + +@test "load.sh: a file stem loads that module only" { + run bash -c 'source "$LIB/load.sh" sys; declare -F sys_has >/dev/null && echo sys; declare -F ui_ok >/dev/null || echo no-ui' + [ "$status" -eq 0 ] + [ "$output" = $'sys\nno-ui' ] +} + +@test "load.sh: an unknown name prints it, loads nothing and returns 1" { + run bash -c 'source "$LIB/load.sh" sys nosuch; echo "rc=$?"; declare -F sys_has || echo none' + [ "$status" -eq 0 ] + [ "$output" = $'load.sh: unknown module nosuch\nrc=1\nnone' ] +} + +@test "load.sh: leaves the caller's positional parameters and no helper variable" { + run bash -c 'source "$LIB/load.sh" sys; echo "$# $1"; declare -p _load_dir _load_names _load_name 2>&1 | grep -c "not found"' _ one two + [ "$status" -eq 0 ] + [ "$output" = $'2 one\n3' ] +} + +@test "load.sh: a directory name loads every module in it, a module path that one" { + run bash -c 'source "$LIB/load.sh" ui; declare -F ui_glyph _ui_strip ui_ok ui_monitor_start ui_confirm | wc -l + declare -F knob_int || echo no-knobs' + [ "$status" -eq 0 ] + [ "$output" = $'5\nno-knobs' ] + run bash -c 'source "$LIB/load.sh" ui/term; declare -F ui_glyph >/dev/null && echo term; declare -F ui_ok || echo no-print' + [ "$output" = $'term\nno-print' ] +} + +@test "load.sh: lists every module file under src/lib exactly once" { + run bash -c 'source "$LIB/load.sh"; printf "%s\n" "${_LOAD_MODULES[@]}" | sort' + [ "$status" -eq 0 ] + [ "$output" = "$(cd "$LIB" && find . -name '*.sh' ! -name load.sh | sed 's|^\./||; s|\.sh$||' | sort)" ] +} diff --git a/tests/lock.bats b/tests/lock.bats new file mode 100644 index 0000000..1795f9c --- /dev/null +++ b/tests/lock.bats @@ -0,0 +1,252 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +# Start a background lock holder for state directory $1 and wait until it +# holds the lock. +hold_lock() { + "$BASH" -c "EMERGER_STATE='$1'; source '$LIB/load.sh' ui lock + lock_acquire || exit 1; echo \$\$ >'$HOME/holder.pid'; touch '$HOME/held'; sleep 30" & + local i + for (( i=0; i<50; i++ )); do [[ -e $HOME/held ]] && return 0; sleep 0.1; done + return 1 +} + +# Print 1 if fd 9 is open in the process running this, else 0. +FD9_PROBE='if [ -e /proc/self/fd/9 ]; then echo 1; else echo 0; fi' + +@test "lock: -rc while another run holds the lock is refused, cache kept" { + mkdir -p "$EMERGER_STATE" "$XDG_CACHE_HOME/emerger" + echo apt >"$XDG_CACHE_HOME/emerger/detected" + flock "$EMERGER_STATE/emerger.lock" sleep 30 & + local holder=$! + sleep 0.5 + run $EMERGER -rc + kill "$holder" + [ "$status" -eq 1 ] + [[ "$output" == *"Another eMerger run"* ]] + [ -f "$XDG_CACHE_HOME/emerger/detected" ] +} + +@test "lock: --rollback while another run holds the lock is refused" { + mkdir -p "$EMERGER_STATE" + flock "$EMERGER_STATE/emerger.lock" sleep 30 & + local holder=$! + sleep 0.5 + run $EMERGER --rollback + kill "$holder" + [ "$status" -eq 1 ] + [[ "$output" == *"Another eMerger run"* ]] +} + +@test "lock without flock: a fresh lock with no pid yet is not taken over" { + mkdir -p "$HOME/bin" + local c + for c in mkdir rm cat sleep stat date touch; do ln -s "$(command -v "$c")" "$HOME/bin/$c"; done + mkdir "$HOME/emerger.lock.d" + run env PATH="$HOME/bin" "$BASH" -c "EMERGER_STATE='$HOME'; source '$LIB/load.sh' ui lock; lock_acquire; echo rc=\$?" + [[ "$output" == *"rc=1"* ]] + [ -d "$HOME/emerger.lock.d" ] + touch -d '1 minute ago' "$HOME/emerger.lock.d" + run env PATH="$HOME/bin" "$BASH" -c "EMERGER_STATE='$HOME'; source '$LIB/load.sh' ui lock; lock_acquire; echo rc=\$?" + [[ "$output" == *"rc=0"* ]] +} + +@test "lock without flock: a takeover racing another takeover never leaves two holders" { + mkdir -p "$HOME/bin" + local c + for c in mkdir rm cat sleep stat date touch; do ln -s "$(command -v "$c")" "$HOME/bin/$c"; done + mkdir "$HOME/emerger.lock.d"; echo 999999999 >"$HOME/emerger.lock.d/pid" + sleep 30 & local live=$! + # The first liveness probe stands in for a second run that takes the + # stale lock over between this run's check and its removal. + run env PATH="$HOME/bin" LIVE="$live" "$BASH" -c "EMERGER_STATE='$HOME'; source '$LIB/load.sh' ui lock + kill() { + if [[ \$1 == -0 && ! -e '$HOME/raced' ]]; then + touch '$HOME/raced'; rm -rf '$HOME/emerger.lock.d'; mkdir '$HOME/emerger.lock.d'; echo \$LIVE >'$HOME/emerger.lock.d/pid'; return 1 + fi + builtin kill \"\$@\" + } + lock_acquire; echo rc=\$?" + local held; held=$(cat "$HOME/emerger.lock.d/pid") + kill "$live" + [[ "$output" == *"rc=1"* ]] + [ "$held" = "$live" ] + [ ! -e "$HOME/emerger.lock.d.break" ] +} + +@test "lock without flock: a stale break lock refuses once, then the next run takes over" { + mkdir -p "$HOME/bin" + local c + for c in mkdir rm cat sleep stat date touch; do ln -s "$(command -v "$c")" "$HOME/bin/$c"; done + mkdir "$HOME/emerger.lock.d" "$HOME/emerger.lock.d.break"; echo 999999999 >"$HOME/emerger.lock.d/pid" + run env PATH="$HOME/bin" "$BASH" -c "EMERGER_STATE='$HOME'; source '$LIB/load.sh' ui lock; lock_acquire; echo rc=\$?" + [[ "$output" == *"rc=1"* ]] + [ -d "$HOME/emerger.lock.d.break" ] + touch -d '1 minute ago' "$HOME/emerger.lock.d.break" + run env PATH="$HOME/bin" "$BASH" -c "EMERGER_STATE='$HOME'; source '$LIB/load.sh' ui lock; lock_acquire; echo rc=\$?" + [[ "$output" == *"rc=1"* ]] + [ ! -e "$HOME/emerger.lock.d.break" ] + run env PATH="$HOME/bin" "$BASH" -c "EMERGER_STATE='$HOME'; source '$LIB/load.sh' ui lock; lock_acquire; echo rc=\$?" + [[ "$output" == *"rc=0"* ]] +} + +@test "lock without flock: attack two concurrent runs, expected second refused" { + mkdir -p "$HOME/bin" + local c + for c in mkdir rm cat sleep touch; do ln -s "$(command -v "$c")" "$HOME/bin/$c"; done + PATH="$HOME/bin" hold_lock "$HOME" + run env PATH="$HOME/bin" "$BASH" -c "EMERGER_STATE='$HOME'; source '$LIB/load.sh' ui lock; lock_acquire; echo rc=\$?" + [[ "$output" == *"rc=1"* ]] + [[ "$output" == *"in progress"* ]] +} + +@test "lock without flock: a dead holder's lock is taken over" { + mkdir -p "$HOME/bin" + local c + for c in mkdir rm cat sleep; do ln -s "$(command -v "$c")" "$HOME/bin/$c"; done + mkdir "$HOME/emerger.lock.d"; echo 999999999 >"$HOME/emerger.lock.d/pid" + run env PATH="$HOME/bin" "$BASH" -c "EMERGER_STATE='$HOME'; source '$LIB/load.sh' ui lock; lock_acquire; echo rc=\$?; lock_release; [ -e '$HOME/emerger.lock.d' ] && echo left || echo gone" + [ "${lines[0]}" = "rc=0" ] + [ "${lines[1]}" = "gone" ] +} + +@test "lock on an unopenable path: attack lock skipped, expected error" { + run lib "EMERGER_STATE=$HOME/missing/dir; lock_acquire; echo rc=\$?" + [[ "$output" == *"rc=1"* ]] + [[ "$output" == *"$HOME/missing/dir/emerger.lock"* ]] +} + +@test "lock refused: attack holder PID wiped, expected PID kept and named" { + command -v flock >/dev/null || skip "flock not available" + hold_lock "$HOME" + local pid; pid=$(cat "$HOME/holder.pid") + run lib "EMERGER_STATE=$HOME; lock_acquire; echo rc=\$?" + [[ "$output" == *"rc=1"* ]] + [[ "$output" == *"PID $pid"* ]] + [[ "$output" != *"remove the lock file"* ]] + [ "$(cat "$HOME/emerger.lock")" = "$pid" ] +} + +@test "lock path: attack cron run without XDG_RUNTIME_DIR, expected same lock file" { + mkdir -p "$HOME/st" + run bash -c "EMERGER_STATE=$HOME/st; XDG_RUNTIME_DIR=$HOME/run; source '$LIB/load.sh' ui lock; lock_acquire; echo \$EMERGER_LOCK" + [ "$output" = "$HOME/st/emerger.lock" ] + [ -f "$HOME/st/emerger.lock" ] +} + +@test "lock fd: attack children inheriting fd 9, expected closed in run_cmd, hooks and plugins" { + [ -e /proc/self/fd ] || skip "no /proc" + mkdir -p "$XDG_CONFIG_HOME/emerger/hooks/post.d" "$XDG_CONFIG_HOME/emerger/managers.d" + printf '%s\n' "$FD9_PROBE >\"\$HOME/hook\"" >"$XDG_CONFIG_HOME/emerger/hooks/post.d/p.sh" + cat >"$XDG_CONFIG_HOME/emerger/managers.d/q.sh" <"\$HOME/plugin"; } +EOF + run lib "exec 9>>$HOME/l; DRY_RUN=0 + run_cmd x sh -c '$FD9_PROBE >\$HOME/quiet' + UI_VERBOSE=1 run_cmd x sh -c '$FD9_PROBE >\$HOME/verbose' + hooks_run post; PKG_MANAGERS=(); plugins_load; plugin_run q + $FD9_PROBE" + [ "${lines[-1]}" = "1" ] + [ "$(cat "$HOME/quiet")" = "0" ] + [ "$(cat "$HOME/verbose")" = "0" ] + [ "$(cat "$HOME/hook")" = "0" ] + [ "$(cat "$HOME/plugin")" = "0" ] +} + +@test "lock fd: attack hook leaves a background child, expected next run starts" { + command -v flock >/dev/null || skip "flock not available" + mkdir -p "$XDG_CONFIG_HOME/emerger/hooks/post.d" + printf 'sleep 20 >/dev/null 2>&1 &\necho $! >"$HOME/bg.pid"\n' >"$XDG_CONFIG_HOME/emerger/hooks/post.d/bg.sh" + run env PATH="$STUBS:$PATH" $EMERGER -y -nl -nc -nt --only none + [ "$status" -eq 0 ] + [ -f "$HOME/bg.pid" ] + run env PATH="$STUBS:$PATH" $EMERGER -n -y -nl -nc -nt --only none + [ "$status" -eq 0 ] + [[ "$output" != *"in progress"* ]] +} + +@test "stderr still works after taking the lock" { + run bash -c "$EMERGER -n -y -nl -nc -nt --only none 2>&1 >/dev/null" + [ "$status" -eq 0 ] + [[ "$output" == *"No supported package managers detected"* ]] +} + +@test "lock fd: attack the monitor and the sudo keep-alive, expected fd 9 closed in both" { + [ -e /proc/self/fd ] || skip "no /proc" + stub sudo 'exit 0' + run lib "exec 9>>$HOME/l; UI_IS_TTY=1 + ui_monitor_start lbl /dev/null >/dev/null; mon=\$_MONITOR_PID + run_sudo_keepalive 30; ka=\$SUDO_KEEPALIVE_PID + echo \$ka >$HOME/ka.pid; sleep 0.3 + echo \"monitor=\$([ -e /proc/\$mon/fd/9 ] && echo 1 || echo 0) keepalive=\$([ -e /proc/\$ka/fd/9 ] && echo 1 || echo 0)\" + ui_monitor_stop >/dev/null; kill \$ka" + [[ "$output" == *"monitor=0 keepalive=0"* ]] +} + +@test "lock fd: attack plugin detect and plugin run under --json, expected fd 9 closed" { + [ -e /proc/self/fd ] || skip "no /proc" + mkdir -p "$XDG_CONFIG_HOME/emerger/managers.d" + cat >"$XDG_CONFIG_HOME/emerger/managers.d/q.sh" <"\$HOME/detect"; return 0; } +pm_q_run() { bash -c '$FD9_PROBE' >"\$HOME/run-json" 2>&1; } +EOF + run lib "exec 9>>$HOME/l; DRY_RUN=0; PKG_MANAGERS=(); plugins_load + plugin_detect q; ARG_JSON=1 plugin_run q" + [ "$(cat "$HOME/detect")" = "0" ] + [ "$(cat "$HOME/run-json")" = "0" ] +} + +@test "lock fd: attack tools run by diff, self-update, root helper, EEPROM check and notification, expected fd 9 closed" { + [ -e /proc/self/fd ] || skip "no /proc" + stub git 'echo "$([ "$1" = -C ] && echo "$3" || echo "$1") $([ -e /proc/self/fd/9 ] && echo 1 || echo 0)" >>"$HOME/git.fd"; exit 0' + for t in brew rpi-eeprom-update notify-send; do + stub "$t" "if [ -e /proc/self/fd/9 ]; then echo 1; else echo 0; fi >\"\$HOME/$t.fd\"; exit 0" + done + mkdir -p "$HOME/co/.git" + run lib "exec 9>>$HOME/l; DRY_RUN=0; ARG_FIRMWARE=0; SUMMARY_ERRORS=0; SUMMARY_MANAGERS=(a); DISPLAY=:0 + diff_snapshot $HOME/snap + self_update $HOME/co + sys_as_root sh -c '$FD9_PROBE >$HOME/root.fd' + rpi_eeprom_run '' + source \"\$LIB/load.sh\" notify; notify_send_result" + [ "$(cat "$HOME/brew.fd")" = "0" ] + grep -q '^fetch 0$' "$HOME/git.fd" + grep -q '^pull 0$' "$HOME/git.fd" + ! grep -q '^\(fetch\|pull\) 1$' "$HOME/git.fd" + [ "$(cat "$HOME/root.fd")" = "0" ] + [ "$(cat "$HOME/rpi-eeprom-update.fd")" = "0" ] + [ "$(cat "$HOME/notify-send.fd")" = "0" ] +} + +@test "lock fd: attack osascript on macOS, expected fd 9 closed" { + [ -e /proc/self/fd ] || skip "no /proc" + stub osascript "if [ -e /proc/self/fd/9 ]; then echo 1; else echo 0; fi >\"\$HOME/osa.fd\"; exit 0" + run lib "exec 9>>$HOME/l; SUMMARY_ERRORS=0; SUMMARY_MANAGERS=(a); unset DISPLAY WAYLAND_DISPLAY + source \"\$LIB/load.sh\" notify; sys_is_macos() { return 0; }; notify_send_result" + [ "$(cat "$HOME/osa.fd")" = "0" ] +} + +@test "lock fd: attack the parallel manager subshell, expected fd 9 closed" { + [ -e /proc/self/fd ] || skip "no /proc" + command -v flock >/dev/null || skip "flock not available" + plugin pp '' 'pm_pp_parallel() { return 0; } +pm_pp_icon() { + if [ "$(readlink /proc/self/fd/2)" = "$EMERGER_STATE/parallel-pp.log" ]; then '"$FD9_PROBE"' >"$HOME/par.fd"; fi + printf x +}' + run $EMERGER -y -nl -nc -nt --parallel --only pp + [ "$status" -eq 0 ] + [ "$(cat "$HOME/par.fd")" = "0" ] +} diff --git a/tests/managers.bats b/tests/managers.bats new file mode 100644 index 0000000..fd5a801 --- /dev/null +++ b/tests/managers.bats @@ -0,0 +1,106 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin + # Managers the tests rely on, so detection does not depend on the host. + for m in apt snap; do printf '#!/bin/sh\nexit 0\n' >"$STUBS/$m"; chmod +x "$STUBS/$m"; done + printf '#!/bin/sh\necho "sudo $*" >>"$HOME/sudo.log"\n' >"$STUBS/sudo"; chmod +x "$STUBS/sudo" +} + +teardown() { + teardown_env +} + +# Run a snippet with the package dispatcher sourced, in dry-run. +pkg() { + lib 'EMERGER_CONFIG=$HOME/.config/emerger + source "$LIB/load.sh" estimate ignore registry detect icon recipes + DRY_RUN=1; ARG_SECURITY=0; ARG_DOWNLOAD_ONLY=0; ARG_DEV=0 + '"$1" +} + +@test "without a filter both stubbed managers run" { + run $EMERGER -n -y --json + [ "$status" -eq 0 ] + [[ "$output" == *'"apt"'* ]] + [[ "$output" == *'"snap"'* ]] +} + +@test "--only filter restricts managers" { + run $EMERGER -n -y --json --only apt + [ "$status" -eq 0 ] + [[ "$output" == *'"apt"'* ]] + [[ "$output" != *'"snap"'* ]] +} + +@test "--except filter skips managers" { + run $EMERGER -n -y --json --except snap + [ "$status" -eq 0 ] + [[ "$output" == *'"apt"'* ]] + [[ "$output" != *'"snap"'* ]] +} + +@test "registry: a plugin answers sudo, dev and security, an unknown name answers no" { + plugin px '' 'pm_px_needs_sudo() { return 0; }; pm_px_dev() { return 0; }; pm_px_security() { return 1; }' + run lib 'plugins_load; for q in pkg_needs_sudo pkg_is_dev pkg_has_security pkg_is_parallelizable; do + if $q px; then echo "$q yes"; else echo "$q no"; fi; $q nosuch && echo "$q nosuch"; done; true' + [ "$status" -eq 0 ] + [ "$output" = "$(printf '%s\n' 'pkg_needs_sudo yes' 'pkg_is_dev yes' 'pkg_has_security no' 'pkg_is_parallelizable no')" ] +} + +@test "detection cache: stale entries are dropped, one line per manager" { + stub apt 'exit 0' + printf '!apt\n!pacman\n' >"$HOME/.cache/emerger/detected" + touch -d '2 days ago' "$HOME/.cache/emerger/detected" + run sys_lib 'pkg_detect pacman || echo "pacman absent" + pkg_detect apt && echo "apt found" + pkg_detect apt && echo "apt found" + sort "$EMERGER_CACHE/detected" | paste -sd,' + [ "$status" -eq 0 ] + [ "${lines[0]}" = "pacman absent" ] + [ "${lines[1]}" = "apt found" ] + [ "${lines[2]}" = "apt found" ] + [ "${lines[3]}" = "!pacman,apt" ] +} + +@test "detection cache: fresh entry is trusted, TTL 0 disables it" { + printf 'pacman\n' >"$HOME/.cache/emerger/detected" + run sys_lib 'pkg_detect pacman && echo cached' + [ "$output" = "cached" ] + run sys_lib 'EMERGER_CACHE_TTL=0; pkg_detect pacman || echo probed' + [ "$output" = "probed" ] +} + +@test "rpi: bootloader update applied only with --firmware" { + cat >"$STUBS/rpi-eeprom-update" <<'EOF' +#!/bin/sh +[ "$1" = "-a" ] && { echo applied >"$HOME/applied"; exit 0; } +echo "BOOTLOADER: update available" +echo " CURRENT: Thu May 8 2025 (1746713597)" +echo " LATEST: Fri Sep 25 2026 (1790351949)" +exit 1 +EOF + chmod +x "$STUBS/rpi-eeprom-update" + run lib "PATH=$STUBS:\$PATH; DRY_RUN=0; ARG_FIRMWARE=0; rpi_eeprom_run ''" + [ "$status" -eq 0 ] + [[ "$output" == *"update available"* ]] + [[ "$output" == *"up --firmware"* ]] + [ ! -e "$HOME/applied" ] + run lib "PATH=$STUBS:\$PATH; DRY_RUN=0; ARG_FIRMWARE=1; rpi_eeprom_run ''; echo pending=\$RPI_EEPROM_IS_PENDING" + [ -e "$HOME/applied" ] + [[ "$output" == *"pending=1"* ]] +} + +@test "softwareupdate accepts the licence only with --accept-licenses" { + run pkg 'ARG_ACCEPT_LICENSES=0; pkg_run softwareupdate' + [ "$status" -eq 0 ] + [[ "$output" != *"--agree-to-license"* ]] + [[ "$output" != *"--install"* ]] + [[ "$output" == *"--accept-licenses"* ]] + run pkg 'ARG_ACCEPT_LICENSES=1; pkg_run softwareupdate' + [ "$status" -eq 0 ] + [[ "$output" == *"softwareupdate --install --all --agree-to-license"* ]] +} diff --git a/tests/metrics.bats b/tests/metrics.bats new file mode 100644 index 0000000..f9bde80 --- /dev/null +++ b/tests/metrics.bats @@ -0,0 +1,64 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_home + export EMERGER_STATE="$HOME/state" + mkdir -p "$EMERGER_STATE" +} + +teardown() { + teardown_home +} + +# Export metrics from a history whose last line is $1. +export_with() { + echo "$1" >"$EMERGER_STATE/history.jsonl" + bash -c 'set -Eeuo pipefail; source "$LIB/load.sh" ui history metrics; metrics_export "$HOME/m.prom"' +} + +@test "metrics: a run with no managers still writes every gauge" { + run export_with '{"ts":"2026-01-01T00:00:00Z","duration":3,"freed_kb":2,"errors":0,"reboot":1,"managers":[]}' + [ "$status" -eq 0 ] + grep -qx 'emerger_last_run_duration_seconds 3' "$HOME/m.prom" + grep -qx 'emerger_last_run_freed_bytes 2048' "$HOME/m.prom" + grep -qx 'emerger_reboot_required 1' "$HOME/m.prom" + [ -z "$(ls "$HOME" | grep 'm.prom.')" ] +} + +@test "metrics: one gauge per manager with its result" { + run export_with '{"ts":"2026-01-01T00:00:00Z","duration":3,"freed_kb":0,"errors":1,"reboot":0,"managers":[{"name":"apt","result":"ok"},{"name":"snap","result":"fail"}]}' + [ "$status" -eq 0 ] + grep -qx 'emerger_manager_ok{manager="apt"} 1' "$HOME/m.prom" + grep -qx 'emerger_manager_ok{manager="snap"} 0' "$HOME/m.prom" + grep -qx 'emerger_last_run_errors 1' "$HOME/m.prom" +} + +@test "metrics: the timestamp converts with BSD date too" { + mkdir -p "$HOME/stubs" + # BSD date: no -d, -j -f parses. Emulated with GNU date. + cat >"$HOME/stubs/date" <<'EOS' +#!/bin/bash +[[ $1 == -d ]] && exit 1 +if [[ $1 == -j ]]; then exec /bin/date -u -d "$5" "$6"; fi +exec /bin/date "$@" +EOS + chmod +x "$HOME/stubs/date" + PATH="$HOME/stubs:$PATH" run export_with '{"ts":"2026-01-01T00:00:00Z","duration":1,"freed_kb":0,"errors":0,"reboot":0,"managers":[]}' + [ "$status" -eq 0 ] + grep -qx 'emerger_last_run_timestamp_seconds 1767225600' "$HOME/m.prom" +} + +@test "metrics: a symlink planted at the temp name is not followed" { + unshare -rpf true 2>/dev/null || skip "PID namespaces unavailable" + echo '{"ts":"2026-01-01T00:00:00Z","duration":5,"freed_kb":1,"errors":0,"reboot":0,"managers":[{"name":"apt","result":"ok"}]}' >"$EMERGER_STATE/history.jsonl" + echo keep >"$HOME/victim" + # In a fresh PID namespace the exporting shell is PID 1: plant every name it could pick. + for pid in 1 2 3; do ln -s "$HOME/victim" "$HOME/out.prom.tmp.$pid"; done + run unshare -rpf bash -c 'source "$LIB/load.sh" ui history metrics; metrics_export "$HOME/out.prom"' + [ "$status" -eq 0 ] + [ "$(cat "$HOME/victim")" = keep ] + grep -q '^emerger_manager_ok{manager="apt"} 1$' "$HOME/out.prom" + [ "$(stat -c %a "$HOME/out.prom")" = 644 ] +} diff --git a/tests/mirrors.bats b/tests/mirrors.bats new file mode 100644 index 0000000..6bb0e2c --- /dev/null +++ b/tests/mirrors.bats @@ -0,0 +1,147 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +# Stub reflector, netselect-apt, install and a logging sudo for mirrors_refresh. +stub_mirror_tools() { + stub reflector 'echo "reflector $*" >>"$HOME/calls"' + stub netselect-apt 'echo "netselect-apt $*" >>"$HOME/calls"; [ "$1" = -o ] && echo "deb http://mirror.example/debian $3 main" >"$2"; exit 0' + stub install 'echo "install $*" >>"$HOME/calls"' + stub sudo 'echo "sudo $*" >>"$HOME/calls"; exec "$@"' +} + +# Shell code that sources the mirror lib and answers as Debian 13. +MIRRORS_DEBIAN='source "$LIB/load.sh" mirrors + _mirrors_os_release() { printf "ID=debian\nVERSION_ID=13\nVERSION_CODENAME=trixie\n"; }' + +# Stub sudo, netselect-apt and install for mirrors_refresh; $1 is install's exit code. +stub_netselect() { + cat >"$STUBS/sudo" <<'EOS' +#!/bin/bash +echo "sudo $*" >>"$HOME/sudo.log" +"$@" +EOS + cat >"$STUBS/netselect-apt" <<'EOS' +#!/bin/sh +echo "netselect-apt $*" >>"$HOME/sudo.log" +[ "$1" = -o ] && echo "deb http://mirror.example/debian $3 main" >"$2" +EOS + printf '#!/bin/sh\nexit %s\n' "$1" >"$STUBS/install" + chmod +x "$STUBS/sudo" "$STUBS/netselect-apt" "$STUBS/install" +} + +# Run mirrors_refresh with the stubs and the os-release file given. +run_mirrors() { + bash -c 'set -Eeuo pipefail; PATH="$STUBS:$PATH"; source "$LIB/load.sh" ui sys mirrors + osr=$1; _mirrors_os_release() { cat "$osr"; }; sys_is_root() { return 1; } + DRY_RUN=0; mirrors_refresh; echo done' _ "$1" +} + +@test "mirrors: as root, reflector and netselect-apt run without sudo" { + stub_mirror_tools + rm "$STUBS/sudo" + run sys_lib "$MIRRORS_DEBIAN"'; sys_is_root() { return 0; }; mirrors_refresh; echo done' + [ "$status" -eq 0 ] + [ "${lines[-1]}" = done ] + [[ "$output" == *"reflector: pacman mirrorlist updated"* ]] + [[ "$output" == *"netselect-apt: wrote"* ]] + grep -q '^install -m 0644 ' "$HOME/calls" +} + +@test "mirrors: as a user, every privileged step goes through sudo" { + stub_mirror_tools + run sys_lib "$MIRRORS_DEBIAN"'; sys_is_root() { return 1; }; mirrors_refresh; echo done' + [ "$status" -eq 0 ] + [ "${lines[-1]}" = done ] + for c in reflector mktemp netselect-apt install rm; do grep -q "^sudo $c " "$HOME/calls"; done +} + +@test "mirrors: a failing sudo mktemp warns and the run goes on" { + stub_mirror_tools + stub sudo 'echo "sudo $*" >>"$HOME/calls"; [ "$1" = mktemp ] && exit 1; exec "$@"' + run sys_lib "$MIRRORS_DEBIAN"'; sys_is_root() { return 1; }; mirrors_refresh; echo done' + [ "$status" -eq 0 ] + [ "${lines[-1]}" = done ] + [[ "$output" == *"netselect-apt: could not create a temp file as root"* ]] + ! grep -q '^netselect-apt' "$HOME/calls" || false +} + +@test "mirrors: the netselect-apt list is created by root, never by the user" { + cat >"$STUBS/sudo" <<'EOS' +#!/bin/bash +echo "sudo $*" >>"$HOME/sudo.log" +if [[ $1 == mktemp ]]; then f=$("$@"); echo "$f" >"$HOME/rootfile"; echo "$f"; exit 0; fi +"$@" +EOS + cat >"$STUBS/netselect-apt" <<'EOS' +#!/bin/sh +[ "$1" = -o ] && echo "deb http://mirror.example/debian stable main" >"$2" +EOS + printf '#!/bin/sh\nexit 0\n' >"$STUBS/install" + chmod +x "$STUBS/sudo" "$STUBS/netselect-apt" "$STUBS/install" + printf 'ID=debian\nVERSION_ID="13"\nVERSION_CODENAME=trixie\n' >"$HOME/os-release" + run bash -c 'PATH="$STUBS:$PATH"; source "$LIB/load.sh" ui sys mirrors; _mirrors_os_release() { cat "$HOME/os-release"; }; sys_is_root() { return 1; }; DRY_RUN=0; mirrors_refresh' + [ "$status" -eq 0 ] + [ -s "$HOME/rootfile" ] + grep -q "^sudo install -m 0644 $(cat "$HOME/rootfile") /etc/apt/sources.list.d/netselect.list$" "$HOME/sudo.log" +} + +@test "mirrors: netselect-apt asks for the running Debian suite" { + stub_netselect 0 + printf 'ID=debian\nVERSION_ID="13"\nVERSION_CODENAME=trixie\n' >"$HOME/os-release" + run run_mirrors "$HOME/os-release" + [ "$status" -eq 0 ] + grep -q '^netselect-apt -o .* trixie$' "$HOME/sudo.log" +} + +@test "mirrors: netselect-apt is skipped on a Debian derivative" { + stub_netselect 0 + printf 'ID=ubuntu\nID_LIKE=debian\nVERSION_CODENAME=noble\n' >"$HOME/os-release" + run run_mirrors "$HOME/os-release" + [ "$status" -eq 0 ] + ! grep -q '^netselect-apt' "$HOME/sudo.log" +} + +@test "mirrors: a failing install warns, removes the temp file and the run goes on" { + stub_netselect 1 + printf 'ID=debian\nVERSION_ID="13"\nVERSION_CODENAME=trixie\n' >"$HOME/os-release" + run run_mirrors "$HOME/os-release" + [ "$status" -eq 0 ] + [[ "$output" == *"could not install"* ]] + [[ "${lines[-1]}" == done ]] + tmp=$(grep -o 'netselect-apt -o [^ ]*' "$HOME/sudo.log" | head -1 | awk '{print $3}') + [ ! -e "$tmp" ] +} + +@test "mirrors: netselect-apt is skipped on testing and sid" { + stub_netselect 0 + printf 'ID=debian\nVERSION_CODENAME=forky\n' >"$HOME/os-release" + run run_mirrors "$HOME/os-release" + [ "$status" -eq 0 ] + ! grep -q '^netselect-apt' "$HOME/sudo.log" 2>/dev/null || false +} + +@test "mirrors: attack netselect-apt output with source options, expected not installed" { + local bad + for bad in 'deb [trusted=yes] http://mirror.example/debian trixie main' \ + 'deb http://mirror.example/debian trixie main; touch /x' \ + 'deb file:///tmp/x trixie main'; do + stub reflector 'exit 1' + stub netselect-apt "[ \"\$1\" = -o ] && printf '%s\n' '$bad' >\"\$2\"; exit 0" + stub install 'echo "install $*" >>"$HOME/calls"' + stub sudo 'exec "$@"' + printf 'ID=debian\nVERSION_ID="13"\nVERSION_CODENAME=trixie\n' >"$HOME/os-release" + run bash -c 'PATH="$STUBS:$PATH"; source "$LIB/load.sh" ui sys mirrors; _mirrors_os_release() { cat "$HOME/os-release"; }; sys_is_root() { return 1; }; DRY_RUN=0; mirrors_refresh' + [ ! -e "$HOME/calls" ] + [[ "$output" == *"not installed"* ]] + done +} diff --git a/tests/monitor.bats b/tests/monitor.bats new file mode 100644 index 0000000..d7ead4e --- /dev/null +++ b/tests/monitor.bats @@ -0,0 +1,124 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +@test "monitor: stop returns only after the monitor exited" { + run lib 'UI_IS_TTY=1; ui_monitor_start lbl /dev/null >/dev/null; p=$_MONITOR_PID; sleep 0.35 + ui_monitor_stop >/dev/null; if kill -0 "$p" 2>/dev/null; then echo alive; else echo gone; fi' + [ "$output" = "gone" ] +} + +@test "monitor: exits once the main process is killed" { + bash -c 'set -uo pipefail; source "$LIB/load.sh" ui log sys progress run + UI_IS_TTY=1; ui_monitor_start lbl /dev/null; echo "$_MONITOR_PID" >"$HOME/m.pid"; sleep 30' >/dev/null 2>&1 & + local parent=$! + sleep 1 + kill -9 "$parent" + sleep 3 + local m; m=$(cat "$HOME/m.pid") + run kill -0 "$m" + kill "$m" 2>/dev/null || true + [ "$status" -ne 0 ] +} + +@test "monitor: a partial line is shown after 2 s without output" { + run lib 'f=$(mktemp); printf "Overwrite config? [y/N] " >"$f" + UI_IS_TTY=1; ui_monitor_start lbl "$f" >"$HOME/mon.out" + # Wait for the frame, bounded: a loaded machine draws frames late. + for (( i = 0; i < 600; i++ )); do + grep -qF "Overwrite config?" "$HOME/mon.out" && break; sleep 0.1 + done + ui_monitor_stop >/dev/null + cat "$HOME/mon.out"' + [[ "$output" == *"Overwrite config? [y/N]"* ]] +} + +@test "monitor: attack OSC in manager output, expected stripped from the live line" { + run lib "printf 'x\033]52;c;SGVsbG8=\007end\n' >$HOME/m.log; UI_IS_TTY=1 + ui_monitor_start lbl $HOME/m.log; sleep 0.5; ui_monitor_stop" + [[ "$output" == *"xend"* ]] + [[ "$output" != *"]52"* ]] + [[ "$output" != *$'\a'* ]] +} + +@test "monitor: attack 160 KB of CSI in one line, expected cleaned within the time bound" { + run lib 'timeout 20 bash -c "source \"\$LIB/load.sh\" ui + line=\$(printf \"\\033[1m%.0s\" \$(seq 40000)) + _ui_clean_line \"\$line\"; echo len=\${#_UI_CLEANED}"; echo rc=$?' + [[ "$output" == *"len=0"* ]] + [[ "$output" == *"rc=0"* ]] +} + +@test "monitor: line cleaning removes CSI, OSC with either terminator and control bytes" { + run lib "_ui_clean_line \$'a\\e[1;31mb\\e]0;t\\acd\\e]8;;u\\e\\\\ef\\x01g\\rh\\e[?25li'; echo \"[\$_UI_CLEANED]\"" + [ "$output" = "[hi]" ] + run lib "_ui_clean_line \$'a\\e[1;31mb\\e]0;t\\acd\\e]8;;u\\e\\\\ef\\x01g'; echo \"[\$_UI_CLEANED]\"" + [ "$output" = "[abcdefg]" ] +} + +@test "monitor: line cleaning keeps at most 1024 characters" { + run lib 'l=$(printf "x%.0s" $(seq 3000)); _ui_clean_line "$l"; echo "len=${#_UI_CLEANED}"' + [ "$output" = "len=1024" ] +} + +@test "monitor: attack C1 introducers (UTF-8 C2 9B, C2 9D) in a line, expected stripped under UTF-8 and C locales" { + local loc + for loc in C.UTF-8 C; do + run env LC_ALL=$loc bash -c 'source "$1/load.sh" ui + _ui_clean_line $'"'"'x\xc2\x9d0;t\xc2\x9cy\xc2\x9b31m caf\xc3\xa9\xc2\xa0'"'"' + printf "%s" "$_UI_CLEANED" | od -An -c | tr -s " " + printf "[%s]\n" "${LC_ALL-unset}"' _ "$LIB" + [[ "$output" != *'302 235'* && "$output" != *'302 234'* && "$output" != *'302 233'* ]] + if [[ $loc == C.UTF-8 ]]; then + [[ "$output" == *'x 0 ; t y 3 1 m'*'303 251 302 240'* ]] + else + # A C locale means a terminal outside UTF-8: every byte above 0x7F goes. + [[ "$output" == *'x 0 ; t y 3 1 m c a f'* && "$output" != *'303'* ]] + fi + [[ "$output" == *"[$loc]" ]] + done +} + +@test "monitor: attack C1 introducers split by another C1 pair or a control byte, expected none reassembled" { + run lib '_ui_clean_line $'"'"'a\xc2\xc2\x9b\x9bb\xc2\x01\x9bc'"'"'; printf %s "$_UI_CLEANED" | od -An -tx1 | tr -d " \n"' + [[ "$output" != *c2* ]] + [[ "$output" != *9b* ]] +} + +@test "monitor: C1 pairs are stripped byte-wise even under a UTF-8 locale" { + run lib 'export LANG=C.UTF-8 LC_ALL=C.UTF-8; _ui_clean_line $'"'"'x\xc2\x9by'"'"'; printf %s "$_UI_CLEANED"' + [ "$output" = "xy" ] +} + +@test "monitor: attack one 400 KB line, expected cleaned without a quadratic scan" { + # The timeout only bounds a hang; the assertion is the output. + run timeout 20 bash -c 'source "$LIB/load.sh" ui >/dev/null + l=$(head -c 400000 /dev/zero | tr "\0" "x") + _ui_clean_line "$l"; echo "${#_UI_CLEANED}"' + [ "$output" = "1024" ] +} + +@test "monitor: attack a lone 0x9B byte under a non-UTF-8 terminal, expected no byte above 0x7F shown" { + run lib 'UI_HAS_UNICODE=0; _ui_clean_line $'"'"'a\x9bb\xe9c'"'"'; printf %s "$_UI_CLEANED"' + [ "$output" = "abc" ] +} + +@test "monitor: UTF-8 text stays intact under a UTF-8 terminal" { + run lib 'UI_HAS_UNICODE=1; _ui_clean_line $'"'"'caf\xc3\xa9'"'"'; printf %s "$_UI_CLEANED"' + [ "$output" = "cafรฉ" ] +} + +@test "ui: LC_ALL=C wins over a UTF-8 LANG, expected ASCII mode" { + run bash -c 'export LANG=en_US.UTF-8 LC_ALL=C; source "$LIB/load.sh" ui >/dev/null; echo "$UI_HAS_UNICODE"' + [ "$output" = "0" ] + run bash -c 'export LANG=C LC_ALL= LC_CTYPE=en_US.UTF-8; source "$LIB/load.sh" ui >/dev/null; echo "$UI_HAS_UNICODE"' + [ "$output" = "1" ] +} diff --git a/tests/notify.bats b/tests/notify.bats new file mode 100644 index 0000000..077e37d --- /dev/null +++ b/tests/notify.bats @@ -0,0 +1,30 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +@test "notify: macOS posts through osascript" { + stub uname 'echo Darwin' + stub osascript 'echo "$*" >>"$HOME/osa.calls"' + run sys_lib 'unset DISPLAY WAYLAND_DISPLAY; SUMMARY_ERRORS=0; SUMMARY_MANAGERS=(apt brew); notify_send_result; echo rc=$?' + [ "$status" -eq 0 ] + [ "$output" = "rc=0" ] + grep -q '2 manager(s) updated' "$HOME/osa.calls" +} + +@test "notify: Linux without a display sends nothing" { + stub notify-send 'echo "$*" >>"$HOME/ns.calls"' + run sys_lib 'unset DISPLAY WAYLAND_DISPLAY; SUMMARY_ERRORS=1; SUMMARY_MANAGERS=(); notify_send_result; echo rc=$?' + [ "$output" = "rc=0" ] + [ ! -e "$HOME/ns.calls" ] + run sys_lib 'DISPLAY=:9; SUMMARY_ERRORS=1; SUMMARY_MANAGERS=(); notify_send_result' + grep -q 'Finished with 1 error' "$HOME/ns.calls" +} diff --git a/tests/parallel.bats b/tests/parallel.bats new file mode 100644 index 0000000..d1039f3 --- /dev/null +++ b/tests/parallel.bats @@ -0,0 +1,32 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +@test "parallel: step counter reaches the total" { + plugin sa '' + plugin sb '' + plugin pc '' 'pm_pc_parallel() { return 0; }' + plugin pd '' 'pm_pd_parallel() { return 0; }' + run $EMERGER -y -nl -nc -nt --parallel --only sa,sb,pc,pd + [ "$status" -eq 0 ] + [[ "$output" == *"1/3"* ]] + [[ "$output" == *"3/3"* ]] + [[ "$output" != *"/4"* ]] +} + +@test "parallel: a transient failure is retried as in a serial run" { + stub flaky 'if [ -e "$HOME/flaked" ]; then exit 0; fi; touch "$HOME/flaked"; echo "Temporary failure resolving host"; exit 1' + plugin pp 'run_cmd step flaky' 'pm_pp_parallel() { return 0; }' + run env RETRY_DELAY=0 $EMERGER -y -nl -nc -nt --parallel --only pp + [ "$status" -eq 0 ] + [ -e "$HOME/flaked" ] + grep -q "step: retry 1" "$EMERGER_STATE/emerger.log" +} diff --git a/tests/preflight.bats b/tests/preflight.bats new file mode 100644 index 0000000..70fdf60 --- /dev/null +++ b/tests/preflight.bats @@ -0,0 +1,146 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +stub_vcgencmd() { + cat >"$STUBS/vcgencmd" <"$HOME/model" +} + +@test "safety prompt: declining the Pi under-voltage prompt exits 1" { + command -v setsid >/dev/null || skip "setsid not available" + echo 'Raspberry Pi 4 Model B' >"$HOME/model" + stub vcgencmd 'case "$1" in get_throttled) echo throttled=0x1;; measure_temp) echo "temp=50.0'"'"'C";; esac' + run setsid -w bash -c 'set -uo pipefail; EMERGER_STATE=$HOME/st; EMERGER_LOG=$HOME/st/log; mkdir -p $HOME/st + RPI_MODEL_FILE=$HOME/model; ARG_YES=0 + source "$LIB/load.sh" ui log sys rpi rpi_eeprom + rpi_health_check; echo continued' /dev/null || skip "setsid not available" + run setsid -w bash -c 'set -uo pipefail; EMERGER_STATE=$HOME/st; EMERGER_LOG=$HOME/st/log; mkdir -p $HOME/st + ARG_YES=0 + source "$LIB/load.sh" ui log sys preflight + sys_is_on_battery() { return 0; }; sys_battery_percent() { echo 5; } + battery_precheck; echo continued' "$HOME/ps/AC/online"; echo 42 >"$HOME/ps/BAT0/capacity" + run sys_lib 'SYS_POWER_DIR=$HOME/ps; sys_is_on_battery || echo off; sys_battery_percent' + [ "${lines[0]}" = "off" ] + [ "${lines[1]}" = "42" ] + echo 0 >"$HOME/ps/AC/online" + run sys_lib 'SYS_POWER_DIR=$HOME/ps; sys_is_on_battery && echo on' + [ "$output" = "on" ] +} + +@test "sys_free_space: prints the free column in the block size asked, empty when df fails" { + stub df 'echo "Filesystem Blocks Used Available Capacity Mounted"; echo "/dev/x 9 1 7$1$2 50% /"' + run sys_lib 'sys_free_space k /; sys_free_space m /home' + [ "$status" -eq 0 ] + [ "$output" = "$(printf '%s\n' '7-Pk/' '7-Pm/home')" ] + stub df 'exit 1' + run sys_lib 'v=$(sys_free_space k /); echo "[$v] rc=$?"' + [ "$output" = "[] rc=0" ] +} + +@test "battery: non-numeric capacity is never evaluated, the reading falls back" { + mkdir -p "$HOME/ps/AC" "$HOME/ps/BAT0" + echo 0 >"$HOME/ps/AC/online" + echo 'BASH_VERSINFO[$(touch $HOME/pwned-bat)]' >"$HOME/ps/BAT0/capacity" + run sys_lib 'source "$LIB/load.sh" preflight; SYS_POWER_DIR=$HOME/ps; ARG_YES=1 + sys_battery_percent; battery_precheck; echo "rc=$?"' + [ "$status" -eq 0 ] + [ "${lines[0]}" = "100" ] + [ "${lines[-1]}" = "rc=0" ] + [ ! -e "$HOME/pwned-bat" ] + echo 'garbage text' >"$HOME/ps/BAT0/capacity" + run sys_lib 'source "$LIB/load.sh" preflight; SYS_POWER_DIR=$HOME/ps; ARG_YES=1; battery_precheck; echo "rc=$?"' + [ "$status" -eq 0 ] + [ "$output" = "rc=0" ] +} + +@test "env seams: SYS_POWER_DIR and REBOOT_REQUIRED_FILE from the environment are ignored" { + touch "$HOME/rr" + run env SYS_POWER_DIR="$HOME/ps" REBOOT_REQUIRED_FILE="$HOME/rr" \ + bash -c 'source "$LIB/load.sh" sys preflight reboot; echo "$SYS_POWER_DIR"; echo "$REBOOT_REQUIRED_FILE"' + [ "$status" -eq 0 ] + [ "${lines[0]}" = "/sys/class/power_supply" ] + [ "${lines[1]}" = "/var/run/reboot-required" ] +} + +@test "rpi: board state decides the line, the warning, the log and the exit status" { + local throttled temp abort code power want unwanted + while IFS='|' read -r throttled temp abort code power want unwanted; do + stub_vcgencmd "$throttled" "$temp" + run lib "PATH=$STUBS:\$PATH; RPI_MODEL_FILE=$HOME/model; ARG_YES=1; RPI_ABORT_ON_UNDERVOLTAGE=$abort; rpi_health_check" + [ "$status" -eq "$code" ] + [[ "$output" == *"Raspberry Pi 5"*"$tempยฐC"* ]] + [[ "$output" == *"$power"* ]] + [[ "$output" == *$want* ]] + [[ "$output" != *$unwanted* ]] + grep -q "rpi: throttled=$throttled temp=$temp" "$HOME/.local/state/emerger/log" + done <<'ROWS' +0x0|51.2|0|0|power ok|51.2ยฐC*power ok|under-voltage +0x50005|55.0|0|0|UNDER-VOLTAGE|under-voltage right now|Aborting +0x50005|55.0|1|1|UNDER-VOLTAGE|Aborting (RPI_ABORT_ON_UNDERVOLTAGE=1)|Update anyway +0x0|84.5|0|0|power ok|SoC is hot (84.5ยฐC)|under-voltage +ROWS +} + +@test "rpi: nothing happens on other boards" { + stub_vcgencmd 0x1 90.0 + echo "Some Other Board" >"$HOME/model" + run lib "PATH=$STUBS:\$PATH; RPI_MODEL_FILE=$HOME/model; rpi_health_check" + [ "$status" -eq 0 ] + [ -z "$output" ] +} + +@test "disk_free_mb: prints the free MiB, empty with exit 0 when df fails under pipefail" { + stub df 'echo "Filesystem Blocks Used Available Capacity Mounted"; echo "/dev/x 9 1 7 50% /"' + run sys_lib 'source "$LIB/load.sh" preflight; disk_free_mb /' + [ "$status" -eq 0 ] + [ "$output" = "7" ] + stub df 'exit 1' + run sys_lib 'source "$LIB/load.sh" preflight; set -eo pipefail; v=$(disk_free_mb /); echo "[$v] rc=$?"; disk_precheck; echo after' + [ "$status" -eq 0 ] + [ "${lines[0]}" = "[] rc=0" ] + [ "${lines[1]}" = "after" ] +} diff --git a/tests/profiles.bats b/tests/profiles.bats new file mode 100644 index 0000000..8a3cdb2 --- /dev/null +++ b/tests/profiles.bats @@ -0,0 +1,62 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +@test "args: repeated --profile loads the last one only" { + mkdir -p "$XDG_CONFIG_HOME/emerger/profiles.d" + echo 'touch "$HOME/prof-a"' >"$XDG_CONFIG_HOME/emerger/profiles.d/a.sh" + echo 'touch "$HOME/prof-b"' >"$XDG_CONFIG_HOME/emerger/profiles.d/b.sh" + run $EMERGER -n -y -nl --only none --profile a --profile=b + [ "$status" -eq 0 ] + [ -e "$HOME/prof-b" ] + [ ! -e "$HOME/prof-a" ] +} + +@test "profiles: safe and work add to ARG_EXCEPT from config.sh" { + run bash -c "ARG_EXCEPT=npm; source '$REPO_DIR/share/profiles/safe.sh'; echo \$ARG_EXCEPT" + [ "$output" = "npm,flatpak,snap" ] + run bash -c "ARG_EXCEPT=npm; source '$REPO_DIR/share/profiles/work.sh'; echo \$ARG_EXCEPT" + [ "$output" = "npm,yay,paru" ] + run bash -c "set -u; source '$REPO_DIR/share/profiles/safe.sh'; echo \$ARG_EXCEPT" + [ "$output" = "flatpak,snap" ] +} + +@test "safe and work profiles skip the right managers" { + run bash -c "source '$REPO_DIR/share/profiles/safe.sh'; echo \$ARG_EXCEPT" + [ "$output" = "flatpak,snap" ] + run bash -c "source '$REPO_DIR/share/profiles/work.sh'; echo \$ARG_EXCEPT \$ARG_NO_FIRMWARE" + [ "$output" = "yay,paru 1" ] +} + +@test "profiles: --list-profiles prints the shipped descriptions in English" { + run $EMERGER --list-profiles + [ "$status" -eq 0 ] + [[ "$output" == *"home"*"everything: dev toolchains, firmware, parallel mode and the weather line"* ]] + [[ "$output" == *"work"*"security only, unattended, no firmware, skips yay and paru"* ]] + [[ "$output" == *"server"*"headless: quiet, security only, no prompts, no firmware"* ]] + [[ "$output" == *"safe"*"least change: security only, no firmware, skips flatpak and snap"* ]] +} + +@test "profiles: the .ps1 descriptions are English and keep their line ending" { + run grep -h '^# description:' "$REPO_DIR"/share/profiles/*.ps1 + [ "$status" -eq 0 ] + [[ "$output" != *" niente "* && "$output" != *" solo "* && "$output" != *"lavoro"* && "$output" != *"nessun"* && "$output" != *"casa"* ]] + [ "$(grep -c $'\r$' "$REPO_DIR/share/profiles/home.ps1")" -gt 0 ] +} + +@test "profiles: a user profile whose last command fails still runs the update" { + plugin pa '' + mkdir -p "$XDG_CONFIG_HOME/emerger/profiles.d" + echo '[[ -f /nonexistent ]] && ARG_YES=1' >"$XDG_CONFIG_HOME/emerger/profiles.d/q.sh" + run $EMERGER -y -nl -nc -nt --only pa --profile q + [ "$status" -eq 0 ] + [ "$(cat "$HOME/ran")" = "pa" ] +} diff --git a/tests/progress.bats b/tests/progress.bats new file mode 100644 index 0000000..bdc75f4 --- /dev/null +++ b/tests/progress.bats @@ -0,0 +1,71 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +@test "progress_summarize: apt counts the packages to remove" { + echo "3 upgraded, 1 newly installed, 2 to remove and 0 not upgraded." >"$HOME/apt.out" + run sys_lib 'progress_summarize apt "$HOME/apt.out"' + [ "$status" -eq 0 ] + [ "$output" = "3 upgraded, 1 new, 2 removed" ] +} + +@test "progress_feed: zero-padded counters read as decimal" { + run sys_lib 'progress_feed pacman "(08/24) upgrading foo" 2>&1; echo "$PROGRESS_CURRENT/$PROGRESS_TOTAL" + progress_reset + progress_feed brew "==> Upgrading 09 outdated packages:" 2>&1 + progress_feed brew "==> Upgrading foo" 2>&1; echo "$PROGRESS_CURRENT/$PROGRESS_TOTAL"' + [ "$status" -eq 0 ] + [ "${lines[0]}" = "8/24" ] + [ "${lines[1]}" = "1/9" ] +} + +@test "progress_summarize returns 0 with no match" { + run lib 'f=$(mktemp); echo nothing >"$f"; out=$(progress_summarize pacman "$f"); echo "rc=$? [$out]"' + [ "$output" = "rc=0 []" ] +} + +@test "progress: apt dlstatus sets the file counter, pmstatus the percent and message" { + run lib 'progress_feed apt "dlstatus:3:0.0000:Retrieving file 3 of 12"; echo "$PROGRESS_CURRENT/$PROGRESS_TOTAL $PROGRESS_PERCENT" + progress_feed apt "pmstatus:libssl3:45.4545:Unpacking libssl3 (arm64)"; echo "$PROGRESS_TOTAL $PROGRESS_PERCENT $PROGRESS_MESSAGE"' + [ "${lines[0]}" = "3/12 -1" ] + [ "${lines[1]}" = "0 45 Unpacking libssl3 (arm64)" ] +} + +@test "progress: (n/N) counters of the other managers set current and total" { + run lib ' + progress_feed pacman "(3/24) upgrading linux-firmware"; echo "$PROGRESS_CURRENT/$PROGRESS_TOTAL" + progress_feed zypper "Retrieving: vim-9.1 (5/9)"; echo "$PROGRESS_CURRENT/$PROGRESS_TOTAL" + progress_feed dnf " Upgrading : kernel-6.1.x86_64 7/30"; echo "$PROGRESS_CURRENT/$PROGRESS_TOTAL" + progress_feed emerge ">>> Emerging (2 of 8) app-misc/foo-1.2::gentoo"; echo "$PROGRESS_CURRENT/$PROGRESS_TOTAL" + progress_feed flatpak "Updating 1/4โ€ฆ"; echo "$PROGRESS_CURRENT/$PROGRESS_TOTAL" + progress_feed pip "[2/6] requests"; echo "$PROGRESS_CURRENT/$PROGRESS_TOTAL $PROGRESS_MESSAGE" + progress_feed snap "Download snap \"core\" 37% 1.2MB/s"; echo "$PROGRESS_PERCENT"' + [ "${lines[0]}" = "3/24" ] + [ "${lines[1]}" = "5/9" ] + [ "${lines[2]}" = "7/30" ] + [ "${lines[3]}" = "2/8" ] + [ "${lines[4]}" = "1/4" ] + [ "${lines[5]}" = "2/6 requests" ] + [ "${lines[6]}" = "37" ] +} + +@test "progress: brew counts each upgrade against the outdated total" { + run lib 'progress_feed brew "==> Upgrading 3 outdated packages:" + progress_feed brew "==> Upgrading git"; progress_feed brew "==> Upgrading jq" + echo "$PROGRESS_CURRENT/$PROGRESS_TOTAL"' + [ "$output" = "2/3" ] +} + +@test "progress: (0/0) and (9/3) are ignored" { + run lib 'progress_feed pacman "(0/0) nothing"; progress_feed pacman "(9/3) bogus"; echo "$PROGRESS_CURRENT/$PROGRESS_TOTAL"' + [ "$output" = "0/0" ] +} diff --git a/tests/ps_args.bats b/tests/ps_args.bats new file mode 100644 index 0000000..9a22f15 --- /dev/null +++ b/tests/ps_args.bats @@ -0,0 +1,147 @@ +#!/usr/bin/env bats +# PowerShell flag parser, short-circuits and the Unix-only flags, run through pwsh where it is installed. + +load ps_helper + +@test "ps: --accept-licenses is parsed and sets AcceptLicenses" { + run ps '(Args-Parse @("--accept-licenses")).AcceptLicenses' + [ "$status" -eq 0 ] + [ "$output" = "True" ] +} + +@test "ps: short flags -V -v -w -err reach the parser instead of common parameters" { + run up_fn -V + [ "$status" -eq 0 ] + [ "$output" = "eMerger $(cat "$REPO_DIR/VERSION")" ] + run up_fn -err + [ "$status" -eq 0 ] + [[ "$output" != *"ambiguous"* ]] + run up_fn -n -v -w -nc -nt -nl + [ "$status" -eq 0 ] + [[ "$output" != *"ambiguous"* ]] +} + +@test "ps: a value flag with a missing or empty value exits 2 with Missing value" { + local f form + for f in only except metrics profile changelog; do + for form in "@('--$f')" "@('--$f', '')" "@('--$f=')" "@('--$f', '', '-n')"; do + run ps "Args-Parse $form | Out-Null; 'parsed'" + [ "$status" -eq 2 ] || { echo "--$f $form: status $status"; return 1; } + [[ "$output" == *"Missing value for --$f"* ]] + [[ "$output" != *parsed* ]] + done + done + run ps "(Args-Parse @('--only', 'winget')).Only" + [ "$status" -eq 0 ] + [ "$output" = winget ] +} + +@test "ps: a repeated --profile loads only the last one" { + mkdir -p "$APPDATA/emerger/profiles.d" + for p in first last; do printf 'Add-Content "%s/trace" "%s"\n' "$HOME" "$p" >"$APPDATA/emerger/profiles.d/$p.ps1"; done + run up_ps '' --profile first --profile last -V + [ "$status" -eq 0 ] + [ "$(cat "$HOME/trace")" = last ] + rm "$HOME/trace" + run up_ps '' --profile=last --profile=first -V + [ "$status" -eq 0 ] + [ "$(cat "$HOME/trace")" = first ] +} + +@test "ps: short-circuits run in the Unix order and -rc touches nothing" { + mkdir -p "$HOME/bin" "$LOCALAPPDATA/emerger/state" "$LOCALAPPDATA/emerger/cache" + printf '#!/bin/sh\necho "git $*" >>"%s/trace"\n' "$HOME" >"$HOME/bin/git"; chmod +x "$HOME/bin/git" + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' --list-profiles -up" + [ "$status" -eq 0 ] + [[ "$output" == *"Available profiles"* ]] + [ ! -e "$HOME/trace" ] + echo '{"ts":"2026-01-01T00:00:00Z","duration":5,"errors":0,"reboot":0,"managers":[]}' >"$LOCALAPPDATA/emerger/state/history.jsonl" + touch "$LOCALAPPDATA/emerger/cache/keep" + run up_ps '' -rc --metrics "$HOME/m.prom" + [ "$status" -eq 0 ] + [[ "$output" == *"metrics written"* ]] + [[ "$output" != *"detection cache"* ]] + [ -e "$LOCALAPPDATA/emerger/cache/keep" ] + [ -e "$HOME/m.prom" ] + run up_ps '' -n -rc -nc -nt + [ "$status" -eq 0 ] + [ -e "$LOCALAPPDATA/emerger/cache/keep" ] + [[ "$output" == *"Windows keeps no detection cache, nothing to clear"* ]] +} + +@test "ps: --changed and --changelog warn and exit 0 without starting an upgrade" { + mkdir -p "$HOME/bin" + printf '#!/bin/sh\necho "scoop $*" >>"%s/trace"\n' "$HOME" >"$HOME/bin/scoop"; chmod +x "$HOME/bin/scoop" + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -y -nc -nt --changed" + [ "$status" -eq 0 ] + [[ "$output" == *"--changed is not supported on Windows"* ]] + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -y -nc -nt --changelog git" + [ "$status" -eq 0 ] + [[ "$output" == *"--changelog is not supported on Windows"* ]] + [ ! -e "$HOME/trace" ] + [ ! -e "$LOCALAPPDATA/emerger/state/history.jsonl" ] +} + +@test "ps: each Unix-only run flag warns and the run goes on" { + local f + for f in --firmware --no-firmware --snapshot --parallel --resume --download-only --deep-clean --refresh-mirrors; do + run up_ps '' -n -y -nc -nt "$f" + [ "$status" -eq 0 ] || { echo "$f: status $status"; return 1; } + [[ "$output" == *"$f is not supported on Windows, ignored."* ]] + [[ "$output" == *"eMerger summary"* ]] + done +} + +@test "ps: --rollback warns and exits 0 without starting an upgrade" { + run up_ps '' -y -nc -nt --rollback + [ "$status" -eq 0 ] + [[ "$output" == *"--rollback is not supported on Windows, nothing to revert."* ]] + [[ "$output" != *"eMerger summary"* ]] + [ ! -e "$LOCALAPPDATA/emerger/state/history.jsonl" ] +} + +@test "ps: -- ends the options as on Unix, the words after it are ignored" { + run ps "(Args-Parse @('-n', '--', '-y', '--bogus')).Yes; 'p=[' + (Args-Prescan-Profile @('--', '--profile', 'work')) + ']'" + [ "$status" -eq 0 ] + [ "${lines[0]}" = False ] + [ "${lines[1]}" = 'p=[]' ] + run up_ps '' -n -nc -nt -- --bogus + [ "$status" -eq 0 ] + [[ "$output" != *"Unknown argument"* ]] +} + +@test "ps: an unknown argument names up --help in double quotes" { + run up_ps '' --bogus + [ "$status" -eq 2 ] + [ "$output" = 'Unknown argument: --bogus (try "up --help")' ] +} + +@test "ps: -rc says Windows keeps no detection cache and removes nothing" { + mkdir -p "$LOCALAPPDATA/emerger/cache" + touch "$LOCALAPPDATA/emerger/cache/keep" + run up_ps '' -rc -nc -nt -y + [ "$status" -eq 0 ] + [[ "$output" == *"Windows keeps no detection cache, nothing to clear"* ]] + [[ "$output" != *"Detection cache cleared"* ]] + [ -e "$LOCALAPPDATA/emerger/cache/keep" ] +} + +@test "ps: --list-profiles lists the profiles in name order even when the directory lists them unsorted" { + mkdir -p "$APPDATA/emerger/profiles.d" + local name + for name in alpha beta gamma; do printf '# description: %s\n' "$name" >"$APPDATA/emerger/profiles.d/$name.ps1"; done + run up_ps 'function Get-ChildItem { $all = @(Microsoft.PowerShell.Management\Get-ChildItem @args); [array]::Reverse($all); $all }' --list-profiles + [ "$status" -eq 0 ] + local order + order=$(printf '%s\n' "$output" | grep -oE '^ (alpha|beta|gamma|home|safe|server|work) ' | tr -d ' ' | tr '\n' ' ') + [ "$order" = "alpha beta gamma home safe server work " ] +} + +@test "ps: --profile is consumed by the prescan and leaves no Profile field in the options" { + run ps '$o = Args-Parse @("--profile", "work", "-n"); "dry=$($o.DryRun) field=$($o.PSObject.Properties.Name -contains "Profile")"' + [ "$status" -eq 0 ] + [ "$output" = "dry=True field=False" ] + run ps 'Args-Parse @("--profile") | Out-Null' + [ "$status" -eq 2 ] + [[ "$output" == *"Missing value for --profile"* ]] +} diff --git a/tests/ps_clean.bats b/tests/ps_clean.bats new file mode 100644 index 0000000..d432395 --- /dev/null +++ b/tests/ps_clean.bats @@ -0,0 +1,107 @@ +#!/usr/bin/env bats +# PowerShell temp folder cleaning, run through pwsh where it is installed. + +load ps_helper + +@test "ps: temp cleanup removes a directory link without touching or counting its target" { + export TEMP="$HOME/tmp" SystemRoot="$HOME/Windows" + mkdir -p "$TEMP/sub/deep" "$HOME/victim" "$SystemRoot" + head -c 1048576 /dev/zero >"$TEMP/sub/deep/junk" + head -c 4194304 /dev/zero >"$HOME/victim/keep" + ln -s "$HOME/victim" "$TEMP/link" + ln -s "$HOME/victim" "$TEMP/sub/deep/inner" + run ps '. (Join-Path $env:PSLIB "clean/Size.ps1"); . (Join-Path $env:PSLIB "clean/Temp.ps1") + "size=$(_Temp-Folder-Size-KB $env:TEMP)" + $script:ArgsGlobal.Yes = $true + Clean-Temp' + [ "$status" -eq 0 ] + [[ "$output" == *"size=1024"$'\n'* ]] + [ -f "$HOME/victim/keep" ] + [ ! -e "$TEMP/link" ] + [ ! -L "$TEMP/link" ] + [ ! -e "$TEMP/sub" ] +} + +@test "ps: temp cleanup does not follow a directory swapped for a link after enumeration" { + export TEMP="$HOME/tmp" SystemRoot="$HOME/Windows" + mkdir -p "$TEMP/x" "$HOME/victim" "$SystemRoot" + echo d >"$TEMP/x/decoy" + echo keep >"$HOME/victim/important.txt" + run ps '. (Join-Path $env:PSLIB "clean/Temp.ps1") + $items = @(Get-ChildItem -LiteralPath $env:TEMP -Force) + foreach ($i in $items) { $null = $i.Attributes } + Remove-Item -Recurse -Force (Join-Path $env:TEMP "x") + New-Item -ItemType SymbolicLink -Path (Join-Path $env:TEMP "x") -Target (Join-Path $env:HOME "victim") | Out-Null + foreach ($i in $items) { _Temp-Remove-NoFollow $i } + "victim=$(Test-Path (Join-Path $env:HOME "victim/important.txt"))"' + [ "$status" -eq 0 ] + [[ "$output" == *"victim=True"* ]] + [ -f "$HOME/victim/important.txt" ] + [ ! -e "$TEMP/x" ] +} + +@test "ps: temp cleanup stops emptying a directory that became a link under it" { + export TEMP="$HOME/tmp" SystemRoot="$HOME/Windows" + mkdir -p "$TEMP/d" "$HOME/victim" + echo a >"$TEMP/d/a"; echo b >"$TEMP/d/b" + echo keep >"$HOME/victim/important.txt" + run ps '. (Join-Path $env:PSLIB "clean/Temp.ps1") + $dir = Get-Item -LiteralPath (Join-Path $env:TEMP "d") + $script:Swapped = $false + # The first fresh attribute read of a child swaps the parent for a link. + function _Temp-Is-Link-Now { + param([string]$Path) + if ((-not $script:Swapped) -and ($Path -like "*/d/*")) { + $script:Swapped = $true + Remove-Item -Recurse -Force $dir.FullName + New-Item -ItemType SymbolicLink -Path $dir.FullName -Target (Join-Path $env:HOME "victim") | Out-Null + } + return (([int][IO.File]::GetAttributes($Path)) -band [int][IO.FileAttributes]::ReparsePoint) -ne 0 + } + try { _Temp-Remove-NoFollow $dir } catch {} + "swapped=$($script:Swapped)" + "victim=$(Test-Path (Join-Path $env:HOME "victim/important.txt"))"' + [[ "$output" == *"swapped=True"* ]] + [[ "$output" == *"victim=True"* ]] + [ -f "$HOME/victim/important.txt" ] +} + +@test "ps: temp cleanup does not empty a directory whose handle cannot be taken as a plain directory" { + export TEMP="$HOME/tmp" SystemRoot="$HOME/Windows" + mkdir -p "$TEMP/d" "$HOME/victim" + echo a >"$TEMP/d/a" + run ps '. (Join-Path $env:PSLIB "clean/Temp.ps1") + function _Temp-Open-Dir { param([string]$Path) return $null } + $dir = Get-Item -LiteralPath (Join-Path $env:TEMP "d") + try { _Temp-Remove-NoFollow $dir; "no throw" } catch { "refused" } + "child=$(Test-Path (Join-Path $env:TEMP "d/a"))"' + [[ "$output" == *"refused"* ]] + [[ "$output" == *"child=True"* ]] +} + +@test "ps: temp cleanup holds the directory handle while emptying it and releases it before the delete" { + export TEMP="$HOME/tmp" SystemRoot="$HOME/Windows" + mkdir -p "$TEMP/d" + echo a >"$TEMP/d/a" + run ps '. (Join-Path $env:PSLIB "clean/Temp.ps1") + $script:Handle = [IO.MemoryStream]::new() + $script:Held = @() + function _Temp-Open-Dir { param([string]$Path) return $script:Handle } + $real = ${function:_Temp-Is-Link-Now} + function _Temp-Is-Link-Now { param([string]$Path) if ($Path -like "*/d/a") { $script:Held += $script:Handle.CanRead }; return (& $real $Path) } + $dir = Get-Item -LiteralPath (Join-Path $env:TEMP "d") + _Temp-Remove-NoFollow $dir + "held=$($script:Held -join ",") released=$(-not $script:Handle.CanRead) gone=$(-not (Test-Path $dir.FullName))"' + [[ "$output" == *"held=True released=True gone=True"* ]] +} + +@test "ps: temp cleanup deletes a file through the file API, never Remove-Item" { + export TEMP="$HOME/tmp" + mkdir -p "$TEMP"; echo x >"$TEMP/ro.txt"; chmod a-w "$TEMP/ro.txt" + # Remove-Item follows a junction swapped in on Windows: it must not be the path taken. + run ps '. (Join-Path $env:PSLIB "clean/Size.ps1"); . (Join-Path $env:PSLIB "clean/Temp.ps1") + function Remove-Item { throw "Remove-Item used" } + _Temp-Remove-NoFollow (Get-Item -LiteralPath (Join-Path $env:TEMP "ro.txt")); "done"' + [ "$status" -eq 0 ] + [ ! -e "$TEMP/ro.txt" ] +} diff --git a/tests/ps_config.bats b/tests/ps_config.bats new file mode 100644 index 0000000..59df425 --- /dev/null +++ b/tests/ps_config.bats @@ -0,0 +1,55 @@ +#!/usr/bin/env bats +# PowerShell settings from config.ps1 and profiles, run through pwsh where it is installed. + +load ps_helper + +@test "ps: a numeric knob that is not a whole number warns and falls back to its default" { + mkdir -p "$APPDATA/emerger" + printf '%s\n' '$script:MANAGER_TIMEOUT = -1' '$script:RETRY_ATTEMPTS = "3x"' '$script:DISK_MIN_FREE_MB = "lots"' \ + '$script:BATTERY_MIN_PCT = "20%"' '$script:RETRY_DELAY = "007"' >"$APPDATA/emerger/config.ps1" + run up_ps 'function Get-PSDrive { [pscustomobject]@{ Free = 10MB } }' -n -y -nc -nt + [ "$status" -eq 0 ] + [[ "$output" == *'MANAGER_TIMEOUT="-1" is not a whole number, using 0'* ]] + [[ "$output" == *'RETRY_ATTEMPTS="3x" is not a whole number, using 2'* ]] + [[ "$output" == *'DISK_MIN_FREE_MB="lots" is not a whole number, using 1024'* ]] + [[ "$output" == *'BATTERY_MIN_PCT="20%" is not a whole number, using 20'* ]] + [[ "$output" != *RETRY_DELAY* ]] + [[ "$output" == *"Low disk space"*"10MB free, threshold 1024MB"* ]] +} + +@test "ps: UI_VERBOSE and Ascii set in config.ps1 or a profile take effect like -v and --ascii" { + mkdir -p "$HOME/bin" "$APPDATA/emerger" + printf '#!/bin/sh\necho "scoop said hi"\n' >"$HOME/bin/scoop"; chmod +x "$HOME/bin/scoop" + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -y -nc -nt" + [ "$status" -eq 0 ] + [[ "$output" != *"scoop said hi"* ]] + printf '$script:UI_VERBOSE = $true\n' >"$APPDATA/emerger/config.ps1" + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -y -nc -nt" + [ "$status" -eq 0 ] + [[ "$output" == *"scoop said hi"* ]] + run ps '$script:UI_VERBOSE = $true; $script:ArgsGlobal.Ascii = $true; UI-Init + "v=$script:UI_VERBOSE n=$script:UI_IS_ASCII u=$script:UI_HAS_UNICODE e=$script:UI_HAS_EMOJI"' + [ "$status" -eq 0 ] + [ "$output" = "v=True n=True u=False e=False" ] +} + +@test "ps: action and query fields set in config.ps1 or a profile have no effect, only the command line sets them" { + mkdir -p "$HOME/bin" "$APPDATA/emerger/profiles.d" + printf '#!/bin/sh\necho "git $*" >>"%s/trace"\n' "$HOME" >"$HOME/bin/git"; chmod +x "$HOME/bin/git" + printf '%s\n' '$script:ArgsGlobal.SelfUpdate = $true' '$script:ArgsGlobal.History = $true' \ + '$script:ArgsGlobal.Metrics = "m.prom"' '$script:ArgsGlobal.Rollback = $true' >"$APPDATA/emerger/config.ps1" + printf '%s\n' '$script:ArgsGlobal.AutoUpdate = $true' '$script:ArgsGlobal.Doctor = $true' \ + '$script:ArgsGlobal.Help = $true' '$script:ArgsGlobal.Reboot = $true' >"$APPDATA/emerger/profiles.d/acts.ps1" + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -n -nc -nt -nl -ni --profile acts" + [ "$status" -eq 0 ] + [ ! -e "$HOME/trace" ] + [[ "$output" == *"eMerger summary"* ]] + [[ "$output" != *"No history yet"* ]] + [[ "$output" != *"--rollback"* ]] + [[ "$output" != *"USAGE"* ]] + [[ "$output" != *"Auto-update"* ]] + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' --history" + [ "$status" -eq 0 ] + [[ "$output" == *"No history yet"* ]] + [ ! -e "$HOME/trace" ] +} diff --git a/tests/ps_doctor.bats b/tests/ps_doctor.bats new file mode 100644 index 0000000..9b63a3a --- /dev/null +++ b/tests/ps_doctor.bats @@ -0,0 +1,38 @@ +#!/usr/bin/env bats +# PowerShell --doctor, run through pwsh where it is installed. + +load ps_helper + +# Doctor-Run with ping refused (github.com drops ICMP), $1 MB free on the +# system drive, and every HTTPS request recorded in $HOME/web. +doctor_ps() { + ps ". (Join-Path \$env:PSLIB 'Summary.ps1'); . (Join-Path \$env:PSLIB 'state/History.ps1'); . (Join-Path \$env:PSLIB 'system/Reboot.ps1'); . (Join-Path \$env:PSLIB 'Doctor.ps1') + function Test-Connection { \$false } + function Get-PSDrive { [pscustomobject]@{ Free = $1 * 1MB } } + function Invoke-WebRequest { param(\$Uri, \$Method, \$TimeoutSec, [switch]\$UseBasicParsing) + Add-Content '$HOME/web' \"\$Method \$Uri \$TimeoutSec\" + if (\$env:WEB_DOWN) { throw 'unreachable' } } + $2 + \$rc = Doctor-Run; \"rc=\$rc\"" +} + +@test "ps: doctor checks the network with an HTTPS request, not a ping" { + run doctor_ps 50000 '' + [ "$status" -eq 0 ] + [[ "$output" == *"network: reachable"* ]] + [[ "$output" == *"rc=0"* ]] + [ "$(cat "$HOME/web")" = "Head https://github.com 4" ] + run env WEB_DOWN=1 bash -c "$(declare -f ps doctor_ps); doctor_ps 50000 ''" + [[ "$output" == *"network: github.com unreachable"* ]] + [[ "$output" == *"rc=1"* ]] +} + +@test "ps: doctor disk threshold follows DISK_MIN_FREE_MB" { + run doctor_ps 1500 '$script:DISK_MIN_FREE_MB = 1024' + [ "$status" -eq 0 ] + [[ "$output" == *"disk: 1500MB free"* ]] + [[ "$output" == *"rc=0"* ]] + run doctor_ps 1500 '$script:DISK_MIN_FREE_MB = 2048' + [[ "$output" == *"low disk space"*"1500MB free"* ]] + [[ "$output" == *"rc=1"* ]] +} diff --git a/tests/ps_elevation.bats b/tests/ps_elevation.bats new file mode 100644 index 0000000..320d191 --- /dev/null +++ b/tests/ps_elevation.bats @@ -0,0 +1,255 @@ +#!/usr/bin/env bats +# PowerShell elevated child for the admin managers, run through pwsh where it is installed. + +load ps_helper + +@test "ps: only the admin managers run elevated, config and hooks stay in the caller" { + elevation_stubs + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps \"\$1\" -y -nc -nt --accept-licenses" _ "$START_PROCESS_STUB" + [ "$status" -eq 0 ] + grep -qx 'start verb=RunAs' "$HOME/trace" + grep -qx 'choco elevated=1' "$HOME/trace" + [ "$(grep -c '^config' "$HOME/trace")" -eq 1 ] + grep -qx 'config elevated=0' "$HOME/trace" + [ "$(grep -c '^hook' "$HOME/trace")" -eq 1 ] + grep -qx 'hook elevated=0' "$HOME/trace" + [[ "$output" == *"choco upgrade all"*"1 upgraded"* ]] + grep -q '|INFO|starting choco' "$LOCALAPPDATA/emerger/state/emerger.log" +} + +@test "ps: the elevated child refuses a non-admin manager and a pre-existing result path" { + run pwsh -NoProfile -NonInteractive -File "$REPO_DIR/src/emerger.ps1" --elevated-child "$HOME/$RESULT_LEAF" scoop 2 3 0 0 + [ "$status" -eq 2 ] + [ ! -e "$HOME/$RESULT_LEAF" ] + run pwsh -NoProfile -NonInteractive -File "$REPO_DIR/src/emerger.ps1" --elevated-child "$HOME/$RESULT_LEAF" choco 2 3 0 0 '-y;x' + [ "$status" -eq 2 ] + elevation_stubs + echo original >"$HOME/victim" + ln -s "$HOME/victim" "$HOME/$RESULT_LEAF" + run env PATH="$HOME/bin:$PATH" pwsh -NoProfile -NonInteractive -File "$REPO_DIR/src/emerger.ps1" --elevated-child "$HOME/$RESULT_LEAF" choco 2 3 0 0 -y + [ "$status" -eq 1 ] + [ "$(cat "$HOME/victim")" = original ] + ! grep -q '^config' "$HOME/trace" +} + +@test "ps: a failing elevated manager gives exit 3 and --json on the caller's stdout" { + elevation_stubs + run env PATH="$HOME/bin:$PATH" CHOCO_RC=1 bash -c "$(declare -f up_ps); up_ps \"\$1\" -y -nc -nt --json 2>/dev/null" _ "$START_PROCESS_STUB" + [ "$status" -eq 3 ] + grep -qx 'choco elevated=1' "$HOME/trace" + [[ "$output" == *'"managers":[{"name":"choco","result":"fail","secs":'[0-9]*'}]'* ]] +} + +@test "ps: a declined UAC prompt fails the admin managers without a crash" { + elevation_stubs + run env PATH="$HOME/bin:$PATH" DECLINE_UAC=1 bash -c "$(declare -f up_ps); up_ps \"\$1\" -y -nc -nt" _ "$START_PROCESS_STUB" + [ "$status" -eq 3 ] + [ "$(grep -c '^choco' "$HOME/trace")" -eq 0 ] + grep -qx 'hook elevated=0' "$HOME/trace" + [[ "$output" == *"canceled by the user"* ]] +} + +@test "ps: elevated relaunch quotes embedded quotes and trailing backslashes" { + run ps 'function Start-Process { param($FilePath, $ArgumentList, $Verb, [switch]$Wait, [switch]$PassThru) + Set-Content (Join-Path $env:HOME "argv") "$ArgumentList"; [pscustomobject]@{ ExitCode = 7 } } + Elevated-Start "C:\e M\emerger.ps1" @("a`"b", "C:\dir x\", "plain")' + [ "$status" -eq 0 ] + [ "$output" = 7 ] + [[ "$(cat "$HOME/argv")" == *'-File "C:\e M\emerger.ps1" "a\"b" "C:\dir x\\" plain' ]] +} + +@test "ps: a result file planted before the elevated child writes is not trusted" { + elevation_stubs + local plant="function Start-Process { + param(\$FilePath, \$ArgumentList, \$Verb, [switch]\$Wait, [switch]\$PassThru) + \$file = ([regex]::Match(\$ArgumentList, '--elevated-child (\S+)')).Groups[1].Value + Set-Content \$file '{\"managers\":[{\"name\":\"choco\",\"result\":\"ok\",\"secs\":1,\"changed\":0,\"steps\":[]}],\"log\":[]}' + \$psi = [Diagnostics.ProcessStartInfo]::new((Get-Process -Id \$PID).Path, \$ArgumentList) + \$psi.UseShellExecute = \$false + \$p = [Diagnostics.Process]::Start(\$psi); \$p.WaitForExit() + [pscustomobject]@{ ExitCode = \$p.ExitCode } + }" + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps \"\$1\" -y -nc -nt --json 2>/dev/null" _ "$plant" + [ "$status" -eq 3 ] + [[ "$output" == *'"managers":[{"name":"choco","result":"fail","secs":'[0-9]*'}]'* ]] +} + +@test "ps: --accept-licenses reaches the elevated child and passes its validation" { + run ps ". (Join-Path \$env:PSLIB 'Elevated.ps1') + \$script:RETRY_ATTEMPTS = 2; \$script:RETRY_DELAY = 3; \$script:MANAGER_TIMEOUT = 0 + \$script:ArgsGlobal.AcceptLicenses = \$true + (Elevated-Args '/r.json' @('PSWindowsUpdate')) -join ' '" + [ "$status" -eq 0 ] + [[ "$output" == *"PSWindowsUpdate 2 3 0 0 --accept-licenses" ]] + run pwsh -NoProfile -NonInteractive -File "$REPO_DIR/src/emerger.ps1" --elevated-child "$HOME/$RESULT_LEAF" PSWindowsUpdate 2 3 0 0 --accept-licenses + [[ "$output" != *"invalid arguments"* ]] + [ "$status" -eq 0 ] || [ "$status" -eq 3 ] + [ -e "$HOME/$RESULT_LEAF" ] +} + +@test "ps: a negative MANAGER_TIMEOUT in config.ps1 does not fail the elevated managers" { + elevation_stubs + printf '$script:MANAGER_TIMEOUT = -1\n' >>"$APPDATA/emerger/config.ps1" + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps \"\$1\" -y -nc -nt" _ "$START_PROCESS_STUB" + [ "$status" -eq 0 ] + grep -qx 'choco elevated=1' "$HOME/trace" + [[ "$output" != *"invalid arguments"* ]] +} + +@test "ps: the elevated child holds the elevated lock while its managers run" { + elevation_stubs + mkdir -p "$LOCALAPPDATA/emerger/state" + printf '#!/bin/sh\nif flock -n "%s" true; then echo "lock free" >>"%s/trace"; else echo "lock held" >>"%s/trace"; fi\n' \ + "$LOCALAPPDATA/emerger/state/elevated.lock" "$HOME" "$HOME" >"$HOME/bin/choco" + run env PATH="$HOME/bin:$PATH" pwsh -NoProfile -NonInteractive -File "$REPO_DIR/src/emerger.ps1" --elevated-child "$HOME/$RESULT_LEAF" choco 2 3 0 0 + [ "$status" -eq 0 ] + grep -qx 'lock held' "$HOME/trace" +} + +@test "ps: the elevated child refuses a result path off the local disk or with a foreign name" { + elevation_stubs + run env PATH="$HOME/bin:$PATH" pwsh -NoProfile -NonInteractive -File "$REPO_DIR/src/emerger.ps1" --elevated-child "//srv/share/$RESULT_LEAF" choco 2 3 0 0 + [ "$status" -eq 2 ] + [[ "$output" == *"invalid arguments"* ]] + run env PATH="$HOME/bin:$PATH" pwsh -NoProfile -NonInteractive -File "$REPO_DIR/src/emerger.ps1" --elevated-child "$HOME/r.json" choco 2 3 0 0 + [ "$status" -eq 2 ] + [ ! -e "$HOME/r.json" ] + [ ! -e "$HOME/trace" ] || ! grep -q '^choco' "$HOME/trace" +} + +@test "ps: the elevated child drops user PATH and PSModulePath entries and keeps the system ones" { + export SystemRoot="$HOME/Windows" ProgramData="$HOME/ProgramData" ProgramFiles="$HOME/PF" + run pwsh -NoProfile -NonInteractive -Command " + \$env:PATH = '$HOME/evil' + [IO.Path]::PathSeparator + \$env:PATH + \$env:PSModulePath = '$HOME/mods' + [IO.Path]::PathSeparator + \$env:PSModulePath + . '$PSLIB/Elevated.ps1' + Elevated-Restrict-Env + \"path=\$env:PATH\" + \"mods=\$env:PSModulePath\"" + [ "$status" -eq 0 ] + [[ "$output" != *"$HOME/evil"* ]] + [[ "$output" != *"$HOME/mods"* ]] + [[ "$output" == *"path="*"$HOME/Windows"* ]] + [[ "$output" == *"$HOME/ProgramData/chocolatey"*"bin"* ]] + [[ "$output" == *"mods="*"$HOME/PF"*"Modules"* ]] +} + +@test "ps: an elevated manager planted in a user PATH directory is not run by the child" { + mkdir -p "$HOME/evil" "$HOME/ProgramData/chocolatey" + printf '#!/bin/sh\necho ran >"%s/marker"\nexit 0\n' "$HOME" >"$HOME/evil/choco" + chmod +x "$HOME/evil/choco" + elevation_stubs + rm -f "$HOME/bin/choco"; rm -rf "$HOME/ProgramData/chocolatey/bin"; mkdir -p "$HOME/ProgramData/chocolatey/bin" + run env PATH="$HOME/evil:$PATH" bash -c "$(declare -f up_ps); up_ps \"\$1\" -y -nc -nt" _ "$START_PROCESS_STUB" + [ ! -e "$HOME/marker" ] +} + +@test "ps: the elevated child holds the lock even without a state directory" { + elevation_stubs + printf '#!/bin/sh\nif [ -e "%s" ] && ! flock -n "%s" true; then echo "lock held" >>"%s/trace"; else echo "lock free" >>"%s/trace"; fi\n' \ + "$LOCALAPPDATA/emerger/state/elevated.lock" "$LOCALAPPDATA/emerger/state/elevated.lock" "$HOME" "$HOME" >"$HOME/bin/choco" + [ ! -e "$LOCALAPPDATA/emerger/state" ] + run env PATH="$HOME/bin:$PATH" pwsh -NoProfile -NonInteractive -File "$REPO_DIR/src/emerger.ps1" --elevated-child "$HOME/$RESULT_LEAF" choco 2 3 0 0 + [ "$status" -eq 0 ] + grep -qx 'lock held' "$HOME/trace" +} + +@test "ps: the elevated child refuses to run its managers when it cannot open the lock" { + elevation_stubs + mkdir -p "$LOCALAPPDATA/emerger/state/elevated.lock" + run env PATH="$HOME/bin:$PATH" pwsh -NoProfile -NonInteractive -File "$REPO_DIR/src/emerger.ps1" --elevated-child "$HOME/$RESULT_LEAF" choco 2 3 0 0 + [ "$status" -eq 1 ] + [[ "$output" == *"cannot take the elevated lock"* ]] + [ ! -e "$HOME/trace" ] || ! grep -q '^choco' "$HOME/trace" +} + +@test "ps: the elevated child refuses a relative result path and a known flag outside its allowlist" { + elevation_stubs + cd "$HOME" + run env PATH="$HOME/bin:$PATH" pwsh -NoProfile -NonInteractive -File "$REPO_DIR/src/emerger.ps1" --elevated-child "$RESULT_LEAF" choco 2 3 0 0 + [ "$status" -eq 2 ] + [[ "$output" == *"elevated child: invalid arguments"* ]] + [ ! -e "$RESULT_LEAF" ] + run env PATH="$HOME/bin:$PATH" pwsh -NoProfile -NonInteractive -File "$REPO_DIR/src/emerger.ps1" --elevated-child "$HOME/$RESULT_LEAF" choco 2 3 0 0 --dev + [ "$status" -eq 2 ] + [[ "$output" == *"elevated child: invalid arguments: --dev"* ]] + [ ! -e "$HOME/trace" ] || ! grep -q '^choco' "$HOME/trace" +} + +@test "ps: the elevated child resets environment variables that steer what runs as administrator" { + export SystemRoot="$HOME/Windows" ProgramData="$HOME/ProgramData" ProgramFiles="$HOME/PF" + run pwsh -NoProfile -NonInteractive -Command " + foreach (\$n in 'DOTNET_STARTUP_HOOKS','COR_ENABLE_PROFILING','COR_PROFILER','COR_PROFILER_PATH','COR_PROFILER_PATH_64','CORECLR_ENABLE_PROFILING','CORECLR_PROFILER_PATH','DOTNET_ADDITIONAL_DEPS','COMPlus_EnableDiagnostics','PSExecutionPolicyPreference','ChocolateyInstall') { Set-Item \"env:\$n\" '$HOME/evil' } + \$env:ComSpec = '$HOME/evil/cmd' + \$env:PATHEXT = '.EVIL' + . '$PSLIB/Elevated.ps1' + Elevated-Restrict-Env + foreach (\$n in 'DOTNET_STARTUP_HOOKS','COR_ENABLE_PROFILING','COR_PROFILER','COR_PROFILER_PATH','COR_PROFILER_PATH_64','CORECLR_ENABLE_PROFILING','CORECLR_PROFILER_PATH','DOTNET_ADDITIONAL_DEPS','COMPlus_EnableDiagnostics','PSExecutionPolicyPreference','ChocolateyInstall') { \"\$n=[\$((Get-Item \"env:\$n\" -ErrorAction SilentlyContinue).Value)]\" } + \"ComSpec=\$env:ComSpec\" + \"PATHEXT=\$env:PATHEXT\"" + [ "$status" -eq 0 ] + [[ "$output" != *"$HOME/evil"* ]] + [[ "$output" != *".EVIL"* ]] + [[ "$output" == *"DOTNET_STARTUP_HOOKS=[]"* ]] + [[ "$output" == *"COR_PROFILER_PATH_64=[]"* ]] + [[ "$output" == *"ChocolateyInstall=[]"* ]] + [[ "$output" == *"ComSpec=$HOME/Windows/System32/cmd.exe"* ]] +} + +@test "ps: the child keeps the machine-scope ChocolateyInstall and ignores the caller's" { + export SystemRoot="$HOME/Windows" ProgramData="$HOME/ProgramData" ProgramFiles="$HOME/PF" + run pwsh -NoProfile -NonInteractive -Command " + \$env:ChocolateyInstall = '$HOME/evil' + . '$PSLIB/Elevated.ps1' + function _Elevated-Machine-Env { param([string]\$Name) if (\$Name -eq 'ChocolateyInstall') { return '$HOME/ProgramData/chocolatey' } } + Elevated-Restrict-Env + \"choco=\$env:ChocolateyInstall\"" + [[ "$output" == *"choco=$HOME/ProgramData/chocolatey"* ]] + [[ "$output" != *"evil"* ]] +} + +@test "ps: a choco.exe planted outside the admin-only locations is refused, one under Program Files is accepted" { + export SystemRoot="$HOME/Windows" ProgramData="$HOME/ProgramData" ProgramFiles="$HOME/PF" + mkdir -p "$HOME/evil" "$HOME/PF/app" + printf '#!/bin/sh\nexit 0\n' >"$HOME/evil/choco"; chmod +x "$HOME/evil/choco" + cp "$HOME/evil/choco" "$HOME/PF/app/choco" + run pwsh -NoProfile -NonInteractive -Command " + . '$PSLIB/Elevated.ps1' + \$env:PATH = '$HOME/evil' + \"planted=[\$(Elevated-Exe-Refusal choco)]\" + \$env:PATH = '$HOME/PF/app' + \"trusted=[\$(Elevated-Exe-Refusal choco)]\" + \$env:PATH = '$HOME/nowhere' + \"absent=[\$(Elevated-Exe-Refusal choco)]\"" + [[ "$output" == *"planted=[choco is outside the administrator-only locations"* ]] + [[ "$output" == *"trusted=[]"* ]] + [[ "$output" == *"absent=[]"* ]] +} + +@test "ps: a choco under ProgramData that standard users can write is refused" { + export SystemRoot="$HOME/Windows" ProgramData="$HOME/ProgramData" ProgramFiles="$HOME/PF" + run pwsh -NoProfile -NonInteractive -Command " + . '$PSLIB/Elevated.ps1' + function _Elevated-Users-Can-Write { param([string]\$Path) return \$true } + \$env:PATH = '$HOME/ProgramData/chocolatey/bin' + New-Item -ItemType Directory -Force '$HOME/ProgramData/chocolatey/bin' | Out-Null + Set-Content '$HOME/ProgramData/chocolatey/bin/choco' x + \"open=[\$(Elevated-Exe-Refusal choco)]\" + function _Elevated-Users-Can-Write { param([string]\$Path) return \$false } + \"closed=[\$(Elevated-Exe-Refusal choco)]\"" + [[ "$output" == *"open=[choco is outside"* ]] + [[ "$output" == *"closed=[]"* ]] +} + +@test "ps: the elevated child fails a manager whose executable is refused and never runs it" { + printf '#!/bin/sh\necho ran >"%s/marker"\n' "$HOME" >"$HOME/choco"; chmod +x "$HOME/choco" + run ps '. (Join-Path $env:PSLIB "Hooks.ps1") + function Elevated-Exe-Refusal { param([string]$Manager) return "$Manager is outside the administrator-only locations" } + function Pkg-Run { param([string]$Manager) Set-Content (Join-Path $env:HOME "marker") ran; return $true } + $script:LOG_BUFFER = New-Object System.Collections.Generic.List[string] + $file = Join-Path $env:HOME "emerger-0123456789abcdef0123456789abcdef.json" + "rc=$(_Elevated-Child-Run $file @("choco"))"' + [[ "$output" == *"rc=3"* ]] + [ ! -e "$HOME/marker" ] + grep -q 'outside the administrator-only' "$HOME/emerger-0123456789abcdef0123456789abcdef.json" +} diff --git a/tests/ps_helper.bash b/tests/ps_helper.bash new file mode 100644 index 0000000..f5b35de --- /dev/null +++ b/tests/ps_helper.bash @@ -0,0 +1,105 @@ +# Shared fixture of the PowerShell tests: temp HOME, and runners for a +# pwsh snippet, the entry point and the profile function. + +setup() { + command -v pwsh >/dev/null || skip "pwsh not installed" + export REPO_DIR="${BATS_TEST_DIRNAME}/.." + export PSLIB="$REPO_DIR/src/pslib" + export HOME_BAK="$HOME" + export HOME="$(mktemp -d)" + export APPDATA="$HOME/AppData/Roaming" LOCALAPPDATA="$HOME/AppData/Local" + export NO_COLOR=1 + mkdir -p "$APPDATA" "$LOCALAPPDATA" +} + +teardown() { + [ -n "${HOME_BAK:-}" ] || return 0 + rm -rf "$HOME" + export HOME="$HOME_BAK" +} + +# File name the caller gives the elevated child for its result. +RESULT_LEAF=emerger-0123456789abcdef0123456789abcdef.json + +# Run pwsh snippet $1 with the libraries dot-sourced and default arguments. +ps() { + pwsh -NoProfile -NonInteractive -Command " + \$ErrorActionPreference = 'Stop' + \$script:EMERGER_STATE = Join-Path \$env:LOCALAPPDATA 'emerger/state' + \$script:EMERGER_CONFIG = Join-Path \$env:APPDATA 'emerger' + foreach (\$f in 'ui/Term','ui/Text','ui/Print','ui/Monitor','ui/Prompt','managers/Progress','Log', + 'Sys','state/Lock','system/Preflight','Elevated','Args','Run','managers/Packages', + 'state/Estimate') { . (Join-Path '$PSLIB' \"\$f.ps1\") } + \$script:ArgsGlobal = Args-Parse @() + UI-Init + $1" +} + +# Run src/emerger.ps1 with $1 as a prelude (stubs defined before the entry +# point), the rest as its arguments. HKLM: maps to $HOME/hklm. +up_ps() { + local prelude="$1"; shift + local args="" word + for word in "$@"; do args+=" '${word//\'/\'\'}'"; done + mkdir -p "$HOME/hklm" + pwsh -NoProfile -NonInteractive -Command " + New-PSDrive -Name HKLM -PSProvider FileSystem -Root '$HOME/hklm' -Scope Global | Out-Null + $prelude + & '$REPO_DIR/src/emerger.ps1' $args + exit \$LASTEXITCODE" +} + +# Write the elevation tests' stubs: a choco on PATH, a config.ps1 and a post +# hook that each append to $HOME/trace whether they ran in the elevated +# child, and a Start-Process that runs the "elevated" process with +# EMERGER_TEST_ELEVATED=1 instead of asking UAC. +elevation_stubs() { + mkdir -p "$HOME/bin" "$APPDATA/emerger/hooks/post.d" + printf '#!/bin/sh\necho "choco elevated=${EMERGER_TEST_ELEVATED:-0}" >>"%s/trace"\necho "Chocolatey upgraded 1/3 packages."\nexit ${CHOCO_RC:-0}\n' "$HOME" >"$HOME/bin/choco" + chmod +x "$HOME/bin/choco" + # The elevated child finds choco only in the system locations. + export ProgramData="$HOME/ProgramData" + mkdir -p "$ProgramData/chocolatey" + ln -sfn "$HOME/bin" "$ProgramData/chocolatey/bin" + printf 'Add-Content "%s/trace" "config elevated=$([int]$env:EMERGER_TEST_ELEVATED)"\n' "$HOME" >"$APPDATA/emerger/config.ps1" + printf 'Add-Content "%s/trace" "hook elevated=$([int]$env:EMERGER_TEST_ELEVATED)"\n' "$HOME" >"$APPDATA/emerger/hooks/post.d/t.ps1" + START_PROCESS_STUB="function Start-Process { + param(\$FilePath, \$ArgumentList, \$Verb, [switch]\$Wait, [switch]\$PassThru) + Add-Content '$HOME/trace' \"start verb=\$Verb\" + if (\$env:DECLINE_UAC) { throw 'The operation was canceled by the user.' } + \$exe = if (\$FilePath -match '^powershell') { (Get-Process -Id \$PID).Path } else { \$FilePath } + \$startInfo = [Diagnostics.ProcessStartInfo]::new(\$exe, (@(\$ArgumentList) -join ' ')) + \$startInfo.UseShellExecute = \$false + \$startInfo.Environment['EMERGER_TEST_ELEVATED'] = '1' + \$startInfo.RedirectStandardOutput = \$true + \$process = [Diagnostics.Process]::Start(\$startInfo) + Set-Content '$HOME/child.out' \$process.StandardOutput.ReadToEnd() + \$process.WaitForExit() + [pscustomobject]@{ ExitCode = \$process.ExitCode } + }" +} + +# Call `up` the way the profile function from install.ps1 does (splatted +# @args), so single-dash flags reach the script as PowerShell would pass them. +up_fn() { + local args="" word + for word in "$@"; do args+=" $word"; done + pwsh -NoProfile -NonInteractive -Command " + function up { & '$REPO_DIR/src/emerger.ps1' @args } + up $args + exit \$LASTEXITCODE" +} + +# Hold lock file $1 (default run.lock) in the state directory from another +# pwsh until $HOME/held appears, the holder's PID written to $HOME/holder. +hold_lock() { + local lock_file="$LOCALAPPDATA/emerger/state/${1:-run.lock}" + mkdir -p "$LOCALAPPDATA/emerger/state" + pwsh -NoProfile -NonInteractive -Command " + \$lock = [IO.File]::Open('$lock_file', 'OpenOrCreate', 'ReadWrite', 'None') + New-Item -ItemType File '$HOME/held' | Out-Null + Start-Sleep 30" >/dev/null 2>&1 & + echo $! >"$HOME/holder" + local tries=0 + while [ ! -e "$HOME/held" ] && [ "$tries" -lt 100 ]; do sleep 0.1; tries=$((tries + 1)); done +} diff --git a/tests/ps_hooks.bats b/tests/ps_hooks.bats new file mode 100644 index 0000000..61a768a --- /dev/null +++ b/tests/ps_hooks.bats @@ -0,0 +1,31 @@ +#!/usr/bin/env bats +# PowerShell user hooks, run through pwsh where it is installed. + +load ps_helper + +@test "ps: a hook ending with exit 1 is reported as failed" { + mkdir -p "$APPDATA/emerger/hooks/pre.d" + printf 'exit 1\n' >"$APPDATA/emerger/hooks/pre.d/bad.ps1" + printf '"good ran"\n' >"$APPDATA/emerger/hooks/pre.d/good.ps1" + run ps ". (Join-Path \$env:PSLIB 'Hooks.ps1'); Log-Init; Hooks-Run pre; 'after'" + [ "$status" -eq 0 ] + [[ "$output" == *"hook bad.ps1 failed (exit 1)"* ]] + [[ "$output" != *"hook good.ps1 failed"* ]] + [[ "$output" == *"good ran"*after* ]] + grep -q '|WARN|hook pre/bad.ps1 failed' "$LOCALAPPDATA/emerger/state/emerger.log" +} + +@test "ps: hooks run in name order even when the directory lists them unsorted" { + mkdir -p "$APPDATA/emerger/hooks/pre.d" + local name + for name in 10-a 20-b 30-c; do + printf 'Add-Content "%s/trace" "%s"\n' "$HOME" "$name" >"$APPDATA/emerger/hooks/pre.d/$name.ps1" + done + # A filesystem that does not sort (FAT, a network share) lists entries in + # any order: the stub returns them reversed. + run ps ". (Join-Path \$env:PSLIB 'Hooks.ps1'); Log-Init + function Get-ChildItem { \$all = @(Microsoft.PowerShell.Management\Get-ChildItem @args); [array]::Reverse(\$all); \$all } + Hooks-Run pre" + [ "$status" -eq 0 ] + [ "$(tr '\n' ' ' <"$HOME/trace")" = "10-a 20-b 30-c " ] +} diff --git a/tests/ps_install.bats b/tests/ps_install.bats new file mode 100644 index 0000000..5cbd65a --- /dev/null +++ b/tests/ps_install.bats @@ -0,0 +1,70 @@ +#!/usr/bin/env bats +# PowerShell installer (install.ps1), run through pwsh where it is installed. + +load ps_helper + +@test "ps: install refuses to shadow an existing up command" { + mkdir -p "$HOME/bin"; printf '#!/bin/sh\necho other\n' >"$HOME/bin/up"; chmod +x "$HOME/bin/up" + run env PATH="$HOME/bin:$PATH" pwsh -NoProfile -NonInteractive -File "$REPO_DIR/install.ps1" + [ "$status" -eq 1 ] + [[ "$output" == *"$HOME/bin/up"* ]] + run pwsh -NoProfile -NonInteractive -Command 'Test-Path $PROFILE.CurrentUserAllHosts' + [ "$output" = "False" ] || ! grep -q emerger "$(pwsh -NoProfile -Command '$PROFILE.CurrentUserAllHosts')" +} + +@test "ps: install registers up when no other up exists" { + run pwsh -NoProfile -NonInteractive -File "$REPO_DIR/install.ps1" + [ "$status" -eq 0 ] + grep -q 'emerger.ps1' "$(pwsh -NoProfile -Command '$PROFILE.CurrentUserAllHosts')" +} + +@test "ps: install install path with quote and subexpression stays literal in the profile" { + local dir="$HOME/a'b\$(ni pwned)" + mkdir -p "$dir" + cp -r "$REPO_DIR/install.ps1" "$REPO_DIR/VERSION" "$REPO_DIR/src" "$dir/" + run pwsh -NoProfile -NonInteractive -File "$dir/install.ps1" + [ "$status" -eq 0 ] + run bash -c "cd '$HOME' && pwsh -NoProfile -NonInteractive -Command '. \$PROFILE.CurrentUserAllHosts; up --version'" + [ ! -e "$HOME/pwned" ] + [ "$status" -eq 0 ] + [[ "$output" == *"eMerger "* ]] +} + +@test "ps: install leaves a Restricted ExecutionPolicy alone without an answer" { + run pwsh -NoProfile -NonInteractive -Command " + function Get-ExecutionPolicy { param(\$Scope) 'Restricted' } + function Set-ExecutionPolicy { New-Item -ItemType File '$HOME/policy-changed' | Out-Null } + & '$REPO_DIR/install.ps1' + exit \$LASTEXITCODE" /dev/null; wait "$(cat "$HOME/holder")" 2>/dev/null || true + [ -e "$HOME/held" ] + [ "$status" -eq 1 ] + [[ "$output" == *"Another eMerger run is in progress"* ]] + run up_ps '' -n -nc -nt + [ "$status" -eq 0 ] +} + +@test "ps: -up, -au, -rc and --reboot wait for the run lock like a run" { + mkdir -p "$HOME/bin" "$LOCALAPPDATA/emerger/cache" + printf '#!/bin/sh\necho "git $*" >>"%s/trace"\n' "$HOME" >"$HOME/bin/git"; chmod +x "$HOME/bin/git" + touch "$LOCALAPPDATA/emerger/cache/keep" + hold_lock + local f out="" + for f in -up -au -rc --reboot; do + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps 'function Register-ScheduledTask { New-Item -ItemType File \"\$env:HOME/task\" | Out-Null }' $f" + out+="$f=$status;" + [[ "$output" == *"Another eMerger run is in progress"* ]] || out+="$f-no-message;" + done + kill "$(cat "$HOME/holder")" 2>/dev/null; wait "$(cat "$HOME/holder")" 2>/dev/null || true + [ -e "$HOME/held" ] + [ "$out" = "-up=1;-au=1;-rc=1;--reboot=1;" ] + [ ! -e "$HOME/trace" ] + [ ! -e "$HOME/task" ] + [ -e "$LOCALAPPDATA/emerger/cache/keep" ] +} + +@test "ps: a run lock the run may not open stops the run with the reason" { + run ps "\$script:EMERGER_STATE = '$HOME' + \$l = Lock-Acquire + \"held=\$(\$null -ne \$l)\" + Lock-Release \$l" + [ "$status" -eq 0 ] + [ "$output" = "held=True" ] + mkdir -p "$LOCALAPPDATA/emerger/state/run.lock" + run up_ps '' -n -nc -nt + [ "$status" -eq 1 ] + [[ "$output" == *"Cannot open the run lock"*"run.lock"* ]] + [[ "$output" != *"Another eMerger run is in progress"* ]] +} + +@test "ps: a run lock name squatted in the shared mutex namespace does not block the run" { + pwsh -NoProfile -NonInteractive -Command " + \$m = [Threading.Mutex]::new(\$false, \"Global\\eMerger-\$([Environment]::UserName)\") + [void]\$m.WaitOne(0) + New-Item -ItemType File '$HOME/held' | Out-Null + Start-Sleep 30" >/dev/null 2>&1 & + local holder=$! n=0 + while [ ! -e "$HOME/held" ] && [ "$n" -lt 100 ]; do sleep 0.1; n=$((n + 1)); done + run up_ps '' -n -nc -nt + kill "$holder" 2>/dev/null; wait "$holder" 2>/dev/null || true + [ -e "$HOME/held" ] + [ "$status" -eq 0 ] + [[ "$output" != *"Another eMerger run is in progress"* ]] +} + +@test "ps: a run is refused while an elevated child of an interrupted run still holds its lock" { + hold_lock elevated.lock + run up_ps '' -n -nc -nt + kill "$(cat "$HOME/holder")" 2>/dev/null; wait "$(cat "$HOME/holder")" 2>/dev/null || true + [ -e "$HOME/held" ] + [ "$status" -eq 1 ] + [[ "$output" == *"Another eMerger run is in progress"* ]] + run up_ps '' -n -nc -nt + [ "$status" -eq 0 ] +} + +@test "ps: Lock-Open takes the file exclusively, a second open of a held lock gets null" { + run ps '. (Join-Path $env:PSLIB "state/Lock.ps1") + $path = Join-Path $env:HOME "x.lock" + $first = Lock-Open $path + $second = Lock-Open $path + "first=$($null -ne $first) second=$($null -ne $second)" + Lock-Release $first + $third = Lock-Open $path + "after release=$($null -ne $third)"' + [ "$status" -eq 0 ] + [[ "$output" == *"first=True second=False"* ]] + [[ "$output" == *"after release=True"* ]] +} diff --git a/tests/ps_managers.bats b/tests/ps_managers.bats new file mode 100644 index 0000000..8349044 --- /dev/null +++ b/tests/ps_managers.bats @@ -0,0 +1,109 @@ +#!/usr/bin/env bats +# PowerShell manager recipes and selection, run through pwsh where it is installed. + +load ps_helper + +@test "ps: winget accepts agreements only with --accept-licenses" { + run ps '$script:ArgsGlobal.DryRun = $true; Pkg-Run winget | Out-Null' + [ "$status" -eq 0 ] + [[ "$output" != *"accept-package-agreements"* ]] + [[ "$output" == *"--accept-licenses"* ]] + run ps '$script:ArgsGlobal.DryRun = $true; $script:ArgsGlobal.AcceptLicenses = $true; Pkg-Run winget | Out-Null' + [ "$status" -eq 0 ] + [[ "$output" == *"--accept-package-agreements --accept-source-agreements"* ]] +} + +@test "ps: --security skips each manager with no security channel and warns" { + mkdir -p "$HOME/bin" + for m in winget choco; do printf '#!/bin/sh\necho "%s ran" >>"%s/trace"\n' "$m" "$HOME" >"$HOME/bin/$m"; chmod +x "$HOME/bin/$m"; done + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -n -y -nc -nt --security" + [ "$status" -eq 0 ] + [[ "$output" == *"skip winget: no security-only updates, --security never runs a full upgrade"* ]] + [[ "$output" == *"skip choco: no security-only updates"* ]] + [[ "$output" != *"[dry-run] choco"* ]] + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -n -y -nc -nt --accept-licenses" + [ "$status" -eq 0 ] + [[ "$output" == *"[dry-run] choco upgrade all"* ]] + [[ "$output" != *"skip choco"* ]] +} + +@test "ps: verbose pip upgrade goes on to the next package after a failing one" { + mkdir -p "$HOME/bin" + printf '#!/bin/sh\nif [ "$1" = list ]; then echo %s; exit 0; fi\necho "install $4" >>"%s/trace"\necho "notice: new pip" >&2\n[ "$4" = b ]\n' \ + "'[{\"name\":\"a\"},{\"name\":\"b\"}]'" "$HOME" >"$HOME/bin/pip" + chmod +x "$HOME/bin/pip" + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f ps); ps \"\$1\"" _ " + \$PSNativeCommandUseErrorActionPreference = \$true + \$script:UI_VERBOSE = \$true + \$ok = Pkg-Run pip + \"ok=\$ok\"" + [ "$status" -eq 0 ] + [ "$(cat "$HOME/trace")" = "install a"$'\n'"install b" ] + [[ "$output" == *"ok=False"* ]] + [[ "$output" != *NativeCommand* ]] +} + +@test "ps: Windows Update writing a non-terminating error fails the step" { + local mod="$HOME/.local/share/powershell/Modules/PSWindowsUpdate" + mkdir -p "$mod" + printf 'function Get-WindowsUpdate { "Accepted [1] Updates"; if ($env:WU_FAIL) { Write-Error "0x80240022 install failed" } }\n' >"$mod/PSWindowsUpdate.psm1" + run env WU_FAIL=1 bash -c "$(declare -f ps); ps \"\$1\"" _ '$ok = Pkg-Run PSWindowsUpdate; "ok=$ok"' + [ "$status" -eq 0 ] + [[ "$output" == *"ok=False"* ]] + [[ "$output" == *"0x80240022"* ]] + run ps '$ok = Pkg-Run PSWindowsUpdate; "ok=$ok"' + [ "$status" -eq 0 ] + [[ "$output" == *"ok=True"* ]] +} + +@test "ps: --only and --except match manager names case-sensitively" { + mkdir -p "$HOME/bin" + for m in winget scoop; do printf '#!/bin/sh\n' >"$HOME/bin/$m"; chmod +x "$HOME/bin/$m"; done + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -n -y -nc -nt --only WINGET,scoop" + [ "$status" -eq 0 ] + [[ "$output" != *"[dry-run] winget"* ]] + [[ "$output" == *"[dry-run] scoop update"* ]] + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -n -y -nc -nt --except SCOOP" + [ "$status" -eq 0 ] + [[ "$output" == *"[dry-run] scoop update"* ]] +} + +@test "ps: Windows Update installs and accepts EULAs only with --accept-licenses" { + local mod="$HOME/.local/share/powershell/Modules/PSWindowsUpdate" + mkdir -p "$mod" + printf 'function Get-WindowsUpdate { [CmdletBinding(SupportsShouldProcess = $true)] param([switch]$AcceptAll, [switch]$Install, [switch]$IgnoreReboot, $Category)\n Add-Content (Join-Path $env:HOME "wu") "accept=$AcceptAll install=$Install" }\n' >"$mod/PSWindowsUpdate.psm1" + run ps '$ok = Pkg-Run PSWindowsUpdate; "ok=$ok"' + [ "$status" -eq 0 ] + [[ "$output" == *"ok=True"* ]] + [[ "$output" == *"run with --accept-licenses"* ]] + [ "$(cat "$HOME/wu")" = "accept=False install=False" ] + rm "$HOME/wu" + run ps '$script:ArgsGlobal.AcceptLicenses = $true; $ok = Pkg-Run PSWindowsUpdate; "ok=$ok"' + [ "$status" -eq 0 ] + [ "$(cat "$HOME/wu")" = "accept=True install=True" ] +} + +@test "ps: a comma list after --only or --except through the profile function names each manager" { + mkdir -p "$HOME/bin" + for m in winget scoop; do printf '#!/bin/sh\n' >"$HOME/bin/$m"; chmod +x "$HOME/bin/$m"; done + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_fn); up_fn -n -y -nc -nt -nl --only winget,scoop" + [ "$status" -eq 0 ] + [[ "$output" == *"[dry-run] winget"* ]] + [[ "$output" == *"[dry-run] scoop update"* ]] + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_fn); up_fn -n -y -nc -nt -nl --except winget,scoop" + [ "$status" -eq 0 ] + [[ "$output" == *"skip winget (--except)"* ]] + [[ "$output" == *"skip scoop (--except)"* ]] +} + +@test "ps: choco upgrades (and accepts package licences) only with --accept-licenses" { + run ps '$script:ArgsGlobal.DryRun = $true; Pkg-Run choco | Out-Null' + [ "$status" -eq 0 ] + [[ "$output" != *"upgrade all"* ]] + [[ "$output" == *"[dry-run] choco outdated"* ]] + [[ "$output" == *"upgrades not installed: they may need licence agreement, run with --accept-licenses"* ]] + run ps '$script:ArgsGlobal.DryRun = $true; $script:ArgsGlobal.AcceptLicenses = $true; Pkg-Run choco | Out-Null' + [ "$status" -eq 0 ] + [[ "$output" == *"[dry-run] choco upgrade all -y"* ]] + [[ "$output" != *"outdated"* ]] +} diff --git a/tests/ps_metrics.bats b/tests/ps_metrics.bats new file mode 100644 index 0000000..935d7e5 --- /dev/null +++ b/tests/ps_metrics.bats @@ -0,0 +1,55 @@ +#!/usr/bin/env bats +# PowerShell --metrics export, run through pwsh where it is installed. + +load ps_helper + +@test "ps: --metrics with an empty or malformed last history line exits 1 with a message" { + mkdir -p "$LOCALAPPDATA/emerger/state" + printf '{"ts":"2026-01-01T00:00:00Z","duration":5}\n{"ts": broken\n' >"$LOCALAPPDATA/emerger/state/history.jsonl" + run up_ps '' --metrics "$HOME/m.prom" + [ "$status" -eq 1 ] + [[ "$output" == *"last line of"*"history.jsonl is not a valid record"* ]] + [[ "$output" != *"ConvertFrom-Json"* ]] + [ ! -e "$HOME/m.prom" ] + : >"$LOCALAPPDATA/emerger/state/history.jsonl" + run up_ps '' --metrics "$HOME/m.prom" + [ "$status" -eq 1 ] + [[ "$output" == *"history.jsonl is empty"* ]] +} + +@test "ps: --metrics never writes through a link planted at a predictable temp name" { + mkdir -p "$LOCALAPPDATA/emerger/state" + echo '{"ts":"2026-01-01T00:00:00Z","duration":5,"errors":0,"reboot":0,"managers":[]}' >"$LOCALAPPDATA/emerger/state/history.jsonl" + echo original >"$HOME/victim" + ln -s "$HOME/victim" "$HOME/m.prom.tmp" + run up_ps '' --metrics "$HOME/m.prom" + [ "$status" -eq 0 ] + [ "$(cat "$HOME/victim")" = original ] + grep -q '^emerger_last_run_duration_seconds 5$' "$HOME/m.prom" + [ "$(ls "$HOME" | grep -c '^m\.prom\..*\.tmp$')" -eq 0 ] +} + +@test "ps: --metrics fills a missing field with 0 and writes to a path with brackets" { + run up_ps '' --metrics "$HOME/m.prom" + [ "$status" -eq 1 ] + [[ "$output" == *"No history yet ($LOCALAPPDATA/emerger/state/history.jsonl missing)"* ]] + mkdir -p "$LOCALAPPDATA/emerger/state" + echo '{"ts":"2026-01-01T00:00:00Z","managers":[{"name":"scoop","result":"ok","secs":1}]}' >"$LOCALAPPDATA/emerger/state/history.jsonl" + run up_ps '' --metrics "$HOME/m[1].prom" + [ "$status" -eq 0 ] + grep -qx 'emerger_last_run_duration_seconds 0' "$HOME/m[1].prom" + grep -qx 'emerger_last_run_freed_bytes 0' "$HOME/m[1].prom" + grep -qx 'emerger_last_run_errors 0' "$HOME/m[1].prom" + grep -qx 'emerger_reboot_required 0' "$HOME/m[1].prom" + grep -qx '# HELP emerger_manager_ok Per-manager success in the last run (1=ok,0=fail)' "$HOME/m[1].prom" + grep -qx 'emerger_manager_ok{manager="scoop"} 1' "$HOME/m[1].prom" +} + +@test "ps: --metrics writes the freed KiB of the last run as bytes, as on Unix" { + mkdir -p "$LOCALAPPDATA/emerger/state" + echo '{"ts":"2026-01-01T00:00:00Z","duration":3,"freed_kb":15,"errors":0,"reboot":0,"managers":[]}' >"$LOCALAPPDATA/emerger/state/history.jsonl" + run up_ps '' --metrics "$HOME/m.prom" + [ "$status" -eq 0 ] + grep -qx '# TYPE emerger_last_run_freed_bytes gauge' "$HOME/m.prom" + grep -qx 'emerger_last_run_freed_bytes 15360' "$HOME/m.prom" +} diff --git a/tests/ps_run.bats b/tests/ps_run.bats new file mode 100644 index 0000000..c9060b3 --- /dev/null +++ b/tests/ps_run.bats @@ -0,0 +1,218 @@ +#!/usr/bin/env bats +# PowerShell step runner: process, output parsing, timeout, interrupt, run through pwsh where it is installed. + +load ps_helper + +@test "ps: progress parsers ignore counters too big for an int" { + run ps ' + $n = "12345678901" + foreach ($c in @(@("winget", "$n upgrades available."), @("winget", "($n/$n) Found X [x.y]"), + @("choco", "Chocolatey upgraded $n/$n packages."), @("scoop", "Updating $n outdated apps:"), + @("PSWindowsUpdate", "Accepted [$n] Updates"), @("PSWindowsUpdate", "Found [$n] Updates in post search"), + @("pip", "[$n/$n] pkg"), @("npm", "($n/$n) done"))) { + Progress-Reset $c[0] 0 + [void](Progress-Feed $c[1]) + "$($c[0]) tot=$($script:PROGRESS_STATE.Total) cur=$($script:PROGRESS_STATE.Current)" + } + Progress-Reset winget 0; [void](Progress-Feed "3 upgrades available."); "small tot=$($script:PROGRESS_STATE.Total)"' + [ "$status" -eq 0 ] + [[ "$output" != *"Cannot convert"* ]] + [ "$(grep -c 'tot=0 cur=0' <<<"$output")" -eq 8 ] + [[ "$output" == *"small tot=3"* ]] +} + +@test "ps: a parser error inside _Run-Consume does not escape to the running step" { + run ps ' + function Progress-Feed { throw "parser broke" } + $st = @{ Log = (New-Object System.Text.StringBuilder); Carry = "" } + _Run-Consume $st "line one`nline two`n" + "consumed log=$($st.Log.Length)"' + [ "$status" -eq 0 ] + [[ "$output" == *"consumed log=18"* ]] +} + +@test "ps: cmd.exe metacharacters in a .cmd shim path are caret-escaped" { + mkdir -p "$HOME/A&B" "$HOME/50%x" "$HOME/C D&E" "$HOME/F G%H" + for d in "A&B" "50%x" "C D&E" "F G%H"; do printf '@echo off\n' >"$HOME/$d/npm.cmd"; chmod +x "$HOME/$d/npm.cmd"; done + run ps " + \$env:ComSpec = 'cmd.exe' + foreach (\$d in 'A&B', '50%x', 'C D&E', 'F G%H') { + \$t = _Run-Resolve (Join-Path '$HOME' \"\$d/npm.cmd\") @('update', '-g') + \"\$(\$t.File)|\$(\$t.Args)\" + }" + [ "$status" -eq 0 ] + [ "${lines[0]}" = "cmd.exe|/d /s /c \"$HOME/A^&B/npm.cmd update -g\"" ] + [ "${lines[1]}" = "cmd.exe|/d /s /c \"$HOME/50^%x/npm.cmd update -g\"" ] + [ "${lines[2]}" = "cmd.exe|/d /s /c \"\"$HOME/C D&E/npm.cmd\" update -g\"" ] + [ "${lines[3]}" = "cmd.exe|/d /s /c \"\"$HOME/F G\"^%\"H/npm.cmd\" update -g\"" ] +} + +@test "ps: MANAGER_TIMEOUT kills a stalled step and its children and reports a failure" { + printf '#!/bin/sh\nsleep 60 &\necho $! >"%s/grandchild"\nwait\n' "$HOME" >"$HOME/stall"; chmod +x "$HOME/stall" + SECONDS=0 + run ps "\$script:RETRY_ATTEMPTS = 2; \$script:RETRY_DELAY = 0; \$script:MANAGER_TIMEOUT = 1 + \$ok = Run-Cmd 'stall' -Exe '$HOME/stall' + \"ok=\$ok\"" + local took=$SECONDS + [ "$status" -eq 0 ] + [[ "$output" == *"ok=False"* ]] + [[ "$output" == *"timed out after 1s"* ]] + [ "$took" -lt 20 ] + ! kill -0 "$(cat "$HOME/grandchild")" 2>/dev/null +} + +@test "ps: MANAGER_TIMEOUT 0 lets a step finish" { + printf '#!/bin/sh\nsleep 1\necho done\n' >"$HOME/slow"; chmod +x "$HOME/slow" + run ps "\$script:MANAGER_TIMEOUT = 0; \$ok = Run-Cmd 'slow' -Exe '$HOME/slow'; \"ok=\$ok\"" + [ "$status" -eq 0 ] + [[ "$output" == *"ok=True"* ]] +} + +@test "ps: MANAGER_TIMEOUT stops a stalled verbose step and fails it" { + printf '#!/bin/sh\nsleep 60\n' >"$HOME/stall"; chmod +x "$HOME/stall" + SECONDS=0 + run ps "\$script:UI_VERBOSE = \$true; \$script:MANAGER_TIMEOUT = 1; \$ok = Run-Cmd 'stall' -Exe '$HOME/stall'; \"ok=\$ok\"" + [ "$status" -eq 0 ] + [[ "$output" == *"ok=False"* ]] + [ "$SECONDS" -lt 20 ] +} + +@test "ps: an interrupted step kills the child's whole process tree" { + printf '#!/bin/sh\nsleep 60 &\necho $! >"%s/grandchild"\nwait\n' "$HOME" >"$HOME/stall"; chmod +x "$HOME/stall" + run ps "function UI-Monitor-Frame { if (Test-Path '$HOME/grandchild') { throw 'interrupted' } } + \$script:RETRY_ATTEMPTS = 1 + \$ok = Run-Cmd 'stall' -Exe '$HOME/stall' + \"ok=\$ok\"" + [ "$status" -eq 0 ] + [[ "$output" == *"ok=False"* ]] + sleep 0.5 + ! kill -0 "$(cat "$HOME/grandchild")" 2>/dev/null +} + +@test "ps: under --json hook and verbose manager output go to stderr" { + mkdir -p "$HOME/bin" "$APPDATA/emerger/hooks/pre.d" + printf '"hook out"; Write-Host "hook host"\n' >"$APPDATA/emerger/hooks/pre.d/h.ps1" + printf '#!/bin/sh\necho "npm out"\n' >"$HOME/bin/npm"; chmod +x "$HOME/bin/npm" + local t + for t in 0 30; do + printf '$script:MANAGER_TIMEOUT = %s\n' "$t" >"$APPDATA/emerger/config.ps1" + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -y -v -nc -nt --dev --only npm --json 2>'$HOME/err'" + [ "$status" -eq 0 ] + [ "${#lines[@]}" -eq 1 ] + [[ "${lines[0]}" == '{"ts":'*'"managers":[{"name":"npm","result":"ok","secs":'[0-9]*'}]}' ]] + grep -q 'hook out' "$HOME/err" + grep -q 'hook host' "$HOME/err" + grep -q 'npm out' "$HOME/err" + done + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -y -v -nc -nt --dev --only npm 2>/dev/null" + [[ "$output" == *"hook out"* ]] + [[ "$output" == *"npm out"* ]] +} + +@test "ps: an interrupted run stops before the next step and exits 1" { + mkdir -p "$HOME/bin" "$HOME/hklm" + printf '#!/bin/sh\necho "scoop $*" >>"%s/trace"\nif [ "$#" -eq 1 ]; then touch "%s/started"; exec sleep 30; fi\n' "$HOME" "$HOME" >"$HOME/bin/scoop" + chmod +x "$HOME/bin/scoop" + # Background jobs start with SIGINT ignored: restore it, as a terminal's Ctrl-C finds it. + env --default-signal=INT PATH="$HOME/bin:$PATH" pwsh -NoProfile -NonInteractive -File "$REPO_DIR/src/emerger.ps1" -y -nc -nt -nl >"$HOME/out" 2>&1 & + local pid=$! n=0 + while [ ! -e "$HOME/started" ] && [ "$n" -lt 150 ]; do sleep 0.1; n=$((n + 1)); done + [ -e "$HOME/started" ] + kill -INT "$pid" + local rc=0 + wait "$pid" || rc=$? + cat "$HOME/out" + [ "$rc" -eq 1 ] + [ "$(cat "$HOME/trace")" = "scoop update" ] + grep -q 'Interrupted (SIGINT), stopping.' "$HOME/out" + grep -q '|WARN|interrupted' "$LOCALAPPDATA/emerger/state/emerger.log" +} + +@test "ps: a MANAGER_TIMEOUT past the int range in milliseconds lets a verbose step finish" { + printf '#!/bin/sh\necho done\n' >"$HOME/quick"; chmod +x "$HOME/quick" + local t + for t in 3000000 999999999; do + run ps "\$script:UI_VERBOSE = \$true; \$script:MANAGER_TIMEOUT = $t; \$ok = Run-Cmd 'quick' -Exe '$HOME/quick'; \"ok=\$ok\"" + [ "$status" -eq 0 ] + [[ "$output" == *"ok=True"* ]] || { echo "MANAGER_TIMEOUT=$t: $output"; return 1; } + [[ "$output" != *"Cannot convert"* ]] + done +} + +@test "ps: the PowerShell host for children and the task is the console host in PSHOME" { + run ps 'Run-PowerShell-Path; $PSHOME' + [ "$status" -eq 0 ] + [[ "${lines[0]}" == "${lines[1]}/pwsh" || "${lines[0]}" == "${lines[1]}/pwsh.exe" ]] +} + +@test "ps: manager output with OSC, reset and control bytes is sanitised in the live line and the failure tail" { + run ps ' + $script:PKG_CURRENT = "npm" + $e = [char]27; $b = [char]7 + $null = Run-Cmd "evil step" -Exe sh -ArgList @("-c", "printf ''${e}]52;c;ZXZpbA==${b}${e}]0;pwned${b}${e}cok${b}\010\n${e}[31mred${e}[0m\n''; exit 1")' + [[ "$output" == *"ok"* ]] + [[ "$output" == *"red"* ]] + [[ "$output" != *$'\e]'* ]] + [[ "$output" != *$'\ec'* ]] + [[ "$output" != *$'\a'* ]] + [[ "$output" != *"52;c;"* ]] + [[ "$output" != *$'\b'* ]] +} + +@test "ps: UI-Sanitize removes OSC, lone ESC sequences, C1 and C0 controls but keeps tab" { + run ps ' + $e = [char]27 + $t = "a${e}]8;;http://x${e}\link${e}]0;t$([char]7)b${e}cc${e}(Bd$([char]0x9d)e$([char]0x01)f`tg" + "[" + (UI-Sanitize $t) + "]"' + [ "$status" -eq 0 ] + [[ "$output" == *"[alinkbcdef"$'\t'"g]"* ]] +} + +@test "ps: output without a newline is cut to a bounded line before parsing" { + run ps ' + $script:Seen = [System.Collections.Generic.List[int]]::new() + function Progress-Feed { param([string]$Line) $script:Seen.Add($Line.Length); return "" } + Progress-Reset "choco" 0 + $state = @{ Log = (New-Object System.Text.StringBuilder); Carry = ""; HasTimedOut = $false } + $chunk = "5" * 8192 + $carryMax = 0 + for ($i = 0; $i -lt 1024; $i++) { _Run-Consume $state $chunk; $carryMax = [math]::Max($carryMax, $state.Carry.Length) } + _Run-Consume $state ("." * 100000 + "`n") + "carrymax=$carryMax" + "lines=$($script:Seen.Count) longest=$(($script:Seen | Measure-Object -Maximum).Maximum)"' + [ "$status" -eq 0 ] + [[ "$output" == *"carrymax=1024"* ]] + [[ "$output" == *"lines=1 longest=1024"* ]] +} + +@test "ps: progress patterns on a hostile line run linear in its length" { + # 1024 characters is the bound _Run-Consume enforces. The patterns must + # not backtrack on it: each attempt is capped by a regex match timeout of + # 250 ms, which a quadratic or cubic scan of 1024 dots or digits exceeds. + run ps ' + $line = "Progress: Downloading x" + ("." * 1000) + $rx = [regex]::new($script:PROGRESS_RX_CHOCO, "None", [TimeSpan]::FromMilliseconds(250)) + $r1 = $rx.IsMatch($line + " ") + $rb = [regex]::new($script:PROGRESS_RX_BYTES, "None", [TimeSpan]::FromMilliseconds(250)) + $r2 = $rb.IsMatch("1" * 1000 + " ") + $rp = [regex]::new($script:PROGRESS_RX_PERCENT, "None", [TimeSpan]::FromMilliseconds(250)) + $r3 = $rp.IsMatch("1" * 1000 + ".") + "choco=$r1 bytes=$r2 percent=$r3" + Progress-Reset choco 0; [void](Progress-Feed "Progress: Downloading git.install 2.1.0... 45%") + "name=$($script:PROGRESS_STATE.Name) pct=$($script:PROGRESS_STATE.Percent)"' + [ "$status" -eq 0 ] + [[ "$output" == *"choco=False bytes=False percent=False"* ]] + [[ "$output" == *"name=git pct=45"* ]] +} + +@test "ps: a manager line forging a ts|ERROR| entry is one log line with no pipe in the message" { + printf 'printf "boom\\n2026-01-01T00:00:00Z|ERROR|forged\\n"\nexit 1\n' >"$HOME/payload.sh" + run ps ' + $script:EMERGER_LOG = Join-Path $env:HOME "up.log" + $script:PKG_CURRENT = "npm" + $script:RETRY_ATTEMPTS = 1 + $null = Run-Cmd "evil step" -Exe sh -ArgList @((Join-Path $env:HOME "payload.sh")) + $log = @(Get-Content -LiteralPath $script:EMERGER_LOG) + "errors=$(@($log | Where-Object { $_ -like "*|ERROR|*" }).Count) forged=$(@($log | Where-Object { $_ -like "2026-01-01*" }).Count)"' + [[ "$output" == *"errors=2 forged=0"* ]] +} diff --git a/tests/ps_summary.bats b/tests/ps_summary.bats new file mode 100644 index 0000000..c1063e1 --- /dev/null +++ b/tests/ps_summary.bats @@ -0,0 +1,127 @@ +#!/usr/bin/env bats +# PowerShell summary, history and log, run through pwsh where it is installed. + +load ps_helper + +# Get-Content that keeps the file open while it emits, and Set-Content that +# fails on a file still open for reading, as Windows PowerShell 5.1 does. +SHARING_STUBS=' + function Get-Content { $global:READING = $true; try { Microsoft.PowerShell.Management\Get-Content @args } finally { $global:READING = $false } } + function Set-Content { + param([Parameter(Position = 0)][Alias("LiteralPath")]$Path, [Parameter(ValueFromPipeline = $true)]$Value) + begin { $all = @() } + process { if ($global:READING) { throw "The process cannot access the file because it is being used by another process." }; $all += $Value } + end { Microsoft.PowerShell.Management\Set-Content -LiteralPath $Path -Value $all } + }' + +@test "ps: log and history rotation finish reading before they rewrite the file" { + mkdir -p "$LOCALAPPDATA/emerger/state" + seq 1 2500 >"$LOCALAPPDATA/emerger/state/emerger.log" + seq 1 600 | sed 's/.*/{"ts":"2026-01-01T00:00:00Z","n":&}/' >"$LOCALAPPDATA/emerger/state/history.jsonl" + run ps ". (Join-Path \$env:PSLIB 'Summary.ps1'); . (Join-Path \$env:PSLIB 'state/History.ps1'); . (Join-Path \$env:PSLIB 'system/Reboot.ps1') + $SHARING_STUBS + Log-Init + \$script:Summary = @() + History-Append (Summary-Json 1) + 'rotated'" + [ "$status" -eq 0 ] + [[ "$output" == *rotated* ]] + [ "$(wc -l <"$LOCALAPPDATA/emerger/state/emerger.log")" -eq 2000 ] + [ "$(head -1 "$LOCALAPPDATA/emerger/state/emerger.log")" = 501 ] + [ "$(wc -l <"$LOCALAPPDATA/emerger/state/history.jsonl")" -eq 500 ] + [[ "$(tail -1 "$LOCALAPPDATA/emerger/state/history.jsonl")" == *'"duration":1'* ]] +} + +@test "ps: elapsed seconds are truncated, not rounded" { + run ps '$t0 = [DateTime]::new(2026, 1, 1, 0, 0, 0, [DateTimeKind]::Utc) + Sys-Elapsed-Seconds $t0 $t0.AddMilliseconds(1900) + Sys-Elapsed-Seconds $t0 $t0.AddSeconds(61.5) + Sys-Elapsed-Seconds $t0 $t0' + [ "$status" -eq 0 ] + [ "$output" = $'1\n61\n0' ] +} + +@test "ps: log and history timestamps use colons whatever the culture's time separator" { + mkdir -p "$LOCALAPPDATA/emerger/state" + run ps ". (Join-Path \$env:PSLIB 'Summary.ps1'); . (Join-Path \$env:PSLIB 'state/History.ps1'); . (Join-Path \$env:PSLIB 'system/Reboot.ps1') + \$c = [Globalization.CultureInfo]::new('en-US'); \$c.DateTimeFormat.TimeSeparator = '.' + [Threading.Thread]::CurrentThread.CurrentCulture = \$c + Log-Init; Log-Info 'x' + \$script:Summary = @(); \$script:ArgsGlobal.Json = \$true + Summary-Print 3" + [ "$status" -eq 0 ] + [[ "$output" =~ \"ts\":\"[0-9-]+T[0-9]{2}:[0-9]{2}:[0-9]{2}Z\" ]] + grep -Eq '^[0-9-]+T[0-9]{2}:[0-9]{2}:[0-9]{2}Z\|INFO\|x$' "$LOCALAPPDATA/emerger/state/emerger.log" + grep -Eq '"ts":"[0-9-]+T[0-9]{2}:[0-9]{2}:[0-9]{2}Z"' "$LOCALAPPDATA/emerger/state/history.jsonl" +} + +@test "ps: -qq still prints the reboot advisory" { + mkdir -p "$LOCALAPPDATA/emerger/state" "$HOME/hklm/SOFTWARE/Microsoft/Windows/CurrentVersion/Component Based Servicing/RebootPending" + run ps "New-PSDrive -Name HKLM -PSProvider FileSystem -Root '$HOME/hklm' | Out-Null + . (Join-Path \$env:PSLIB 'Summary.ps1'); . (Join-Path \$env:PSLIB 'state/History.ps1'); . (Join-Path \$env:PSLIB 'system/Reboot.ps1') + \$script:Summary = @([pscustomobject]@{ Name = 'winget'; Result = 'ok'; Secs = 1 }) + \$script:QUIET_LEVEL = 2 + Summary-Print 3" + [ "$status" -eq 0 ] + [[ "$output" == *"1 managers ok, 0m03s"* ]] + [[ "$output" == *"Reboot recommended"* ]] +} + +@test "ps: the time estimate rounds a half-second average up" { + mkdir -p "$LOCALAPPDATA/emerger/state" + printf '{"managers":[{"name":"winget","secs":2}]}\n{"managers":[{"name":"winget","secs":3}]}\n{"managers":[{"name":"scoop","secs":0}]}\n' >"$LOCALAPPDATA/emerger/state/history.jsonl" + run ps '"[$(Estimate-Read winget)][$(Estimate-Read scoop)]"' + [ "$status" -eq 0 ] + [ "$output" = "[~3s][]" ] +} + +@test "ps: a dry run writes no history line and a real run writes one at every quiet level" { + mkdir -p "$HOME/bin" + printf '#!/bin/sh\n' >"$HOME/bin/scoop"; chmod +x "$HOME/bin/scoop" + local hist="$LOCALAPPDATA/emerger/state/history.jsonl" q n=0 + for q in -q -qq -qqq --json; do + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -n -y -nc -nt $q" + [ "$status" -eq 0 ] + [ ! -e "$hist" ] || { echo "dry run $q wrote history"; return 1; } + done + for q in -q -qq -qqq --json; do + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -y -nc -nt $q" + [ "$status" -eq 0 ] + n=$((n + 1)) + [ "$(wc -l <"$hist")" -eq "$n" ] || { echo "real run $q: $(wc -l <"$hist") lines"; return 1; } + done +} + +@test "ps: the --json line is the history line, with per-manager secs" { + mkdir -p "$HOME/bin" + printf '#!/bin/sh\n' >"$HOME/bin/scoop"; chmod +x "$HOME/bin/scoop" + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f up_ps); up_ps '' -y -nc -nt --json 2>/dev/null" + [ "$status" -eq 0 ] + [ "${#lines[@]}" -eq 1 ] + [[ "${lines[0]}" == *'"managers":[{"name":"scoop","result":"ok","secs":'[0-9]*'}]}' ]] + [ "${lines[0]}" = "$(cat "$LOCALAPPDATA/emerger/state/history.jsonl")" ] +} + +@test "ps: a run's freed space goes to history.jsonl as freed_kb in KiB" { + run ps '. (Join-Path $env:PSLIB "clean/Size.ps1"); . (Join-Path $env:PSLIB "Summary.ps1") + $script:SUMMARY_FREED_KB = 2048 + function Reboot-Pending { $false } + (Summary-Json 1 | ConvertFrom-Json).freed_kb + Size-Format-KB 2048; Size-Format-KB 1572864' + [ "$status" -eq 0 ] + [ "${lines[0]}" = 2048 ] + [ "${lines[1]}" = 2.0MB ] + [ "${lines[2]}" = 1.5GB ] +} + +@test "ps: --errors and --history with nothing recorded print the Unix messages" { + run ps ". (Join-Path \$env:PSLIB 'state/History.ps1'); \$script:QUIET_LEVEL = 0; Log-Show-Errors; History-Show" + [ "$status" -eq 0 ] + [[ "$output" == *"No log yet."* ]] + [[ "$output" == *"No history yet."* ]] + mkdir -p "$LOCALAPPDATA/emerger/state" + echo "2026-01-01T00:00:00Z|INFO|x" >"$LOCALAPPDATA/emerger/state/emerger.log" + run ps "Log-Show-Errors" + [ "$status" -eq 0 ] + [[ "$output" == *"No errors logged."* ]] +} diff --git a/tests/ps_system.bats b/tests/ps_system.bats new file mode 100644 index 0000000..db388dc --- /dev/null +++ b/tests/ps_system.bats @@ -0,0 +1,77 @@ +#!/usr/bin/env bats +# PowerShell platform checks: reboot, weather, battery, run through pwsh where it is installed. + +load ps_helper + +@test "ps: --dry-run with --reboot and a pending reboot does not restart" { + mkdir -p "$HOME/hklm/SOFTWARE/Microsoft/Windows/CurrentVersion/Component Based Servicing/RebootPending" + run up_ps "function Restart-Computer { New-Item -ItemType File '$HOME/rebooted' | Out-Null }" -n --reboot + [ "$status" -eq 0 ] + [ ! -e "$HOME/rebooted" ] + [[ "$output" == *"[dry-run] would reboot"* ]] +} + +@test "ps: --reboot with a pending reboot restarts outside dry-run" { + mkdir -p "$HOME/hklm/SOFTWARE/Microsoft/Windows/CurrentVersion/Component Based Servicing/RebootPending" + run up_ps "function Restart-Computer { New-Item -ItemType File '$HOME/rebooted' | Out-Null }" --reboot + [ "$status" -eq 0 ] + [ -e "$HOME/rebooted" ] +} + +@test "ps: -w and --weather print the wttr.in line with control characters stripped" { + local stub="function Invoke-WebRequest { + param(\$Uri, \$TimeoutSec, [switch]\$UseBasicParsing) + Add-Content '$HOME/fetched' \"\$Uri|\$TimeoutSec\" + [pscustomobject]@{ Content = \"Milan: \$([char]27)[31mSun\$([char]27)[0m +20C\$([char]7)\$([char]27)]0;title\$([char]7)\`nend\" } + }" + run up_ps "$stub" -n -nc -nt -w + [ "$status" -eq 0 ] + [[ "$output" == *"Milan: Sun +20C end"* ]] + [[ "$output" != *$'\e'* ]] + [[ "$output" != *$'\a'* ]] + [[ "$output" != *title* ]] + [ "$(cat "$HOME/fetched")" = "https://wttr.in/?format=%l:+%c+%t+%w+%m|3" ] + run up_ps "$stub" -ynw -nc -nt + [ "$status" -eq 0 ] + [[ "$output" == *"Milan: Sun +20C end"* ]] + rm -f "$HOME/fetched" + run up_ps "$stub" -n -nc -nt + [ "$status" -eq 0 ] + [ ! -e "$HOME/fetched" ] + run up_ps "function Invoke-WebRequest { throw 'offline' }" -n -nc -nt --weather + [ "$status" -eq 0 ] + [[ "$output" != *offline* ]] +} + +@test "ps: battery percent with two batteries is their average" { + run ps 'function Get-CimInstance { @([pscustomobject]@{ EstimatedChargeRemaining = 10; BatteryStatus = 1 }, + [pscustomobject]@{ EstimatedChargeRemaining = 25; BatteryStatus = 2 }) } + Preflight-Battery-Percent + Preflight-Is-On-Battery + function Get-CimInstance { [pscustomobject]@{ EstimatedChargeRemaining = 42; BatteryStatus = 2 } } + Preflight-Battery-Percent + Preflight-Is-On-Battery' + [ "$status" -eq 0 ] + [ "$output" = $'17\nTrue\n42\nFalse' ] +} + +@test "ps: declining the low-battery prompt aborts with exit 1" { + run up_ps 'function Get-CimInstance { [pscustomobject]@{ EstimatedChargeRemaining = 5; BatteryStatus = 1 } }' -nc -nt &2; exit 1 ;;\n pull) echo pulled >>"%s/trace" ;;\nesac\nexit 0\n' "$HOME" >"$HOME/bin/git" + chmod +x "$HOME/bin/git" + run env PATH="$HOME/bin:$PATH" bash -c "$(declare -f ps); ps \"\$1\"" _ ". (Join-Path \$env:PSLIB 'SelfUpdate.ps1') + \$PSNativeCommandUseErrorActionPreference = \$true + \$rc = SelfUpdate-Run '$HOME/root' + \"rc=\$rc\"" + [ "$status" -eq 0 ] + [[ "$output" == *"git fetch failed"* ]] + [[ "$output" == *"rc=1"* ]] + [[ "$output" != *NativeCommand* ]] + [ ! -e "$HOME/trace" ] +} + +@test "ps: the scheduled task starts the PowerShell host that registered it" { + run ps ". (Join-Path \$env:PSLIB 'AutoUpdate.ps1') + function New-ScheduledTaskAction { param(\$Execute, \$Argument) Set-Content '$HOME/task' \"\$Execute|\$Argument\"; 'action' } + function New-ScheduledTaskTrigger { 'trigger' } + function New-ScheduledTaskSettingsSet { 'settings' } + function New-ScheduledTaskPrincipal { 'principal' } + function Register-ScheduledTask { } + \$rc = AutoUpdate-Register '/opt/e M' + \"rc=\$rc host=\$((Get-Process -Id \$PID).Path)\"" + [ "$status" -eq 0 ] + [[ "$output" == *"rc=0"* ]] + local host="${output##*host=}" + [ "$(cut -d'|' -f1 "$HOME/task")" = "$host" ] + [[ "$(cut -d'|' -f2 "$HOME/task")" == *'-File "/opt/e M'*'emerger.ps1" -y -q -nl -ni' ]] +} diff --git a/tests/quiet_hours.bats b/tests/quiet_hours.bats new file mode 100644 index 0000000..8ab705a --- /dev/null +++ b/tests/quiet_hours.bats @@ -0,0 +1,55 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +# Stub date so `date +%H%M` prints $1, every other call reaching the real date. +stub_clock() { + local real + real=$(PATH=${PATH#"$STUBS:"} command -v date) + stub date "[ \"\$1\" = +%H%M ] && { echo $1; exit 0; }; exec $real \"\$@\"" +} + +@test "quiet hours: the clock comes from date, never from the environment" { + stub_clock 0700 + run env QUIET_HOURS=08:00-18:00 EMERGER_NOW_HHMM=1200 $EMERGER -n -y -nl --only none + [ "$status" -eq 0 ] + [[ "$output" != *"quiet hours"* ]] + [[ "$output" == *"No supported package managers"* ]] +} + +@test "quiet hours: inside the window skips the run, at its end time the run goes on, across midnight too" { + local window clock verdict + while read -r window clock verdict; do + stub_clock "$clock" + run env QUIET_HOURS="$window" $EMERGER -n -y -nl --only none + [ "$status" -eq 0 ] + [[ "$output" != *"value too great"* ]] + [[ "$output" != *"QUIET_HOURS="* ]] + if [[ $verdict == skip ]]; then + [[ "$output" == *"quiet hours, skipping"* ]] + [[ "$output" != *"No supported package managers"* ]] + else + [[ "$output" != *"quiet hours"* ]] + [[ "$output" == *"No supported package managers"* ]] + fi + done <<'ROWS' +08:00-18:00 1200 skip +22:00-07:00 0659 skip +22:00-07:00 0700 run +ROWS +} + +@test "quiet hours: a malformed window warns and the run proceeds" { + run env QUIET_HOURS=soon $EMERGER -n -y -nl --only none + [ "$status" -eq 0 ] + [[ "$output" == *'QUIET_HOURS="soon"'* ]] + [[ "$output" == *"No supported package managers"* ]] +} diff --git a/tests/reboot.bats b/tests/reboot.bats new file mode 100644 index 0000000..008f14e --- /dev/null +++ b/tests/reboot.bats @@ -0,0 +1,64 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +@test "reboot_check: Arch without the linux package returns 0, no reboot" { + stub pacman '[ "$1" = "-Q" ] && exit 1; exit 0' + stub dpkg-query 'exit 1' + run sys_lib 'REBOOT_REQUIRED_FILE=$HOME/none; reboot_check; echo "rc=$? need=$REBOOT_IS_NEEDED"' + [ "$status" -eq 0 ] + [ "$output" = "rc=0 need=0" ] +} + +@test "reboot_check: dnf needs-restarting exit 1 means reboot, other failures unknown" { + stub dnf 'exit 1' + run sys_lib 'REBOOT_REQUIRED_FILE=$HOME/none; reboot_check; echo "need=$REBOOT_IS_NEEDED $REBOOT_REASON"' + [ "$output" = "need=1 dnf needs-restarting" ] + stub dnf 'echo "Unknown argument" >&2; exit 2' + run sys_lib 'REBOOT_REQUIRED_FILE=$HOME/none; reboot_check; echo "need=$REBOOT_IS_NEEDED"' + [ "$status" -eq 0 ] + [ "$output" = "need=0" ] + stub needs-restarting 'exit 3' + run sys_lib 'REBOOT_REQUIRED_FILE=$HOME/none; reboot_check; echo "need=$REBOOT_IS_NEEDED"' + [ "$output" = "need=0" ] +} + +@test "reboot_check: flag file counts its packages" { + touch "$HOME/rr"; printf 'linux\nlibc6\n' >"$HOME/rr.pkgs" + run sys_lib 'REBOOT_REQUIRED_FILE=$HOME/rr; reboot_check; echo "need=$REBOOT_IS_NEEDED $REBOOT_REASON"' + [ "$output" = "need=1 $HOME/rr exists (2 pkg(s))" ] +} + +@test "reboot_now: root runs reboot itself, a user goes through sudo, dry-run only prints" { + stub reboot 'echo "reboot $*" >>"$HOME/calls"' + run sys_lib 'DRY_RUN=0; sys_is_root() { return 0; }; reboot_now; echo after' + [[ "$output" != *after* ]] + [ "$(cat "$HOME/calls")" = "reboot " ] + stub sudo 'echo "sudo $*" >>"$HOME/calls"; exec "$@"' + rm "$HOME/calls" + run sys_lib 'DRY_RUN=0; sys_is_root() { return 1; }; reboot_now' + [ "$(head -n 1 "$HOME/calls")" = "sudo reboot" ] + rm "$HOME/calls" + run sys_lib 'DRY_RUN=1; REBOOT_REASON=why; sys_is_root() { return 0; }; reboot_now; echo "rc=$?"' + [[ "$output" == *"would reboot: reboot (why)"* ]] + [[ "$output" == *"rc=0"* ]] + run sys_lib 'DRY_RUN=1; REBOOT_REASON=why; sys_is_root() { return 1; }; reboot_now' + [[ "$output" == *"would reboot: sudo reboot (why)"* ]] + [ ! -e "$HOME/calls" ] +} + +@test "reboot advisory: names reboot without sudo as root" { + run sys_lib 'REBOOT_IS_NEEDED=1; REBOOT_REASON=x; sys_is_root() { return 0; }; reboot_advisory' + [[ "$output" == *"run reboot or up --reboot"* ]] + run sys_lib 'REBOOT_IS_NEEDED=1; REBOOT_REASON=x; sys_is_root() { return 1; }; reboot_advisory' + [[ "$output" == *"run sudo reboot or up --reboot"* ]] +} diff --git a/tests/resume.bats b/tests/resume.bats new file mode 100644 index 0000000..b526b7a --- /dev/null +++ b/tests/resume.bats @@ -0,0 +1,26 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +@test "resume: a manager that failed in the last run is not skipped" { + plugin pa '[ ! -e "$HOME/fail-pa" ]' + plugin pb '[ ! -e "$HOME/fail-pb" ]' + touch "$HOME/fail-pa" + run $EMERGER -y -nl -nc -nt --only pa,pb + [ "$status" -eq 3 ] + rm "$HOME/fail-pa"; touch "$HOME/fail-pb" + run $EMERGER -y -nl -nc -nt --only pa,pb + [ "$status" -eq 3 ] + rm "$HOME/fail-pb" "$HOME/ran" + run $EMERGER -y -nl -nc -nt --only pa,pb --resume + [ "$status" -eq 0 ] + [ "$(cat "$HOME/ran")" = "pb" ] +} diff --git a/tests/run_cmd.bats b/tests/run_cmd.bats new file mode 100644 index 0000000..01e517f --- /dev/null +++ b/tests/run_cmd.bats @@ -0,0 +1,113 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +@test "run_cmd: an unwritable TMPDIR fails with the reason" { + run lib 'TMPDIR=$HOME/missing run_cmd step true; echo "rc=$?"' + [[ "$output" == *"cannot create a temp file"* ]] + [[ "$output" == *"rc=1" ]] +} + +@test "MANAGER_TIMEOUT without timeout: warns once that no limit applies" { + mkdir -p "$HOME/bin" + local c + for c in mktemp cat rm sed tr tail; do ln -s "$(command -v "$c")" "$HOME/bin/$c"; done + run lib 'PATH=$HOME/bin; MANAGER_TIMEOUT=5; run_cmd a cat /dev/null; run_cmd b cat /dev/null' + [ "$(grep -c 'MANAGER_TIMEOUT' <<<"$output")" -eq 1 ] + [[ "$output" == *"not applied"* ]] +} + +@test "run_cmd temp: attack capture left after an interrupt, expected removed by cleanup" { + mkdir -p "$HOME/tmp" + run lib "export TMPDIR=$HOME/tmp; DRY_RUN=0 + trap 'run_cmd_cleanup; exit 143' TERM + run_cmd x bash -c 'echo secret; kill -TERM \$PPID; sleep 0.2'" + [ "$status" -eq 143 ] + [ -z "$(ls -A "$HOME/tmp")" ] +} + +@test "MANAGER_TIMEOUT: attack stalled command, expected stopped with rc 124" { + command -v timeout >/dev/null || skip "timeout not available" + run lib "DRY_RUN=0; MANAGER_TIMEOUT=1; SECONDS=0; run_cmd stall sleep 20; echo rc=\$? t=\$SECONDS" + [[ "$output" == *"timed out after 1s"* ]] + [[ "$output" =~ rc=124\ t=[12]$ ]] +} + +@test "MANAGER_TIMEOUT: 0 means no limit and shell functions still run" { + run lib "DRY_RUN=0; MANAGER_TIMEOUT=0; run_cmd ok sleep 1; echo rc=\$? + f() { return 0; }; MANAGER_TIMEOUT=5; run_cmd fn f; echo rc=\$?" + [[ "$output" == *"rc=0"*"rc=0"* ]] + [[ "$output" != *"rc=1"* ]] +} + +@test "run_cmd failure tail: attack OSC in manager output, expected stripped" { + run lib "DRY_RUN=0; RETRY_ATTEMPTS=1; run_cmd x sh -c 'printf \"\\033]52;c;SGVsbG8=\\007boom\\n\"; exit 1'" + [[ "$output" == *"boom"* ]] + [[ "$output" != *"]52"* ]] +} + +@test "run_cmd failure log: attack escapes and a forged ERROR line in manager output, expected neither in the log" { + run lib "DRY_RUN=0; RETRY_ATTEMPTS=1; log_init + run_cmd x sh -c 'printf \"boom\\033]52;c;SGVsbG8=\\007\\n2026-01-01T00:00:00Z|ERROR|forged\\n\"; exit 1' >/dev/null 2>&1 + echo \"esc=\$(grep -c \$'\\033' \"\$EMERGER_LOG\") errors=\$(grep -c '|ERROR|' \"\$EMERGER_LOG\")\"" + [[ "$output" == *"esc=0 errors=2"* ]] +} + +@test "run_cmd: a transient failure retries up to RETRY_ATTEMPTS, sleeping RETRY_DELAY" { + run lib 'RETRY_ATTEMPTS=2; RETRY_DELAY=1; QUIET_LEVEL=0 + sleep() { echo "$1" >>"$HOME/sleeps"; } + run_cmd "flaky" bash -c "echo Temporary failure resolving host; exit 100"; rc=$? + echo "rc=$rc sleeps=$(paste -sd, "$HOME/sleeps")"' + [[ "$output" == *"retrying (1/2)"* ]] + [[ "$output" == *"rc=100 sleeps=1" ]] +} + +@test "run_sanitize: attack C1 CSI and OSC introducers (UTF-8 C2 9B, C2 9D), expected stripped and text kept" { + run lib 'printf "a\xc2\x9d0;title\xc2\x9cb\xc2\x9b31mc caf\xc3\xa9\xc2\xa0z\n" | run_sanitize >"$HOME/out" + echo "c1=$(LC_ALL=C grep -c $'"'"'\xc2[\x80-\x9f]'"'"' "$HOME/out")"; cat "$HOME/out"' + [ "${lines[0]}" = "c1=0" ] + [ "${lines[1]}" = $'a0;titleb31mc caf\xc3\xa9\xc2\xa0z' ] +} + +@test "run_sanitize: attack C1 introducers split by another C1 pair or a control byte, expected none reassembled" { + run lib 'printf "a\xc2\xc2\x9b\x9bb\xc2\x01\x9bc\n" | run_sanitize | od -An -tx1 | tr -d " \n"' + [ "$output" = "6162630a" ] + [[ "$output" != *c2* ]] + [[ "$output" != *9b* ]] +} + +@test "run_sanitize: attack one long line of nested C1 pairs, expected stripped in one linear pass" { + # 100k nested pairs: a rescanning loop needs 100k passes over 200 KB. The + # timeout only bounds a hang; the assertion is the output. + run lib '{ printf a; head -c 100000 /dev/zero | tr "\\0" "\\302"; head -c 100000 /dev/zero | tr "\\0" "\\233"; printf "z\\n"; } >"$HOME/in" + timeout 20 bash -c "source \"\$LIB/load.sh\" all >/dev/null 2>&1; run_sanitize <\"\$HOME/in\"" | od -An -tx1 | tr -d " \n"' + [ "$output" = "617a0a" ] +} + +@test "run_sanitize: without iconv, expected C1 bytes dropped and ASCII text kept" { + run lib 'iconv() { return 127; }; command() { [[ $2 == iconv ]] && return 1; builtin command "$@"; } + printf "ab\xc2\x9bcd\xc2\xc2\x9b\x9be\n" | run_sanitize | od -An -v -tx1 | tr -s " \n" "\n" | grep .' + # One byte per line. Lone 0xC2 bytes may stay: no encoding reads them as a control. + [ "$(printf "%s\n" "${lines[@]}" | grep -v "^c2$" | tr -d "\n")" = "61626364650a" ] + ! printf "%s\n" "${lines[@]}" | grep -q "^[89][0-9a-f]$" || false +} + +@test "run_sanitize: attack a valid UTF-8 character holding 0x9B under a non-UTF-8 terminal, expected no byte above 0x7F" { + run lib 'UI_HAS_UNICODE=0; printf "x\xc3\x9b31m caf\xc3\xa9\n" | run_sanitize' + [ "$output" = "x31m caf" ] + run lib 'UI_HAS_UNICODE=1; printf "caf\xc3\xa9\n" | run_sanitize' + [ "$output" = "cafรฉ" ] +} + +@test "run_sanitize log mode: valid UTF-8 kept for the log file even under a non-UTF-8 terminal" { + run lib 'UI_HAS_UNICODE=0; printf "caf\xc3\xa9 \xc2\x9bfail\n" | run_sanitize log' + [ "$output" = "cafรฉ fail" ] +} diff --git a/tests/security_only.bats b/tests/security_only.bats new file mode 100644 index 0000000..32bd27b --- /dev/null +++ b/tests/security_only.bats @@ -0,0 +1,39 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +@test "--security: apt without unattended-upgrades is skipped and names the package to install" { + # A PATH of every system command except unattended-upgrade. + mkdir -p "$HOME/sysbin" + local f + for f in /usr/bin/* /bin/*; do + [ -d "$f" ] || [ "${f##*/}" = unattended-upgrade ] || ln -sf "$f" "$HOME/sysbin/${f##*/}" + done + stub apt 'exit 0' + run env PATH="$STUBS:$HOME/sysbin" EMERGER_CACHE_TTL=0 $EMERGER -n -y -nl -nc -nt --security --only apt + [ "$status" -eq 0 ] + [[ "$output" == *"skip apt: no security-only updates"* ]] + [[ "$output" == *"install the unattended-upgrades package to get security-only updates with apt"* ]] +} + +@test "--security: attack full upgrade on a manager without a security channel, expected skipped" { + stub pacman 'exit 0' + run env PATH="$STUBS:$PATH" EMERGER_CACHE_TTL=0 $EMERGER -n -y -nl -nc -nt --security --only pacman + [ "$status" -eq 0 ] + [[ "$output" == *"pacman"*"no security"* ]] + [[ "$output" != *"pacman -Syu"* ]] +} + +@test "--security: managers with a security channel keep it" { + run lib "source $LIB/load.sh registry detect icon recipes; sys_has() { [[ \$1 == dnf || \$1 == zypper ]]; } + for m in dnf zypper yum apt pacman flatpak; do pkg_has_security \$m && echo \$m; done" + [ "$output" = "$(printf 'dnf\nzypper\nyum')" ] +} diff --git a/tests/snapshot.bats b/tests/snapshot.bats new file mode 100644 index 0000000..f81f6ed --- /dev/null +++ b/tests/snapshot.bats @@ -0,0 +1,96 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +@test "--snapshot: snapper failing aborts with exit 1 and names snapper" { + stub snapper 'case "$1" in list-configs) echo "root | /";; *) echo "snapper: quota error" >&2; exit 3;; esac' + stub sudo 'if [ "$1" = snapper ]; then shift; exec snapper "$@"; fi; echo "sudo $*" >>"$HOME/sudo.log"; exit 1' + plugin pa '' + run $EMERGER -y -nl -nc -nt --snapshot --only pa + [ "$status" -eq 1 ] + [[ "$output" == *"snapper"*"exit 3"* ]] + [[ "$output" == *"No snapshot taken"* ]] + [[ "$output" != *"No snapshot tool available"* ]] + [ ! -e "$HOME/ran" ] +} + +@test "--snapshot: no snapshot tool aborts with exit 1 before any manager" { + plugin pa '' + run env PATH="$STUBS:/usr/bin:/bin" $EMERGER -y -nl -nc -nt --snapshot --only pa + [ "$status" -eq 1 ] + [[ "$output" == *"No snapshot tool available"* ]] + [[ "$output" == *"No snapshot taken"* ]] + [[ "$output" != *"continuing without"* ]] + [ ! -e "$HOME/ran" ] +} + +@test "rollback: snapper number column is used, not the type" { + stub snapper 'case "$*" in + list-configs) echo "root | /" ;; + "-c root list") printf " # | Type | Pre # | Date | User | Cleanup | Description | Userdata\n---+--------+-------+------+------+---------+------------------------+---------\n0 | single | | | root | | current |\n7 | single | | now | root | number | eMerger pre-update x |\n12-| single | | now | root | number | eMerger pre-update y |\n" ;; +esac' + run sys_lib 'DRY_RUN=1; snapshot_rollback' + [ "$status" -eq 0 ] + [[ "$output" == *"snapper -c root rollback 12"* ]] +} + +@test "rollback: snapper box-drawing table yields the latest eMerger snapshot number" { + stub snapper 'case "$*" in + list-configs) echo "root โ”‚ /" ;; + "-c root list") printf " # โ”‚ Type โ”‚ Description\n 9 โ”‚ single โ”‚ eMerger pre-update z\n" ;; +esac' + run sys_lib 'DRY_RUN=1; snapshot_rollback' + [[ "$output" == *"snapper -c root rollback 9"* ]] +} + +@test "snapshot: snapper and timeshift run without sudo as root, through sudo as a user" { + stub snapper 'case "$1" in list-configs) echo "root | /" ;; *) echo "snapper $*" >>"$HOME/calls"; exit 1 ;; esac' + stub timeshift 'echo "timeshift $*" >>"$HOME/calls"' + run sys_lib 'sys_is_root() { return 0; }; snapshot_create' + [ "$status" -eq 0 ] + [[ "$output" == *"timeshift snapshot created"* ]] + grep -q '^snapper -c root create ' "$HOME/calls" + grep -q '^timeshift --create ' "$HOME/calls" + stub sudo 'echo "sudo $*" >>"$HOME/calls"; exec "$@"' + rm "$HOME/calls" + run sys_lib 'sys_is_root() { return 1; }; snapshot_create' + [ "$status" -eq 0 ] + grep -q '^sudo snapper -c root create ' "$HOME/calls" + grep -q '^sudo timeshift --create ' "$HOME/calls" +} + +@test "rollback: snapper rollback and timeshift restore run without sudo as root" { + stub snapper 'case "$*" in + list-configs) echo "root | /" ;; + "-c root list") printf " # | Type | Description\n7 | single | eMerger pre-update x\n" ;; + *) echo "snapper $*" >>"$HOME/calls" ;; +esac' + run sys_lib 'DRY_RUN=0; sys_is_root() { return 0; }; snapshot_rollback' + [ "$status" -eq 0 ] + [[ "$output" == *"Rollback queued"* ]] + [ "$(cat "$HOME/calls")" = "snapper -c root rollback 7" ] + rm "$STUBS/snapper" "$HOME/calls" + stub timeshift 'echo "timeshift $*" >>"$HOME/calls"' + run sys_lib 'DRY_RUN=0; sys_is_root() { return 0; }; snapshot_rollback' + [ "$status" -eq 0 ] + [ "$(cat "$HOME/calls")" = "timeshift --restore" ] +} + +@test "rollback: long snapper list-configs output does not hide the root config" { + stub snapper 'case "$*" in + list-configs) awk "BEGIN { print \"root | /\"; for (i = 0; i < 400000; i++) print \"other | /x\" }" ;; + "-c root list") printf " # | Type | Description\n5 | single | eMerger pre-update x\n" ;; +esac' + run sys_lib 'DRY_RUN=1; snapshot_rollback' + [ "$status" -eq 0 ] + [[ "$output" == *"snapper -c root rollback 5"* ]] +} diff --git a/tests/sudo.bats b/tests/sudo.bats new file mode 100644 index 0000000..b593632 --- /dev/null +++ b/tests/sudo.bats @@ -0,0 +1,79 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +@test "sudo keepalive: does not hold stdout open after the run" { + stub sudo 'exit 0' + SECONDS=0 + run timeout 20 bash -c "lib_out=\$(bash -c 'source \"$LIB/load.sh\" ui log sys run; run_sudo_keepalive; echo started'); echo \"\$lib_out\"" + [ "$status" -eq 0 ] + [ "$output" = "started" ] + [ "$SECONDS" -lt 10 ] +} + +@test "sudo keepalive: TERM stops its sleep too" { + stub sudo 'exit 0' + # Follow this keepalive's own sleep by PID: other runs on the machine may sleep too. + run lib 'run_sudo_keepalive 737; sleep 0.5 + child=$(pgrep -P "$SUDO_KEEPALIVE_PID" -x sleep) + kill -TERM "$SUDO_KEEPALIVE_PID"; sleep 0.5 + [[ -n $child ]] && ! kill -0 "$child" 2>/dev/null && echo stopped' + [ "$output" = "stopped" ] +} + +@test "sudo keepalive: exits once its parent is killed" { + stub sudo 'exit 0' + bash -c 'source "$LIB/load.sh" ui log sys run + run_sudo_keepalive 1; echo "$SUDO_KEEPALIVE_PID" >"$HOME/k.pid"; sleep 30' >/dev/null 2>&1 & + local parent=$! + sleep 1 + kill -9 "$parent" + sleep 3 + local k; k=$(cat "$HOME/k.pid") + run kill -0 "$k" + kill "$k" 2>/dev/null || true + [ "$status" -ne 0 ] +} + +@test "sudo check: --no-firmware leaves fwupd out" { + stub fwupdmgr 'exit 0' + run lib 'ARG_FIRMWARE=1; ARG_NO_FIRMWARE=1; ARG_ONLY=fwupd + if run_needs_sudo; then echo sudo; else echo none; fi' + [ "$output" = "none" ] +} + +@test "sudo check: --resume leaves completed managers out" { + stub apt 'exit 0' + run lib 'ARG_RESUME=1; ARG_ONLY=apt; RESUME_DONE=(apt) + if run_needs_sudo; then echo sudo; else echo none; fi' + [ "$output" = "none" ] + run lib 'ARG_ONLY=apt; RESUME_DONE=() + if run_needs_sudo; then echo sudo; else echo none; fi' + [ "$output" = "sudo" ] +} + +@test "pkg_run: sudo prefix only when not root" { + stub apt 'exit 0' + run lib 'DRY_RUN=1; PATH=$STUBS:/usr/bin:/bin; sys_is_root() { return 0; }; pkg_run apt 2>&1' + [[ "$output" == *"[dry-run] apt"* ]] + [[ "$output" != *"sudo"* ]] + run lib 'DRY_RUN=1; PATH=$STUBS:/usr/bin:/bin; sys_is_root() { return 1; }; pkg_run apt 2>&1' + [[ "$output" == *"[dry-run] sudo apt"* ]] +} + +@test "privilege prefix: empty as root, sudo otherwise" { + run sys_lib 'sys_is_root() { return 0; }; echo "root=[$(sys_sudo_prefix)]" + sys_is_root() { return 1; }; echo "user=[$(sys_sudo_prefix)]"' + [ "$status" -eq 0 ] + [ "${lines[0]}" = "root=[]" ] + [ "${lines[1]}" = "user=[sudo]" ] +} diff --git a/tests/summary.bats b/tests/summary.bats new file mode 100644 index 0000000..a058545 --- /dev/null +++ b/tests/summary.bats @@ -0,0 +1,31 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +@test "summary: -qqq --reboot-exit with a reboot pending exits 4" { + stub needs-restarting 'exit 1' + run $EMERGER -n -y -qqq --reboot-exit --only none + [ "$status" -eq 4 ] + [[ "$output" != *"Reboot recommended"* ]] +} + +@test "summary: -qq history line records the pending reboot" { + stub needs-restarting 'exit 1' + run $EMERGER -y -qq -nl -nc -nt --only none + [ "$status" -eq 0 ] + [[ "$(tail -n 1 "$EMERGER_STATE/history.jsonl")" == *'"reboot":1'* ]] +} + +@test "summary: -qqq still appends the history line" { + run $EMERGER -y -qqq -nl -nc -nt --only none + [ "$status" -eq 0 ] + [ "$(wc -l <"$EMERGER_STATE/history.jsonl")" -eq 1 ] +} diff --git a/tests/test_helper.bash b/tests/test_helper.bash new file mode 100644 index 0000000..6fdab1b --- /dev/null +++ b/tests/test_helper.bash @@ -0,0 +1,117 @@ +# Shared fixture of the bash test files: `load test_helper` from a file's top. + +# Point HOME at a fresh temp directory, the old value kept in HOME_BAK, and +# export REPO_DIR, LIB, EMERGER (the entry point command), NO_COLOR and an +# empty stub directory STUBS. +setup_home() { + export REPO_DIR="${BATS_TEST_DIRNAME}/.." + export LIB="$REPO_DIR/src/lib" + export EMERGER="bash $REPO_DIR/src/emerger.sh" + export HOME_BAK="$HOME" + export HOME="$(mktemp -d)" + export NO_COLOR=1 + export STUBS="$HOME/stubs" + mkdir -p "$STUBS" +} + +# Export the XDG cache, config, state and runtime directories under HOME and +# create them, with an empty eMerger config directory. +setup_xdg() { + export XDG_CACHE_HOME="$HOME/.cache" + export XDG_CONFIG_HOME="$HOME/.config" + export XDG_STATE_HOME="$HOME/.local/state" + export XDG_RUNTIME_DIR="$HOME/run" + mkdir -p "$XDG_CACHE_HOME" "$XDG_CONFIG_HOME" "$XDG_STATE_HOME" "$XDG_RUNTIME_DIR" + mkdir -p "$XDG_CONFIG_HOME/emerger" +} + +# Remove the temp HOME and restore the one setup_home saved. +teardown_home() { + rm -rf "$HOME" + export HOME="$HOME_BAK" +} + +# Write executable stub $1 into $STUBS, running shell code $2. +stub() { + printf '#!/bin/sh\n%s\n' "$2" >"$STUBS/$1" + chmod +x "$STUBS/$1" +} + +# Set up the full fixture of the feature files: setup_home and setup_xdg, EMERGER_STATE, +# the detection cache directory and an empty TMPDIR under HOME, no display or +# QUIET_HOURS, stubs first on PATH, and ibus (logging to $HOME/ibus.log) and +# notify-send stubbed so a real run never reaches the host's. +setup_env() { + setup_home + setup_xdg + export EMERGER_STATE="$XDG_STATE_HOME/emerger" + export TMPDIR="$HOME/tmp" + unset DISPLAY WAYLAND_DISPLAY QUIET_HOURS + mkdir -p "$TMPDIR" "$XDG_CACHE_HOME/emerger" + stub ibus 'echo "ibus $*" >>"$HOME/ibus.log"' + stub notify-send 'exit 0' + export PATH="$STUBS:$PATH" +} + +# Stop every background helper whose PID a test left in $HOME/*.pid, then +# teardown_home. +teardown_env() { + local p + for p in "$HOME"/*.pid; do + [[ -f $p ]] && kill "$(cat "$p")" 2>/dev/null + done + teardown_home +} + +# Create $MINBIN holding links to the basic host tools only, so no host +# package manager answers a probe made through sys_lib. +setup_minbin() { + export MINBIN="$HOME/minbin" + mkdir -p "$MINBIN" + local t p + for t in bash sh awk cat cut date df du find grep head mkdir mktemp numfmt \ + paste rm sed sleep sort stat tail timeout touch tr uname wc id comm join env mv; do + p=$(command -v "$t") && ln -s "$p" "$MINBIN/$t" + done +} + +# Run snippet $1 in a fresh bash with the run's libs sourced and the state, +# log and config paths under HOME. +lib() { + bash -c 'set -uo pipefail; printf -v IFS "\n\t" + EMERGER_STATE=$HOME/.local/state/emerger; EMERGER_LOG=$EMERGER_STATE/log + EMERGER_CONFIG=$HOME/.config/emerger + mkdir -p "$EMERGER_STATE" + source "$LIB/load.sh" ui knobs log sys progress estimate run args ignore registry detect icon \ + recipes clean rpi rpi_eeprom trust hooks plugins selfupdate autoupdate history lock \ + resume preflight reboot diff summary + '"$1" +} + +# Run snippet $1 under the entry point's shell options with the libs sourced, +# PATH limited to the stubs and $MINBIN (see setup_minbin). +sys_lib() { + PATH="$STUBS:$MINBIN" "$MINBIN/bash" -c 'set -Eeuo pipefail; printf -v IFS "\n\t" + EMERGER_STATE=$HOME/.local/state/emerger; EMERGER_LOG=$EMERGER_STATE/log + EMERGER_CACHE=$HOME/.cache/emerger; EMERGER_CONFIG=$HOME/.config/emerger + mkdir -p "$EMERGER_STATE" "$EMERGER_CACHE" + DRY_RUN=0; ARG_YES=0; QUIET_LEVEL=0; SUMMARY_FREED_KB=0 + source "$LIB/load.sh" ui log sys progress estimate run ignore registry detect icon recipes clean rpi rpi_eeprom preflight reboot \ + snapshot diff changelog doctor notify + '"$1" +} + +# Write plugin $1 into the user's managers.d: its run appends its name to +# $HOME/ran, then runs shell code $2. Extra function definitions go in $3. +plugin() { + mkdir -p "$XDG_CONFIG_HOME/emerger/managers.d" + cat >"$XDG_CONFIG_HOME/emerger/managers.d/$1.sh" <>"\$HOME/ran" + $2 +} +$3 +EOF +} diff --git a/tests/trust.bats b/tests/trust.bats new file mode 100644 index 0000000..d9d458d --- /dev/null +++ b/tests/trust.bats @@ -0,0 +1,128 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +# Run trust_file on a dummy file with stat reporting "$1" and id reporting +# group $2 (gid) named $3 for a user named $4. +trust_with() { + stub stat "echo '$1'" + stub id "case \$1 in -g) echo $2 ;; -gn) echo $3 ;; -un) echo $4 ;; *) echo 0 ;; esac" + touch "$HOME/f" + lib "PATH=$STUBS:\$PATH; trust_file $HOME/f; echo rc=\$?" +} + +@test "state files: attack other users read the log, expected 0700 dir and 0600 log" { + run bash -c "umask 022; $EMERGER -n -y -nl -nc -nt --only none" + [ "$status" -eq 0 ] + [ "$(stat -c %a "$XDG_STATE_HOME/emerger")" = "700" ] + [ "$(stat -c %a "$XDG_CACHE_HOME/emerger")" = "700" ] + [ "$(stat -c %a "$XDG_STATE_HOME/emerger/emerger.log")" = "600" ] +} + +@test "config trust: attack group-writable config.sh, expected refused" { + printf 'touch "$HOME/M"\n' >"$XDG_CONFIG_HOME/emerger/config.sh" + chmod 666 "$XDG_CONFIG_HOME/emerger/config.sh" + run $EMERGER -n -y -nl -nc -nt --only none + [ "$status" -eq 1 ] + [[ "$output" == *"config.sh"*"writable"* ]] + [ ! -e "$HOME/M" ] +} + +@test "trust_file: accepts own files and private-group write, refuses other owners, group or other write and unreadable modes" { + local me; me=$(id -u) + run trust_with "$me 500 644" 500 alice alice + [ "${lines[-1]}" = "rc=0" ] + run trust_with "$me 500 664" 500 alice alice + [ "${lines[-1]}" = "rc=0" ] + run trust_with "$me 27 664" 500 alice alice + [ "${lines[-1]}" = "rc=1" ] + [[ "$output" == *"writable by group"* ]] + run trust_with "$me 500 664" 500 staff alice + [ "${lines[-1]}" = "rc=1" ] + run trust_with "$me 500 646" 500 alice alice + [ "${lines[-1]}" = "rc=1" ] + run trust_with "4242 500 600" 500 alice alice + [ "${lines[-1]}" = "rc=1" ] + [[ "$output" == *"not owned by you"* ]] + run trust_with "garbage" 500 alice alice + [ "${lines[-1]}" = "rc=1" ] +} + +@test "profile trust: attack profile owned by another user, expected refused" { + [ "$(stat -L -c %u /etc/os-release)" != "$(id -u)" ] || skip "running as the owner of /etc/os-release" + mkdir -p "$XDG_CONFIG_HOME/emerger/profiles.d" + ln -s /etc/os-release "$XDG_CONFIG_HOME/emerger/profiles.d/evil.sh" + run $EMERGER -n -y -nl -nc -nt --only none --profile evil + [ "$status" -eq 2 ] + [[ "$output" == *"evil.sh"*"not owned"* ]] +} + +@test "plugin and hook trust: attack group-writable files, expected skipped" { + mkdir -p "$XDG_CONFIG_HOME/emerger/hooks/post.d" "$XDG_CONFIG_HOME/emerger/managers.d" + printf 'touch "$HOME/hook"\n' >"$XDG_CONFIG_HOME/emerger/hooks/post.d/h.sh" + printf 'touch "$HOME/plugin"\nPM_PLUGIN_SLUG=z\n' >"$XDG_CONFIG_HOME/emerger/managers.d/z.sh" + chmod 666 "$XDG_CONFIG_HOME/emerger/hooks/post.d/h.sh" "$XDG_CONFIG_HOME/emerger/managers.d/z.sh" + run env PATH="$STUBS:$PATH" $EMERGER -y -nl -nc -nt --only none + [ "$status" -eq 0 ] + [[ "$output" == *"h.sh"*"writable"* ]] + [[ "$output" == *"z.sh"*"writable"* ]] + [ ! -e "$HOME/hook" ] + [ ! -e "$HOME/plugin" ] +} + +@test "hook trust: attack a hooks directory writable by others, expected skipped" { + mkdir -p "$XDG_CONFIG_HOME/emerger/hooks/post.d" + printf 'touch "$HOME/hook"\n' >"$XDG_CONFIG_HOME/emerger/hooks/post.d/h.sh" + chmod 644 "$XDG_CONFIG_HOME/emerger/hooks/post.d/h.sh" + chmod 757 "$XDG_CONFIG_HOME/emerger/hooks/post.d" + run env PATH="$STUBS:$PATH" $EMERGER -y -nl -nc -nt --only none + [ "$status" -eq 0 ] + [[ "$output" == *"post.d"*"writable"* ]] + [ ! -e "$HOME/hook" ] +} + +@test "root trust: attack sudo -E with a user HOME, expected refused" { + [ "$(id -u)" -eq 0 ] || skip "needs uid 0 (run under unshare -r)" + [ "$(stat -c %u /)" != 0 ] || skip "no directory owned by another uid" + run env HOME=/ $EMERGER -n -y -nl -nc -nt --only none + [ "$status" -eq 1 ] + [[ "$output" == *"HOME"* ]] +} + +@test "checkout: attack a library file writable by other, expected refusal before any module loads" { + mkdir -p "$HOME/co" + cp -r "$REPO_DIR/src" "$REPO_DIR/VERSION" "$HOME/co/" + chmod -R go-w "$HOME/co" + run env PATH="$STUBS:$PATH" bash "$HOME/co/src/emerger.sh" -V + [ "$status" -eq 0 ] + chmod o+w "$HOME/co/src/lib/log.sh" + run env PATH="$STUBS:$PATH" bash "$HOME/co/src/emerger.sh" -V + [ "$status" -eq 1 ] + [[ "$output" == *"log.sh is writable by group or other"* ]] + chmod o-w "$HOME/co/src/lib/log.sh" + chmod o+w "$HOME/co/src/lib" + run env PATH="$STUBS:$PATH" bash "$HOME/co/src/emerger.sh" -V + [ "$status" -eq 1 ] +} + +@test "checkout: attack a group-writable file when the user has no private group, expected refusal" { + mkdir -p "$HOME/co" + cp -r "$REPO_DIR/src" "$REPO_DIR/VERSION" "$HOME/co/" + chmod -R go-w "$HOME/co" + chmod g+w "$HOME/co/src/lib/log.sh" + # The group is the caller's own: accepted only while the group is private to the user. + run env PATH="$STUBS:$PATH" bash "$HOME/co/src/emerger.sh" -V + [ "$status" -eq 0 ] + stub id 'case "$1" in -gn) echo shared;; -un) echo me;; *) exec /usr/bin/id "$@";; esac' + run env PATH="$STUBS:$PATH" bash "$HOME/co/src/emerger.sh" -V + [ "$status" -eq 1 ] + [[ "$output" == *"log.sh is writable by group or other"* ]] +} diff --git a/tests/ui.bats b/tests/ui.bats new file mode 100644 index 0000000..5f80fa5 --- /dev/null +++ b/tests/ui.bats @@ -0,0 +1,58 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env +} + +teardown() { + teardown_env +} + +@test "ui_confirm without a tty uses the default" { + command -v setsid >/dev/null || skip "setsid not available" + run setsid -w bash -c "source '$LIB/load.sh' ui; ui_confirm 'Q?' n; echo rc=\$?" /dev/null || skip "script not available" + run bash -c "sleep 3 | script -qfec \"EMERGER_PROMPT_TIMEOUT=1 bash -c 'source $LIB/load.sh ui; ui_confirm Question n; echo rc=\\\$?'\" /dev/null" + [[ "$output" == *"no answer after 1s"* ]] + [[ "$output" == *"rc=1"* ]] +} + +@test "ui_confirm says yes with -y" { + run lib 'ARG_YES=1; ui_confirm "Q?" n; echo rc=$?' + [ "$output" = "rc=0" ] +} + +@test "EMERGER_EMOJI=0 gives symbols, 1 gives emoji" { + run lib 'LANG=C.UTF-8; EMERGER_EMOJI=0; ui_reinit; source "$LIB/load.sh" registry detect icon recipes; pkg_icon apt' + [ "$output" = "โ—†" ] + run lib 'LANG=C.UTF-8; EMERGER_EMOJI=1; ui_reinit; source "$LIB/load.sh" registry detect icon recipes; pkg_icon flatpak' + [ "$output" = "๐Ÿ“ฆ" ] +} + +@test "non-UTF-8 locale falls back to ASCII" { + run lib 'LANG=C LC_ALL=C; ui_reinit; ui_glyph check; ui_glyph hline' + [ "$output" = "[OK]-" ] +} + +@test "progress bar is 10 columns wide" { + run lib 'LANG=C.UTF-8; ui_reinit; for p in 0 7 55 99 100 140; do ui_bar $p; _ui_strip "$_UI_BAR"; printf "%s " "${#_UI_STRIPPED}"; done' + [ "$output" = "10 10 10 10 10 10 " ] + run lib 'LANG=C LC_ALL=C; ui_reinit; ui_bar 50; echo "$_UI_BAR"' + [ "$output" = "#####-----" ] +} + +@test "ui_highlight: adds no escape codes when colours are off, colours error words when on" { + run bash -c "NO_COLOR=1; source '$LIB/load.sh' ui; printf 'E: boom\nWARNING x\nerror y\n' | ui_highlight" + [ "$status" -eq 0 ] + [ "$output" = "$(printf 'E: boom\nWARNING x\nerror y')" ] + run bash -c "unset NO_COLOR; source '$LIB/load.sh' ui; C_RED=r; C_YELLOW=y; printf 'error y\n' | ui_highlight" + [[ "$output" == *$'\033[31merror'* ]] +} diff --git a/tests/uninstall.bats b/tests/uninstall.bats new file mode 100644 index 0000000..e6c2f85 --- /dev/null +++ b/tests/uninstall.bats @@ -0,0 +1,114 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_home + export XDG_CONFIG_HOME="$HOME/.config" + export SHELL=/bin/bash + # crontab backed by a file; systemctl records its calls. + cat >"$STUBS/crontab" <<'EOS' +#!/bin/bash +if [[ $1 == -l ]]; then [[ -s $HOME/crontab ]] && cat "$HOME/crontab"; exit 0; fi +[[ $1 == - ]] && cat >"$HOME/crontab" +EOS + cat >"$STUBS/systemctl" <<'EOS' +#!/bin/bash +echo "systemctl $*" >>"$HOME/systemctl.log" +[[ $* == *list-unit-files* ]] && ls "$HOME/.config/systemd/user" 2>/dev/null +exit 0 +EOS + chmod +x "$STUBS/crontab" "$STUBS/systemctl" + export PATH="$STUBS:$PATH" +} + +teardown() { + teardown_home +} + +@test "uninstall: removes the only crontab line and still removes the timer" { + echo '0 10 * * 0 bash "/x/src/emerger.sh" -y -q -nl -ni' >"$HOME/crontab" + mkdir -p "$HOME/.config/systemd/user" + touch "$HOME/.config/systemd/user/emerger.service" "$HOME/.config/systemd/user/emerger.timer" + touch "$HOME/.bashrc" + run bash "$REPO_DIR/uninstall.sh" + [ "$status" -eq 0 ] + [ ! -s "$HOME/crontab" ] + [ ! -e "$HOME/.config/systemd/user/emerger.timer" ] +} + +@test "uninstall: removes exactly what install.sh wrote and keeps the user's lines" { + printf 'export EDITOR=vim\n# eMerger notes I wrote myself\nalias ll="ls -l"\n' >"$HOME/.bashrc" + run env PATH="$STUBS:/usr/bin:/bin" bash "$REPO_DIR/install.sh" + [ "$status" -eq 0 ] + grep -q emerger.sh "$HOME/.bashrc" + [ -e "$HOME/.local/share/bash-completion/completions/up" ] + run bash "$REPO_DIR/uninstall.sh" + [ "$status" -eq 0 ] + ! grep -q emerger.sh "$HOME/.bashrc" || false + grep -qx '# eMerger notes I wrote myself' "$HOME/.bashrc" + grep -qx 'export EDITOR=vim' "$HOME/.bashrc" + [ ! -e "$HOME/.local/share/bash-completion/completions/up" ] + [ ! -e "$HOME/.zsh/completions/_up" ] + [ ! -e "$HOME/.config/fish/completions/up.fish" ] +} + +@test "uninstall: attack unreadable crontab, expected no rewrite of it" { + cat >"$STUBS/crontab" <<'EOS' +#!/bin/bash +if [[ $1 == -l ]]; then echo "crontab: temporary read failure" >&2; exit 1; fi +cat >"$HOME/crontab-written" +EOS + touch "$HOME/.bashrc" + run bash "$REPO_DIR/uninstall.sh" + [ ! -e "$HOME/crontab-written" ] +} + +@test "uninstall: cron removal keeps unrelated lines that name emerger.sh" { + printf '%s\n' '0 3 * * * /opt/backup/emerger.sh --sync' '0 10 * * 0 bash "/x/src/emerger.sh" -y -q -nl -ni' >"$HOME/crontab" + touch "$HOME/.bashrc" + run bash "$REPO_DIR/uninstall.sh" + [ "$status" -eq 0 ] + [ "$(cat "$HOME/crontab")" = '0 3 * * * /opt/backup/emerger.sh --sync' ] +} + +@test "uninstall: removes the man page install.sh installed" { + touch "$HOME/.bashrc" + run env PATH="$STUBS:/usr/bin:/bin" bash "$REPO_DIR/install.sh" + [ -e "$HOME/.local/share/man/man1/up.1" ] + run bash "$REPO_DIR/uninstall.sh" + [ "$status" -eq 0 ] + [ ! -e "$HOME/.local/share/man/man1/up.1" ] +} + +# Run uninstall.sh on a pseudo-terminal, answering $1 to its question. +uninstall_answering() { + mkdir -p "$XDG_CONFIG_HOME/emerger" "$HOME/.local/state/emerger" "$HOME/.cache/emerger" + touch "$XDG_CONFIG_HOME/emerger/config.sh" "$HOME/.local/state/emerger/history.jsonl" "$HOME/.cache/emerger/detected" "$HOME/.bashrc" + printf '%s\n' "$1" | script -qec "bash '$REPO_DIR/uninstall.sh'" /dev/null +} + +@test "uninstall: answering y deletes settings, history and cache" { + run uninstall_answering y + [ "$status" -eq 0 ] + [ ! -e "$XDG_CONFIG_HOME/emerger" ] + [ ! -e "$HOME/.local/state/emerger" ] + [ ! -e "$HOME/.cache/emerger" ] + [[ "$output" != *"Remove manually"* ]] +} + +@test "uninstall: answering n keeps settings, history and cache and says how to remove them" { + run uninstall_answering n + [ "$status" -eq 0 ] + [ -e "$XDG_CONFIG_HOME/emerger/config.sh" ] + [ -e "$HOME/.local/state/emerger/history.jsonl" ] + [[ "$output" == *"Remove manually"* ]] +} + +@test "uninstall: without a terminal keeps settings, history and cache" { + mkdir -p "$XDG_CONFIG_HOME/emerger"; touch "$XDG_CONFIG_HOME/emerger/config.sh" "$HOME/.bashrc" + run bash "$REPO_DIR/uninstall.sh" "$STUBS/$m"; chmod +x "$STUBS/$m"; done + printf '#!/bin/sh\necho "sudo $*" >>"$HOME/sudo.log"\n' >"$STUBS/sudo"; chmod +x "$STUBS/sudo" +} + +teardown() { + teardown_env +} + +@test "weather: empty curl output prints no line and the run goes on" { + printf '#!/bin/sh\nexit 0\n' >"$STUBS/curl"; chmod +x "$STUBS/curl" + run $EMERGER -n -y -w --only none + [ "$status" -eq 0 ] + [[ "$output" == *"No supported package managers"* ]] +} + +@test "weather: attack OSC 52 from wttr.in, expected control bytes stripped" { + stub curl 'printf "Rome: \033]52;c;SGVsbG8=\007sunny\033]0;t\007 +20C\r\n"' + run env PATH="$STUBS:$PATH" $EMERGER -n -y -w -ni -nc -nt --only none + [ "$status" -eq 0 ] + [[ "$output" == *"sunny"* ]] + [[ "$output" != *$'\e'* ]] + [[ "$output" != *$'\a'* ]] +} + +@test "weather: attack a 100 KB body from wttr.in, expected cut to 512 bytes" { + stub curl 'head -c 100000 /dev/zero | tr "\0" x' + run env PATH="$STUBS:$PATH" $EMERGER -n -y -w -ni -nc -nt --only none + [ "$status" -eq 0 ] + longest=$(printf '%s\n' "$output" | awk '{ if (length($0) > m) m = length($0) } END { print m }') + [ "$longest" -gt 400 ] + [ "$longest" -lt 600 ] +} diff --git a/uninstall.ps1 b/uninstall.ps1 index 43ed77f..c011260 100644 --- a/uninstall.ps1 +++ b/uninstall.ps1 @@ -2,14 +2,18 @@ <# .SYNOPSIS Remove the eMerger Windows integration: `up` function, scheduled task. - Config and state under %APPDATA%\emerger and %LOCALAPPDATA%\emerger are kept. + Config and state under %APPDATA%\emerger and %LOCALAPPDATA%\emerger go only + when the user answers yes. #> [CmdletBinding()] param() $ErrorActionPreference = 'Stop' $REPO = Split-Path -Parent $PSCommandPath -. "$REPO\src\pslib\UI.ps1" +. "$REPO\src\pslib\ui\Term.ps1" +. "$REPO\src\pslib\ui\Text.ps1" +. "$REPO\src\pslib\ui\Print.ps1" +. "$REPO\src\pslib\ui\Prompt.ps1" UI-Title 'eMerger uninstall (Windows)' @@ -31,15 +35,26 @@ if (Test-Path $profilePath) { # Scheduled task. try { - $t = Get-ScheduledTask -TaskName 'eMerger' -ErrorAction Stop - if ($t) { + $task = Get-ScheduledTask -TaskName 'eMerger' -ErrorAction Stop + if ($task) { Unregister-ScheduledTask -TaskName 'eMerger' -Confirm:$false UI-Ok "Removed scheduled task 'eMerger'" } } catch {} -UI-Muted "Config kept at: $env:APPDATA\emerger\" -UI-Muted "State kept at: $env:LOCALAPPDATA\emerger\" -UI-Muted "Delete manually if you want a truly clean wipe." +# Settings, history and cache go only on an explicit yes. +$configDir = Join-Path $env:APPDATA 'emerger' +$stateDir = Join-Path $env:LOCALAPPDATA 'emerger' +if (UI-Confirm 'Delete your settings, history and cache too?' 'n') { + foreach ($dir in @($configDir, $stateDir)) { + if (Test-Path -LiteralPath $dir) { Remove-Item -LiteralPath $dir -Recurse -Force } + } + UI-Ok 'Removed settings, history and cache' +} else { + UI-Muted 'Settings, history and cache kept at:' + UI-Muted " $configDir\" + UI-Muted " $stateDir\" + UI-Muted 'Remove manually if you want them gone.' +} UI-Ok "Uninstall complete. Repo still at $REPO." diff --git a/uninstall.sh b/uninstall.sh index 10522b9..c79c8f3 100755 --- a/uninstall.sh +++ b/uninstall.sh @@ -3,28 +3,72 @@ set -Eeuo pipefail REPO_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -# shellcheck source=src/lib/ui.sh -source "$REPO_DIR/src/lib/ui.sh" -# shellcheck source=src/lib/sys.sh -source "$REPO_DIR/src/lib/sys.sh" +# Installers take no flags: the environment never reaches ui_* arithmetic. +# Both read by the ui functions. +# shellcheck disable=SC2034 +QUIET_LEVEL=0 +# shellcheck disable=SC2034 +UI_VERBOSE=0 + +# shellcheck source=src/lib/load.sh +source "$REPO_DIR/src/lib/load.sh" ui sys autoupdate ui_title "eMerger uninstall" -removed_any=0 -for rc in "$HOME/.bashrc" "${ZDOTDIR:-$HOME}/.zshrc" "$HOME/.config/fish/config.fish"; do +# Drop the lines install.sh wrote to an rc file: the "# eMerger" header with the +# alias after it, and any other `up` alias pointing at emerger.sh. The user's +# own lines, comments mentioning eMerger included, stay. +_strip_rc() { + local rc="$1" tmp + tmp=$(mktemp "$rc.XXXXXX") + awk ' + /^alias up[ =].*emerger\.sh/ { held = ""; next } + held != "" { print held; held = "" } + /^# eMerger( \(|$)/ { held = $0; next } + { print } + END { if (held != "") print held } + ' "$rc" >"$tmp" && cat "$tmp" >"$rc" + rm -f "$tmp" +} + +has_removed=0 +for rc in "$HOME/.bashrc" "${ZDOTDIR:-$HOME}/.zshrc" "$HOME/.config/fish/config.fish" "$(sys_shell_rc)"; do [[ -f $rc ]] || continue if grep -q "emerger.sh" "$rc"; then - sed -i.bak '/emerger\.sh/d;/# eMerger/d' "$rc" - rm -f "$rc.bak" + _strip_rc "$rc" ui_ok "Cleaned $rc" - removed_any=1 + has_removed=1 + fi +done +(( has_removed )) || ui_muted "No shell rc entries found." + +# Remove the completion files install.sh installed, recognised by their header. +bash_comp="${BASH_COMPLETION_USER_DIR:-$HOME/.local/share/bash-completion/completions}" +zsh_comp="$HOME/.zsh/completions" +fish_comp="$HOME/.config/fish/completions" +if brew_prefix=$(sys_brew_prefix); then + [[ -d "$brew_prefix/etc/bash_completion.d" ]] && bash_comp="$brew_prefix/etc/bash_completion.d" + [[ -d "$brew_prefix/share/zsh/site-functions" ]] && zsh_comp="$brew_prefix/share/zsh/site-functions" +fi +for comp in "$bash_comp/up" "$zsh_comp/_up" "$fish_comp/up.fish"; do + if [[ -f $comp ]] && grep -q "completion for eMerger" "$comp"; then + rm -f "$comp" + ui_ok "Removed completion: $comp" fi done -(( removed_any )) || ui_muted "No shell rc entries found." -if sys_has crontab && crontab -l 2>/dev/null | grep -q "emerger.sh"; then - crontab -l 2>/dev/null | grep -v "emerger.sh" | crontab - - ui_ok "Removed cronjob" +# Remove the man page install.sh installed, recognised by its title line. +man_page="${XDG_DATA_HOME:-$HOME/.local/share}/man/man1/up.1" +if [[ -f $man_page ]] && grep -q '^\.TH UP 1 .*eMerger' "$man_page"; then + rm -f "$man_page" + ui_ok "Removed man page: $man_page" +fi + +if sys_has crontab && crontab -l 2>/dev/null | grep -q -E '^0 10 \* \* 0 bash ".*/src/emerger\.sh" -y -q -nl -ni$'; then + if others=$(autoupdate_crontab_others); then + { [[ -z $others ]] || printf '%s\n' "$others"; } | crontab - + ui_ok "Removed cronjob" + fi fi if sys_has systemctl && systemctl --user list-unit-files 2>/dev/null | grep -q emerger; then @@ -34,9 +78,20 @@ if sys_has systemctl && systemctl --user list-unit-files 2>/dev/null | grep -q e ui_ok "Removed systemd user timer" fi -ui_muted "State and config kept at:" -ui_muted " ${XDG_CONFIG_HOME:-$HOME/.config}/emerger/" -ui_muted " ${XDG_STATE_HOME:-$HOME/.local/state}/emerger/" -ui_muted "Remove manually if you want them gone." +# Settings, history and cache go only on an explicit yes: no terminal or no +# answer keeps them. +config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/emerger" +state_dir="${XDG_STATE_HOME:-$HOME/.local/state}/emerger" +cache_dir="${XDG_CACHE_HOME:-$HOME/.cache}/emerger" +if ui_confirm "Delete your settings, history and cache too?" n; then + rm -rf -- "$config_dir" "$state_dir" "$cache_dir" + ui_ok "Removed settings, history and cache" +else + ui_muted "Settings, history and cache kept at:" + ui_muted " $config_dir/" + ui_muted " $state_dir/" + ui_muted " $cache_dir/" + ui_muted "Remove manually if you want them gone." +fi ui_ok "Uninstall complete. Repo still at $REPO_DIR." diff --git a/update.ps1 b/update.ps1 deleted file mode 100644 index 65db7bf..0000000 --- a/update.ps1 +++ /dev/null @@ -1,5 +0,0 @@ -#Requires -Version 5.1 -# Thin wrapper for `up --self-update`. -param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Arguments) -$REPO = Split-Path -Parent $PSCommandPath -& "$REPO\src\emerger.ps1" --self-update @Arguments diff --git a/update.sh b/update.sh deleted file mode 100755 index 88a21e5..0000000 --- a/update.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash -# Thin wrapper; delegates to `up --self-update`. -set -Eeuo pipefail -REPO_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -exec bash "$REPO_DIR/src/emerger.sh" --self-update "$@"