Debian Codegraph @

cli/src/commands/metaedit.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 clap_complete::ArgValueCompleter;
18 use futures::TryStreamExt as _;
19 use jj_lib::backend::Timestamp;
20 use jj_lib::commit::Commit;
21 use jj_lib::object_id::ObjectId as _;
22 use jj_lib::time_util::parse_datetime;
23 use tracing::instrument;
24
25 use crate::cli_util::CommandHelper;
26 use crate::cli_util::RevisionArg;
27 use crate::cli_util::print_updated_commits;
28 use crate::command_error::CommandError;
29 use crate::complete;
30 use crate::description_util::join_message_paragraphs;
31 use crate::text_util::parse_author;
32 use crate::ui::Ui;
33
34 /// Modify the metadata of a revision without changing its content
35 ///
36 /// Whenever any metadata is updated, the committer name, email, and timestamp
37 /// are also updated for all rebased commits. The name and email may come from
38 /// the `JJ_USER` and `JJ_EMAIL` environment variables, as well as by passing
39 /// `--config user.name` and `--config user.email`.
40 #[derive(clap::Args, Clone, Debug)]
41 pub(crate) struct MetaeditArgs {
42 /// The revision(s) to modify (default: @) [aliases: -r]
43 #[arg(value_name = "REVSETS")]
44 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
45 revisions_pos: Vec<RevisionArg>,
46
47 #[arg(short = 'r', hide = true, value_name = "REVSETS")]
48 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
49 revisions_opt: Vec<RevisionArg>,
50
51 /// Generate a new change-id
52 ///
53 /// This generates a new change-id for the revision.
54 #[arg(long)]
55 update_change_id: bool,
56
57 /// Update the change description
58 ///
59 /// This updates the change description, without opening the editor.
60 ///
61 /// Use `jj describe` if you want to use an editor.
62 #[arg(long = "message", short, value_name = "MESSAGE")]
63 message_paragraphs: Option<Vec<String>>,
64
65 /// Update the author timestamp
66 ///
67 /// This updates the author date to the current time, without modifying the
68 /// author.
69 #[arg(long)]
70 update_author_timestamp: bool,
71
72 /// Update the author to the configured user
73 ///
74 /// This updates the author name and email. The author timestamp is
75 /// not modified – use --update-author-timestamp to update the author
76 /// timestamp.
77 ///
78 /// You can use it in combination with the JJ_USER and JJ_EMAIL
79 /// environment variables to set a different author:
80 ///
81 /// $ JJ_USER='Foo Bar' [email protected] jj metaedit --update-author
82 #[arg(long)]
83 update_author: bool,
84
85 /// Set author to the provided string
86 ///
87 /// This changes author name and email while retaining author
88 /// timestamp for non-discardable commits.
89 ///
90 /// ```shell
91 /// $ jj metaedit --author "Foo Bar <[email protected]>"
92 /// ```
93 #[arg(
94 long,
95 conflicts_with = "update_author",
96 value_parser = parse_author
97 )]
98 author: Option<(String, String)>,
99
100 /// Set the author date to the given date
101 ///
102 /// The date can either be human readable
103 /// ([RFC2822], eg 'Sun, 23 Jan 2000 01:23:45 PST')
104 /// or a time stamp ([RFC3339], eg '2000-01-23T01:23:45-08:00').
105 ///
106 /// [RFC2822]: https://datatracker.ietf.org/doc/html/rfc2822
107 ///
108 /// [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339
109 #[arg(
110 long,
111 conflicts_with = "update_author_timestamp",
112 value_parser = parse_datetime
113 )]
114 author_timestamp: Option<Timestamp>,
115
116 /// Rewrite the commit, even if no other metadata changed
117 ///
118 /// This updates the committer timestamp to the current time, as well as the
119 /// committer name and email.
120 ///
121 /// Even if this option is not passed, the committer name, email, and
122 /// timestamp will be updated if other metadata is updated. This option
123 /// just forces every commit to be rewritten whether or not there are other
124 /// changes.
125 ///
126 /// You can use it in combination with the `JJ_USER` and `JJ_EMAIL`
127 /// environment variables to set a different committer:
128 ///
129 /// $ JJ_USER='Foo Bar' [email protected] jj metaedit --force-rewrite
130 #[arg(long)]
131 force_rewrite: bool,
132 }
133
134 #[instrument(skip_all)]
135 pub(crate) async fn cmd_metaedit(
136 ui: &mut Ui,
137 command: &CommandHelper,
138 args: &MetaeditArgs,
139 ) -> Result<(), CommandError> {
140 let mut workspace_command = command.workspace_helper(ui).await?;
141
142 let target_expr = if !args.revisions_pos.is_empty() || !args.revisions_opt.is_empty() {
143 workspace_command
144 .parse_union_revsets(ui, &[&*args.revisions_pos, &*args.revisions_opt].concat())?
145 } else {
146 workspace_command.parse_revset(ui, &RevisionArg::AT)?
147 }
148 .resolve()?;
149 workspace_command
150 .check_rewritable_expr(&target_expr)
151 .await?;
152 let commit_ids: Vec<_> = target_expr
153 .evaluate(workspace_command.repo().as_ref())?
154 .stream()
155 .try_collect()
156 .await?;
157 if commit_ids.is_empty() {
158 writeln!(ui.status(), "No revisions to modify.")?;
159 return Ok(());
160 }
161
162 let mut tx = workspace_command.start_transaction();
163 let tx_description = match commit_ids.as_slice() {
164 [] => unreachable!(),
165 [commit] => format!("edit commit metadata for commit {}", commit.hex()),
166 [first_commit, remaining_commits @ ..] => {
167 format!(
168 "edit commit metadata for commit {} and {} more",
169 first_commit.hex(),
170 remaining_commits.len()
171 )
172 }
173 };
174
175 let new_description = args
176 .message_paragraphs
177 .as_deref()
178 .map(join_message_paragraphs);
179
180 let mut num_reparented = 0;
181 let commit_ids_set: HashSet<_> = commit_ids.iter().cloned().collect();
182 let mut modified: Vec<Commit> = Vec::new();
183 // Even though `MutableRepo::rewrite_commit` and
184 // `MutableRepo::rebase_descendants` can handle rewriting of a commit even
185 // if it is a descendant of another commit being rewritten, using
186 // `MutableRepo::transform_descendants` prevents us from rewriting the same
187 // commit multiple times, and adding additional entries in the predecessor
188 // chain.
189 tx.repo_mut()
190 .transform_descendants(commit_ids, async |rewriter| {
191 if commit_ids_set.contains(rewriter.old_commit().id()) {
192 let mut rewrite = args.force_rewrite || rewriter.parents_changed();
193
194 let old_author = rewriter.old_commit().author().clone();
195 let mut commit_builder = rewriter.reparent();
196 let mut new_author = commit_builder.author().clone();
197 if let Some((name, email)) = args.author.clone() {
198 new_author.name = name;
199 new_author.email = email;
200 } else if args.update_author {
201 new_author.name = commit_builder.committer().name.clone();
202 new_author.email = commit_builder.committer().email.clone();
203 }
204 if args.update_author_timestamp {
205 new_author.timestamp = commit_builder.committer().timestamp;
206 }
207 if let Some(author_date) = args.author_timestamp {
208 new_author.timestamp = author_date;
209 }
210 // If the old commit had an unset author, the commit builder
211 // may already have the author updated from the current config.
212 // Thus, compare to the actual old_author to correctly detect
213 // changes.
214 if new_author.name != old_author.name
215 || new_author.email != old_author.email
216 || (new_author.timestamp != commit_builder.author().timestamp
217 && new_author.timestamp != old_author.timestamp)
218 {
219 commit_builder = commit_builder.set_author(new_author);
220 rewrite = true;
221 }
222
223 if let Some(description) = &new_description
224 && description != commit_builder.description()
225 {
226 commit_builder = commit_builder.set_description(description);
227 rewrite = true;
228 }
229
230 if args.update_change_id {
231 commit_builder = commit_builder.generate_new_change_id();
232 rewrite = true;
233 }
234
235 if rewrite {
236 let new_commit = commit_builder.write().await?;
237 modified.push(new_commit);
238 }
239 } else if rewriter.parents_changed() {
240 rewriter.reparent().write().await?;
241 num_reparented += 1;
242 }
243 Ok(())
244 })
245 .await?;
246 if !modified.is_empty() {
247 writeln!(ui.status(), "Modified {} commits:", modified.len())?;
248 if let Some(mut formatter) = ui.status_formatter() {
249 print_updated_commits(formatter.as_mut(), &tx.commit_summary_template(), &modified)?;
250 }
251 }
252 if num_reparented > 0 {
253 writeln!(ui.status(), "Rebased {num_reparented} descendant commits.")?;
254 }
255 tx.finish(ui, tx_description).await?;
256 Ok(())
257 }