podbox-cli 0.7.1

Declarative Podman-native container environment manager. Define an environment as a TOML file and let systemd own its lifecycle.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Container lifecycle commands: build, enable/disable, start/stop,
//! update, remove. Snapshot/restore live in [`snapshot`].

mod snapshot;

pub use snapshot::{run_restore, run_snapshot, run_snapshot_list, run_snapshot_prune};

use std::io::Write;

use anyhow::{Context, Result};

use podbox::config::Config;
use podbox::env::HostEnv;
use podbox::systemd;
use podbox::xdg::ResolvedXdgDirs;

/// Build the container image (or pull a prebuilt image).
pub fn run_build(
    config: &Config,
    env: &HostEnv,
    xdg: &ResolvedXdgDirs,
    dry_run: bool,
    rebuild: bool,
    no_diff: bool,
) -> Result<()> {
    podbox::build::run(config, env, xdg, dry_run, rebuild)?;
    if !dry_run {
        let _ = podbox::history::record(&config.container.name, "build", "");
        if config.lifecycle.quadlet {
            println!(
                "\nRun `podbox enable {}` to install Quadlet files.",
                config.container.name
            );
        }
    }
    // Post-build drift check (best-effort).
    if !dry_run && !no_diff {
        let name = &config.container.name;
        if let Ok(state) = podbox::podman::query_state(name)
            && state == podbox::podman::ContainerState::Running
        {
            match podbox::diff::compute(config, name, &env.username) {
                Ok(result) if result.has_drift => {
                    println!("\n── Package drift detected ──");
                    println!("{}", podbox::diff::format_report(&result));
                    println!("Run `podbox diff --apply` to update the TOML.");
                }
                Ok(_) => {}
                Err(e) => eprintln!("Warning: drift check skipped ({e})"),
            }
        }
    }
    Ok(())
}

/// Install Quadlet files (enable systemd container lifecycle).
pub fn run_enable(
    config: &Config,
    env: &HostEnv,
    xdg: &ResolvedXdgDirs,
    dry_run: bool,
    yes: bool,
) -> Result<()> {
    // Guard: reinstalling Quadlet on a running container restarts its systemd unit.
    if !dry_run {
        let name = &config.container.name;
        let is_running = podbox::podman::query_state(name)
            .map(|s| s == podbox::podman::ContainerState::Running)
            .unwrap_or(false);
        if is_running {
            if !yes {
                if podbox::codegen::distros::is_tty() {
                    let prompt = format!(
                        "Container '{name}' is running — reinstalling Quadlet will reload systemd and may restart it. Continue?"
                    );
                    let confirmed =
                        dialoguer::Confirm::with_theme(&dialoguer::theme::ColorfulTheme::default())
                            .with_prompt(prompt)
                            .default(false)
                            .interact_opt()?
                            .unwrap_or(false);
                    if !confirmed {
                        anyhow::bail!(
                            "Aborted. Container '{name}' is still running. Rerun with --yes or stop it first: `podbox enable {name} --yes`"
                        );
                    }
                } else {
                    anyhow::bail!(
                        "Container '{name}' is running — refusing to reinstall Quadlet without --yes (non-interactive). Use `podbox enable {name} --yes` or `podbox stop {name}` first."
                    );
                }
            }
            podbox::ui::warn(&format!(
                "Reinstalling Quadlet for running container '{name}' — systemd will reload and may restart it..."
            ));
        }
    }

    podbox::quadlet_install::install(config, env, xdg, dry_run)?;
    if !dry_run {
        let _ = podbox::history::record(&config.container.name, "enable", "");
        println!("\nRun `podbox shell` to start and enter the container.");
    }
    Ok(())
}

/// Remove Quadlet files (disable systemd container lifecycle).
pub fn run_disable(name: &str) -> Result<()> {
    podbox::quadlet_install::uninstall(name)?;
    let _ = podbox::history::record(name, "disable", "");
    Ok(())
}

/// Start the container, auto-healing missing images and Quadlet files.
pub fn run_start(
    config: &Config,
    env: &HostEnv,
    xdg: &ResolvedXdgDirs,
    name: &str,
    dry_run: bool,
    timeout_secs: u64,
) -> Result<()> {
    if dry_run {
        println!("podman start {name}");
        return Ok(());
    }

    let local_tag = format!("localhost/podbox-{}:latest", config.image.name);
    if !podbox::podman::image_exists(&local_tag).unwrap_or(false) {
        println!("Image not found, building first...");
        podbox::build::run(config, env, xdg, false, false)?;
    }

    if !podbox::quadlet_install::is_installed(name) {
        println!("Quadlet files not found, installing...");
        podbox::quadlet_install::install(config, env, xdg, false)?;
    }

    // Abort early with a clear, actionable message if a published host port
    // is already occupied — pasta would otherwise fail and the start would
    // surface as a cryptic systemd unit failure. Skipped when the container
    // is already running (pasta itself then holds the port).
    let already_running = podbox::podman::query_state(name)
        .map(|s| s == podbox::podman::ContainerState::Running)
        .unwrap_or(false);
    if !already_running {
        let conflicts = podbox::ports::check_host_ports(&config.network.ports);
        if !conflicts.is_empty() {
            let mut msg = String::from("Cannot start: published host port(s) already in use:\n");
            for c in &conflicts {
                use std::fmt::Write as _;
                let _ = writeln!(msg, "  - {c}");
            }
            msg.push_str("\nFind the process with: `ss -ltnp 'sport = :<port>'`\n");
            msg.push_str("Either stop that process or change the mapping in [network]ports.");
            anyhow::bail!(msg);
        }
    }

    println!("Starting container...");
    crate::commands::ensure_running(name, false, timeout_secs)?;
    println!("Container '{name}' is running!");
    let _ = podbox::history::record(name, "start", "");
    Ok(())
}

/// Stop the container.
///
/// Uses `systemctl --user stop` when quadlet is enabled so that systemd
/// tracks the service state transition (preventing a stale "unknown" in
/// subsequent `systemctl is-active` checks).
pub fn run_stop(config: &Config, name: &str, dry_run: bool) -> Result<()> {
    if dry_run {
        if config.lifecycle.quadlet && systemd::is_available() {
            println!("systemctl --user stop {name}");
        } else {
            println!("podman stop {name}");
        }
        return Ok(());
    }
    if config.lifecycle.quadlet && systemd::is_available() {
        systemd::stop_unit(name)?;
    } else {
        let args = podbox::process::args(&["stop", name]);
        podbox::process::spawn_interactive("podman", &args)?;
    }
    let _ = podbox::history::record(name, "stop", "");
    Ok(())
}

/// Update a container: pull latest image, rebuild, and restart.
pub fn run_update(
    config: &Config,
    env: &HostEnv,
    xdg: &ResolvedXdgDirs,
    name: &str,
    dry_run: bool,
    no_restart: bool,
) -> Result<()> {
    if dry_run {
        println!("podbox update: pull/rebuild and restart {name}");
        println!("  build::run(config, env, xdg, dry_run: true, rebuild: true)");
        if !no_restart {
            if config.lifecycle.quadlet && systemd::is_available() {
                println!("  systemctl --user restart {name}");
            } else {
                println!("  podman restart {name}");
            }
        }
        return Ok(());
    }

    println!("Updating '{name}'...");

    podbox::build::run(config, env, xdg, false, true)?;

    if no_restart {
        println!("Image updated. Restart skipped (--no-restart).");
        return Ok(());
    }

    println!("Restarting container...");
    if config.lifecycle.quadlet && systemd::is_available() {
        systemd::reset_failed(name)?;
        systemd::restart_unit(name)?;
    } else {
        let args = podbox::process::args(&["restart", name]);
        podbox::process::spawn_interactive("podman", &args)?;
    }

    println!("Update complete.");
    let _ = podbox::history::record(name, "update", "");
    Ok(())
}

/// Remove a container and optionally its home directory.
pub fn run_remove(
    config: &Config,
    name: &str,
    dry_run: bool,
    all: bool,
    force: bool,
    remove_config: bool,
) -> Result<()> {
    if dry_run {
        println!("podman stop {name}");
        println!("podman rm -f {name}");
        if config.lifecycle.quadlet {
            println!("quadlet_install::uninstall({name})");
            println!("systemctl --user reset-failed {name}.service");
        }
        if remove_config {
            let p = podbox::config::find_config_path(name)
                .unwrap_or_else(|| podbox::config::profiles_dir().join(format!("{name}.toml")));
            println!("rm {}", p.display());
        }
        if all {
            println!("rm -rf {}", config.container.home.display());
        }
        return Ok(());
    }

    if !force {
        print!("Remove container '{name}'? [y/N] ");
        std::io::stdout().flush()?;
        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;
        if !input.trim().eq_ignore_ascii_case("y") {
            println!("Cancelled.");
            return Ok(());
        }
    }

    // 1. Stop and remove the podman container (best-effort)
    if let Err(e) = podbox::process::run_piped("podman", &podbox::process::args(&["stop", name])) {
        eprintln!("Warning: failed to stop container '{name}': {e}");
    }
    if let Err(e) =
        podbox::process::run_piped("podman", &podbox::process::args(&["rm", "-f", name]))
    {
        eprintln!("Warning: failed to remove container '{name}': {e}");
    }

    // 2. Clean up Quadlet files and systemd units
    if config.lifecycle.quadlet {
        if let Err(e) = systemd::stop_unit(name) {
            eprintln!("Warning: failed to stop systemd unit '{name}': {e}");
        }
        if let Err(e) = podbox::quadlet_install::uninstall(name) {
            eprintln!("Warning: failed to uninstall Quadlet files for '{name}': {e}");
        }
        if let Err(e) = systemd::reset_failed(name) {
            eprintln!("Warning: failed to reset failed state for '{name}': {e}");
        }
    }

    // 3. Optionally delete the TOML definition
    if remove_config {
        if let Some(config_path) = podbox::config::find_config_path(name) {
            std::fs::remove_file(&config_path)?;
            println!("Config '{}' removed.", config_path.display());
        }
    }

    println!("Container '{name}' removed.");
    let _ = podbox::history::record(name, "remove", "container removed");

    // 4. Optionally remove the home directory
    if all {
        let home = &config.container.home;
        if home.exists() {
            if !force {
                print!("Remove home directory '{}'? [y/N] ", home.display());
                std::io::stdout().flush()?;
                let mut input = String::new();
                std::io::stdin().read_line(&mut input)?;
                if !input.trim().eq_ignore_ascii_case("y") {
                    println!("Home directory kept.");
                    return Ok(());
                }
            }
            let status = std::process::Command::new("podman")
                .args(["unshare", "rm", "-rf"])
                .arg(home)
                .status()
                .context("failed to run podman unshare")?;
            if !status.success() {
                anyhow::bail!(
                    "Failed to delete home directory '{}' via podman unshare (sub-UID files need rootless namespace)",
                    home.display()
                );
            }
            println!("Home directory '{}' removed.", home.display());
        }
    }

    Ok(())
}

/// Find orphaned Quadlet files that have no matching TOML config.
///
/// A container is stale only when its `.container` Quadlet file exists on
/// disk but the corresponding `~/.config/podbox/{profiles/,}<name>.toml` has
/// been deleted. Stopped or failed containers with a config are never stale.
fn find_stale_containers() -> Vec<String> {
    let mut stale = Vec::new();

    for name in podbox::quadlet_install::list_installed_names() {
        if podbox::config::find_config_path(&name).is_none() {
            stale.push(name);
        }
    }

    stale
}

/// Remove orphaned Quadlet files (those whose TOML config has been deleted).
///
/// Only containers with no matching TOML config are considered stale.
/// Stopped or failed containers with an existing config are never touched.
pub fn run_remove_stale(dry_run: bool, force: bool) -> Result<()> {
    let stale = find_stale_containers();
    if stale.is_empty() {
        println!("No stale containers found.");
        return Ok(());
    }

    println!("Orphaned Quadlet runtimes found:");
    for name in &stale {
        println!("  {name}  (no config TOML)");
    }

    if !force {
        print!("Remove these? [y/N] ");
        std::io::stdout().flush()?;
        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;
        if !input.trim().eq_ignore_ascii_case("y") {
            println!("Cancelled.");
            return Ok(());
        }
    }

    for name in &stale {
        if dry_run {
            println!("Would remove: {name}");
            continue;
        }

        if let Err(e) = podbox::quadlet_install::uninstall(name) {
            eprintln!("Warning: failed to uninstall '{name}': {e}");
        }

        if let Err(e) =
            podbox::process::run_piped("podman", &podbox::process::args(&["rm", "-f", name]))
        {
            eprintln!("Warning: failed to remove container '{name}': {e}");
        }

        if let Err(e) = systemd::reset_failed(name) {
            eprintln!("Warning: failed to reset failed state for '{name}': {e}");
        }

        println!("✓ Stale runtime files for '{name}' removed");
    }

    Ok(())
}