Debian Codegraph @

cli/src/commands/squash.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
15 use std::collections::HashMap;
16 use std::iter::once;
17
18 use clap_complete::ArgValueCandidates;
19 use clap_complete::ArgValueCompleter;
20 use futures::TryStreamExt as _;
21 use futures::future::try_join_all;
22 use indoc::formatdoc;
23 use jj_lib::commit::Commit;
24 use jj_lib::commit::CommitIteratorExt as _;
25 use jj_lib::matchers::Matcher;
26 use jj_lib::merge::Diff;
27 use jj_lib::object_id::ObjectId as _;
28 use jj_lib::repo::Repo as _;
29 use jj_lib::rewrite;
30 use jj_lib::rewrite::CommitWithSelection;
31 use jj_lib::rewrite::merge_commit_trees;
32 use tracing::instrument;
33
34 use crate::cli_util::CommandHelper;
35 use crate::cli_util::DiffSelector;
36 use crate::cli_util::RevisionArg;
37 use crate::cli_util::WorkspaceCommandTransaction;
38 use crate::cli_util::compute_commit_location;
39 use crate::cli_util::print_unmatched_explicit_paths;
40 use crate::command_error::CommandError;
41 use crate::command_error::user_error;
42 use crate::complete;
43 use crate::description_util::add_trailers;
44 use crate::description_util::combine_messages_for_editing;
45 use crate::description_util::description_template;
46 use crate::description_util::edit_description;
47 use crate::description_util::join_message_paragraphs;
48 use crate::description_util::try_combine_messages;
49 use crate::revset_util::RevsetEvaluationSizeError;
50 use crate::revset_util::evaluate_revset_to_single_commit;
51 use crate::ui::Ui;
52
53 /// Move changes from a revision into another revision
54 ///
55 /// Without any options, moves the changes from the working-copy revision to the
56 /// parent revision.
57 ///
58 /// With the `-r` option, moves the changes from the specified revision to the
59 /// parent revision. Fails if there are several parent revisions (i.e., the
60 /// given revision is a merge).
61 ///
62 /// With the `--from` and/or `--into` options, moves changes from/to the given
63 /// revisions. If either is left out, it defaults to the working-copy commit.
64 /// For example, `jj squash --into @--` moves changes from the working-copy
65 /// commit to the grandparent.
66 ///
67 /// If, after moving changes out, the source revision is empty compared to its
68 /// parent(s), and `--keep-emptied` is not set, it will be abandoned. Without
69 /// `--interactive` or paths, the source revision will always be empty.
70 ///
71 /// If the source was abandoned and both the source and destination had a
72 /// non-empty description, you will be asked for the combined description. If
73 /// either was empty, then the other one will be used.
74 ///
75 /// If a working-copy commit gets abandoned, it will be given a new, empty
76 /// commit. This is true in general; it is not specific to this command.
77 ///
78 /// The name "squash" comes from the idea of combining (squashing) the changes
79 /// from multiple revisions together.
80 ///
81 /// EXPERIMENTAL FEATURES
82 ///
83 /// An alternative squashing UI is available via the `-o`, `-A`, and `-B`
84 /// options. Using any of these options creates a new commit. They can be used
85 /// together with one or more `--from` options (if no `--from` is specified,
86 /// `--from @` is assumed).
87 #[derive(clap::Args, Clone, Debug)]
88 pub(crate) struct SquashArgs {
89 /// Revision to squash into its parent (default: @). Incompatible with the
90 /// experimental `-o`/`-A`/`-B` options.
91 #[arg(long, short, value_name = "REVSET")]
92 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
93 revision: Option<RevisionArg>,
94
95 /// Revision(s) to squash from (default: @)
96 #[arg(long, short, conflicts_with = "revision", value_name = "REVSETS")]
97 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
98 from: Vec<RevisionArg>,
99
100 /// Revision to squash into (default: @)
101 #[arg(
102 long,
103 short = 't',
104 conflicts_with = "revision",
105 visible_alias = "to",
106 value_name = "REVSET"
107 )]
108 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
109 into: Option<RevisionArg>,
110
111 /// (Experimental) The revision(s) to use as parent for the new commit (can
112 /// be repeated to create a merge commit)
113 #[arg(
114 long,
115 visible_alias = "destination",
116 short,
117 visible_short_alias = 'd',
118 conflicts_with_all = ["into", "revision"],
119 value_name = "REVSETS"
120 )]
121 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
122 onto: Option<Vec<RevisionArg>>,
123
124 /// (Experimental) The revision(s) to insert the new commit after (can be
125 /// repeated to create a merge commit)
126 #[arg(
127 long,
128 short = 'A',
129 visible_alias = "after",
130 conflicts_with_all = ["onto", "into", "revision"],
131 value_name = "REVSETS"
132 )]
133 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
134 insert_after: Option<Vec<RevisionArg>>,
135
136 /// (Experimental) The revision(s) to insert the new commit before (can be
137 /// repeated to create a merge commit)
138 #[arg(
139 long,
140 short = 'B',
141 visible_alias = "before",
142 conflicts_with_all = ["onto", "into", "revision"],
143 value_name = "REVSETS"
144 )]
145 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
146 insert_before: Option<Vec<RevisionArg>>,
147
148 /// The description to use for squashed revision (don't open editor)
149 #[arg(long = "message", short, value_name = "MESSAGE")]
150 message_paragraphs: Option<Vec<String>>,
151
152 /// Use the description of the destination revision and discard the
153 /// description(s) of the source revision(s)
154 #[arg(long, short, conflicts_with = "message_paragraphs")]
155 use_destination_message: bool,
156
157 /// Open an editor to edit the change description
158 ///
159 /// Forces an editor to open when using `--message` to allow the
160 /// message to be edited afterwards.
161 #[arg(long)]
162 editor: bool,
163
164 /// Interactively choose which parts to squash
165 #[arg(long, short)]
166 interactive: bool,
167
168 /// Specify diff editor to be used (implies --interactive)
169 #[arg(long, value_name = "NAME")]
170 #[arg(add = ArgValueCandidates::new(complete::diff_editors))]
171 tool: Option<String>,
172
173 /// Move only changes to these paths (instead of all paths)
174 #[arg(value_name = "FILESETS", value_hint = clap::ValueHint::AnyPath)]
175 #[arg(add = ArgValueCompleter::new(complete::squash_revision_files))]
176 paths: Vec<String>,
177
178 /// The source revision will not be abandoned
179 #[arg(long, short)]
180 keep_emptied: bool,
181 }
182
183 #[instrument(skip_all)]
184 pub(crate) async fn cmd_squash(
185 ui: &mut Ui,
186 command: &CommandHelper,
187 args: &SquashArgs,
188 ) -> Result<(), CommandError> {
189 let insert_destination_commit =
190 args.onto.is_some() || args.insert_after.is_some() || args.insert_before.is_some();
191
192 let mut workspace_command = command.workspace_helper(ui).await?;
193
194 let mut sources: Vec<Commit>;
195 let pre_existing_destination;
196
197 if !args.from.is_empty() || args.into.is_some() || insert_destination_commit {
198 sources = if args.from.is_empty() {
199 workspace_command.parse_revset(ui, &RevisionArg::AT)?
200 } else {
201 workspace_command.parse_union_revsets(ui, &args.from)?
202 }
203 .evaluate_to_commits()?
204 .try_collect()
205 .await?;
206 if insert_destination_commit {
207 pre_existing_destination = None;
208 } else {
209 let destination = workspace_command
210 .resolve_single_rev(ui, args.into.as_ref().unwrap_or(&RevisionArg::AT))
211 .await?;
212 // remove the destination from the sources
213 sources.retain(|source| source.id() != destination.id());
214 pre_existing_destination = Some(destination);
215 }
216 // Reverse the set so we apply the oldest commits first. It shouldn't affect the
217 // result, but it avoids creating transient conflicts and is therefore probably
218 // a little faster.
219 sources.reverse();
220 } else {
221 let revision_arg = args.revision.as_ref().unwrap_or(&RevisionArg::AT);
222 let source_expression = workspace_command.parse_revset(ui, revision_arg)?;
223 let source = evaluate_revset_to_single_commit(&source_expression)
224 .await
225 .map_err(|err| {
226 let was_multiple = matches!(err, RevsetEvaluationSizeError::Multiple(_, _));
227 let command_error = err.to_command_error(
228 revision_arg.as_ref(),
229 &workspace_command.commit_summary_template(),
230 );
231 if was_multiple {
232 command_error.hinted(
233 "--revision must resolve to a single revision. Use --from and --into \
234 instead if you want to squash multiple revisions.",
235 )
236 } else {
237 command_error
238 }
239 })?;
240 let mut parents = source.parents().await?;
241 if parents.len() != 1 {
242 return Err(
243 user_error("Cannot squash merge commits without a specified destination")
244 .hinted("Use `--into` to specify which parent to squash into"),
245 );
246 }
247 sources = vec![source];
248 pre_existing_destination = Some(parents.pop().unwrap());
249 }
250
251 workspace_command
252 .check_rewritable(sources.iter().chain(&pre_existing_destination).ids())
253 .await?;
254
255 // prepare the tx description before possibly rebasing the source commits
256 let source_ids: Vec<_> = sources.iter().ids().collect();
257 let tx_description = if let Some(destination) = &pre_existing_destination {
258 format!("squash commits into {}", destination.id().hex())
259 } else {
260 match &source_ids[..] {
261 [] => format!("squash {} commits", source_ids.len()),
262 [id] => format!("squash commit {}", id.hex()),
263 [first, others @ ..] => {
264 format!("squash commit {} and {} more", first.hex(), others.len())
265 }
266 }
267 };
268
269 let mut tx = workspace_command.start_transaction();
270 let mut num_rebased = 0;
271 let destination = if let Some(commit) = pre_existing_destination {
272 commit
273 } else {
274 // create the new destination commit
275 let (parent_ids, child_ids) = compute_commit_location(
276 ui,
277 tx.base_workspace_helper(),
278 args.onto.as_deref(),
279 args.insert_after.as_deref(),
280 args.insert_before.as_deref(),
281 "squashed commit",
282 )
283 .await?;
284 let parent_commits = try_join_all(parent_ids.iter().map(|commit_id| {
285 tx.base_workspace_helper()
286 .repo()
287 .store()
288 .get_commit_async(commit_id)
289 }))
290 .await?;
291 let merged_tree = merge_commit_trees(tx.repo(), &parent_commits).await?;
292 let commit = tx
293 .repo_mut()
294 .new_commit(parent_ids.clone(), merged_tree)
295 .write()
296 .await?;
297 let mut rewritten = HashMap::new();
298 tx.repo_mut()
299 .transform_descendants(child_ids.clone(), async |mut rewriter| {
300 let old_commit_id = rewriter.old_commit().id().clone();
301 for parent_id in &parent_ids {
302 rewriter.replace_parent(parent_id, [commit.id()]);
303 }
304 let new_parents = rewriter.new_parents();
305 if child_ids.contains(&old_commit_id) && !new_parents.contains(commit.id()) {
306 rewriter.set_new_parents(
307 new_parents
308 .iter()
309 .cloned()
310 .chain(once(commit.id().clone()))
311 .collect(),
312 );
313 }
314 let new_commit = rewriter.rebase().await?.write().await?;
315 rewritten.insert(old_commit_id, new_commit);
316 num_rebased += 1;
317 Ok(())
318 })
319 .await?;
320 for source in &mut *sources {
321 if let Some(rewritten_source) = rewritten.remove(source.id()) {
322 *source = rewritten_source;
323 }
324 }
325 commit
326 };
327
328 let fileset_expression = tx
329 .base_workspace_helper()
330 .parse_file_patterns(ui, &args.paths)?;
331 let matcher = fileset_expression.to_matcher();
332 let diff_selector =
333 tx.base_workspace_helper()
334 .diff_selector(ui, args.tool.as_deref(), args.interactive)?;
335 let text_editor = tx.base_workspace_helper().text_editor()?;
336 let squashed_description = SquashedDescription::from_args(args);
337
338 let source_commits =
339 select_diff(ui, &tx, &sources, &destination, &matcher, &diff_selector).await?;
340
341 print_unmatched_explicit_paths(
342 ui,
343 tx.base_workspace_helper(),
344 &fileset_expression,
345 source_commits.iter().map(|commit| &commit.selected_tree),
346 )
347 .await?;
348
349 if let Some(squashed) = rewrite::squash_commits(
350 tx.repo_mut(),
351 &source_commits,
352 &destination,
353 args.keep_emptied,
354 )
355 .await?
356 {
357 let mut commit_builder = squashed.commit_builder.detach();
358 let single_description = match squashed_description {
359 SquashedDescription::Exact(description) => Some(description),
360 SquashedDescription::UseDestination => Some(destination.description().to_owned()),
361 SquashedDescription::Combine => {
362 let abandoned_commits = &squashed.abandoned_commits;
363 try_combine_messages(abandoned_commits, &destination)
364 }
365 };
366 let description = if let Some(description) = single_description {
367 if description.is_empty() && !args.editor {
368 description
369 } else {
370 commit_builder.set_description(&description);
371 let description_with_trailers = add_trailers(ui, &tx, &commit_builder).await?;
372 if args.editor {
373 commit_builder.set_description(&description_with_trailers);
374 let temp_commit = commit_builder.write_hidden().await?;
375 let intro = "";
376 let template = description_template(ui, &tx, intro, &temp_commit)?;
377 edit_description(&text_editor, &template)?
378 } else {
379 description_with_trailers
380 }
381 }
382 } else {
383 // edit combined
384 let abandoned_commits = &squashed.abandoned_commits;
385 let combined = combine_messages_for_editing(
386 ui,
387 &tx,
388 abandoned_commits,
389 (!insert_destination_commit).then_some(&destination),
390 &commit_builder,
391 )
392 .await?;
393 // It's weird that commit.description() contains "JJ: " lines, but works.
394 commit_builder.set_description(combined);
395 let temp_commit = commit_builder.write_hidden().await?;
396 let intro = "Enter a description for the combined commit.";
397 let template = description_template(ui, &tx, intro, &temp_commit)?;
398 edit_description(&text_editor, &template)?
399 };
400 commit_builder.set_description(description);
401 if insert_destination_commit {
402 // forget about the intermediate commit
403 commit_builder.set_predecessors(
404 commit_builder
405 .predecessors()
406 .iter()
407 .filter(|p| p != &destination.id())
408 .cloned()
409 .collect(),
410 );
411 }
412 let commit = commit_builder.write(tx.repo_mut()).await?;
413 let num_rebased = tx.repo_mut().rebase_descendants().await?;
414 if let Some(mut formatter) = ui.status_formatter() {
415 if insert_destination_commit {
416 write!(formatter, "Created new commit ")?;
417 tx.write_commit_summary(formatter.as_mut(), &commit)?;
418 writeln!(formatter)?;
419 }
420 if num_rebased > 0 {
421 writeln!(formatter, "Rebased {num_rebased} descendant commits.")?;
422 }
423 }
424 } else {
425 if diff_selector.is_interactive() {
426 return Err(user_error("No changes selected"));
427 }
428
429 if let Some(mut formatter) = ui.status_formatter() {
430 if insert_destination_commit {
431 write!(formatter, "Created new commit ")?;
432 tx.write_commit_summary(formatter.as_mut(), &destination)?;
433 writeln!(formatter)?;
434 }
435 if num_rebased > 0 {
436 writeln!(formatter, "Rebased {num_rebased} descendant commits.")?;
437 }
438 }
439
440 if let [only_path] = &*args.paths {
441 let no_rev_arg = args.revision.is_none() && args.from.is_empty() && args.into.is_none();
442 if no_rev_arg
443 && tx
444 .base_workspace_helper()
445 .parse_revset(ui, &RevisionArg::from(only_path.to_owned()))
446 .is_ok()
447 {
448 writeln!(
449 ui.warning_default(),
450 "The argument {only_path:?} is being interpreted as a fileset expression. To \
451 specify a revset, pass -r {only_path:?} instead."
452 )?;
453 }
454 }
455 }
456 tx.finish(ui, tx_description).await?;
457 Ok(())
458 }
459
460 enum SquashedDescription {
461 // Use this exact description.
462 Exact(String),
463 // Use the destination's description and discard the descriptions of the
464 // source revisions.
465 UseDestination,
466 // Combine the descriptions of the source and destination revisions.
467 Combine,
468 }
469
470 impl SquashedDescription {
471 fn from_args(args: &SquashArgs) -> Self {
472 // These options are incompatible and Clap is configured to prevent this.
473 assert!(args.message_paragraphs.is_none() || !args.use_destination_message);
474
475 if let Some(paragraphs) = &args.message_paragraphs {
476 Self::Exact(join_message_paragraphs(paragraphs))
477 } else if args.use_destination_message {
478 Self::UseDestination
479 } else {
480 Self::Combine
481 }
482 }
483 }
484
485 async fn select_diff(
486 ui: &Ui,
487 tx: &WorkspaceCommandTransaction<'_>,
488 sources: &[Commit],
489 destination: &Commit,
490 matcher: &dyn Matcher,
491 diff_selector: &DiffSelector,
492 ) -> Result<Vec<CommitWithSelection>, CommandError> {
493 let mut source_commits = vec![];
494 for source in sources {
495 let parent_tree = source.parent_tree(tx.repo()).await?;
496 let source_tree = source.tree();
497 let format_instructions = || {
498 formatdoc! {"
499 You are moving changes from: {source}
500 into commit: {destination}
501
502 The left side of the diff shows the contents of the parent commit. The
503 right side initially shows the contents of the commit you're moving
504 changes from.
505
506 Adjust the right side until the diff shows the changes you want to move
507 to the destination. If you don't make any changes, then all the changes
508 from the source will be moved into the destination.
509 ",
510 source = tx.format_commit_summary(source),
511 destination = tx.format_commit_summary(destination),
512 }
513 };
514 let selected_tree = diff_selector
515 .select(
516 ui,
517 Diff::new(&parent_tree, &source_tree),
518 Diff::new(
519 source.parents_conflict_label().await?,
520 source.conflict_label(),
521 ),
522 matcher,
523 format_instructions,
524 )
525 .await?;
526 source_commits.push(CommitWithSelection {
527 commit: source.clone(),
528 selected_tree,
529 parent_tree,
530 });
531 }
532 Ok(source_commits)
533 }