use jj_lib::object_id::ObjectId;
use jj_lib::repo::Repo;
use jj_lib::rewrite::merge_commit_trees;
use tracing::instrument;
use crate::cli_util::{join_message_paragraphs, user_error, CommandError, CommandHelper};
use crate::description_util::{description_template_for_commit, edit_description};
use crate::ui::Ui;
#[derive(clap::Args, Clone, Debug)]
#[command(visible_aliases=&["ci"])]
pub(crate) struct CommitArgs {
#[arg(short, long)]
interactive: bool,
#[arg(long = "message", short, value_name = "MESSAGE")]
message_paragraphs: Vec<String>,
#[arg(value_hint = clap::ValueHint::AnyPath)]
paths: Vec<String>,
}
#[instrument(skip_all)]
pub(crate) fn cmd_commit(
ui: &mut Ui,
command: &CommandHelper,
args: &CommitArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let commit_id = workspace_command
.get_wc_commit_id()
.ok_or_else(|| user_error("This command requires a working copy"))?;
let commit = workspace_command.repo().store().get_commit(commit_id)?;
let matcher = workspace_command.matcher_from_values(&args.paths)?;
let mut tx = workspace_command.start_transaction();
let base_tree = merge_commit_trees(tx.repo(), &commit.parents())?;
let instructions = format!(
"\
You are splitting the working-copy commit: {}
The diff initially shows all changes. Adjust the right side until it shows the
contents you want for the first commit. The remainder will be included in the
new working-copy commit.
",
tx.format_commit_summary(&commit)
);
let tree_id = tx.select_diff(
ui,
&base_tree,
&commit.tree()?,
matcher.as_ref(),
&instructions,
args.interactive,
)?;
let middle_tree = tx.repo().store().get_root_tree(&tree_id)?;
if !args.paths.is_empty() && middle_tree.id() == base_tree.id() {
writeln!(
ui.warning(),
"The given paths do not match any file: {}",
args.paths.join(" ")
)?;
}
let template = description_template_for_commit(
ui,
command.settings(),
tx.base_workspace_helper(),
"",
commit.description(),
&base_tree,
&middle_tree,
)?;
let description = if !args.message_paragraphs.is_empty() {
join_message_paragraphs(&args.message_paragraphs)
} else {
edit_description(tx.base_repo(), &template, command.settings())?
};
let new_commit = tx
.mut_repo()
.rewrite_commit(command.settings(), &commit)
.set_tree_id(tree_id)
.set_description(description)
.write()?;
let workspace_ids = tx
.mut_repo()
.view()
.workspaces_for_wc_commit_id(commit.id());
if !workspace_ids.is_empty() {
let new_wc_commit = tx
.mut_repo()
.new_commit(
command.settings(),
vec![new_commit.id().clone()],
commit.tree_id().clone(),
)
.write()?;
for workspace_id in workspace_ids {
tx.mut_repo().edit(workspace_id, &new_wc_commit).unwrap();
}
}
tx.finish(ui, format!("commit {}", commit.id().hex()))?;
Ok(())
}