Debian Codegraph @

cli/src/commands/absorb.rs

raw
1 // Copyright 2024 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 clap_complete::ArgValueCandidates;
16 use clap_complete::ArgValueCompleter;
17 use indoc::formatdoc;
18 use jj_lib::absorb::AbsorbSource;
19 use jj_lib::absorb::absorb_hunks;
20 use jj_lib::absorb::split_hunks_to_trees;
21 use jj_lib::matchers::EverythingMatcher;
22 use jj_lib::merge::Diff;
23 use tracing::instrument;
24
25 use crate::cli_util::CommandHelper;
26 use crate::cli_util::RevisionArg;
27 use crate::cli_util::print_unmatched_explicit_paths;
28 use crate::cli_util::print_updated_commits;
29 use crate::command_error::CommandError;
30 use crate::command_error::user_error;
31 use crate::complete;
32 use crate::diff_util::DiffFormat;
33 use crate::ui::Ui;
34
35 /// Move changes from a revision into the stack of mutable revisions
36 ///
37 /// This command splits changes in the source revision and moves each change to
38 /// the closest mutable ancestor where the corresponding lines were modified
39 /// last. If the destination revision cannot be determined unambiguously, the
40 /// change will be left in the source revision.
41 ///
42 /// With the `--interactive` option, only the selected changes will be
43 /// considered for absorption. This allows picking specific hunks to absorb
44 /// (which may then be distributed across multiple ancestors). The `--tool`
45 /// option can be used to select a different diff editor.
46 ///
47 /// The source revision will be abandoned if all changes are absorbed into the
48 /// destination revisions, and if the source revision has no description.
49 ///
50 /// The modification made by `jj absorb` can be reviewed by `jj op show -p`.
51 #[derive(clap::Args, Clone, Debug)]
52 pub(crate) struct AbsorbArgs {
53 /// Source revision to absorb from
54 #[arg(long, short, default_value = "@", value_name = "REVSET")]
55 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
56 from: RevisionArg,
57
58 /// Destination revisions to absorb into
59 ///
60 /// Only ancestors of the source revision will be considered.
61 #[arg(
62 long,
63 short = 't',
64 visible_alias = "to",
65 default_value = "mutable()",
66 value_name = "REVSETS"
67 )]
68 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
69 into: Vec<RevisionArg>,
70
71 /// Move only changes to these paths (instead of all paths)
72 #[arg(value_name = "FILESETS", value_hint = clap::ValueHint::AnyPath)]
73 #[arg(add = ArgValueCompleter::new(complete::modified_from_files))]
74 paths: Vec<String>,
75
76 /// Interactively choose which parts to absorb
77 #[arg(long, short)]
78 interactive: bool,
79
80 /// Specify diff editor to be used (implies --interactive)
81 #[arg(long, value_name = "NAME")]
82 #[arg(add = ArgValueCandidates::new(complete::diff_editors))]
83 tool: Option<String>,
84 }
85
86 #[instrument(skip_all)]
87 pub(crate) async fn cmd_absorb(
88 ui: &mut Ui,
89 command: &CommandHelper,
90 args: &AbsorbArgs,
91 ) -> Result<(), CommandError> {
92 let mut workspace_command = command.workspace_helper(ui).await?;
93
94 let source_commit = workspace_command.resolve_single_rev(ui, &args.from).await?;
95 let destinations = workspace_command
96 .parse_union_revsets(ui, &args.into)?
97 .resolve()?;
98
99 let fileset_expression = workspace_command.parse_file_patterns(ui, &args.paths)?;
100 let matcher = fileset_expression.to_matcher();
101
102 print_unmatched_explicit_paths(
103 ui,
104 &workspace_command,
105 &fileset_expression,
106 [&source_commit.tree()],
107 )
108 .await?;
109
110 let diff_selector =
111 workspace_command.diff_selector(ui, args.tool.as_deref(), args.interactive)?;
112 let repo = workspace_command.repo().as_ref();
113 let source = if diff_selector.is_interactive() {
114 let parent_tree = source_commit.parent_tree(repo).await?;
115 let source_tree = source_commit.tree();
116 let format_instructions = || {
117 formatdoc! {"
118 You are selecting changes from: {source} to be considered for
119 absorption into ancestors.
120
121 The left side of the diff shows the parent commit. The right side
122 initially shows the contents of the commit you're absorbing from.
123
124 Adjust the right side until the diff shows the changes you want to
125 absorb. Selected hunks will be considered for assignment to the
126 closest ancestor where the corresponding lines were last modified
127 (using annotation). Any hunks that cannot be absorbed unambiguously
128 remain in the source commit.
129 ",
130 source = workspace_command.format_commit_summary(&source_commit),
131 }
132 };
133 let selected_tree = diff_selector
134 .select(
135 ui,
136 Diff::new(&parent_tree, &source_tree),
137 Diff::new(
138 source_commit.parents_conflict_label().await?,
139 source_commit.conflict_label(),
140 ),
141 &matcher,
142 format_instructions,
143 )
144 .await?;
145 if selected_tree.tree_ids() == parent_tree.tree_ids() {
146 return Err(user_error("No changes selected"));
147 }
148 AbsorbSource::from_tree(source_commit.clone(), selected_tree, parent_tree).await?
149 } else {
150 AbsorbSource::from_commit(repo, source_commit.clone()).await?
151 };
152
153 let selected_trees = split_hunks_to_trees(repo, &source, &destinations, &matcher).await?;
154
155 let path_converter = workspace_command.path_converter();
156 for (path, reason) in selected_trees.skipped_paths {
157 let ui_path = path_converter.format_file_path(&path);
158 writeln!(ui.warning_default(), "Skipping {ui_path}: {reason}")?;
159 }
160
161 workspace_command
162 .check_rewritable(selected_trees.target_commits.keys())
163 .await?;
164
165 let mut tx = workspace_command.start_transaction();
166 let stats = absorb_hunks(tx.repo_mut(), &source, selected_trees.target_commits).await?;
167
168 if let Some(mut formatter) = ui.status_formatter() {
169 if !stats.rewritten_destinations.is_empty() {
170 writeln!(
171 formatter,
172 "Absorbed changes into {} revisions:",
173 stats.rewritten_destinations.len()
174 )?;
175 print_updated_commits(
176 formatter.as_mut(),
177 &tx.commit_summary_template(),
178 stats.rewritten_destinations.iter().rev(),
179 )?;
180 }
181 if stats.num_rebased > 0 {
182 writeln!(
183 formatter,
184 "Rebased {} descendant commits.",
185 stats.num_rebased
186 )?;
187 }
188 }
189
190 tx.finish(
191 ui,
192 format!(
193 "absorb changes into {} commits",
194 stats.rewritten_destinations.len()
195 ),
196 )
197 .await?;
198
199 if let Some(mut formatter) = ui.status_formatter()
200 && let Some(commit) = &stats.rewritten_source
201 {
202 let repo = workspace_command.repo().as_ref();
203 if !commit.is_empty(repo).await? {
204 writeln!(formatter, "Remaining changes:")?;
205 let diff_renderer = workspace_command.diff_renderer(vec![DiffFormat::Summary]);
206 let matcher = &EverythingMatcher; // also print excluded paths
207 let width = ui.term_width();
208 diff_renderer
209 .show_patch(ui, formatter.as_mut(), commit, matcher, width)
210 .await?;
211 }
212 }
213 Ok(())
214 }