use std::io::Write;
use jj_lib::matchers::EverythingMatcher;
use jj_lib::object_id::ObjectId;
use jj_lib::rewrite::merge_commit_trees;
use tracing::instrument;
use crate::cli_util::{CommandError, CommandHelper, RevisionArg};
use crate::ui::Ui;
#[derive(clap::Args, Clone, Debug)]
pub(crate) struct DiffeditArgs {
#[arg(long, short)]
revision: Option<RevisionArg>,
#[arg(long, conflicts_with = "revision")]
from: Option<RevisionArg>,
#[arg(long, conflicts_with = "revision")]
to: Option<RevisionArg>,
}
#[instrument(skip_all)]
pub(crate) fn cmd_diffedit(
ui: &mut Ui,
command: &CommandHelper,
args: &DiffeditArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let (target_commit, base_commits, diff_description);
if args.from.is_some() || args.to.is_some() {
target_commit =
workspace_command.resolve_single_rev(args.to.as_deref().unwrap_or("@"), ui)?;
base_commits =
vec![workspace_command.resolve_single_rev(args.from.as_deref().unwrap_or("@"), ui)?];
diff_description = format!(
"The diff initially shows the commit's changes relative to:\n{}",
workspace_command.format_commit_summary(&base_commits[0])
);
} else {
target_commit =
workspace_command.resolve_single_rev(args.revision.as_deref().unwrap_or("@"), ui)?;
base_commits = target_commit.parents();
diff_description = "The diff initially shows the commit's changes.".to_string();
};
workspace_command.check_rewritable([&target_commit])?;
let mut tx = workspace_command.start_transaction();
let instructions = format!(
"\
You are editing changes in: {}
{diff_description}
Adjust the right side until it shows the contents you want. If you
don't make any changes, then the operation will be aborted.",
tx.format_commit_summary(&target_commit),
);
let base_tree = merge_commit_trees(tx.repo(), base_commits.as_slice())?;
let tree = target_commit.tree()?;
let tree_id = tx.edit_diff(ui, &base_tree, &tree, &EverythingMatcher, &instructions)?;
if tree_id == *target_commit.tree_id() {
writeln!(ui.stderr(), "Nothing changed.")?;
} else {
let mut_repo = tx.mut_repo();
let new_commit = mut_repo
.rewrite_commit(command.settings(), &target_commit)
.set_tree_id(tree_id)
.write()?;
let num_rebased = tx.mut_repo().rebase_descendants(command.settings())?;
write!(ui.stderr(), "Created ")?;
tx.write_commit_summary(ui.stderr_formatter().as_mut(), &new_commit)?;
writeln!(ui.stderr())?;
if num_rebased > 0 {
writeln!(ui.stderr(), "Rebased {num_rebased} descendant commits")?;
}
tx.finish(ui, format!("edit commit {}", target_commit.id().hex()))?;
}
Ok(())
}