feat(cli): add pi2 uninstall for cross-channel state cleanup
`install.sh --uninstall`, `brew uninstall`, `npm rm -g` and `pi2 uninstall-service` each own one slice; none of them removed the runtime directory, and deleting the binary left a running daemon behind. `pi2 uninstall` now owns the state for every channel: disable and remove the unit, stop the daemon, delete the runtime dir, and — with `--purge` / `--purge-config` — the data, state and env file. On the curl channel `--purge` also deletes the install tree, last, because the running binary lives inside it; npm/brew/AUR trees stay with their package manager, and the command to remove them is printed instead. Destructive by design: the plan is always printed, `--yes` (or an interactive `y`) is required, non-TTY runs refuse without it, and everything a reinstall would silently lose is an explicit opt-in. The next-steps footer names what no CLI can clean: the browser's site data and the plugin-private copy from `:PiWebInstall`. Docs: rewrite the install.md uninstall section around the two layers (state vs. binaries) with a table of every path, point deployment.md at the new command, and update the README.
This commit is contained in:
1 parent
c2d1f1d960
commit
2240289426
7 files changed
+1000
-6
No files matched your search
@@ -47,12 +47,19 @@ points `~/.local/lib/pi2d/current` at it, writes an install receipt and symlinks
|
||||
`~/.local/bin/pi2`. After that, `pi2 update` upgrades it in place (verified download, SLSA
|
||||
provenance check, atomic `current` switch, one-step rollback).
|
||||
|
||||
To uninstall:
|
||||
To uninstall, first remove the daemon's local state (runtime, service unit, and — with flags —
|
||||
data/state/config), then the binaries:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh -s -- --uninstall
|
||||
pi2 uninstall --dry-run # what would be removed
|
||||
pi2 uninstall --purge --purge-config --yes # daemon state, logs, env file (curl channel: also the tree)
|
||||
```
|
||||
|
||||
On the npm / Homebrew / AUR channels the binary tree belongs to the package manager:
|
||||
`npm rm -g @yuez/pi2d`, `brew uninstall pi2d`, `sudo pacman -R pi2d-bin`. See
|
||||
[Complete removal](docs/install.md#uninstall) for the full table of paths and the two things
|
||||
no CLI can clean (browser site data, the plugin-private copy).
|
||||
|
||||
### Channel C: System packages (Homebrew, AUR)
|
||||
|
||||
*(Available once the release that publishes binaries has shipped)*:
|
||||
@@ -127,6 +134,7 @@ pi2 install-service --write # render and write user service file
|
||||
pi2 service status # unit, enabled, active, linger (--json for machines)
|
||||
pi2 service enable # daemon-reload + enable --now (start|stop|disable too)
|
||||
pi2 uninstall-service --write # remove user service file
|
||||
pi2 uninstall [--dry-run] [--yes] [--purge] # remove local state (all channels)
|
||||
pi2 status # daemon status, active instances, and health
|
||||
pi2 doctor # verify node/runtime, nvim, pi, curl, sockets, protocol
|
||||
pi2 --version # print version
|
||||
|
||||
@@ -564,6 +564,12 @@ too). For a login-less service to keep running on Linux enable linger
|
||||
(`loginctl enable-linger $USER`, `pi2 doctor` warns when it is off;
|
||||
`pi2 service status --json` reports `linger`).
|
||||
|
||||
`pi2 uninstall` chains the same steps plus the rest of the daemon's files:
|
||||
disable + remove the unit, stop the daemon, delete the runtime directory, and
|
||||
with `--purge` / `--purge-config` the data, state and env file as well. Use it
|
||||
instead of this command when the goal is a clean machine, not just a missing
|
||||
unit — see [install.md](install.md#uninstall) for the full table of paths.
|
||||
|
||||
## 10. Logs and health
|
||||
|
||||
- `pi2 daemon` logs JSONL to stderr: `systemctl --user status pi2` /
|
||||
|
||||
+64
-4
@@ -357,7 +357,57 @@ systemctl --user restart pi2.service
|
||||
yay -Syu pi2d-bin
|
||||
```
|
||||
|
||||
### Uninstall per channel
|
||||
### Uninstall
|
||||
|
||||
Removal has two layers: the daemon's **local state** (the same for every channel) and
|
||||
the **binaries** (owned by the channel that installed them).
|
||||
|
||||
#### Step 1 — remove the daemon's local state: `pi2 uninstall`
|
||||
|
||||
```bash
|
||||
pi2 uninstall --dry-run # print the plan, change nothing
|
||||
pi2 uninstall # interactive confirmation
|
||||
pi2 uninstall --yes # scripts / no TTY
|
||||
pi2 uninstall --purge --purge-config --yes # state and env file too
|
||||
```
|
||||
|
||||
The command is channel-agnostic and runs in this order:
|
||||
|
||||
1. `pi2 service disable` + remove the unit file — unless `--keep-service`
|
||||
2. stop a running daemon (`pi2 stop`)
|
||||
3. delete the runtime directory — sockets, `cli.token`, `daemon.lock`
|
||||
4. with `--purge`: delete the data directory (`devices.json`, `workspaces.json`) and the
|
||||
state directory (instance logs, `host-init/`, the update cache)
|
||||
5. with `--purge-config`: delete `~/.config/pi2/env`
|
||||
6. on the **curl channel only**, with `--purge`: delete `<prefix>` (`~/.local/lib/pi2d`)
|
||||
and the `~/.local/bin/pi2` symlink. This runs last because the running binary lives
|
||||
inside that tree.
|
||||
|
||||
| What | Default location (Linux) | Removed by | Why it is not always removed |
|
||||
|---|---|---|---|
|
||||
| Runtime | `$XDG_RUNTIME_DIR/pi2` | always | throwaway: sockets, lock, CLI token |
|
||||
| Data | `~/.local/share/pi2` | `--purge` | paired devices, workspace trust and aliases |
|
||||
| State | `~/.local/state/pi2` | `--purge` | instance logs, generated host-init, update cache |
|
||||
| Config | `~/.config/pi2/env` | `--purge-config` | user-authored; may hold tokens for other tools |
|
||||
| Service | `~/.config/systemd/user/pi2.service` (launchd plist on macOS) | default, or keep with `--keep-service` | — |
|
||||
| Install tree | `~/.local/lib/pi2d` | `--purge` on the curl channel | npm/brew/AUR own their trees |
|
||||
|
||||
`pi2 uninstall` never deletes a tree a package manager tracks. Instead it prints the
|
||||
command that does, plus the two things no CLI can clean for you:
|
||||
|
||||
- the **browser's site data** for the console (it caches the paired device token in
|
||||
`localStorage`);
|
||||
- the **plugin-private daemon copy** made by `:PiWebInstall` under Neovim's
|
||||
`stdpath("data")/pi2d`.
|
||||
|
||||
Without `--purge` the command also prints the exact `rm -rf` fallback for the directories
|
||||
it kept, so a full wipe never requires knowing the layout.
|
||||
|
||||
> Removing the state is safe to redo: a reinstall recreates the runtime directory, and
|
||||
> `--purge` is the only thing that makes a reinstall forget paired devices and workspace
|
||||
> trust.
|
||||
|
||||
#### Step 2 — remove the binaries (per channel)
|
||||
|
||||
- **Channel A (npm / pnpm / bun)**:
|
||||
```bash
|
||||
@@ -365,7 +415,8 @@ systemctl --user restart pi2.service
|
||||
# or: pnpm rm -g @yuez/pi2d / bun rm -g @yuez/pi2d
|
||||
```
|
||||
|
||||
- **Channel B (curl installer)**:
|
||||
- **Channel B (curl installer)** — after `pi2 uninstall --purge`, or instead of it when the
|
||||
state does not matter:
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh -s -- --uninstall
|
||||
```
|
||||
@@ -381,9 +432,18 @@ systemctl --user restart pi2.service
|
||||
sudo pacman -R pi2d-bin
|
||||
```
|
||||
|
||||
If you configured a user service, remember to remove it before uninstalling the binary:
|
||||
If you only want the unit gone and the daemon kept running, `pi2 uninstall-service --write`
|
||||
removes the file alone (and prints the disable commands).
|
||||
|
||||
#### Complete removal, copy-paste
|
||||
|
||||
```bash
|
||||
pi2 uninstall-service --write
|
||||
# curl installer
|
||||
pi2 uninstall --purge --purge-config --yes
|
||||
# npm
|
||||
pi2 uninstall --purge --purge-config --yes && npm rm -g @yuez/pi2d
|
||||
# assert nothing is left behind
|
||||
pi2 config --json | grep -E 'runtimeDir|dataDir|stateDir' # all should be gone
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
* pi2 pairing create a pairing code for another device
|
||||
* pi2 install-service render/install a systemd user unit or LaunchAgent
|
||||
* pi2 uninstall-service remove it again
|
||||
* pi2 uninstall remove the daemon's local state (all channels)
|
||||
* pi2 service … status/start/stop/enable/disable that unit
|
||||
*
|
||||
* Everything is discovered from the runtime dir: `daemon.json` carries the
|
||||
@@ -50,6 +51,7 @@ import { diagnose, formatReport, reportToJson, type DoctorReport } from "./docto
|
||||
import { runStop, STOP_USAGE, type StopOptions } from "./stop.js";
|
||||
import { runConfig, CONFIG_USAGE, type RunConfigOptions } from "./config.js";
|
||||
import { runUpdate, UPDATE_USAGE } from "./update.js";
|
||||
import { runUninstall, UNINSTALL_USAGE, type UninstallOptions } from "./uninstall.js";
|
||||
import {
|
||||
parseServiceArgs,
|
||||
runServiceCommand,
|
||||
@@ -86,6 +88,7 @@ Usage:
|
||||
pi2 pairing [--base <url>] [--json] create a pairing code (URL + code + QR)
|
||||
pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent
|
||||
pi2 uninstall-service [--dry-run|--write] remove the unit
|
||||
pi2 uninstall [--dry-run] [--yes] [--purge] remove the daemon's local state
|
||||
pi2 service status|start|stop|enable|disable control that unit (status [--json])
|
||||
pi2 update [--check|--dry-run] upgrade a standalone (curl installer) pi2 in place
|
||||
pi2 --version | --help
|
||||
@@ -749,6 +752,8 @@ export interface Pi2Options {
|
||||
serviceExists?: (path: string) => boolean;
|
||||
serviceUid?: number;
|
||||
serviceUser?: string;
|
||||
/** Injected `pi2 uninstall` runner (defaults to `runUninstall`). */
|
||||
uninstall?: (options: UninstallOptions) => Promise<number>;
|
||||
}
|
||||
|
||||
export async function main(argv: readonly string[], options: Pi2Options = {}): Promise<number> {
|
||||
@@ -896,6 +901,47 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
|
||||
};
|
||||
return command === "install-service" ? runInstallService(serviceOptions) : runUninstallService(serviceOptions);
|
||||
}
|
||||
case "uninstall": {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = parseArgs(rest, {
|
||||
booleans: [
|
||||
"--dry-run",
|
||||
"--yes",
|
||||
"--purge",
|
||||
"--purge-config",
|
||||
"--keep-service",
|
||||
"--keep-install",
|
||||
"--help",
|
||||
],
|
||||
aliases: { "-y": "--yes", "-h": "--help" },
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof UsageError) throw new UsageError(error.message, UNINSTALL_USAGE);
|
||||
throw error;
|
||||
}
|
||||
if (boolFlag(parsed.flags, "--help")) {
|
||||
out(UNINSTALL_USAGE);
|
||||
return 0;
|
||||
}
|
||||
if (parsed.positionals.length > 0) {
|
||||
throw new UsageError(`unexpected argument "${parsed.positionals[0]}"`, UNINSTALL_USAGE);
|
||||
}
|
||||
return await (options.uninstall ?? runUninstall)({
|
||||
dryRun: boolFlag(parsed.flags, "--dry-run"),
|
||||
yes: boolFlag(parsed.flags, "--yes"),
|
||||
purge: boolFlag(parsed.flags, "--purge"),
|
||||
purgeConfig: boolFlag(parsed.flags, "--purge-config"),
|
||||
keepService: boolFlag(parsed.flags, "--keep-service"),
|
||||
keepInstall: boolFlag(parsed.flags, "--keep-install"),
|
||||
print: out,
|
||||
warn: err,
|
||||
...(options.runtime === undefined ? {} : { runtime: options.runtime }),
|
||||
...(options.platform === undefined ? {} : { platform: options.platform }),
|
||||
...(options.servicePaths === undefined ? {} : { servicePaths: options.servicePaths }),
|
||||
...(options.isTTY === undefined ? {} : { isTTY: options.isTTY }),
|
||||
});
|
||||
}
|
||||
case "update": {
|
||||
let parsed;
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,485 @@
|
||||
/**
|
||||
* `pi2 uninstall` — remove what pi2 wrote to this machine.
|
||||
*
|
||||
* Every other removal path owns one slice and knows nothing about the others:
|
||||
* `npm rm -g`, `brew uninstall`, `install.sh --uninstall` own a binary tree,
|
||||
* `pi2 uninstall-service` owns the unit file, and none of them touches the
|
||||
* runtime/data/state directories. Deleting the binary while the daemon still
|
||||
* runs also leaves an orphan process. This command owns the *state* for every
|
||||
* channel, and prints the channel's own command for the binary tree instead of
|
||||
* deleting a tree a package manager tracks.
|
||||
*
|
||||
* The layout is the one `docs/deployment.md` documents:
|
||||
*
|
||||
* runtime sockets, `cli.token`, `daemon.lock` always removed
|
||||
* data `devices.json`, `workspaces.json` `--purge`
|
||||
* state instance logs, host-init, update cache `--purge`
|
||||
* config `~/.config/pi2/env` `--purge-config`
|
||||
* unit systemd/launchd file removed unless --keep-service
|
||||
* install `<prefix>` on the curl channel `--purge` (last: we run from it)
|
||||
*
|
||||
* Destructive by design, so: a plan is printed first, nothing happens without
|
||||
* `--yes` (or an interactive `y`), and everything a reinstall would silently
|
||||
* lose is an explicit opt-in.
|
||||
*
|
||||
* Every side effect is injected (`removeDir`, `removeFile`, `disableService`,
|
||||
* `removeService`, `stopDaemon`, `daemonPid`, `serviceInstalled`, `channel`,
|
||||
* `confirm`) so the tests never touch the filesystem, systemd or a process.
|
||||
*/
|
||||
import { existsSync, rmSync } from "node:fs";
|
||||
import { homedir, platform as osPlatform } from "node:os";
|
||||
import { join, sep } from "node:path";
|
||||
import { isBundledRuntime, versionedLayoutFor } from "../core/install.js";
|
||||
import { dataDir, realpathSafe, runtimeDir, stateDir } from "../core/paths.js";
|
||||
import { channelUninstallCommand } from "../core/release.js";
|
||||
import {
|
||||
assessLock,
|
||||
DAEMON_JSON_FILE,
|
||||
isPidAlive,
|
||||
LOCK_FILE,
|
||||
readBootId,
|
||||
readDaemonJson,
|
||||
readLockFile,
|
||||
} from "./lock.js";
|
||||
import { defaultServicePaths, renderService, type ServicePaths, type ServicePlatform } from "./service.js";
|
||||
import { runServiceCommand } from "./service-control.js";
|
||||
import { runStop } from "./stop.js";
|
||||
import { CliError, errorMessage } from "./util.js";
|
||||
|
||||
export const UNINSTALL_USAGE = `pi2 uninstall — remove pi2's local state
|
||||
|
||||
Usage:
|
||||
pi2 uninstall [options]
|
||||
|
||||
Stops the daemon, disables and removes the user service unit when one is
|
||||
installed, and deletes the runtime directory (sockets, CLI token, lock).
|
||||
Everything a reinstall would silently lose is opt-in:
|
||||
|
||||
--purge also delete the data dir (paired devices, workspace trust)
|
||||
and the state dir (instance logs, host-init, update cache)
|
||||
--purge-config also delete the env file (~/.config/pi2/env)
|
||||
|
||||
On the standalone channel (curl installer) \`--purge\` also removes the install
|
||||
tree. It goes last, because the running binary lives inside it.
|
||||
|
||||
Options:
|
||||
--dry-run print the plan, change nothing
|
||||
-y, --yes do not ask for confirmation (required when stdin is not a TTY)
|
||||
--purge also remove the data and state directories
|
||||
--purge-config also remove the env file
|
||||
--keep-service leave the user service unit installed
|
||||
--keep-install never remove the curl-installer tree, even with --purge
|
||||
-h, --help print this help and exit
|
||||
|
||||
The binaries themselves belong to the channel that installed them (npm, brew,
|
||||
the AUR, or \`install.sh --uninstall\`); this command prints that command rather
|
||||
than deleting a tree it does not own.
|
||||
|
||||
Environment:
|
||||
PI2_RUNTIME_DIR runtime directory (default: $XDG_RUNTIME_DIR/pi2)
|
||||
PI2_DATA_DIR data directory (default: ~/.local/share/pi2)
|
||||
PI2_STATE_DIR state directory (default: ~/.local/state/pi2)
|
||||
XDG_CONFIG_HOME locates the env file (default: ~/.config/pi2/env)`;
|
||||
|
||||
export type UninstallTarget = "service" | "daemon" | "runtime" | "data" | "state" | "config" | "install";
|
||||
|
||||
/** One line of the plan; `remove: false` is the "kept, and here is the flag" case. */
|
||||
export interface UninstallStep {
|
||||
target: UninstallTarget;
|
||||
/** Absolute paths this step deletes. Empty for `daemon`. */
|
||||
paths: string[];
|
||||
remove: boolean;
|
||||
/** `pid 4242` for the daemon step. */
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
export type UninstallChannelName = "curl" | "brew" | "aur" | "npm" | "unknown";
|
||||
|
||||
export interface UninstallChannel {
|
||||
installer: UninstallChannelName;
|
||||
/** curl-installer layout only: `<prefix>` holding `versions/` and `current`. */
|
||||
prefix?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which channel owns the binary tree. The versioned layout is unambiguous (only
|
||||
* `install.sh` writes `<prefix>/versions/<version>/bin/pi2`); the rest is a
|
||||
* best-effort read of where the executable sits, used only for the hint text.
|
||||
*/
|
||||
export function detectUninstallChannel(execPath: string, bundled: boolean): UninstallChannel {
|
||||
const layout = versionedLayoutFor(execPath);
|
||||
if (layout !== undefined) return { installer: "curl", prefix: layout.prefix };
|
||||
if (!bundled) return { installer: "npm" };
|
||||
if (execPath.includes("/Cellar/") || execPath.includes("/homebrew/")) return { installer: "brew" };
|
||||
if (execPath.startsWith("/usr/")) return { installer: "aur" };
|
||||
return { installer: "unknown" };
|
||||
}
|
||||
|
||||
/** `$XDG_CONFIG_HOME/pi2/env` — the `EnvironmentFile=` a systemd unit points at. */
|
||||
export function configEnvPath(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
home: string = homedir(),
|
||||
): string {
|
||||
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "pi2", "env");
|
||||
}
|
||||
|
||||
const TARGET_LABEL: Record<UninstallTarget, string> = {
|
||||
service: "service unit",
|
||||
daemon: "daemon",
|
||||
runtime: "runtime dir",
|
||||
data: "data dir",
|
||||
state: "state dir",
|
||||
config: "config file",
|
||||
install: "install tree",
|
||||
};
|
||||
|
||||
/** Why a kept path is kept — the flag that would remove it. */
|
||||
const TARGET_HINT: Partial<Record<UninstallTarget, string>> = {
|
||||
data: "--purge",
|
||||
state: "--purge",
|
||||
config: "--purge-config",
|
||||
install: "--purge",
|
||||
service: "--keep-service",
|
||||
};
|
||||
|
||||
export interface UninstallPlanOptions {
|
||||
runtime: string;
|
||||
data: string;
|
||||
state: string;
|
||||
configEnv: string;
|
||||
/** The unit file path (`renderService(...).path`). */
|
||||
serviceUnit: string;
|
||||
purge: boolean;
|
||||
purgeConfig: boolean;
|
||||
keepService?: boolean;
|
||||
keepInstall?: boolean;
|
||||
serviceInstalled: boolean;
|
||||
daemonPid?: number;
|
||||
channel: UninstallChannel;
|
||||
/** Injected in tests; `existsSync` otherwise. */
|
||||
exists?: (path: string) => boolean;
|
||||
}
|
||||
|
||||
/** Pure: what would be touched, in execution order. */
|
||||
export function planUninstall(options: UninstallPlanOptions): UninstallStep[] {
|
||||
const exists = options.exists ?? existsSync;
|
||||
const steps: UninstallStep[] = [];
|
||||
|
||||
if (options.serviceInstalled) {
|
||||
steps.push({
|
||||
target: "service",
|
||||
paths: [options.serviceUnit],
|
||||
remove: options.keepService !== true,
|
||||
});
|
||||
}
|
||||
if (options.daemonPid !== undefined) {
|
||||
steps.push({ target: "daemon", paths: [], remove: true, detail: `pid ${options.daemonPid}` });
|
||||
}
|
||||
if (exists(options.runtime)) {
|
||||
steps.push({ target: "runtime", paths: [options.runtime], remove: true });
|
||||
}
|
||||
|
||||
const optional: [UninstallTarget, string, boolean][] = [
|
||||
["data", options.data, options.purge],
|
||||
["state", options.state, options.purge],
|
||||
["config", options.configEnv, options.purgeConfig],
|
||||
];
|
||||
for (const [target, path, remove] of optional) {
|
||||
if (!exists(path)) continue;
|
||||
steps.push({ target, paths: [path], remove });
|
||||
}
|
||||
|
||||
// Only the tree pi2 itself wrote can be deleted here; npm/brew/AUR own theirs.
|
||||
if (
|
||||
options.purge &&
|
||||
options.channel.installer === "curl" &&
|
||||
options.channel.prefix !== undefined &&
|
||||
exists(options.channel.prefix)
|
||||
) {
|
||||
steps.push({
|
||||
target: "install",
|
||||
paths: [options.channel.prefix],
|
||||
remove: options.keepInstall !== true,
|
||||
});
|
||||
}
|
||||
|
||||
return steps;
|
||||
}
|
||||
|
||||
/** One plan line: verb, target label, path (or pid), and the flag that keeps it. */
|
||||
export function formatUninstallStep(step: UninstallStep, dryRun = false): string {
|
||||
const verb = step.remove
|
||||
? dryRun
|
||||
? step.target === "daemon"
|
||||
? "would stop"
|
||||
: "would remove"
|
||||
: step.target === "daemon"
|
||||
? "stop"
|
||||
: "remove"
|
||||
: "keep";
|
||||
const target = step.detail ?? step.paths.join(", ");
|
||||
// The hint names the flag that would change the outcome, so it only makes
|
||||
// sense on a kept step.
|
||||
const hint = step.remove ? undefined : TARGET_HINT[step.target];
|
||||
return ` ${verb.padEnd(14)}${TARGET_LABEL[step.target].padEnd(14)}${target}${hint === undefined ? "" : ` (${hint})`}`;
|
||||
}
|
||||
|
||||
/** `~/.local/bin/pi2`, when it is a symlink into the curl-installer prefix. */
|
||||
export function installerBinSymlink(prefix: string, home: string = homedir()): string | undefined {
|
||||
const candidate = join(home, ".local", "bin", "pi2");
|
||||
if (!existsSync(candidate)) return undefined;
|
||||
return realpathSafe(candidate).startsWith(`${prefix}${sep}`) ? candidate : undefined;
|
||||
}
|
||||
|
||||
export interface UninstallOptions {
|
||||
runtime?: string;
|
||||
data?: string;
|
||||
state?: string;
|
||||
configEnv?: string;
|
||||
purge?: boolean;
|
||||
purgeConfig?: boolean;
|
||||
keepService?: boolean;
|
||||
keepInstall?: boolean;
|
||||
dryRun?: boolean;
|
||||
yes?: boolean;
|
||||
platform?: ServicePlatform;
|
||||
servicePaths?: ServicePaths;
|
||||
execPath?: string;
|
||||
isBundled?: boolean;
|
||||
homeDir?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
isTTY?: boolean;
|
||||
print?: (line: string) => void;
|
||||
warn?: (line: string) => void;
|
||||
confirm?: (question: string) => Promise<boolean>;
|
||||
exists?: (path: string) => boolean;
|
||||
removeDir?: (path: string) => void;
|
||||
removeFile?: (path: string) => void;
|
||||
/** Live daemon pid, `undefined` when none is running. */
|
||||
daemonPid?: (runtime: string) => number | undefined;
|
||||
serviceInstalled?: (unitPath: string) => boolean;
|
||||
stopDaemon?: (runtime: string) => Promise<void>;
|
||||
disableService?: () => Promise<void>;
|
||||
removeService?: (unitPath: string) => void;
|
||||
channel?: UninstallChannel;
|
||||
}
|
||||
|
||||
function defaultDaemonPid(runtime: string): number | undefined {
|
||||
const lock = readDaemonJson(join(runtime, DAEMON_JSON_FILE)) ?? readLockFile(join(runtime, LOCK_FILE));
|
||||
if (lock === undefined) return undefined;
|
||||
return assessLock(lock, { isPidAlive, bootId: readBootId }).live ? lock.pid : undefined;
|
||||
}
|
||||
|
||||
/** `pi2 stop`, with "there is nothing to stop" treated as success. */
|
||||
async function defaultStopDaemon(runtime: string): Promise<void> {
|
||||
try {
|
||||
await runStop({ runtime, print: () => undefined });
|
||||
} catch (error) {
|
||||
if (error instanceof CliError && error.message.includes("no running pi2 daemon")) return;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** A single `y`/`yes` on stdin; everything else (including EOF) is a no. */
|
||||
function defaultConfirm(question: string): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
process.stdout.write(question);
|
||||
const finish = (answer: boolean): void => {
|
||||
process.stdin.pause();
|
||||
process.stdin.removeListener("data", onData);
|
||||
process.stdin.removeListener("end", onEnd);
|
||||
resolve(answer);
|
||||
};
|
||||
const onData = (chunk: Buffer | string): void => finish(/^y(es)?$/i.test(String(chunk).trim()));
|
||||
// EOF (Ctrl-D, a closed pipe) is a no, never a hang.
|
||||
const onEnd = (): void => finish(false);
|
||||
process.stdin.resume();
|
||||
process.stdin.once("data", onData);
|
||||
process.stdin.once("end", onEnd);
|
||||
});
|
||||
}
|
||||
|
||||
/** The commands that finish the job on the channel that owns the binaries. */
|
||||
export function uninstallNextSteps(
|
||||
steps: readonly UninstallStep[],
|
||||
channel: UninstallChannel,
|
||||
): string[] {
|
||||
const lines: string[] = [];
|
||||
const installRemoved = steps.some((step) => step.target === "install" && step.remove);
|
||||
if (!installRemoved) {
|
||||
lines.push(`remove the binaries (${channel.installer} channel): ${channelUninstallCommand(channel.installer)}`);
|
||||
}
|
||||
const kept = steps.filter((step) => !step.remove && step.target !== "service");
|
||||
const keptDirs = kept.filter((step) => step.target !== "config").flatMap((step) => step.paths);
|
||||
|
||||
lines.push("clear the console's site data in the browser — it caches the paired device token");
|
||||
lines.push('remove the plugin-private daemon copy, if `:PiWebInstall` ran: rm -rf <nvim stdpath("data")>/pi2d');
|
||||
if (keptDirs.length > 0) {
|
||||
lines.push(`rm -rf ${keptDirs.join(" ")}`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/** Kept service unit → the command that takes it down, platform-specific. */
|
||||
export function keptServiceHint(platform: ServicePlatform, paths: ServicePaths): string | undefined {
|
||||
return renderService(platform, paths).removeCommands[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the daemon's local state.
|
||||
*
|
||||
* Returns 0 when there was nothing to do or everything succeeded, 1 when the
|
||||
* confirmation was declined or any removal failed (each failure is reported on
|
||||
* `warn` and does not stop the remaining steps).
|
||||
*/
|
||||
export async function runUninstall(options: UninstallOptions = {}): Promise<number> {
|
||||
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
|
||||
const warn = options.warn ?? ((line: string) => process.stderr.write(`pi2: ${line}\n`));
|
||||
const exists = options.exists ?? existsSync;
|
||||
const removeDir = options.removeDir ?? ((path: string) => rmSync(path, { recursive: true, force: true }));
|
||||
const removeFile = options.removeFile ?? ((path: string) => rmSync(path, { force: true }));
|
||||
const home = options.homeDir ?? homedir();
|
||||
const platform = options.platform ?? (osPlatform() === "darwin" ? "darwin" : "linux");
|
||||
const servicePaths = options.servicePaths ?? defaultServicePaths();
|
||||
const service = renderService(platform, servicePaths);
|
||||
const channel =
|
||||
options.channel ??
|
||||
detectUninstallChannel(
|
||||
options.execPath ?? process.execPath,
|
||||
options.isBundled ?? isBundledRuntime(),
|
||||
);
|
||||
const dryRun = options.dryRun === true;
|
||||
const paths = {
|
||||
runtime: options.runtime ?? runtimeDir(),
|
||||
data: options.data ?? dataDir(),
|
||||
state: options.state ?? stateDir(),
|
||||
configEnv: options.configEnv ?? configEnvPath(options.env ?? process.env, home),
|
||||
};
|
||||
|
||||
const steps = planUninstall({
|
||||
...paths,
|
||||
serviceUnit: service.path,
|
||||
purge: options.purge === true,
|
||||
purgeConfig: options.purgeConfig === true,
|
||||
...(options.keepService === undefined ? {} : { keepService: options.keepService }),
|
||||
...(options.keepInstall === undefined ? {} : { keepInstall: options.keepInstall }),
|
||||
serviceInstalled: (options.serviceInstalled ?? exists)(service.path),
|
||||
...(options.daemonPid === undefined
|
||||
? { daemonPid: defaultDaemonPid(paths.runtime) }
|
||||
: { daemonPid: options.daemonPid(paths.runtime) }),
|
||||
channel,
|
||||
exists,
|
||||
});
|
||||
|
||||
const installStep = steps.find((step) => step.target === "install");
|
||||
if (installStep !== undefined && channel.prefix !== undefined) {
|
||||
const link = installerBinSymlink(channel.prefix, home);
|
||||
if (link !== undefined) installStep.paths.push(link);
|
||||
}
|
||||
|
||||
print(dryRun ? "pi2 uninstall — dry run, nothing will be changed" : "pi2 uninstall");
|
||||
for (const step of steps) print(formatUninstallStep(step, dryRun));
|
||||
|
||||
const removable = steps.filter((step) => step.remove);
|
||||
if (removable.length === 0) {
|
||||
print("nothing to remove: pi2 keeps no state for this user");
|
||||
printNextSteps(print, steps, channel, keptServiceHint(platform, servicePaths));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (dryRun) {
|
||||
printNextSteps(print, steps, channel, keptServiceHint(platform, servicePaths));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (options.yes !== true) {
|
||||
const isTTY = options.isTTY ?? process.stdin.isTTY === true;
|
||||
if (!isTTY && options.confirm === undefined) {
|
||||
throw new CliError(
|
||||
"refusing to remove anything without confirmation.\n" +
|
||||
" re-run with --yes (scripts), or --dry-run to inspect the plan first.",
|
||||
);
|
||||
}
|
||||
const confirmed = await (options.confirm ?? defaultConfirm)(`Remove these ${removable.length} item(s)? [y/N] `);
|
||||
if (!confirmed) {
|
||||
print("aborted — nothing was removed");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
let removed = 0;
|
||||
let failures = 0;
|
||||
let stopped: number | undefined;
|
||||
const stopDaemon = options.stopDaemon ?? defaultStopDaemon;
|
||||
const disableService = options.disableService ?? (() => defaultDisableService(platform, servicePaths));
|
||||
const removeService = options.removeService ?? ((path: string) => removeFile(path));
|
||||
|
||||
for (const step of removable) {
|
||||
if (step.target === "service") {
|
||||
try {
|
||||
await disableService();
|
||||
} catch (error) {
|
||||
warn(`could not disable ${service.name}: ${errorMessage(error)}`);
|
||||
}
|
||||
try {
|
||||
removeService(service.path);
|
||||
removed += 1;
|
||||
} catch (error) {
|
||||
failures += 1;
|
||||
warn(`could not remove ${service.path}: ${errorMessage(error)}`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (step.target === "daemon") {
|
||||
try {
|
||||
await stopDaemon(paths.runtime);
|
||||
stopped = 1;
|
||||
} catch (error) {
|
||||
failures += 1;
|
||||
warn(`could not stop the daemon: ${errorMessage(error)}`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const path of step.paths) {
|
||||
try {
|
||||
if (step.target === "config") removeFile(path);
|
||||
else removeDir(path);
|
||||
removed += 1;
|
||||
} catch (error) {
|
||||
failures += 1;
|
||||
warn(`could not remove ${path}: ${errorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const parts = [`removed ${removed} path(s)`];
|
||||
if (stopped !== undefined) parts.push("stopped the daemon");
|
||||
if (failures > 0) parts.push(`${failures} failure(s)`);
|
||||
print(parts.join(", "));
|
||||
printNextSteps(print, steps, channel, keptServiceHint(platform, servicePaths));
|
||||
return failures > 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
function printNextSteps(
|
||||
print: (line: string) => void,
|
||||
steps: readonly UninstallStep[],
|
||||
channel: UninstallChannel,
|
||||
serviceHint?: string,
|
||||
): void {
|
||||
const lines = uninstallNextSteps(steps, channel);
|
||||
const keptService = steps.some((step) => step.target === "service" && !step.remove);
|
||||
if (keptService && serviceHint !== undefined) {
|
||||
lines.push(`the service unit is still enabled: ${serviceHint}`);
|
||||
}
|
||||
if (lines.length === 0) return;
|
||||
print("");
|
||||
print("Next:");
|
||||
for (const line of lines) print(` - ${line}`);
|
||||
}
|
||||
|
||||
/** `pi2 service disable` — a missing manager is a warning, not a failure. */
|
||||
async function defaultDisableService(platform: ServicePlatform, paths: ServicePaths): Promise<void> {
|
||||
await runServiceCommand("disable", { platform, paths, print: () => undefined });
|
||||
}
|
||||
@@ -225,3 +225,25 @@ export function channelUpgradeCommand(installer: string): string {
|
||||
return "npm i -g @yuez/pi2d@latest # or: brew upgrade pi2d";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The command that removes the *binary tree* for a channel, for `pi2 uninstall`.
|
||||
*
|
||||
* `pi2 uninstall` owns the state (runtime/data/state/config) and never touches a
|
||||
* tree a package manager tracks — except the curl layout, which is the one pi2
|
||||
* wrote itself and can delete.
|
||||
*/
|
||||
export function channelUninstallCommand(installer: string): string {
|
||||
switch (installer) {
|
||||
case "brew":
|
||||
return "brew uninstall pi2d";
|
||||
case "aur":
|
||||
return "sudo pacman -R pi2d-bin";
|
||||
case "npm":
|
||||
return "npm rm -g @yuez/pi2d";
|
||||
case "curl":
|
||||
return `curl -fsSL https://raw.githubusercontent.com/${RELEASE_REPO}/main/scripts/install.sh | sh -s -- --uninstall`;
|
||||
default:
|
||||
return "npm rm -g @yuez/pi2d # or: brew uninstall pi2d";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
import { mkdirSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { main } from "../../src/cli/pi2.js";
|
||||
import {
|
||||
detectUninstallChannel,
|
||||
formatUninstallStep,
|
||||
installerBinSymlink,
|
||||
planUninstall,
|
||||
runUninstall,
|
||||
uninstallNextSteps,
|
||||
configEnvPath,
|
||||
type UninstallChannel,
|
||||
type UninstallOptions,
|
||||
type UninstallStep,
|
||||
} from "../../src/cli/uninstall.js";
|
||||
import { CliError } from "../../src/cli/util.js";
|
||||
import { removeDir, tempDir } from "./helpers.js";
|
||||
|
||||
const RUNTIME = "/home/u/run/pi2";
|
||||
const DATA = "/home/u/.local/share/pi2";
|
||||
const STATE = "/home/u/.local/state/pi2";
|
||||
const CONFIG = "/home/u/.config/pi2/env";
|
||||
const UNIT = "/home/u/.config/systemd/user/pi2.service";
|
||||
const PREFIX = "/home/u/.local/lib/pi2d";
|
||||
|
||||
interface Harness {
|
||||
options: UninstallOptions;
|
||||
removed: string[];
|
||||
removedFiles: string[];
|
||||
lines: string[];
|
||||
warnings: string[];
|
||||
calls: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A fake filesystem + fake systemd: `exists` answers from a set, removals are
|
||||
* recorded, and every hook appends to `calls` so ordering is assertable.
|
||||
*/
|
||||
function harness(present: readonly string[], overrides: UninstallOptions = {}): Harness {
|
||||
const files = new Set(present);
|
||||
const removed: string[] = [];
|
||||
const removedFiles: string[] = [];
|
||||
const lines: string[] = [];
|
||||
const warnings: string[] = [];
|
||||
const calls: string[] = [];
|
||||
|
||||
const options: UninstallOptions = {
|
||||
runtime: RUNTIME,
|
||||
data: DATA,
|
||||
state: STATE,
|
||||
configEnv: CONFIG,
|
||||
servicePaths: { homeDir: "/home/u", stateDir: STATE },
|
||||
homeDir: "/home/u",
|
||||
yes: true,
|
||||
channel: { installer: "npm" },
|
||||
print: (line) => lines.push(line),
|
||||
warn: (line) => warnings.push(line),
|
||||
exists: (path) => files.has(path),
|
||||
removeDir: (path) => {
|
||||
removed.push(path);
|
||||
calls.push(`rmdir ${path}`);
|
||||
},
|
||||
removeFile: (path) => {
|
||||
removedFiles.push(path);
|
||||
calls.push(`rm ${path}`);
|
||||
},
|
||||
daemonPid: () => undefined,
|
||||
serviceInstalled: (unitPath) => files.has(unitPath),
|
||||
stopDaemon: async () => {
|
||||
calls.push("stop daemon");
|
||||
},
|
||||
disableService: async () => {
|
||||
calls.push("disable service");
|
||||
},
|
||||
removeService: (path) => {
|
||||
removedFiles.push(path);
|
||||
calls.push(`rm ${path}`);
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
return { options, removed, removedFiles, lines, warnings, calls };
|
||||
}
|
||||
|
||||
describe("planUninstall", () => {
|
||||
const base = {
|
||||
runtime: RUNTIME,
|
||||
data: DATA,
|
||||
state: STATE,
|
||||
configEnv: CONFIG,
|
||||
serviceUnit: UNIT,
|
||||
serviceInstalled: true,
|
||||
daemonPid: 4242,
|
||||
channel: { installer: "npm" } as UninstallChannel,
|
||||
exists: () => true,
|
||||
};
|
||||
|
||||
it("removes the service, the daemon and the runtime dir, and keeps the rest", () => {
|
||||
const steps = planUninstall({ ...base, purge: false, purgeConfig: false });
|
||||
|
||||
expect(steps.map((step) => [step.target, step.remove])).toEqual([
|
||||
["service", true],
|
||||
["daemon", true],
|
||||
["runtime", true],
|
||||
["data", false],
|
||||
["state", false],
|
||||
["config", false],
|
||||
]);
|
||||
expect(steps[1]?.detail).toBe("pid 4242");
|
||||
});
|
||||
|
||||
it("--purge adds data and state, --purge-config adds the env file", () => {
|
||||
const steps = planUninstall({ ...base, purge: true, purgeConfig: true });
|
||||
const removed = steps.filter((step) => step.remove).map((step) => step.target);
|
||||
|
||||
expect(removed).toEqual(["service", "daemon", "runtime", "data", "state", "config"]);
|
||||
});
|
||||
|
||||
it("--keep-service keeps the unit but still cleans the state", () => {
|
||||
const steps = planUninstall({ ...base, purge: false, purgeConfig: false, keepService: true });
|
||||
expect(steps.find((step) => step.target === "service")?.remove).toBe(false);
|
||||
expect(steps.find((step) => step.target === "runtime")?.remove).toBe(true);
|
||||
});
|
||||
|
||||
it("only offers the install tree on the curl channel, and only with --purge", () => {
|
||||
const curl: UninstallChannel = { installer: "curl", prefix: PREFIX };
|
||||
|
||||
expect(
|
||||
planUninstall({ ...base, channel: curl, purge: false, purgeConfig: false }).some(
|
||||
(step) => step.target === "install",
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
const purged = planUninstall({ ...base, channel: curl, purge: true, purgeConfig: false });
|
||||
expect(purged.filter((step) => step.target === "install").map((step) => [step.paths, step.remove])).toEqual([
|
||||
[[PREFIX], true],
|
||||
]);
|
||||
|
||||
const kept = planUninstall({
|
||||
...base,
|
||||
channel: curl,
|
||||
purge: true,
|
||||
purgeConfig: false,
|
||||
keepInstall: true,
|
||||
});
|
||||
expect(kept.find((step) => step.target === "install")?.remove).toBe(false);
|
||||
});
|
||||
|
||||
it("skips paths that do not exist and steps with nothing to stop", () => {
|
||||
const steps = planUninstall({
|
||||
...base,
|
||||
purge: true,
|
||||
purgeConfig: true,
|
||||
serviceInstalled: false,
|
||||
daemonPid: undefined,
|
||||
exists: (path) => path === DATA,
|
||||
});
|
||||
|
||||
expect(steps.map((step) => [step.target, step.remove])).toEqual([["data", true]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatUninstallStep", () => {
|
||||
const step: UninstallStep = { target: "data", paths: [DATA], remove: false };
|
||||
|
||||
it("names the flag that keeps a path", () => {
|
||||
expect(formatUninstallStep(step)).toContain(`(${"--purge"})`);
|
||||
});
|
||||
|
||||
it("does not suggest a flag on a step that is already removed", () => {
|
||||
expect(formatUninstallStep({ ...step, remove: true })).not.toContain("--purge");
|
||||
});
|
||||
|
||||
it("speaks in the future tense for a dry run", () => {
|
||||
expect(formatUninstallStep({ ...step, remove: true }, true)).toContain("would remove");
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectUninstallChannel", () => {
|
||||
it("recognises the versioned curl layout", () => {
|
||||
expect(detectUninstallChannel(`${PREFIX}/versions/0.1.9/bin/pi2`, true)).toEqual({
|
||||
installer: "curl",
|
||||
prefix: PREFIX,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the shape of the path for the package managers", () => {
|
||||
expect(detectUninstallChannel("/usr/local/lib/node_modules/@yuez/pi2d/dist/cli/pi2.js", false).installer).toBe(
|
||||
"npm",
|
||||
);
|
||||
expect(detectUninstallChannel("/opt/homebrew/Cellar/pi2d/0.1.9/bin/pi2", true).installer).toBe("brew");
|
||||
expect(detectUninstallChannel("/usr/bin/pi2", true).installer).toBe("aur");
|
||||
expect(detectUninstallChannel("/tmp/pi2", true).installer).toBe("unknown");
|
||||
});
|
||||
});
|
||||
|
||||
describe("configEnvPath", () => {
|
||||
it("honours XDG_CONFIG_HOME", () => {
|
||||
expect(configEnvPath({ XDG_CONFIG_HOME: "/x" }, "/home/u")).toBe("/x/pi2/env");
|
||||
expect(configEnvPath({}, "/home/u")).toBe("/home/u/.config/pi2/env");
|
||||
});
|
||||
});
|
||||
|
||||
describe("runUninstall", () => {
|
||||
it("dry-run prints the plan and touches nothing", async () => {
|
||||
const h = harness([RUNTIME, DATA, STATE, CONFIG, UNIT], { dryRun: true });
|
||||
|
||||
expect(await runUninstall(h.options)).toBe(0);
|
||||
expect(h.calls).toEqual([]);
|
||||
expect(h.lines[0]).toContain("dry run");
|
||||
expect(h.lines.join("\n")).toContain("--purge");
|
||||
expect(h.lines.join("\n")).toContain("npm rm -g @yuez/pi2d");
|
||||
});
|
||||
|
||||
it("stops the daemon, disables and removes the unit, then deletes the runtime dir", async () => {
|
||||
const h = harness([RUNTIME, DATA, STATE, CONFIG, UNIT], { daemonPid: () => 4242 });
|
||||
|
||||
expect(await runUninstall(h.options)).toBe(0);
|
||||
expect(h.calls).toEqual([
|
||||
"disable service",
|
||||
`rm ${UNIT}`,
|
||||
"stop daemon",
|
||||
`rmdir ${RUNTIME}`,
|
||||
]);
|
||||
expect(h.removed).not.toContain(DATA);
|
||||
expect(h.lines.at(-1)).toContain("rm -rf");
|
||||
});
|
||||
|
||||
it("--purge also deletes data and state; --purge-config the env file", async () => {
|
||||
const h = harness([RUNTIME, DATA, STATE, CONFIG], { purge: true, purgeConfig: true, serviceInstalled: () => false });
|
||||
|
||||
expect(await runUninstall(h.options)).toBe(0);
|
||||
expect(h.removed).toEqual([RUNTIME, DATA, STATE]);
|
||||
expect(h.removedFiles).toEqual([CONFIG]);
|
||||
expect(h.lines.join("\n")).not.toContain(`rm -rf ${DATA}`);
|
||||
});
|
||||
|
||||
it("removes the curl install tree last, together with the bin symlink", async () => {
|
||||
const dir = tempDir("pi2-uninstall-");
|
||||
try {
|
||||
const prefix = join(dir, "lib", "pi2d");
|
||||
const binDir = join(prefix, "versions", "1.0.0", "bin");
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
writeFileSync(join(binDir, "pi2"), "");
|
||||
const home = join(dir, "home");
|
||||
mkdirSync(join(home, ".local", "bin"), { recursive: true });
|
||||
symlinkSync(join(binDir, "pi2"), join(home, ".local", "bin", "pi2"));
|
||||
|
||||
const h = harness([RUNTIME, prefix], {
|
||||
homeDir: home,
|
||||
purge: true,
|
||||
channel: { installer: "curl", prefix },
|
||||
});
|
||||
expect(installerBinSymlink(prefix, home)).toBe(join(home, ".local", "bin", "pi2"));
|
||||
|
||||
expect(await runUninstall(h.options)).toBe(0);
|
||||
expect(h.removed).toEqual([RUNTIME, prefix, join(home, ".local", "bin", "pi2")]);
|
||||
expect(h.lines.join("\n")).not.toContain("install.sh");
|
||||
} finally {
|
||||
removeDir(dir);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps going when the service manager refuses, and reports the failure", async () => {
|
||||
const h = harness([UNIT, RUNTIME], {
|
||||
disableService: async () => {
|
||||
throw new CliError("systemctl --user disable --now pi2.service failed: nope");
|
||||
},
|
||||
});
|
||||
|
||||
expect(await runUninstall(h.options)).toBe(0);
|
||||
expect(h.warnings[0]).toContain("could not disable pi2.service");
|
||||
expect(h.removed).toEqual([RUNTIME]);
|
||||
});
|
||||
|
||||
it("counts a failed removal as a failure and exits 1", async () => {
|
||||
const h = harness([RUNTIME, DATA], {
|
||||
purge: true,
|
||||
removeDir: (path) => {
|
||||
if (path === DATA) throw new Error("EPERM");
|
||||
},
|
||||
});
|
||||
|
||||
expect(await runUninstall(h.options)).toBe(1);
|
||||
expect(h.warnings[0]).toContain("could not remove");
|
||||
expect(h.lines.join("\n")).toContain("1 failure(s)");
|
||||
});
|
||||
|
||||
it("asks before removing and honours a no", async () => {
|
||||
const h = harness([RUNTIME], { yes: false, isTTY: true, confirm: async () => false });
|
||||
|
||||
expect(await runUninstall(h.options)).toBe(1);
|
||||
expect(h.calls).toEqual([]);
|
||||
expect(h.lines.at(-1)).toContain("aborted");
|
||||
});
|
||||
|
||||
it("refuses to run non-interactively without --yes", async () => {
|
||||
const h = harness([RUNTIME], { yes: false, isTTY: false });
|
||||
|
||||
await expect(runUninstall(h.options)).rejects.toThrow("refusing to remove anything without confirmation");
|
||||
expect(h.calls).toEqual([]);
|
||||
});
|
||||
|
||||
it("succeeds when there is nothing left to remove", async () => {
|
||||
const h = harness([]);
|
||||
|
||||
expect(await runUninstall(h.options)).toBe(0);
|
||||
expect(h.lines.join("\n")).toContain("nothing to remove");
|
||||
expect(h.calls).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("uninstallNextSteps", () => {
|
||||
it("prints the channel that owns the binaries", () => {
|
||||
const steps: UninstallStep[] = [{ target: "runtime", paths: [RUNTIME], remove: true }];
|
||||
|
||||
expect(uninstallNextSteps(steps, { installer: "npm" }).join("\n")).toContain("npm rm -g @yuez/pi2d");
|
||||
expect(uninstallNextSteps(steps, { installer: "brew" }).join("\n")).toContain("brew uninstall pi2d");
|
||||
expect(uninstallNextSteps(steps, { installer: "curl" }).join("\n")).toContain("--uninstall");
|
||||
});
|
||||
|
||||
it("skips the channel command once the install tree is gone", () => {
|
||||
const steps: UninstallStep[] = [{ target: "install", paths: [PREFIX], remove: true }];
|
||||
expect(uninstallNextSteps(steps, { installer: "curl" }).join("\n")).not.toContain("install.sh");
|
||||
});
|
||||
});
|
||||
|
||||
describe("pi2 uninstall (dispatch)", () => {
|
||||
it("maps the flags onto the runner", async () => {
|
||||
const seen: UninstallOptions[] = [];
|
||||
const code = await main(["uninstall", "--dry-run", "--purge", "--purge-config", "--keep-service", "-y"], {
|
||||
out: () => undefined,
|
||||
runtime: "/tmp/pi2-run",
|
||||
uninstall: async (options) => {
|
||||
seen.push(options);
|
||||
return 0;
|
||||
},
|
||||
});
|
||||
|
||||
expect(code).toBe(0);
|
||||
expect(seen[0]).toMatchObject({
|
||||
dryRun: true,
|
||||
yes: true,
|
||||
purge: true,
|
||||
purgeConfig: true,
|
||||
keepService: true,
|
||||
runtime: "/tmp/pi2-run",
|
||||
});
|
||||
});
|
||||
|
||||
it("prints the command help", async () => {
|
||||
const out: string[] = [];
|
||||
const code = await main(["uninstall", "--help"], { out: (line) => out.push(line) });
|
||||
|
||||
expect(code).toBe(0);
|
||||
expect(out.join("\n")).toContain("--purge-config");
|
||||
});
|
||||
|
||||
it("rejects a positional argument with the command usage", async () => {
|
||||
const err: string[] = [];
|
||||
const code = await main(["uninstall", "everything"], { err: (line) => err.push(line) });
|
||||
|
||||
expect(code).toBe(2);
|
||||
expect(err.join("\n")).toContain("unexpected argument");
|
||||
expect(err.join("\n")).toContain("pi2 uninstall");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user