Debian Codegraph @

cli/src/commands/rebase.rs

raw
1 // Copyright 2020-2023 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
15 use std::io::Write as _;
16 use std::sync::Arc;
17
18 use clap::ArgGroup;
19 use clap_complete::ArgValueCompleter;
20 use futures::TryStreamExt as _;
21 use jj_lib::backend::CommitId;
22 use jj_lib::commit::Commit;
23 use jj_lib::object_id::ObjectId as _;
24 use jj_lib::repo::ReadonlyRepo;
25 use jj_lib::repo::Repo as _;
26 use jj_lib::revset::RevsetExpression;
27 use jj_lib::rewrite::EmptyBehavior;
28 use jj_lib::rewrite::MoveCommitsLocation;
29 use jj_lib::rewrite::MoveCommitsStats;
30 use jj_lib::rewrite::MoveCommitsTarget;
31 use jj_lib::rewrite::RebaseOptions;
32 use jj_lib::rewrite::RewriteRefsOptions;
33 use jj_lib::rewrite::compute_move_commits;
34 use jj_lib::rewrite::find_duplicate_divergent_commits;
35 use tracing::instrument;
36
37 use crate::cli_util::CommandHelper;
38 use crate::cli_util::RevisionArg;
39 use crate::cli_util::WorkspaceCommandHelper;
40 use crate::cli_util::compute_commit_location;
41 use crate::cli_util::print_updated_commits;
42 use crate::cli_util::short_commit_hash;
43 use crate::command_error::CommandError;
44 use crate::command_error::user_error;
45 use crate::complete;
46 use crate::ui::Ui;
47
48 /// Move revisions to different parent(s)
49 ///
50 /// This command moves revisions to different parent(s) while preserving the
51 /// changes (diff) in the revisions.
52 ///
53 /// There are three different ways of specifying which revisions to rebase:
54 ///
55 /// * `--source/-s` to rebase a revision and its descendants
56 /// * `--branch/-b` to rebase a whole branch, relative to the destination
57 /// * `--revisions/-r` to rebase the specified revisions without their
58 /// descendants
59 ///
60 /// If no option is specified, it defaults to `-b @`.
61 ///
62 /// There are three different ways of specifying where the revisions should be
63 /// rebased to:
64 ///
65 /// * `--onto/-o` to rebase the revisions onto the specified targets
66 /// * `--insert-after/-A` to rebase the revisions onto the specified targets and
67 /// to rebase the targets' descendants onto the rebased revisions
68 /// * `--insert-before/-B` to rebase the revisions onto the specified targets'
69 /// parents and to rebase the targets and their descendants onto the rebased
70 /// revisions
71 ///
72 /// See the sections below for details about the different ways of specifying
73 /// which revisions to rebase where.
74 ///
75 /// If a working-copy revision gets abandoned, it will be given a new, empty
76 /// revision. This is true in general; it is not specific to this command.
77 ///
78 /// ### Specifying which revisions to rebase
79 ///
80 /// With `--source/-s`, the command rebases the specified revision and its
81 /// descendants to the destination. For example, `jj rebase -s M -o O` would
82 /// transform your history like this (letters followed by an apostrophe are
83 /// post-rebase versions):
84 ///
85 /// ```text
86 /// O N'
87 /// | |
88 /// | N M'
89 /// | | |
90 /// | M O
91 /// | | => |
92 /// | | L | L
93 /// | |/ | |
94 /// | K | K
95 /// |/ |/
96 /// J J
97 /// ```
98 ///
99 /// Each revision passed to `-s` will become a direct child of the destination,
100 /// so if you instead run `jj rebase -s M -s N -o O` (or `jj rebase -s 'M|N' -o
101 /// O`) in the example above, then N' would instead be a direct child of O.
102 ///
103 /// With `--branch/-b`, the command rebases the whole "branch" containing the
104 /// specified revision. A "branch" is the set of revisions that includes:
105 ///
106 /// * the specified revision and ancestors that are not also ancestors of the
107 /// destination
108 /// * all descendants of those revisions
109 ///
110 /// In other words, `jj rebase -b X -o Y` rebases revisions in the revset
111 /// `(Y..X)::` (which is equivalent to `jj rebase -s 'roots(Y..X)' -o Y` for a
112 /// single root). For example, either `jj rebase -b L -o O` or `jj rebase -b M
113 /// -o O` would transform your history like this (because `L` and `M` are on the
114 /// same "branch", relative to the destination):
115 ///
116 /// ```text
117 /// O N'
118 /// | |
119 /// | N M'
120 /// | | |
121 /// | M | L'
122 /// | | => |/
123 /// | | L K'
124 /// | |/ |
125 /// | K O
126 /// |/ |
127 /// J J
128 /// ```
129 ///
130 /// With `--revisions/-r`, the command rebases only the specified revisions to
131 /// the destination. Any "hole" left behind will be filled by rebasing
132 /// descendants onto the specified revisions' parent(s). For example,
133 /// `jj rebase -r K -o M` would transform your history like this:
134 ///
135 /// ```text
136 /// M K'
137 /// | |
138 /// | L M
139 /// | | => |
140 /// | K | L'
141 /// |/ |/
142 /// J J
143 /// ```
144 ///
145 /// Multiple revisions can be specified, and any dependencies (graph edges)
146 /// within the set will be preserved. For example, `jj rebase -r 'K|N' -o O`
147 /// would transform your history like this:
148 ///
149 /// ```text
150 /// O N'
151 /// | |
152 /// | N K'
153 /// | | |
154 /// | M O
155 /// | | => |
156 /// | | L | M'
157 /// | |/ |/
158 /// | K | L'
159 /// |/ |/
160 /// J J
161 /// ```
162 ///
163 /// `jj rebase -s X` is similar to `jj rebase -r X::` and will behave the same
164 /// if X is a single revision. However, if X is a set of multiple revisions,
165 /// or if you passed multiple `-s` arguments, then `jj rebase -s` will make each
166 /// of the specified revisions an immediate child of the destination, while
167 /// `jj rebase -r` will preserve dependencies within the set.
168 ///
169 /// Note that you can create a merge revision by repeating the `-o` argument.
170 /// For example, if you realize that revision L actually depends on revision M
171 /// in order to work (in addition to its current parent K), you can run `jj
172 /// rebase -s L -o K -o M`:
173 ///
174 /// ```text
175 /// M L'
176 /// | |\
177 /// | L M |
178 /// | | => | |
179 /// | K | K
180 /// |/ |/
181 /// J J
182 /// ```
183 ///
184 /// ### Specifying where to rebase the revisions
185 ///
186 /// With `--onto/-o`, the command rebases the selected revisions onto the
187 /// targets. Existing descendants of the targets will not be affected. See
188 /// the section above for examples.
189 ///
190 /// With `--insert-after/-A`, the selected revisions will be inserted after the
191 /// targets. This is similar to `-o`, but if the targets have any existing
192 /// descendants, then those will be rebased onto the rebased selected revisions.
193 ///
194 /// For example, `jj rebase -r K -A L` will rewrite history like this:
195 /// ```text
196 /// N N'
197 /// | |
198 /// | M | M'
199 /// |/ |/
200 /// L => K'
201 /// | |
202 /// | K L
203 /// |/ |
204 /// J J
205 /// ```
206 ///
207 /// The `-A` (and `-B`) argument can also be used for reordering revisions. For
208 /// example, `jj rebase -r M -A J` will rewrite history like this:
209 /// ```text
210 /// M L'
211 /// | |
212 /// L K'
213 /// | => |
214 /// K M'
215 /// | |
216 /// J J
217 /// ```
218 ///
219 /// With `--insert-before/-B`, the selected revisions will be inserted before
220 /// the targets. This is achieved by rebasing the selected revisions onto the
221 /// target revisions' parents, and then rebasing the target revisions and their
222 /// descendants onto the rebased revisions.
223 ///
224 /// For example, `jj rebase -r K -B L` will rewrite history like this:
225 /// ```text
226 /// N N'
227 /// | |
228 /// | M | M'
229 /// |/ |/
230 /// L => L'
231 /// | |
232 /// | K K'
233 /// |/ |
234 /// J J
235 /// ```
236 ///
237 /// The `-A` and `-B` arguments can also be combined, which can be useful around
238 /// merges. For example, you can use `jj rebase -r K -A J -B M` to create a new
239 /// merge (but `jj rebase -r M -o L -o K` might be simpler in this particular
240 /// case):
241 /// ```text
242 /// M M'
243 /// | |\
244 /// L L |
245 /// | => | |
246 /// | K | K'
247 /// |/ |/
248 /// J J
249 /// ```
250 ///
251 /// To insert a commit inside an existing merge with `jj rebase -r O -A K -B M`:
252 /// ```text
253 /// O N'
254 /// | |\
255 /// N | M'
256 /// |\ | |\
257 /// | M | O'|
258 /// | | => |/ /
259 /// | L | L
260 /// | | | |
261 /// K | K |
262 /// |/ |/
263 /// J J
264 /// ```
265 #[derive(clap::Args, Clone, Debug)]
266 #[command(verbatim_doc_comment)]
267 #[command(group(ArgGroup::new("to_rebase").args(&["branch", "source", "revisions"])))]
268 pub(crate) struct RebaseArgs {
269 /// Rebase the whole branch relative to destination's ancestors (can be
270 /// repeated)
271 ///
272 /// `jj rebase -b=br -o=dst` is equivalent to `jj rebase '-s=roots(dst..br)'
273 /// -o=dst`.
274 ///
275 /// If none of `-b`, `-s`, or `-r` is provided, then the default is `-b @`.
276 #[arg(long, short, value_name = "REVSETS")]
277 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
278 branch: Vec<RevisionArg>,
279
280 /// Rebase specified revision(s) together with their trees of descendants
281 /// (can be repeated)
282 ///
283 /// Each specified revision will become a direct child of the destination
284 /// revision(s), even if some of the source revisions are descendants
285 /// of others.
286 ///
287 /// If none of `-b`, `-s`, or `-r` is provided, then the default is `-b @`.
288 #[arg(long, short, value_name = "REVSETS")]
289 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
290 source: Vec<RevisionArg>,
291
292 /// Rebase the given revisions, rebasing descendants onto this revision's
293 /// parent(s)
294 ///
295 /// Unlike `-s` or `-b`, you may `jj rebase -r` a revision `A` onto a
296 /// descendant of `A`.
297 ///
298 /// If none of `-b`, `-s`, or `-r` is provided, then the default is `-b @`.
299 #[arg(long = "revision", short, value_name = "REVSETS", alias = "revisions")]
300 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
301 revisions: Vec<RevisionArg>,
302
303 #[command(flatten)]
304 destination: RebaseDestinationArgs,
305
306 /// If true, when rebasing would produce an empty commit, the commit is
307 /// abandoned. It will not be abandoned if it was already empty before the
308 /// rebase. Will never skip merge commits with multiple non-empty
309 /// parents.
310 #[arg(long)]
311 skip_emptied: bool,
312
313 /// Keep divergent commits while rebasing
314 ///
315 /// Without this flag, divergent commits are abandoned while rebasing if
316 /// another commit with the same change ID is already present in the
317 /// destination with identical changes.
318 #[arg(long)]
319 keep_divergent: bool,
320
321 /// Simplify parents of rebased commits, like `jj simplify-parents`, while
322 /// rebasing them. Any parents that are ancestors of other parents will be
323 /// removed.
324 #[arg(long)]
325 simplify_parents: bool,
326 }
327
328 #[derive(clap::Args, Clone, Debug)]
329 #[group(required = true)]
330 pub struct RebaseDestinationArgs {
331 /// The revision(s) to rebase onto (can be repeated to create a merge
332 /// commit)
333 #[arg(
334 long,
335 visible_alias = "destination",
336 short,
337 visible_short_alias = 'd',
338 value_name = "REVSETS"
339 )]
340 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
341 onto: Option<Vec<RevisionArg>>,
342
343 /// The revision(s) to insert after (can be repeated to create a merge
344 /// commit)
345 #[arg(
346 long,
347 short = 'A',
348 visible_alias = "after",
349 conflicts_with = "onto",
350 value_name = "REVSETS"
351 )]
352 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
353 insert_after: Option<Vec<RevisionArg>>,
354
355 /// The revision(s) to insert before (can be repeated to create a merge
356 /// commit)
357 #[arg(
358 long,
359 short = 'B',
360 visible_alias = "before",
361 conflicts_with = "onto",
362 value_name = "REVSETS"
363 )]
364 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
365 insert_before: Option<Vec<RevisionArg>>,
366 }
367
368 #[instrument(skip_all)]
369 pub(crate) async fn cmd_rebase(
370 ui: &mut Ui,
371 command: &CommandHelper,
372 args: &RebaseArgs,
373 ) -> Result<(), CommandError> {
374 let rebase_options = RebaseOptions {
375 empty: match args.skip_emptied {
376 true => EmptyBehavior::AbandonNewlyEmpty,
377 false => EmptyBehavior::Keep,
378 },
379 rewrite_refs: RewriteRefsOptions {
380 delete_abandoned_bookmarks: false,
381 },
382 simplify_ancestor_merge: args.simplify_parents,
383 };
384 let mut workspace_command = command.workspace_helper(ui).await?;
385
386 let loc = if !args.revisions.is_empty() {
387 plan_rebase_revisions(ui, &workspace_command, &args.revisions, &args.destination).await?
388 } else if !args.source.is_empty() {
389 plan_rebase_source(ui, &workspace_command, &args.source, &args.destination).await?
390 } else {
391 plan_rebase_branch(ui, &workspace_command, &args.branch, &args.destination).await?
392 };
393
394 let target_ids = match &loc.target {
395 MoveCommitsTarget::Commits(ids) => ids,
396 MoveCommitsTarget::Roots(ids) => ids,
397 };
398 if target_ids.is_empty() {
399 writeln!(ui.status(), "No revisions to rebase.")?;
400 return Ok(());
401 }
402
403 let mut tx = workspace_command.start_transaction();
404 let mut computed_move = compute_move_commits(tx.repo(), &loc).await?;
405 if !args.keep_divergent {
406 let abandoned_divergent =
407 find_duplicate_divergent_commits(tx.repo(), &loc.new_parent_ids, &loc.target).await?;
408 computed_move.record_to_abandon(abandoned_divergent.iter().map(Commit::id).cloned());
409 if !abandoned_divergent.is_empty()
410 && let Some(mut formatter) = ui.status_formatter()
411 {
412 writeln!(
413 formatter,
414 "Abandoned {} divergent commits that were already present in the destination:",
415 abandoned_divergent.len(),
416 )?;
417 print_updated_commits(
418 formatter.as_mut(),
419 &tx.base_workspace_helper().commit_summary_template(),
420 &abandoned_divergent,
421 )?;
422 }
423 }
424 let stats = computed_move.apply(tx.repo_mut(), &rebase_options).await?;
425 print_move_commits_stats(ui, &stats)?;
426 tx.finish(ui, tx_description(&loc.target)).await?;
427
428 Ok(())
429 }
430
431 async fn plan_rebase_revisions(
432 ui: &Ui,
433 workspace_command: &WorkspaceCommandHelper,
434 revisions: &[RevisionArg],
435 rebase_destination: &RebaseDestinationArgs,
436 ) -> Result<MoveCommitsLocation, CommandError> {
437 let target_expr = workspace_command
438 .parse_union_revsets(ui, revisions)?
439 .resolve()?;
440 workspace_command
441 .check_rewritable_expr(&target_expr)
442 .await?;
443 let target_commit_ids: Vec<_> = target_expr
444 .evaluate(workspace_command.repo().as_ref())?
445 .stream()
446 .try_collect()
447 .await?; // in reverse topological order
448
449 let (new_parent_ids, new_child_ids) = compute_commit_location(
450 ui,
451 workspace_command,
452 rebase_destination.onto.as_deref(),
453 rebase_destination.insert_after.as_deref(),
454 rebase_destination.insert_before.as_deref(),
455 "rebased commits",
456 )
457 .await?;
458 if rebase_destination.onto.is_some() {
459 for id in &target_commit_ids {
460 if new_parent_ids.contains(id) {
461 return Err(user_error(format!(
462 "Cannot rebase {} onto itself",
463 short_commit_hash(id),
464 )));
465 }
466 }
467 }
468 Ok(MoveCommitsLocation {
469 new_parent_ids,
470 new_child_ids,
471 target: MoveCommitsTarget::Commits(target_commit_ids),
472 })
473 }
474
475 async fn plan_rebase_source(
476 ui: &Ui,
477 workspace_command: &WorkspaceCommandHelper,
478 source: &[RevisionArg],
479 rebase_destination: &RebaseDestinationArgs,
480 ) -> Result<MoveCommitsLocation, CommandError> {
481 let source_commit_ids = Vec::from_iter(
482 workspace_command
483 .resolve_revsets_ordered(ui, source)
484 .await?,
485 );
486 workspace_command
487 .check_rewritable(&source_commit_ids)
488 .await?;
489
490 let (new_parent_ids, new_child_ids) = compute_commit_location(
491 ui,
492 workspace_command,
493 rebase_destination.onto.as_deref(),
494 rebase_destination.insert_after.as_deref(),
495 rebase_destination.insert_before.as_deref(),
496 "rebased commits",
497 )
498 .await?;
499 if rebase_destination.onto.is_some() {
500 for id in &source_commit_ids {
501 let commit = workspace_command
502 .repo()
503 .store()
504 .get_commit_async(id)
505 .await?;
506 check_rebase_destinations(workspace_command.repo(), &new_parent_ids, &commit).await?;
507 }
508 }
509
510 Ok(MoveCommitsLocation {
511 new_parent_ids,
512 new_child_ids,
513 target: MoveCommitsTarget::Roots(source_commit_ids),
514 })
515 }
516
517 async fn plan_rebase_branch(
518 ui: &Ui,
519 workspace_command: &WorkspaceCommandHelper,
520 branch: &[RevisionArg],
521 rebase_destination: &RebaseDestinationArgs,
522 ) -> Result<MoveCommitsLocation, CommandError> {
523 let branch_commit_ids: Vec<_> = if branch.is_empty() {
524 vec![
525 workspace_command
526 .resolve_single_rev(ui, &RevisionArg::AT)
527 .await?
528 .id()
529 .clone(),
530 ]
531 } else {
532 workspace_command
533 .resolve_revsets_ordered(ui, branch)
534 .await?
535 .into_iter()
536 .collect()
537 };
538
539 let (new_parent_ids, new_child_ids) = compute_commit_location(
540 ui,
541 workspace_command,
542 rebase_destination.onto.as_deref(),
543 rebase_destination.insert_after.as_deref(),
544 rebase_destination.insert_before.as_deref(),
545 "rebased commits",
546 )
547 .await?;
548 let roots_expression = RevsetExpression::commits(new_parent_ids.clone())
549 .range(&RevsetExpression::commits(branch_commit_ids))
550 .roots();
551 workspace_command
552 .check_rewritable_expr(&roots_expression)
553 .await?;
554 let root_commit_ids: Vec<_> = roots_expression
555 .evaluate(workspace_command.repo().as_ref())
556 .unwrap()
557 .stream()
558 .try_collect()
559 .await?;
560 if rebase_destination.onto.is_some() {
561 for id in &root_commit_ids {
562 let commit = workspace_command
563 .repo()
564 .store()
565 .get_commit_async(id)
566 .await?;
567 check_rebase_destinations(workspace_command.repo(), &new_parent_ids, &commit).await?;
568 }
569 }
570
571 Ok(MoveCommitsLocation {
572 new_parent_ids,
573 new_child_ids,
574 target: MoveCommitsTarget::Roots(root_commit_ids),
575 })
576 }
577
578 async fn check_rebase_destinations(
579 repo: &Arc<ReadonlyRepo>,
580 new_parents: &[CommitId],
581 commit: &Commit,
582 ) -> Result<(), CommandError> {
583 for parent_id in new_parents {
584 if parent_id == commit.id() {
585 return Err(user_error(format!(
586 "Cannot rebase {} onto itself",
587 short_commit_hash(commit.id()),
588 )));
589 }
590 if repo.index().is_ancestor(commit.id(), parent_id).await? {
591 return Err(user_error(format!(
592 "Cannot rebase {} onto descendant {}",
593 short_commit_hash(commit.id()),
594 short_commit_hash(parent_id)
595 )));
596 }
597 }
598 Ok(())
599 }
600
601 fn tx_description(target: &MoveCommitsTarget) -> String {
602 match &target {
603 MoveCommitsTarget::Commits(ids) => match &ids[..] {
604 [] => format!("rebase {} commits", ids.len()),
605 [id] => format!("rebase commit {}", id.hex()),
606 [first, others @ ..] => {
607 format!("rebase commit {} and {} more", first.hex(), others.len())
608 }
609 },
610 MoveCommitsTarget::Roots(ids) => match &ids[..] {
611 [id] => format!("rebase commit {} and descendants", id.hex()),
612 _ => format!("rebase {} commits and their descendants", ids.len()),
613 },
614 }
615 }
616
617 /// Print details about the provided [`MoveCommitsStats`].
618 fn print_move_commits_stats(ui: &Ui, stats: &MoveCommitsStats) -> std::io::Result<()> {
619 let Some(mut formatter) = ui.status_formatter() else {
620 return Ok(());
621 };
622 let &MoveCommitsStats {
623 num_rebased_targets,
624 num_rebased_descendants,
625 num_skipped_rebases,
626 num_abandoned_empty,
627 rebased_commits: _,
628 } = stats;
629 if num_skipped_rebases > 0 {
630 writeln!(
631 formatter,
632 "Skipped rebase of {num_skipped_rebases} commits that were already in place."
633 )?;
634 }
635 if num_rebased_targets > 0 {
636 writeln!(
637 formatter,
638 "Rebased {num_rebased_targets} commits to destination."
639 )?;
640 }
641 if num_rebased_descendants > 0 {
642 writeln!(
643 formatter,
644 "Rebased {num_rebased_descendants} descendant commits."
645 )?;
646 }
647 if num_abandoned_empty > 0 {
648 writeln!(
649 formatter,
650 "Abandoned {num_abandoned_empty} newly emptied commits."
651 )?;
652 }
653 Ok(())
654 }