Debian Codegraph @

cli/src/commands/sign.rs

raw
1 // Copyright 2023 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 clap_complete::ArgValueCompleter;
16 use futures::TryStreamExt as _;
17 use indexmap::IndexSet;
18 use itertools::Itertools as _;
19 use jj_lib::commit::Commit;
20 use jj_lib::commit::CommitIteratorExt as _;
21 use jj_lib::repo::Repo as _;
22 use jj_lib::revset::RevsetStreamExt as _;
23 use jj_lib::signing::SignBehavior;
24
25 use crate::cli_util::CommandHelper;
26 use crate::cli_util::RevisionArg;
27 use crate::cli_util::print_updated_commits;
28 use crate::cli_util::short_change_hash;
29 use crate::command_error::CommandError;
30 use crate::command_error::user_error;
31 use crate::complete;
32 use crate::progress::ProgressWriter;
33 use crate::ui::Ui;
34
35 /// Cryptographically sign a revision
36 ///
37 /// This command requires configuring a [commit signing] backend.
38 ///
39 /// [commit signing]:
40 /// https://docs.jj-vcs.dev/latest/config/#commit-signing
41 #[derive(clap::Args, Clone, Debug)]
42 pub struct SignArgs {
43 /// What revision(s) to sign
44 ///
45 /// If no revisions are specified, this defaults to the `revsets.sign`
46 /// setting.
47 ///
48 /// Note that revisions are always re-signed.
49 ///
50 /// While that leads to discomfort for users, which sign with hardware
51 /// devices, as of now we cannot reliably check if a commit is already
52 /// signed by the user without creating a signature (see [#5786]).
53 ///
54 /// [#5786]:
55 /// https://github.com/jj-vcs/jj/issues/5786
56 #[arg(long = "revision", short, value_name = "REVSETS", alias = "revisions")]
57 #[arg(add = ArgValueCompleter::new(complete::revset_expression_mutable))]
58 revisions: Vec<RevisionArg>,
59
60 /// The key used for signing
61 #[arg(long)]
62 key: Option<String>,
63 }
64
65 pub async fn cmd_sign(
66 ui: &mut Ui,
67 command: &CommandHelper,
68 args: &SignArgs,
69 ) -> Result<(), CommandError> {
70 let mut workspace_command = command.workspace_helper(ui).await?;
71
72 if !workspace_command.repo().store().signer().can_sign() {
73 return Err(user_error(
74 "No signing backend configured").hinted(
75 "For configuring a signing backend, see https://docs.jj-vcs.dev/latest/config/#commit-signing",
76 ));
77 }
78
79 let revset_expression = if args.revisions.is_empty() {
80 let revset_string = workspace_command.settings().get_string("revsets.sign")?;
81 workspace_command.parse_revset(ui, &RevisionArg::from(revset_string))?
82 } else {
83 workspace_command.parse_union_revsets(ui, &args.revisions)?
84 }
85 .resolve()?;
86
87 workspace_command
88 .check_rewritable_expr(&revset_expression)
89 .await?;
90
91 let to_sign: IndexSet<Commit> = revset_expression
92 .evaluate(workspace_command.repo().as_ref())?
93 .stream()
94 .commits(workspace_command.repo().store())
95 .try_collect()
96 .await?;
97
98 let mut tx = workspace_command.start_transaction();
99
100 let mut signed_commits = vec![];
101 let mut num_reparented = 0;
102
103 {
104 let mut progress_writer = ProgressWriter::new(ui, "Signing");
105
106 tx.repo_mut()
107 .transform_descendants(
108 to_sign.iter().ids().cloned().collect_vec(),
109 async |rewriter| {
110 let old_commit = rewriter.old_commit().clone();
111 let mut commit_builder = rewriter.reparent();
112
113 if let Some(writer) = &mut progress_writer {
114 writer
115 .display(&short_change_hash(old_commit.change_id()))
116 .ok();
117 }
118
119 if to_sign.contains(&old_commit) {
120 if let Some(key) = &args.key {
121 commit_builder = commit_builder.set_sign_key(key.clone());
122 }
123
124 let new_commit = commit_builder
125 .set_sign_behavior(SignBehavior::Force)
126 .write()
127 .await?;
128
129 signed_commits.push(new_commit);
130 } else {
131 commit_builder.write().await?;
132 num_reparented += 1;
133 }
134
135 Ok(())
136 },
137 )
138 .await?;
139 }
140
141 if let Some(mut formatter) = ui.status_formatter()
142 && !signed_commits.is_empty()
143 {
144 writeln!(formatter, "Signed {} commits:", signed_commits.len())?;
145 print_updated_commits(
146 formatter.as_mut(),
147 &tx.commit_summary_template(),
148 &signed_commits,
149 )?;
150 }
151
152 let num_not_authored_by_me = signed_commits
153 .iter()
154 .filter(|commit| commit.author().email != tx.settings().user_email())
155 .count();
156 if num_not_authored_by_me > 0 {
157 writeln!(
158 ui.warning_default(),
159 "{num_not_authored_by_me} of these commits are not authored by you.",
160 )?;
161 }
162
163 if num_reparented > 0 {
164 writeln!(ui.status(), "Rebased {num_reparented} descendant commits.")?;
165 }
166
167 let transaction_description = match &*signed_commits {
168 [] => "".to_string(),
169 [commit] => format!("sign commit {}", commit.id()),
170 commits => format!(
171 "sign commit {} and {} more",
172 commits[0].id(),
173 commits.len() - 1
174 ),
175 };
176 tx.finish(ui, transaction_description).await?;
177
178 Ok(())
179 }