use anyhow::Context;
use worktrunk::git::Repository;
use worktrunk::shell_exec::Cmd;
pub fn step_diff(target: Option<&str>, extra_args: &[String]) -> anyhow::Result<()> {
let repo = Repository::current()?;
let wt = repo.current_worktree();
let integration_target = repo.require_target_ref(target)?;
let merge_base = repo
.merge_base("HEAD", &integration_target)?
.context("No common ancestor with target branch")?;
let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());
let worktree_root = wt.root()?;
let real_index = wt.git_dir()?.join("index");
let temp_index = tempfile::NamedTempFile::new().context("Failed to create temporary index")?;
let temp_index_path = temp_index
.path()
.to_str()
.context("Temporary index path is not valid UTF-8")?;
std::fs::copy(&real_index, temp_index.path()).context("Failed to copy index file")?;
Cmd::new("git")
.args(["add", "--intent-to-add", "."])
.current_dir(&worktree_root)
.context(¤t_branch)
.env("GIT_INDEX_FILE", temp_index_path)
.run()
.context("Failed to register untracked files")?;
let mut diff_args = vec!["diff".to_string(), merge_base];
diff_args.extend_from_slice(extra_args);
Cmd::new("git")
.args(&diff_args)
.current_dir(&worktree_root)
.context(¤t_branch)
.env("GIT_INDEX_FILE", temp_index_path)
.stream()?;
Ok(())
}