Debian Codegraph @

cli/src/commands/split.rs

raw
1 // Copyright 2020 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 use std::collections::HashMap;
15 use std::io::Write as _;
16
17 use clap_complete::ArgValueCandidates;
18 use clap_complete::ArgValueCompleter;
19 use jj_lib::backend::CommitId;
20 use jj_lib::commit::Commit;
21 use jj_lib::matchers::Matcher;
22 use jj_lib::merge::Diff;
23 use jj_lib::merge::Merge;
24 use jj_lib::merged_tree::MergedTree;
25 use jj_lib::object_id::ObjectId as _;
26 use jj_lib::rewrite::CommitRewriter;
27 use jj_lib::rewrite::CommitWithSelection;
28 use jj_lib::rewrite::EmptyBehavior;
29 use jj_lib::rewrite::MoveCommitsLocation;
30 use jj_lib::rewrite::MoveCommitsTarget;
31 use jj_lib::rewrite::RebaseOptions;
32 use jj_lib::rewrite::RebasedCommit;
33 use jj_lib::rewrite::RewriteRefsOptions;
34 use jj_lib::rewrite::move_commits;
35 use tracing::instrument;
36
37 use crate::cli_util::CommandHelper;
38 use crate::cli_util::DiffSelector;
39 use crate::cli_util::RevisionArg;
40 use crate::cli_util::WorkspaceCommandHelper;
41 use crate::cli_util::WorkspaceCommandTransaction;
42 use crate::cli_util::compute_commit_location;
43 use crate::cli_util::print_unmatched_explicit_paths;
44 use crate::command_error::CommandError;
45 use crate::complete;
46 use crate::description_util::add_trailers;
47 use crate::description_util::description_template;
48 use crate::description_util::edit_description;
49 use crate::description_util::join_message_paragraphs;
50 use crate::ui::Ui;
51
52 /// Split a revision in two
53 ///
54 /// Starts a [diff editor] on the changes in the revision. Edit the right side
55 /// of the diff until it has the content you want in the first commit. Once you
56 /// close the editor, your revision will be split into two commits.
57 ///
58 /// [diff editor]:
59 /// https://docs.jj-vcs.dev/latest/config/#editing-diffs
60 ///
61 /// By default, the selected changes stay in the original commit, and the
62 /// remaining changes go into a new child commit:
63 ///
64 /// ```text
65 /// L L'
66 /// | |
67 /// K (split) => K" (remaining)
68 /// | |
69 /// J K' (selected)
70 /// |
71 /// J
72 /// ```
73 ///
74 /// With `--parallel/-p`, the two parts become sibling commits instead of
75 /// parent and child:
76 ///
77 /// ```text
78 /// L'
79 /// L / \
80 /// | K' | (selected)
81 /// K (split) => | K" (remaining)
82 /// | \ /
83 /// J J
84 /// ```
85 ///
86 /// With `-o`, `-A`, or `-B`, the selected changes are extracted into a new
87 /// commit at the specified location, while the remaining changes stay in place:
88 ///
89 /// ```text
90 /// M M'
91 /// | |
92 /// L L'
93 /// | |
94 /// K (split) => K' (remaining, stays here)
95 /// | |
96 /// J J'
97 /// |
98 /// K" (selected, inserted before J with -B J)
99 /// ```
100 ///
101 /// If the change you split had a description, you will be asked to enter a
102 /// change description for each commit. If the change did not have a
103 /// description, the second commit will not get a description, and you will be
104 /// asked for a description only for the first commit.
105 ///
106 /// Splitting an empty commit is not supported because the same effect can be
107 /// achieved with `jj new`.
108 #[derive(clap::Args, Clone, Debug)]
109 #[command(verbatim_doc_comment)]
110 pub(crate) struct SplitArgs {
111 /// Interactively choose which parts to split
112 ///
113 /// This is the default if no filesets are provided.
114 #[arg(long, short)]
115 interactive: bool,
116
117 /// Specify diff editor to be used (implies --interactive)
118 #[arg(long, value_name = "NAME")]
119 #[arg(add = ArgValueCandidates::new(complete::diff_editors))]
120 tool: Option<String>,
121
122 /// The revision to split
123 #[arg(long, short, default_value = "@", value_name = "REVSET")]
124 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
125 revision: RevisionArg,
126
127 /// The revision(s) to rebase the selected changes onto (can be repeated to
128 /// create a merge commit)
129 ///
130 /// Extracts the selected changes into a new commit based on the given
131 /// revision(s). The remaining changes stay in the original commit's
132 /// location.
133 #[arg(
134 long,
135 visible_alias = "destination",
136 short,
137 visible_short_alias = 'd',
138 conflicts_with = "parallel",
139 value_name = "REVSETS"
140 )]
141 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
142 onto: Option<Vec<RevisionArg>>,
143
144 /// The revision(s) to insert after (can be repeated to create a merge
145 /// commit)
146 ///
147 /// Extracts the selected changes into a new commit inserted after the
148 /// given revision(s). The remaining changes stay in the original commit's
149 /// location.
150 #[arg(
151 long,
152 short = 'A',
153 visible_alias = "after",
154 conflicts_with_all = ["onto", "parallel"],
155 value_name = "REVSETS"
156 )]
157 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
158 insert_after: Option<Vec<RevisionArg>>,
159
160 /// The revision(s) to insert before (can be repeated to create a merge
161 /// commit)
162 ///
163 /// Extracts the selected changes into a new commit inserted before the
164 /// given revision(s). The remaining changes stay in the original commit's
165 /// location.
166 #[arg(
167 long,
168 short = 'B',
169 visible_alias = "before",
170 conflicts_with_all = ["onto", "parallel"],
171 value_name = "REVSETS"
172 )]
173 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
174 insert_before: Option<Vec<RevisionArg>>,
175
176 /// The change description to use for the selected changes (don't open
177 /// editor)
178 ///
179 /// Sets the description for the revision containing the selected changes.
180 /// The other revision will keep its original description, if any.
181 #[arg(long = "message", short, value_name = "MESSAGE")]
182 message_paragraphs: Option<Vec<String>>,
183
184 /// Open an editor to edit the change description(s)
185 ///
186 /// Forces an editor to open when using `--message` to allow the message to
187 /// be edited afterward.
188 #[arg(long)]
189 editor: bool,
190
191 /// Split the revision into two parallel revisions instead of a parent and
192 /// child
193 #[arg(long, short)]
194 parallel: bool,
195
196 /// Files matching any of these filesets are put in the selected changes
197 #[arg(value_name = "FILESETS", value_hint = clap::ValueHint::AnyPath)]
198 #[arg(add = ArgValueCompleter::new(complete::modified_revision_files))]
199 paths: Vec<String>,
200 }
201
202 impl SplitArgs {
203 /// Resolves the raw SplitArgs into the components necessary to run the
204 /// command. Returns an error if the command cannot proceed.
205 async fn resolve(
206 &self,
207 ui: &Ui,
208 workspace_command: &WorkspaceCommandHelper,
209 ) -> Result<ResolvedSplitArgs, CommandError> {
210 let target_commit = workspace_command
211 .resolve_single_rev(ui, &self.revision)
212 .await?;
213 workspace_command
214 .check_rewritable([target_commit.id()])
215 .await?;
216 let repo = workspace_command.repo();
217 let fileset_expression = workspace_command.parse_file_patterns(ui, &self.paths)?;
218 let matcher = fileset_expression.to_matcher();
219 let diff_selector = workspace_command.diff_selector(
220 ui,
221 self.tool.as_deref(),
222 self.interactive || self.paths.is_empty(),
223 )?;
224 let use_move_flags =
225 self.onto.is_some() || self.insert_after.is_some() || self.insert_before.is_some();
226 let (new_parent_ids, new_child_ids) = if use_move_flags {
227 compute_commit_location(
228 ui,
229 workspace_command,
230 self.onto.as_deref(),
231 self.insert_after.as_deref(),
232 self.insert_before.as_deref(),
233 "split-out commit",
234 )
235 .await?
236 } else {
237 Default::default()
238 };
239
240 print_unmatched_explicit_paths(
241 ui,
242 workspace_command,
243 &fileset_expression,
244 [
245 // We check the parent commit to account for deleted files.
246 &target_commit.parent_tree(repo.as_ref()).await?,
247 &target_commit.tree(),
248 ],
249 )
250 .await?;
251
252 Ok(ResolvedSplitArgs {
253 target_commit,
254 matcher,
255 diff_selector,
256 parallel: self.parallel,
257 use_move_flags,
258 new_parent_ids,
259 new_child_ids,
260 })
261 }
262 }
263
264 struct ResolvedSplitArgs {
265 target_commit: Commit,
266 matcher: Box<dyn Matcher>,
267 diff_selector: DiffSelector,
268 parallel: bool,
269 use_move_flags: bool,
270 new_parent_ids: Vec<CommitId>,
271 new_child_ids: Vec<CommitId>,
272 }
273
274 #[instrument(skip_all)]
275 pub(crate) async fn cmd_split(
276 ui: &mut Ui,
277 command: &CommandHelper,
278 args: &SplitArgs,
279 ) -> Result<(), CommandError> {
280 let mut workspace_command = command.workspace_helper(ui).await?;
281 let ResolvedSplitArgs {
282 target_commit,
283 matcher,
284 diff_selector,
285 parallel,
286 use_move_flags,
287 new_parent_ids,
288 new_child_ids,
289 } = args.resolve(ui, &workspace_command).await?;
290 let text_editor = workspace_command.text_editor()?;
291 let mut tx = workspace_command.start_transaction();
292
293 // Prompt the user to select the changes they want for the first commit.
294 let target = select_diff(ui, &tx, &target_commit, &matcher, &diff_selector).await?;
295
296 // Create the first commit, which includes the changes selected by the user.
297 let first_commit = {
298 let mut commit_builder = tx.repo_mut().rewrite_commit(&target.commit).detach();
299 commit_builder.set_tree(target.selected_tree.clone());
300 if use_move_flags {
301 commit_builder.clear_rewrite_source();
302 // Generate a new change id so that the commit being split doesn't
303 // become divergent.
304 commit_builder.generate_new_change_id();
305 }
306 let use_editor = args.message_paragraphs.is_none() || args.editor;
307 let description = match &args.message_paragraphs {
308 Some(paragraphs) => join_message_paragraphs(paragraphs),
309 None => commit_builder.description().to_owned(),
310 };
311 // The first trailer would become the first line of the description.
312 // Also, a commit with no description is treated in a special way in
313 // jujutsu: it can be discarded as soon as it's no longer the working
314 // copy. Adding a trailer to an empty description would break that
315 // logic.
316 let description = if !description.is_empty() || use_editor {
317 commit_builder.set_description(description);
318 add_trailers(ui, &tx, &commit_builder).await?
319 } else {
320 description
321 };
322 let description = if use_editor {
323 commit_builder.set_description(description);
324 let temp_commit = commit_builder.write_hidden().await?;
325 let intro = "Enter a description for the selected changes.";
326 let template = description_template(ui, &tx, intro, &temp_commit)?;
327 edit_description(&text_editor, &template)?
328 } else {
329 description
330 };
331 commit_builder.set_description(description);
332 commit_builder.write(tx.repo_mut()).await?
333 };
334
335 // Create the second commit, which includes everything the user didn't
336 // select.
337 let second_commit = {
338 let target_tree = target.commit.tree();
339 let new_tree = if parallel {
340 // Merge the original commit tree with its parent using the tree
341 // containing the user selected changes as the base for the merge.
342 // This results in a tree with the changes the user didn't select.
343 let selected_diff = target
344 .diff_with_labels(
345 "parents of split revision",
346 "selected changes for split",
347 "split revision",
348 )
349 .await?;
350 MergedTree::merge(Merge::from_diffs(
351 (
352 target_tree,
353 format!("split revision ({})", target.commit.conflict_label()),
354 ),
355 [selected_diff.invert()],
356 ))
357 .await?
358 } else {
359 target_tree
360 };
361 let parents = if parallel {
362 target.commit.parent_ids().to_vec()
363 } else {
364 vec![first_commit.id().clone()]
365 };
366 let mut commit_builder = tx.repo_mut().rewrite_commit(&target.commit).detach();
367 commit_builder.set_parents(parents).set_tree(new_tree);
368 let mut show_editor = args.editor;
369 if !use_move_flags {
370 commit_builder.clear_rewrite_source();
371 // Generate a new change id so that the commit being split doesn't
372 // become divergent.
373 commit_builder.generate_new_change_id();
374 }
375 let description = if target.commit.description().is_empty() {
376 // If there was no description before, don't ask for one for the
377 // second commit.
378 "".to_string()
379 } else {
380 show_editor = show_editor || args.message_paragraphs.is_none();
381 // Just keep the original message unchanged
382 commit_builder.description().to_owned()
383 };
384 let description = if show_editor {
385 let new_description = add_trailers(ui, &tx, &commit_builder).await?;
386 commit_builder.set_description(new_description);
387 let temp_commit = commit_builder.write_hidden().await?;
388 let intro = "Enter a description for the remaining changes.";
389 let template = description_template(ui, &tx, intro, &temp_commit)?;
390 edit_description(&text_editor, &template)?
391 } else {
392 description
393 };
394 commit_builder.set_description(description);
395 commit_builder.write(tx.repo_mut()).await?
396 };
397
398 let (first_commit, second_commit, num_rebased) = if use_move_flags {
399 move_first_commit(
400 &mut tx,
401 &target,
402 first_commit,
403 second_commit,
404 new_parent_ids,
405 new_child_ids,
406 )
407 .await?
408 } else {
409 rewrite_descendants(&mut tx, &target, first_commit, second_commit, parallel).await?
410 };
411 if let Some(mut formatter) = ui.status_formatter() {
412 if num_rebased > 0 {
413 writeln!(formatter, "Rebased {num_rebased} descendant commits.")?;
414 }
415 write!(formatter, "Selected changes : ")?;
416 tx.write_commit_summary(formatter.as_mut(), &first_commit)?;
417 write!(formatter, "\nRemaining changes: ")?;
418 tx.write_commit_summary(formatter.as_mut(), &second_commit)?;
419 writeln!(formatter)?;
420 }
421 tx.finish(ui, format!("split commit {}", target.commit.id().hex()))
422 .await?;
423 Ok(())
424 }
425
426 async fn move_first_commit(
427 tx: &mut WorkspaceCommandTransaction<'_>,
428 target: &CommitWithSelection,
429 mut first_commit: Commit,
430 mut second_commit: Commit,
431 new_parent_ids: Vec<CommitId>,
432 new_child_ids: Vec<CommitId>,
433 ) -> Result<(Commit, Commit, usize), CommandError> {
434 let mut rewritten_commits: HashMap<CommitId, CommitId> = HashMap::new();
435 rewritten_commits.insert(target.commit.id().clone(), second_commit.id().clone());
436 tx.repo_mut()
437 .transform_descendants(
438 vec![target.commit.id().clone()],
439 async |rewriter: CommitRewriter<'_>| {
440 let old_commit_id = rewriter.old_commit().id().clone();
441 let new_commit = rewriter.rebase().await?.write().await?;
442 rewritten_commits.insert(old_commit_id, new_commit.id().clone());
443 Ok(())
444 },
445 )
446 .await?;
447
448 let new_parent_ids: Vec<_> = new_parent_ids
449 .iter()
450 .map(|commit_id| rewritten_commits.get(commit_id).unwrap_or(commit_id))
451 .cloned()
452 .collect();
453 let new_child_ids: Vec<_> = new_child_ids
454 .iter()
455 .map(|commit_id| rewritten_commits.get(commit_id).unwrap_or(commit_id))
456 .cloned()
457 .collect();
458 let stats = move_commits(
459 tx.repo_mut(),
460 &MoveCommitsLocation {
461 new_parent_ids,
462 new_child_ids,
463 target: MoveCommitsTarget::Commits(vec![first_commit.id().clone()]),
464 },
465 &RebaseOptions {
466 empty: EmptyBehavior::Keep,
467 rewrite_refs: RewriteRefsOptions {
468 delete_abandoned_bookmarks: false,
469 },
470 simplify_ancestor_merge: false,
471 },
472 )
473 .await?;
474
475 // 1 for the transformation of the original commit to the second commit
476 // that was inserted in rewritten_commits
477 let mut num_new_rebased = 1;
478 if let Some(RebasedCommit::Rewritten(commit)) = stats.rebased_commits.get(first_commit.id()) {
479 first_commit = commit.clone();
480 num_new_rebased += 1;
481 }
482 if let Some(RebasedCommit::Rewritten(commit)) = stats.rebased_commits.get(second_commit.id()) {
483 second_commit = commit.clone();
484 }
485
486 let num_rebased = rewritten_commits.len() + stats.rebased_commits.len()
487 // don't count the commit generated by the split in the rebased commits
488 - num_new_rebased
489 // only count once a commit that may have been rewritten twice in the process
490 - rewritten_commits
491 .iter()
492 .filter(|(_, rewritten)| stats.rebased_commits.contains_key(rewritten))
493 .count();
494
495 Ok((first_commit, second_commit, num_rebased))
496 }
497
498 async fn rewrite_descendants(
499 tx: &mut WorkspaceCommandTransaction<'_>,
500 target: &CommitWithSelection,
501 first_commit: Commit,
502 second_commit: Commit,
503 parallel: bool,
504 ) -> Result<(Commit, Commit, usize), CommandError> {
505 let legacy_bookmark_behavior = tx.settings().get_bool("split.legacy-bookmark-behavior")?;
506 if legacy_bookmark_behavior {
507 // Mark the commit being split as rewritten to the second commit. This
508 // moves any bookmarks pointing to the target commit to the second
509 // commit.
510 tx.repo_mut()
511 .set_rewritten_commit(target.commit.id().clone(), second_commit.id().clone());
512 }
513 let mut num_rebased = 0;
514 tx.repo_mut()
515 .transform_descendants(
516 vec![target.commit.id().clone()],
517 async |mut rewriter: CommitRewriter<'_>| {
518 num_rebased += 1;
519 if parallel && legacy_bookmark_behavior {
520 // The old_parent is the second commit due to the rewrite above.
521 rewriter.replace_parent(
522 second_commit.id(),
523 [first_commit.id(), second_commit.id()],
524 );
525 } else if parallel {
526 rewriter
527 .replace_parent(first_commit.id(), [first_commit.id(), second_commit.id()]);
528 } else {
529 rewriter.replace_parent(first_commit.id(), [second_commit.id()]);
530 }
531 rewriter.rebase().await?.write().await?;
532 Ok(())
533 },
534 )
535 .await?;
536 // Move the working copy commit (@) to the second commit for any workspaces
537 // where the target commit is the working copy commit.
538 for (name, working_copy_commit) in tx.base_repo().clone().view().wc_commit_ids() {
539 if working_copy_commit == target.commit.id() {
540 tx.repo_mut().edit(name.clone(), &second_commit).await?;
541 }
542 }
543
544 Ok((first_commit, second_commit, num_rebased))
545 }
546
547 /// Prompts the user to select the content they want in the first commit and
548 /// returns the target commit and the tree corresponding to the selection.
549 async fn select_diff(
550 ui: &Ui,
551 tx: &WorkspaceCommandTransaction<'_>,
552 target_commit: &Commit,
553 matcher: &dyn Matcher,
554 diff_selector: &DiffSelector,
555 ) -> Result<CommitWithSelection, CommandError> {
556 let format_instructions = || {
557 format!(
558 "\
559 You are splitting a commit into two: {}
560
561 The diff initially shows the changes in the commit you're splitting.
562
563 Adjust the right side until it shows the contents you want to split into the
564 new commit.
565 The changes that are not selected will replace the original commit.
566 ",
567 tx.format_commit_summary(target_commit)
568 )
569 };
570 let parent_tree = target_commit.parent_tree(tx.repo()).await?;
571 let selected_tree = diff_selector
572 .select(
573 ui,
574 Diff::new(&parent_tree, &target_commit.tree()),
575 Diff::new(
576 target_commit.parents_conflict_label().await?,
577 target_commit.conflict_label(),
578 ),
579 matcher,
580 format_instructions,
581 )
582 .await?;
583 let selection = CommitWithSelection {
584 commit: target_commit.clone(),
585 selected_tree,
586 parent_tree,
587 };
588 if selection.is_full_selection() {
589 writeln!(
590 ui.warning_default(),
591 "All changes have been selected, so the original revision will become empty."
592 )?;
593 } else if selection.is_empty_selection() {
594 writeln!(
595 ui.warning_default(),
596 "No changes have been selected, so the new revision will be empty."
597 )?;
598 }
599
600 Ok(selection)
601 }