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 @@
[](https://sonarcloud.io/dashboard?id=MasterCruelty_eMerger)
-
+
-**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