Debian Codegraph @

cli/src/commands/describe.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;
17 use std::io::Read as _;
18 use std::iter;
19
20 use clap_complete::ArgValueCompleter;
21 use futures::TryStreamExt as _;
22 use futures::future::try_join_all;
23 use itertools::Itertools as _;
24 use jj_lib::object_id::ObjectId as _;
25 use jj_lib::repo::Repo as _;
26 use jj_lib::revset::RevsetStreamExt as _;
27 use tracing::instrument;
28
29 use crate::cli_util::CommandHelper;
30 use crate::cli_util::RevisionArg;
31 use crate::command_error::CommandError;
32 use crate::command_error::user_error;
33 use crate::complete;
34 use crate::description_util::ParsedBulkEditMessage;
35 use crate::description_util::add_trailers_with_template;
36 use crate::description_util::description_template;
37 use crate::description_util::edit_description;
38 use crate::description_util::edit_multiple_descriptions;
39 use crate::description_util::join_message_paragraphs;
40 use crate::description_util::parse_trailers_template;
41 use crate::text_util::complete_newline;
42 use crate::ui::Ui;
43
44 /// Update the change description or other metadata [default alias: desc]
45 ///
46 /// Starts an editor to let you edit the description of changes. Set `ui.editor`
47 /// to customize your editor. See `jj help -k config` or the [editor docs] for
48 /// more information on how the editor is chosen.
49 ///
50 /// [editor docs]: https://docs.jj-vcs.dev/latest/config/#editor
51 #[derive(clap::Args, Clone, Debug)]
52 pub(crate) struct DescribeArgs {
53 /// The revision(s) whose description to edit (default: @) [aliases: -r]
54 #[arg(value_name = "REVSETS")]
55 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
56 revisions_pos: Vec<RevisionArg>,
57
58 #[arg(short = 'r', hide = true, value_name = "REVSETS")]
59 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
60 revisions_opt: Vec<RevisionArg>,
61
62 /// The change description to use (don't open editor)
63 ///
64 /// If multiple revisions are specified, the same description will be used
65 /// for all of them.
66 #[arg(
67 long = "message",
68 short,
69 value_name = "MESSAGE",
70 conflicts_with = "stdin"
71 )]
72 message_paragraphs: Option<Vec<String>>,
73
74 /// Read the change description from stdin
75 ///
76 /// If multiple revisions are specified, the same description will be used
77 /// for all of them.
78 #[arg(long)]
79 stdin: bool,
80
81 /// Open an editor to edit the change description
82 ///
83 /// Forces an editor to open when using `--stdin` or `--message` to
84 /// allow the message to be edited afterwards.
85 #[arg(long)]
86 editor: bool,
87 }
88
89 #[instrument(skip_all)]
90 pub(crate) async fn cmd_describe(
91 ui: &mut Ui,
92 command: &CommandHelper,
93 args: &DescribeArgs,
94 ) -> Result<(), CommandError> {
95 let mut workspace_command = command.workspace_helper(ui).await?;
96 let target_expr = if !args.revisions_pos.is_empty() || !args.revisions_opt.is_empty() {
97 workspace_command
98 .parse_union_revsets(ui, &[&*args.revisions_pos, &*args.revisions_opt].concat())?
99 } else {
100 workspace_command.parse_revset(ui, &RevisionArg::AT)?
101 }
102 .resolve()?;
103 workspace_command
104 .check_rewritable_expr(&target_expr)
105 .await?;
106 let commits: Vec<_> = target_expr
107 .evaluate(workspace_command.repo().as_ref())?
108 .stream()
109 .commits(workspace_command.repo().store()) // in reverse topological order
110 .try_collect()
111 .await?;
112 if commits.is_empty() {
113 writeln!(ui.status(), "No revisions to describe.")?;
114 return Ok(());
115 }
116 let text_editor = workspace_command.text_editor()?;
117
118 let mut tx = workspace_command.start_transaction();
119 let tx_description = match commits.as_slice() {
120 [] => unreachable!(),
121 [commit] => format!("describe commit {}", commit.id().hex()),
122 [first_commit, remaining_commits @ ..] => {
123 format!(
124 "describe commit {} and {} more",
125 first_commit.id().hex(),
126 remaining_commits.len()
127 )
128 }
129 };
130
131 let shared_description = if args.stdin {
132 let mut buffer = String::new();
133 io::stdin().read_to_string(&mut buffer)?;
134 Some(complete_newline(buffer))
135 } else {
136 args.message_paragraphs
137 .as_deref()
138 .map(join_message_paragraphs)
139 };
140
141 let mut commit_builders = commits
142 .iter()
143 .map(|commit| {
144 let mut commit_builder = tx.repo_mut().rewrite_commit(commit).detach();
145 if let Some(description) = &shared_description {
146 commit_builder.set_description(description);
147 }
148 commit_builder
149 })
150 .collect_vec();
151
152 let use_editor = args.editor || shared_description.is_none();
153
154 if let Some(trailer_template) = parse_trailers_template(ui, &tx)? {
155 for commit_builder in &mut commit_builders {
156 // The first trailer would become the first line of the description.
157 // Also, a commit with no description is treated in a special way in jujutsu: it
158 // can be discarded as soon as it's no longer the working copy. Adding a
159 // trailer to an empty description would break that logic.
160 if use_editor || !commit_builder.description().is_empty() {
161 let temp_commit = commit_builder.write_hidden().await?;
162 let new_description = add_trailers_with_template(&trailer_template, &temp_commit)?;
163 commit_builder.set_description(new_description);
164 }
165 }
166 }
167
168 if use_editor {
169 let temp_commits: Vec<_> = try_join_all(
170 iter::zip(&commits, &commit_builders)
171 // Edit descriptions in topological order
172 .rev()
173 .map(async |(commit, commit_builder)| {
174 commit_builder
175 .write_hidden()
176 .await
177 .map(|temp_commit| (commit.id(), temp_commit))
178 }),
179 )
180 .await?;
181
182 if let [(_, temp_commit)] = &*temp_commits {
183 let intro = "";
184 let template = description_template(ui, &tx, intro, temp_commit)?;
185 let description = edit_description(&text_editor, &template)?;
186 commit_builders[0].set_description(description);
187 } else {
188 let ParsedBulkEditMessage {
189 descriptions,
190 missing,
191 duplicates,
192 unexpected,
193 } = edit_multiple_descriptions(ui, &text_editor, &tx, &temp_commits)?;
194 if !missing.is_empty() {
195 return Err(user_error(format!(
196 "The description for the following commits were not found in the edited \
197 message: {}",
198 missing.join(", ")
199 )));
200 }
201 if !duplicates.is_empty() {
202 return Err(user_error(format!(
203 "The following commits were found in the edited message multiple times: {}",
204 duplicates.join(", ")
205 )));
206 }
207 if !unexpected.is_empty() {
208 return Err(user_error(format!(
209 "The following commits were not being edited, but were found in the edited \
210 message: {}",
211 unexpected.join(", ")
212 )));
213 }
214
215 for (commit, commit_builder) in iter::zip(&commits, &mut commit_builders) {
216 let description = descriptions.get(commit.id()).unwrap();
217 commit_builder.set_description(description);
218 }
219 }
220 }
221
222 // Filter out unchanged commits to avoid rebasing descendants in
223 // `transform_descendants` below unnecessarily.
224 let commit_builders: HashMap<_, _> = iter::zip(&commits, commit_builders)
225 .filter(|(old_commit, commit_builder)| {
226 old_commit.description() != commit_builder.description()
227 })
228 .map(|(old_commit, commit_builder)| (old_commit.id(), commit_builder))
229 .collect();
230
231 let mut num_described = 0;
232 let mut num_reparented = 0;
233 // Even though `MutableRepo::rewrite_commit` and
234 // `MutableRepo::rebase_descendants` can handle rewriting of a commit even
235 // if it is a descendant of another commit being rewritten, using
236 // `MutableRepo::transform_descendants` prevents us from rewriting the same
237 // commit multiple times, and adding additional entries in the predecessor
238 // chain.
239 tx.repo_mut()
240 .transform_descendants(
241 commit_builders.keys().map(|&id| id.clone()).collect(),
242 async |rewriter| {
243 let old_commit_id = rewriter.old_commit().id().clone();
244 let commit_builder = rewriter.reparent();
245 if let Some(temp_builder) = commit_builders.get(&old_commit_id) {
246 commit_builder
247 .set_description(temp_builder.description())
248 .write()
249 .await?;
250 num_described += 1;
251 } else {
252 commit_builder.write().await?;
253 num_reparented += 1;
254 }
255 Ok(())
256 },
257 )
258 .await?;
259 if num_described > 1 {
260 writeln!(ui.status(), "Updated {num_described} commits.")?;
261 }
262 if num_reparented > 0 {
263 writeln!(ui.status(), "Rebased {num_reparented} descendant commits.")?;
264 }
265 tx.finish(ui, tx_description).await?;
266 Ok(())
267 }