Debian Codegraph @

cli/src/commands/converge.rs

raw
1 // Copyright 2026 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::collections::HashSet;
16 use std::fmt::Write as _;
17 use std::hash::Hash;
18 use std::io;
19
20 use clap_complete::ArgValueCompleter;
21 use indexmap::IndexMap;
22 use indoc::indoc;
23 use itertools::Itertools as _;
24 use jj_lib::backend::ChangeId;
25 use jj_lib::backend::CommitId;
26 use jj_lib::backend::Signature;
27 use jj_lib::commit::Commit;
28 use jj_lib::conflict_labels::ConflictLabels;
29 use jj_lib::conflicts::ConflictMarkerStyle;
30 use jj_lib::conflicts::ConflictMaterializeOptions;
31 use jj_lib::conflicts::materialize_merge_result_to_bytes;
32 use jj_lib::converge::CommitsByChangeId;
33 use jj_lib::converge::ConvergedAttribute;
34 use jj_lib::converge::TruncatedEvolutionGraph;
35 use jj_lib::converge::apply_solution;
36 use jj_lib::converge::converge_change;
37 use jj_lib::converge::find_divergent_changes;
38 use jj_lib::files::FileMergeHunkLevel;
39 use jj_lib::merge::MergeBuilder;
40 use jj_lib::merge::SameChange;
41 use jj_lib::repo::ReadonlyRepo;
42 use jj_lib::repo::Repo as _;
43 use jj_lib::tree_merge::MergeOptions;
44
45 use crate::cli_util::CommandHelper;
46 use crate::cli_util::RevisionArg;
47 use crate::cli_util::WorkspaceCommandTransaction;
48 use crate::cli_util::short_change_hash;
49 use crate::cli_util::short_commit_hash;
50 use crate::command_error::CommandError;
51 use crate::command_error::internal_error;
52 use crate::command_error::user_error;
53 use crate::complete;
54 use crate::description_util::TextEditor;
55 use crate::formatter::Formatter;
56 use crate::templater::TemplateRenderer;
57 use crate::ui::Ui;
58
59 /// Converge divergent changes
60 ///
61 /// Attempts to resolve divergence by replacing two or more visible revisions
62 /// for a given change with a single revision. `jj converge` evaluates the
63 /// revset(s) given by the `--revisions` arg (or the `revsets.converge` setting
64 /// if none are specified) and groups the resulting revisions by change ID.
65 /// Change IDs with more than one revision are divergent.
66 ///
67 /// If there is no divergence it returns successfully. If there is more than one
68 /// divergent change it prompts the user to choose one. The command then applies
69 /// heuristics to try to automatically come up with a good solution (i.e. a new
70 /// revision) that replaces the divergent revisions. If the heuristics are
71 /// inconclusive `jj converge` falls back to prompting the user. Use
72 /// `--no-interactive` to print a warning instead of prompting the user.
73 ///
74 /// The user may be prompted for any of the following: to merge revision
75 /// descriptions, to choose parents for the solution, and/or (very rarely) to
76 /// choose a revision author.
77 ///
78 /// When a solution is found, the new revision replaces the divergent revisions
79 /// of the specific change ID (but only those matching the revsets; if there are
80 /// other visible revisions for the same change ID outside the revset, those
81 /// will remain and you will still have divergence, though it will be reduced).
82 /// Descendants of the divergent revisions are rebased onto the solution, and
83 /// local bookmarks pointing to any divergent revision are updated to point to
84 /// the solution.
85 ///
86 /// Note that there may be file conflicts in the solution whether or not there
87 /// were conflicts to begin with.
88 ///
89 /// The modifications made by `jj converge` can be reviewed by `jj op show -p`.
90 /// You can inspect the change evolution with `jj evolog`. If not satisfied with
91 /// the result you can run `jj undo`.
92 #[derive(clap::Args, Clone, Debug)]
93 pub(crate) struct ConvergeArgs {
94 /// The search space to look for divergent revisions
95 ///
96 /// If no revisions are specified, this defaults to the `revsets.converge`
97 /// setting.
98 #[arg(long = "revision", short, value_name = "REVSETS", alias = "revisions")]
99 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
100 revisions: Vec<RevisionArg>,
101
102 /// Do not prompt the user for help resolving divergence
103 ///
104 /// If the command cannot solve divergence automatically it will print a
105 /// warning and exit without making any changes (divergence will still be
106 /// present).
107 #[arg(long, conflicts_with = "_interactive")]
108 no_interactive: bool,
109
110 /// No-op flag to pair with --no-interactive
111 #[arg(long, short, hide = true)]
112 _interactive: bool,
113 }
114
115 // TODO: consider adding logic to deal with more than one divergent change-id in
116 // one invocation. Pick one, solve it, pick another one, solve it, etc.
117 // NOTE: currently we walk the operation history as far back as necessary when
118 // building the TruncatedEvolutionGraph. If this ever becomes a problem (because
119 // of a very deep fork in the op log), we could add a config setting to limit
120 // the walk and pretend that a "root" operation happened at that point.
121 pub(crate) async fn cmd_converge(
122 ui: &mut Ui,
123 command: &CommandHelper,
124 args: &ConvergeArgs,
125 ) -> Result<(), CommandError> {
126 let mut workspace_command = command.workspace_helper(ui).await?;
127 let settings = workspace_command.settings();
128
129 let search_space = {
130 if args.revisions.is_empty() {
131 let revset_string = settings.get_string("revsets.converge")?;
132 workspace_command.parse_revset(ui, &RevisionArg::from(revset_string))?
133 } else {
134 workspace_command.parse_union_revsets(ui, &args.revisions)?
135 }
136 }
137 .resolve()?;
138
139 workspace_command
140 .check_rewritable_expr(&search_space)
141 .await?;
142
143 let interactive = !args.no_interactive;
144
145 let tx = workspace_command.start_transaction();
146
147 // Find all divergent changes and choose one to converge.
148 let divergent_changes = find_divergent_changes(tx.base_repo(), search_space).await?;
149 if divergent_changes.is_empty() {
150 if args.revisions.is_empty() {
151 writeln!(ui.status(), "No divergent changes found.")?;
152 } else {
153 writeln!(
154 ui.status(),
155 "No divergence found among the specified revisions."
156 )?;
157 }
158 return Ok(());
159 }
160 report_divergent_changes(ui, &divergent_changes, &tx.commit_summary_template())?;
161 let Some(change_id) = choose_change(ui, &divergent_changes, interactive)? else {
162 return Ok(());
163 };
164
165 Converge::new(ui, tx, &divergent_changes, change_id.clone(), interactive)
166 .await?
167 .run()
168 .await
169 }
170
171 struct Converge<'a> {
172 ui: &'a Ui,
173 tx: WorkspaceCommandTransaction<'a>,
174 divergent_changes: &'a CommitsByChangeId,
175 change_id: ChangeId,
176 truncated_evolution_graph: TruncatedEvolutionGraph,
177 interactive: bool,
178 }
179
180 impl<'a> Converge<'a> {
181 async fn new(
182 ui: &'a Ui,
183 tx: WorkspaceCommandTransaction<'a>,
184 divergent_changes: &'a CommitsByChangeId,
185 change_id: ChangeId,
186 interactive: bool,
187 ) -> Result<Self, CommandError> {
188 let divergent_commits = divergent_changes
189 .get(&change_id)
190 .expect("change_id is in divergent_changes")
191 .clone();
192 let truncated_evolution_graph =
193 TruncatedEvolutionGraph::new(tx.base_repo().clone(), divergent_commits).await?;
194 Ok(Self {
195 ui,
196 tx,
197 divergent_changes,
198 change_id,
199 truncated_evolution_graph,
200 interactive,
201 })
202 }
203
204 fn repo(&self) -> &ReadonlyRepo {
205 self.truncated_evolution_graph.repo()
206 }
207
208 fn text_editor(&self) -> Result<TextEditor, CommandError> {
209 Ok(self.tx.base_workspace_helper().text_editor()?)
210 }
211
212 async fn run(mut self) -> Result<(), CommandError> {
213 writeln!(
214 self.ui.stderr_formatter(),
215 "Attempting to converge change {}...\n",
216 short_change_hash(&self.change_id)
217 )?;
218
219 // Call the library function to attempt to converge the change automatically.
220 let automatic_converge_result = {
221 // Initially we start with zero knowledge about what the solution should look
222 // like.
223 let author = None;
224 let description = None;
225 let parents = None;
226 let tree = None;
227 converge_change(
228 &self.truncated_evolution_graph,
229 author,
230 description,
231 parents,
232 tree,
233 )
234 .await?
235 };
236
237 // Now solve the author, description and parents, prompting the user for input
238 // if necessary.
239 let author = self.generic_solver(automatic_converge_result.author, Self::choose_author)?;
240 let description = self.generic_solver(
241 automatic_converge_result.description,
242 Self::merge_description,
243 )?;
244 let parents =
245 self.generic_solver(automatic_converge_result.parents, Self::choose_parents)?;
246
247 let (Some(author), Some(description), Some(parents)) = (&author, &description, &parents)
248 else {
249 if author.is_none() {
250 writeln!(self.ui.status(), "Could not determine which author to use.")?;
251 }
252 if description.is_none() {
253 writeln!(
254 self.ui.status(),
255 "Could not determine which description to use."
256 )?;
257 }
258 if parents.is_none() {
259 writeln!(
260 self.ui.status(),
261 "Could not determine which parents to use."
262 )?;
263 }
264 return Err(user_error("Could not converge change"));
265 };
266
267 // If we do not have a tree yet, call the converge_change library function
268 // again, now that we have the author, description and parents.
269 let tree = match automatic_converge_result.tree {
270 Some(tree) => Ok(tree),
271 None => {
272 let converge_result = converge_change(
273 &self.truncated_evolution_graph,
274 Some(author.clone()),
275 Some(description.clone()),
276 Some(parents.clone()),
277 None,
278 )
279 .await?;
280 match converge_result.tree {
281 Some(tree) => Ok(tree),
282 None => Err(user_error("Failed to converge tree")),
283 }
284 }
285 }?;
286
287 let (solution_commit, num_rebased) = apply_solution(
288 author.clone(),
289 description.clone(),
290 parents.clone(),
291 tree,
292 self.change_id.clone(),
293 self.truncated_evolution_graph.divergent_commit_ids(),
294 self.tx.repo_mut(),
295 )
296 .await?;
297
298 let change_id = solution_commit.change_id();
299 let short_solution_id = short_commit_hash(solution_commit.id());
300 let short_change_id = short_change_hash(change_id);
301 let num_divergent_commits = self
302 .divergent_changes
303 .get(change_id)
304 .map(|m| m.len())
305 .unwrap_or(0);
306 writeln!(
307 self.ui.status(),
308 "Successfully converged change: created commit {short_solution_id}."
309 )?;
310 if num_rebased > 0 {
311 writeln!(self.ui.status(), "Rebased {num_rebased} descendants")?;
312 }
313 if self.divergent_changes.len() > 1 {
314 writeln!(
315 self.ui.hint_default(),
316 "There are still {} divergent changes remaining in the specified revset, you can \
317 run this command again to converge another one.",
318 self.divergent_changes.len() - 1
319 )?;
320 }
321
322 let transaction_description =
323 format!("converge {short_change_id} with {num_divergent_commits} predecessors");
324 self.tx.finish(self.ui, transaction_description).await?;
325 Ok(())
326 }
327
328 fn generic_solver<T, InteractiveConvergeFn>(
329 &self,
330 automatic_convergence: ConvergedAttribute<T>,
331 interactive_converge: InteractiveConvergeFn,
332 ) -> Result<Option<T>, CommandError>
333 where
334 T: Eq + Hash + Clone,
335 InteractiveConvergeFn: Fn(&Self, CommitId, HashSet<CommitId>) -> Result<T, CommandError>,
336 {
337 match automatic_convergence {
338 ConvergedAttribute::Solved(value) => Ok(Some(value)),
339 ConvergedAttribute::Unsolved {
340 base_commit,
341 excluded_divergent_commits,
342 } => {
343 if !self.interactive {
344 Ok(None)
345 } else {
346 Ok(Some(interactive_converge(
347 self,
348 base_commit,
349 excluded_divergent_commits,
350 )?))
351 }
352 }
353 }
354 }
355
356 fn choose_author(
357 &self,
358 _base_commit: CommitId,
359 _excluded_divergent_commits: HashSet<CommitId>,
360 ) -> Result<Signature, CommandError> {
361 choose_helper(
362 self.ui,
363 self.truncated_evolution_graph.divergent_commits(),
364 "Could not determine automatically which author to use",
365 |commit| commit.author().clone(),
366 |commit, _formatter| {
367 Ok(format!(
368 "{} ({}, {})\n",
369 short_commit_hash(commit.id()),
370 commit.author().name,
371 commit.author().email
372 ))
373 },
374 indoc! {"
375 Enter the index of the author you want to use"},
376 )
377 }
378
379 fn choose_parents(
380 &self,
381 _base_commit: CommitId,
382 excluded_divergent_commits: HashSet<CommitId>,
383 ) -> Result<Vec<CommitId>, CommandError> {
384 let viable_commits = self
385 .truncated_evolution_graph
386 .divergent_commits()
387 .iter()
388 .filter(|commit| !excluded_divergent_commits.contains(commit.id()))
389 .cloned()
390 .collect_vec();
391
392 let value_fn = |commit: &Commit| commit.parent_ids().to_vec();
393
394 // A function that takes one of the divergent commits and returns a string that
395 // displays that commit's id and then its parents (one parent per line)
396 let display_fn = |commit: &Commit, _formatter: &mut dyn Formatter| {
397 let mut display_string = String::new();
398 writeln!(display_string, "{}:", short_commit_hash(commit.id()))
399 .map_err(internal_error)?;
400 for parent in commit.parent_ids() {
401 let parent_summary = self
402 .tx
403 .format_commit_summary(&self.repo().store().get_commit(parent)?);
404 writeln!(display_string, " Parent: {parent_summary}")
405 .map_err(internal_error)?;
406 }
407 Ok(display_string)
408 };
409
410 choose_helper(
411 self.ui,
412 &viable_commits,
413 "Could not determine automatically which parents to use",
414 value_fn,
415 display_fn,
416 indoc! {"
417 Enter the index of one of the divergent commits whose parent(s) will be the parents of the solution"},
418 )
419 }
420
421 // TODO: Run the user's configured merge tool.
422 fn merge_description(
423 &self,
424 base_commit: CommitId,
425 _excluded_divergent_commits: HashSet<CommitId>,
426 ) -> Result<String, CommandError> {
427 let distinct_values = {
428 // Add the values of the divergent commits to the map, deduplicating them as we
429 // go.
430 let mut distinct_values = IndexMap::new();
431 for commit in self.truncated_evolution_graph.divergent_commits() {
432 distinct_values
433 .entry(commit.description())
434 .or_insert(commit);
435 }
436 distinct_values
437 };
438 if distinct_values.len() == 1 {
439 return Ok(distinct_values
440 .first()
441 .expect("values is not empty")
442 .0
443 .to_string());
444 }
445
446 let candidate_commits = distinct_values
447 .iter()
448 .map(|(_description, commit)| commit)
449 .copied()
450 .collect_vec();
451
452 let base_commit = self.repo().store().get_commit(&base_commit)?;
453 let conflicted_description =
454 materialize_conflicted_description(&candidate_commits, &base_commit);
455 let merge_in_text_editor = self.ui.prompt_yes_no(
456 indoc! {"
457 There are divergent descriptions. You can choose to merge them now in a
458 text editor, or skip merging and use the conflicted description (with
459 conflict markers). Do you want to merge them now?"},
460 Some(true),
461 )?;
462 writeln!(self.ui.status(), "\n")?;
463 let description = if merge_in_text_editor {
464 self.text_editor()?
465 .edit_str(conflicted_description, Some(".jj-converge-description"))
466 .map_err(|err| err.with_name("description"))?
467 } else {
468 conflicted_description
469 };
470 Ok(description)
471 }
472 }
473
474 /// Prompts the user to choose a change-id to converge, if there are multiple
475 /// divergent change-ids.
476 fn choose_change<'a>(
477 ui: &Ui,
478 divergent_changes: &'a CommitsByChangeId,
479 interactive: bool,
480 ) -> Result<Option<&'a ChangeId>, CommandError> {
481 assert!(!divergent_changes.is_empty());
482 let mut formatter = ui.stderr_formatter();
483 if divergent_changes.len() == 1 {
484 return Ok(Some(divergent_changes.keys().next().unwrap()));
485 }
486 // TODO: consider using heuristics to automatically choose a "good" change-id to
487 // converge, falling back to prompting the user only if the heuristics are
488 // inconclusive. This is specially important in non-interactive mode.
489 if !interactive {
490 return Err(
491 user_error("Cannot automatically choose which change to converge").hinted(
492 "Run `jj converge` in interactive mode, or specify a revset that resolves to only \
493 one change ID",
494 ),
495 );
496 }
497 writeln!(
498 formatter,
499 "Choose which change to converge (jj converge only converges one change at a time):",
500 )?;
501
502 let mut choices: Vec<String> = Default::default();
503 let change_ids: Vec<&ChangeId> = divergent_changes.keys().collect();
504 for (i, change_id) in change_ids.iter().enumerate() {
505 // TODO: is there a better way to display the change-id? perhaps with
506 // format_short_change_id?
507 writeln!(formatter, "{}: {}", i + 1, short_change_hash(change_id))?;
508 choices.push(format!("{}", i + 1));
509 }
510 writeln!(formatter, "q: abort")?;
511 choices.push("q".to_string());
512 drop(formatter);
513 let index = ui.prompt_choice("Enter the index of the change to converge", &choices, None)?;
514 writeln!(ui.status(), "\n")?;
515 if index >= change_ids.len() {
516 writeln!(ui.status(), "Aborting... nothing changed.")?;
517 Ok(None)
518 } else {
519 Ok(Some(change_ids[index]))
520 }
521 }
522
523 fn choose_helper<T, ValueFn, DisplayFn>(
524 ui: &Ui,
525 divergent_commits: &[Commit],
526 introduction: &str,
527 value_fn: ValueFn,
528 display_fn: DisplayFn,
529 prompt: &str,
530 ) -> Result<T, CommandError>
531 where
532 T: Eq + Hash + Clone,
533 ValueFn: Fn(&Commit) -> T,
534 DisplayFn: Fn(&Commit, &mut dyn Formatter) -> Result<String, CommandError>,
535 {
536 assert!(!divergent_commits.is_empty());
537 let distinct_values = {
538 // Add the values of the divergent commits to the map, deduplicating them as we
539 // go.
540 let mut distinct_values = IndexMap::new();
541 for commit in divergent_commits {
542 distinct_values.entry(value_fn(commit)).or_insert(commit);
543 }
544 distinct_values
545 };
546 if distinct_values.len() == 1 {
547 return Ok(distinct_values
548 .first()
549 .expect("values is not empty")
550 .0
551 .clone());
552 }
553
554 writeln!(ui.stderr_formatter(), "{introduction}")?;
555 let mut choices: Vec<String> = Default::default();
556 for (index, (_value, commit)) in distinct_values.iter().enumerate() {
557 let display_string = display_fn(commit, ui.stderr_formatter().as_mut())?;
558 assert!(display_string.ends_with('\n'));
559 write!(ui.stderr_formatter(), "{}: {}", index + 1, display_string)?;
560 choices.push(format!("{}", index + 1));
561 }
562 writeln!(ui.stderr_formatter(), "q: abort")?;
563 choices.push("q".to_string());
564 let index = ui.prompt_choice(prompt, &choices, None)?;
565 writeln!(ui.status(), "\n")?;
566 if index >= distinct_values.len() {
567 Err(user_error("Aborting... nothing changed."))
568 } else {
569 Ok(distinct_values.get_index(index).unwrap().0.clone())
570 }
571 }
572
573 fn materialize_conflicted_description(
574 divergent_commits: &[&Commit],
575 base_commit: &Commit,
576 ) -> String {
577 if divergent_commits.is_empty() {
578 return String::new();
579 }
580 let (description_merge, conflict_labels) = {
581 let base = base_commit.description();
582 let base_label = base_commit.conflict_label();
583 let mut merge_builder = MergeBuilder::default();
584 let mut labels = vec![];
585 merge_builder.extend([divergent_commits[0].description().to_string()]);
586 labels.push(divergent_commits[0].conflict_label());
587 for commit in divergent_commits.iter().skip(1) {
588 merge_builder.extend([base.to_string(), commit.description().to_string()]);
589 labels.extend([base_label.clone(), commit.conflict_label()]);
590 }
591 (merge_builder.build(), ConflictLabels::from_vec(labels))
592 };
593 let options = ConflictMaterializeOptions {
594 marker_style: ConflictMarkerStyle::Diff,
595 marker_len: None,
596 merge: MergeOptions {
597 hunk_level: FileMergeHunkLevel::Line,
598 same_change: SameChange::Accept,
599 },
600 };
601 materialize_merge_result_to_bytes(&description_merge, &conflict_labels, &options).to_string()
602 }
603
604 fn report_divergent_changes(
605 ui: &Ui,
606 divergent_changes: &CommitsByChangeId,
607 commit_summary_template: &TemplateRenderer<Commit>,
608 ) -> io::Result<()> {
609 let mut formatter = ui.stderr_formatter();
610 let n = divergent_changes.len();
611 writeln!(
612 formatter,
613 "Found {n} divergent change(s) in the specified revset:",
614 )?;
615 for (change_id, commits) in divergent_changes {
616 writeln!(
617 formatter,
618 "- Change: {} with {} commits:",
619 short_change_hash(change_id),
620 commits.len(),
621 )?;
622 for commit in commits.iter().take(10) {
623 write!(formatter, " ")?;
624 commit_summary_template.format(commit, formatter.as_mut())?;
625 writeln!(formatter)?;
626 }
627 if commits.len() > 10 {
628 write!(formatter, " ... and {} more", commits.len() - 10)?;
629 }
630 writeln!(formatter)?;
631 }
632 Ok(())
633 }