//! Implements `limb prune`. Drops admin entries for missing worktrees.

use anyhow::Result;

use crate::cli::PruneArgs;
use crate::context::Context;
use crate::git;

/// Runs `limb prune`.
///
/// Thin wrapper over `git worktree prune`, forwarding `--dry-run`,
/// `--verbose`, and `--expire`. Use when you've moved or deleted
/// worktrees outside of `limb`.
///
/// # Errors
///
/// Returns an error if the git invocation fails.
pub fn run(ctx: &Context, args: &PruneArgs) -> Result<()> {
    let repo = ctx.repo()?;
    let mut cmd: Vec<String> = vec!["worktree".into(), "prune".into()];
    if args.dry_run {
        cmd.push("--dry-run".into());
    }
    if args.report {
        cmd.push("--verbose".into());
    }
    if let Some(expire) = args.expire.as_deref() {
        cmd.push("--expire".into());
        cmd.push(expire.into());
    }
    let refs: Vec<&str> = cmd.iter().map(String::as_str).collect();
    git::run(&repo, &refs)?;
    if !ctx.json && !ctx.quiet && !args.report && !args.dry_run {
        let ok = crate::style::OK;
        anstream::eprintln!("{ok}✓{ok:#} pruned stale worktree admin entries");
    }
    Ok(())
}
