Debian Codegraph @

cli/src/commands/revert.rs

raw
1 // Copyright 2025 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
17 use bstr::ByteVec as _;
18 use clap::ArgGroup;
19 use clap_complete::ArgValueCompleter;
20 use futures::TryStreamExt as _;
21 use futures::future::try_join_all;
22 use indexmap::IndexSet;
23 use itertools::Itertools as _;
24 use jj_lib::backend::CommitId;
25 use jj_lib::commit::conflict_label_for_commits;
26 use jj_lib::merge::Merge;
27 use jj_lib::merged_tree::MergedTree;
28 use jj_lib::object_id::ObjectId as _;
29 use jj_lib::repo::Repo as _;
30 use jj_lib::rewrite::merge_commit_trees;
31 use tracing::instrument;
32
33 use crate::cli_util::CommandHelper;
34 use crate::cli_util::RevisionArg;
35 use crate::cli_util::compute_commit_location;
36 use crate::cli_util::print_updated_commits;
37 use crate::command_error::CommandError;
38 use crate::complete;
39 use crate::ui::Ui;
40
41 /// Apply the reverse of the given revision(s)
42 ///
43 /// The reverse of each of the given revisions is applied sequentially in
44 /// reverse topological order at the given location.
45 ///
46 /// The description of the new revisions can be customized with the
47 /// `templates.revert_description` config variable.
48 #[derive(clap::Args, Clone, Debug)]
49 #[command(group(ArgGroup::new("location").args(&["onto", "insert_after", "insert_before"]).multiple(true).required(true)))]
50 pub(crate) struct RevertArgs {
51 /// The revision(s) to apply the reverse of
52 #[arg(
53 long = "revision",
54 short,
55 value_name = "REVSETS",
56 required = true,
57 alias = "revisions"
58 )]
59 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
60 revisions: Vec<RevisionArg>,
61
62 /// The revision(s) to apply the reverse changes on top of
63 #[arg(
64 long,
65 visible_alias = "destination",
66 short,
67 visible_short_alias = 'd',
68 value_name = "REVSETS"
69 )]
70 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
71 onto: Option<Vec<RevisionArg>>,
72
73 /// The revision(s) to insert the reverse changes after (can be repeated to
74 /// create a merge commit)
75 #[arg(
76 long,
77 short = 'A',
78 visible_alias = "after",
79 conflicts_with = "onto",
80 value_name = "REVSETS"
81 )]
82 #[arg(add = ArgValueCompleter::new(complete::revset_expression_all))]
83 insert_after: Option<Vec<RevisionArg>>,
84
85 /// The revision(s) to insert the reverse changes before (can be repeated to
86 /// create a merge commit)
87 #[arg(
88 long,
89 short = 'B',
90 visible_alias = "before",
91 conflicts_with = "onto",
92 value_name = "REVSETS"
93 )]
94 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
95 insert_before: Option<Vec<RevisionArg>>,
96 }
97
98 #[instrument(skip_all)]
99 pub(crate) async fn cmd_revert(
100 ui: &mut Ui,
101 command: &CommandHelper,
102 args: &RevertArgs,
103 ) -> Result<(), CommandError> {
104 let mut workspace_command = command.workspace_helper(ui).await?;
105 let to_revert: Vec<_> = workspace_command
106 .parse_union_revsets(ui, &args.revisions)?
107 .evaluate_to_commits()?
108 .try_collect()
109 .await?; // in reverse topological order
110 if to_revert.is_empty() {
111 writeln!(ui.status(), "No revisions to revert.")?;
112 return Ok(());
113 }
114 let (new_parent_ids, new_child_ids) = compute_commit_location(
115 ui,
116 &workspace_command,
117 args.onto.as_deref(),
118 args.insert_after.as_deref(),
119 args.insert_before.as_deref(),
120 "reverted commits",
121 )
122 .await?;
123 let transaction_description = if to_revert.len() == 1 {
124 format!("revert commit {}", to_revert[0].id().hex())
125 } else {
126 format!(
127 "revert commit {} and {} more",
128 to_revert[0].id().hex(),
129 to_revert.len() - 1
130 )
131 };
132 let commits_to_revert_with_new_commit_descriptions = {
133 let template_text = command
134 .settings()
135 .get_string("templates.revert_description")?;
136 let template = workspace_command.parse_commit_template(ui, &template_text)?;
137
138 to_revert
139 .into_iter()
140 .map(|commit| {
141 let commit_description = template.format_plain_text(&commit).into_string_lossy();
142 (commit, commit_description)
143 })
144 .collect_vec()
145 };
146 let mut tx = workspace_command.start_transaction();
147 let original_parent_commit_ids: HashSet<_> = new_parent_ids.iter().cloned().collect();
148 let new_parents = try_join_all(
149 new_parent_ids
150 .iter()
151 .map(|id| tx.repo().store().get_commit_async(id)),
152 )
153 .await?;
154 let mut new_base_tree = merge_commit_trees(tx.repo(), &new_parents).await?;
155 let mut parent_ids = new_parent_ids;
156 let mut parent_labels = conflict_label_for_commits(&new_parents);
157
158 let mut reverted_commits = vec![];
159 for (commit_to_revert, new_commit_description) in
160 &commits_to_revert_with_new_commit_descriptions
161 {
162 let old_parents = commit_to_revert.parents().await?;
163 let old_base_tree = commit_to_revert.parent_tree(tx.repo()).await?;
164 let old_tree = commit_to_revert.tree();
165 let new_tree = MergedTree::merge(Merge::from_vec(vec![
166 (
167 new_base_tree,
168 format!("{parent_labels} (revert destination)"),
169 ),
170 (
171 old_tree,
172 format!("{} (reverted revision)", commit_to_revert.conflict_label()),
173 ),
174 (
175 old_base_tree,
176 format!(
177 "{} (parents of reverted revision)",
178 conflict_label_for_commits(&old_parents)
179 ),
180 ),
181 ]))
182 .await?;
183 let new_commit = tx
184 .repo_mut()
185 .new_commit(parent_ids, new_tree.clone())
186 .set_description(new_commit_description)
187 .write()
188 .await?;
189 parent_ids = vec![new_commit.id().clone()];
190 parent_labels = new_commit.conflict_label();
191 reverted_commits.push(new_commit);
192 new_base_tree = new_tree;
193 }
194
195 // Rebase new children onto the reverted commit.
196 let new_head_ids: Vec<_> = parent_ids;
197 let children_commit_ids_set: HashSet<CommitId> = new_child_ids.iter().cloned().collect();
198 let mut num_rebased = 0;
199 tx.repo_mut()
200 .transform_descendants(new_child_ids, async |mut rewriter| {
201 if children_commit_ids_set.contains(rewriter.old_commit().id()) {
202 let mut child_new_parent_ids = IndexSet::new();
203 for old_parent_id in rewriter.old_commit().parent_ids() {
204 // If the original parents of the new children are the new parents of
205 // `target_head_ids`, replace them with `new_head_ids` since we are
206 // "inserting" the new commits in between the new parents and the new
207 // children.
208 if original_parent_commit_ids.contains(old_parent_id) {
209 child_new_parent_ids.extend(new_head_ids.clone());
210 } else {
211 child_new_parent_ids.insert(old_parent_id.clone());
212 }
213 }
214 // If not already present, add `new_head_ids` as parents of the new child
215 // commit.
216 child_new_parent_ids.extend(new_head_ids.clone());
217 rewriter.set_new_parents(child_new_parent_ids.into_iter().collect());
218 }
219 num_rebased += 1;
220 rewriter.rebase().await?.write().await?;
221 Ok(())
222 })
223 .await?;
224
225 if let Some(mut formatter) = ui.status_formatter() {
226 writeln!(
227 formatter,
228 "Reverted {} commits as follows:",
229 reverted_commits.len()
230 )?;
231 print_updated_commits(
232 formatter.as_mut(),
233 &tx.commit_summary_template(),
234 &reverted_commits,
235 )?;
236 if num_rebased > 0 {
237 writeln!(formatter, "Rebased {num_rebased} descendant commits.")?;
238 }
239 }
240 tx.finish(ui, transaction_description).await?;
241
242 Ok(())
243 }