//! Implements `limb repair`. Fixes worktree admin files after manual moves.

use anyhow::Result;

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

/// Runs `limb repair`.
///
/// Thin wrapper over `git worktree repair [<path>...]`. Use after you've
/// moved `.bare/` or a worktree directory by hand and git has lost track
/// of the link between them. Without paths, repairs every worktree
/// attached to the current repo.
///
/// # Errors
///
/// Returns an error if the git invocation fails.
pub fn run(ctx: &Context, args: &RepairArgs) -> Result<()> {
    let repo = ctx.repo()?;
    let mut cmd: Vec<String> = vec!["worktree".into(), "repair".into()];
    for p in &args.paths {
        cmd.push(p.to_string_lossy().into_owned());
    }
    let refs: Vec<&str> = cmd.iter().map(String::as_str).collect();
    git::run(&repo, &refs)?;
    if !ctx.json && !ctx.quiet {
        let ok = crate::style::OK;
        anstream::eprintln!("{ok}✓{ok:#} repaired worktree administrative files");
    }
    Ok(())
}
