Debian Codegraph @

cli/src/commands/abandon.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::io::Write as _;
17
18 use clap_complete::ArgValueCompleter;
19 use futures::TryStreamExt as _;
20 use futures::future::try_join_all;
21 use indexmap::IndexSet;
22 use itertools::Itertools as _;
23 use jj_lib::refs::diff_named_ref_targets;
24 use jj_lib::repo::Repo as _;
25 use jj_lib::revset::RevsetExpression;
26 use jj_lib::rewrite::RewriteRefsOptions;
27 use tracing::instrument;
28
29 use crate::cli_util::CommandHelper;
30 use crate::cli_util::RevisionArg;
31 #[cfg(feature = "git")]
32 use crate::cli_util::has_tracked_remote_bookmarks;
33 use crate::cli_util::print_updated_commits;
34 use crate::command_error::CommandError;
35 use crate::complete;
36 use crate::ui::Ui;
37
38 /// Abandon a revision
39 ///
40 /// Abandon a revision, rebasing descendants onto its parent(s). The behavior is
41 /// similar to `jj restore --changes-in`; the difference is that `jj abandon`
42 /// gives you a new change, while `jj restore` updates the existing change.
43 ///
44 /// If a working-copy commit gets abandoned, it will be given a new, empty
45 /// commit. This is true in general; it is not specific to this command.
46 #[derive(clap::Args, Clone, Debug)]
47 pub(crate) struct AbandonArgs {
48 /// The revision(s) to abandon (default: @) [aliases: -r]
49 #[arg(value_name = "REVSETS")]
50 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
51 revisions_pos: Vec<RevisionArg>,
52
53 #[arg(short = 'r', hide = true, value_name = "REVSETS")]
54 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
55 revisions_opt: Vec<RevisionArg>,
56
57 /// Do not delete bookmarks pointing to the revisions to abandon
58 ///
59 /// Bookmarks will be moved to the parent revisions instead.
60 #[arg(long)]
61 retain_bookmarks: bool,
62
63 /// Do not modify the content of the children of the abandoned commits
64 #[arg(long)]
65 restore_descendants: bool,
66 }
67
68 #[instrument(skip_all)]
69 pub(crate) async fn cmd_abandon(
70 ui: &mut Ui,
71 command: &CommandHelper,
72 args: &AbandonArgs,
73 ) -> Result<(), CommandError> {
74 let mut workspace_command = command.workspace_helper(ui).await?;
75 let to_abandon = {
76 let target_expr = if !args.revisions_pos.is_empty() || !args.revisions_opt.is_empty() {
77 workspace_command
78 .parse_union_revsets(ui, &[&*args.revisions_pos, &*args.revisions_opt].concat())?
79 } else {
80 workspace_command.parse_revset(ui, &RevisionArg::AT)?
81 }
82 .resolve()?;
83 let visible_expr = target_expr.intersection(&RevsetExpression::visible_heads().ancestors());
84 workspace_command
85 .check_rewritable_expr(&visible_expr)
86 .await?;
87 let visible: IndexSet<_> = visible_expr
88 .evaluate(workspace_command.repo().as_ref())?
89 .stream()
90 .try_collect()
91 .await?;
92
93 let targets: Vec<_> = target_expr
94 .evaluate(workspace_command.repo().as_ref())?
95 .stream()
96 .try_collect()
97 .await?;
98 if visible.len() < targets.len() {
99 writeln!(
100 ui.status(),
101 "Skipping {n} revisions that are already hidden.",
102 n = targets.len() - visible.len()
103 )?;
104 }
105 visible
106 };
107 if to_abandon.is_empty() {
108 writeln!(ui.status(), "No revisions to abandon.")?;
109 return Ok(());
110 }
111
112 let mut tx = workspace_command.start_transaction();
113 let options = RewriteRefsOptions {
114 delete_abandoned_bookmarks: !args.retain_bookmarks,
115 };
116 let mut num_rebased = 0;
117 tx.repo_mut()
118 .transform_descendants_with_options(
119 to_abandon.iter().cloned().collect(),
120 &RevsetExpression::none(),
121 &HashMap::new(),
122 &options,
123 async |rewriter| {
124 if to_abandon.contains(rewriter.old_commit().id()) {
125 rewriter.abandon();
126 } else if args.restore_descendants {
127 rewriter.reparent().write().await?;
128 num_rebased += 1;
129 } else {
130 rewriter.rebase().await?.write().await?;
131 num_rebased += 1;
132 }
133 Ok(())
134 },
135 )
136 .await?;
137
138 let deleted_bookmarks = diff_named_ref_targets(
139 tx.base_repo().view().local_bookmarks(),
140 tx.repo().view().local_bookmarks(),
141 )
142 .filter(|(_, (_old, new))| new.is_absent())
143 .map(|(name, _)| name.to_owned())
144 .collect_vec();
145
146 if let Some(mut formatter) = ui.status_formatter() {
147 writeln!(formatter, "Abandoned {} commits:", to_abandon.len())?;
148 let abandoned_commits = try_join_all(
149 to_abandon
150 .iter()
151 .map(|id| tx.base_repo().store().get_commit_async(id)),
152 )
153 .await?;
154 print_updated_commits(
155 formatter.as_mut(),
156 &tx.base_workspace_helper().commit_summary_template(),
157 &abandoned_commits,
158 )?;
159 if !deleted_bookmarks.is_empty() {
160 writeln!(
161 formatter,
162 "Deleted bookmarks: {}",
163 deleted_bookmarks.iter().map(|n| n.as_symbol()).join(", ")
164 )?;
165 }
166 if num_rebased > 0 {
167 if args.restore_descendants {
168 writeln!(
169 formatter,
170 "Rebased {num_rebased} descendant commits (while preserving their content) \
171 onto parents of abandoned commits.",
172 )?;
173 } else {
174 writeln!(
175 formatter,
176 "Rebased {num_rebased} descendant commits onto parents of abandoned commits.",
177 )?;
178 }
179 }
180 }
181
182 let transaction_description = if to_abandon.len() == 1 {
183 format!("abandon commit {}", to_abandon[0])
184 } else {
185 format!(
186 "abandon commit {} and {} more",
187 to_abandon[0],
188 to_abandon.len() - 1
189 )
190 };
191 tx.finish(ui, transaction_description).await?;
192
193 #[cfg(feature = "git")]
194 if jj_lib::git::get_git_backend(workspace_command.repo().store()).is_ok() {
195 let repo = workspace_command.repo().as_ref();
196 if deleted_bookmarks
197 .iter()
198 .any(|name| has_tracked_remote_bookmarks(repo, name))
199 {
200 writeln!(
201 ui.hint_default(),
202 "Deleted bookmarks can be pushed by name or all at once with `jj git push \
203 --deleted`."
204 )?;
205 }
206 }
207 Ok(())
208 }