Debian Codegraph @

src/cli/types/key_designator.rs

raw
1 use std::str::FromStr;
2
3 use anyhow::Result;
4
5 use typenum::Unsigned;
6
7 use sequoia_openpgp as openpgp;
8 use openpgp::KeyHandle;
9
10 /// Argument parser options.
11
12 pub type DefaultOptions = typenum::U0;
13
14 /// Normally it is possible to designate multiple keys. This errors
15 /// out if there is more than one value.
16 pub type OneValue = typenum::U1;
17
18 /// Normally it is possible to designate primary keys. This errors
19 /// out if the primary key is used.
20 pub type OnlySubkeys = typenum::U2;
21
22 pub trait AdditionalDocs {
23 /// Text to be added to the help text.
24 // XXX: This should return a Cow<'static, str>, but there is no
25 // implementation of From<Cow<'static, str>> for StyledStr,
26 // see https://github.com/clap-rs/clap/issues/5785
27 fn help(_arg: &'static str, help: &'static str) -> clap::builder::StyledStr {
28 help.into()
29 }
30 }
31
32 /// No additional documentation.
33 pub struct NoDoc(());
34 impl AdditionalDocs for NoDoc {}
35
36 /// A user ID designator.
37 #[derive(Debug)]
38 pub enum KeyDesignator {
39 KeyHandle(KeyHandle),
40 }
41
42 /// A data structure that can be flattened into a clap `Command`, and
43 /// adds arguments to address key IDs.
44 ///
45 /// `Options` are the set of options to the argument parser. By
46 /// default, at least one key designator must be specified.
47 pub struct KeyDesignators<Options=typenum::U0, Doc=NoDoc>
48 {
49 /// The set of key designators.
50 pub designators: Vec<KeyDesignator>,
51
52 arguments: std::marker::PhantomData<(Options, Doc)>,
53 }
54
55 impl<Options, Doc> std::fmt::Debug for KeyDesignators<Options, Doc>
56 {
57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58 f.debug_struct("KeyDesignators")
59 .field("designators", &self.designators)
60 .finish()
61 }
62 }
63
64 #[allow(dead_code)]
65 impl KeyDesignators<DefaultOptions, NoDoc> {
66 pub fn none() -> Option<Self> {
67 None
68 }
69 }
70
71 #[allow(dead_code)]
72 impl<Options, Doc> KeyDesignators<Options, Doc> {
73 /// Like `Vec::push`.
74 pub fn push(&mut self, designator: KeyDesignator) {
75 self.designators.push(designator)
76 }
77
78 /// Like `Vec::is_empty`.
79 pub fn is_empty(&self) -> bool {
80 self.designators.is_empty()
81 }
82
83 /// Like `Vec::len`.
84 pub fn len(&self) -> usize {
85 self.designators.len()
86 }
87
88 /// Iterates over the user ID designators.
89 pub fn iter(&self) -> impl Iterator<Item=&KeyDesignator> {
90 self.designators.iter()
91 }
92 }
93
94 impl<Options, Doc> clap::Args for KeyDesignators<Options, Doc>
95 where
96 Options: typenum::Unsigned,
97 Doc: AdditionalDocs,
98 {
99 fn augment_args(mut cmd: clap::Command) -> clap::Command
100 {
101 let options = Options::to_usize();
102 let one_value = (options & OneValue::to_usize()) > 0;
103
104 let group = format!("key-designator-{:X}", options);
105 let mut arg_group = clap::ArgGroup::new(&group);
106
107 arg_group = arg_group.required(true);
108
109 if one_value {
110 arg_group = arg_group.multiple(false);
111 } else {
112 arg_group = arg_group.multiple(true);
113 }
114
115 let action = if one_value {
116 clap::ArgAction::Set
117 } else {
118 clap::ArgAction::Append
119 };
120
121 // Converts a string to a valid `KeyHandle`.
122 //
123 // Note: `<KeyHandle as FromStr>::from_str` is not enough, as
124 // we also want to bail if the fingerprint format is unknown.
125 // That is, KeyHandle will happily parse a 24 character hex
126 // string, but v4 fignerprints are 20 characters, and v6
127 // fingerprints are 32 characters.
128 fn parse_as_key_handle(s: &str) -> Result<KeyHandle> {
129 let kh = KeyHandle::from_str(s)?;
130 if kh.is_invalid() {
131 Err(anyhow::anyhow!(
132 "{:?} is not a valid fingerprint or key ID \
133 (hint: v4 fingerprints are 20 hex characters, \
134 key IDs are 16 hex characters, you provided {} \
135 characters)",
136 s, s.chars().count()))
137 } else {
138 Ok(kh)
139 }
140 }
141
142 let full_name = "key";
143 cmd = cmd.arg(
144 clap::Arg::new(&full_name)
145 .long(&full_name)
146 .value_name("FINGERPRINT|KEYID")
147 .value_parser(parse_as_key_handle)
148 .action(action.clone())
149 .help(Doc::help(
150 "doc",
151 "Use the key with the specified \
152 fingerprint or key ID")));
153 arg_group = arg_group.arg(full_name);
154
155 cmd = cmd.group(arg_group);
156
157 cmd
158 }
159
160 fn augment_args_for_update(cmd: clap::Command) -> clap::Command
161 {
162 Self::augment_args(cmd)
163 }
164 }
165
166 impl<Options, Doc> clap::FromArgMatches for KeyDesignators<Options, Doc>
167 where
168 Options: typenum::Unsigned,
169 {
170 fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches)
171 -> Result<(), clap::Error>
172 {
173 // eprintln!("matches: {:#?}", matches);
174
175 let mut designators = Vec::new();
176
177 if let Ok(Some(keys)) = matches.try_get_many::<KeyHandle>("key")
178 {
179 for key in keys.cloned() {
180 designators.push(
181 KeyDesignator::KeyHandle(key));
182 }
183 }
184
185 self.designators = designators;
186 Ok(())
187 }
188
189 fn from_arg_matches(matches: &clap::ArgMatches)
190 -> Result<Self, clap::Error>
191 {
192 let mut designators = Self {
193 designators: Vec::new(),
194 arguments: std::marker::PhantomData,
195 };
196
197 // The way we use clap, this is never called.
198 designators.update_from_arg_matches(matches)?;
199 Ok(designators)
200 }
201 }
202
203 #[cfg(test)]
204 mod test {
205 use super::*;
206
207 // Check that flattening KeyDesignators works as expected.
208 #[test]
209 fn key_designators() {
210 use clap::Parser;
211 use clap::CommandFactory;
212 use clap::FromArgMatches;
213
214 #[derive(Parser, Debug)]
215 #[clap(name = "prog")]
216 struct CLI {
217 #[command(flatten)]
218 pub keys: KeyDesignators,
219 }
220
221 let command = CLI::command();
222
223 // Check if --key is recognized.
224 let m = command.clone().try_get_matches_from(vec![
225 "prog",
226 "--key", "0D45C6A756A038670FDFD85CB1C82E8D27DB23A1",
227 "--key", "EB28F26E2739A4870ECC47726F0073F60FD0CBF0",
228 ]);
229 let m = m.expect("valid arguments");
230 let c = CLI::from_arg_matches(&m).expect("ok");
231 assert_eq!(c.keys.designators.len(), 2);
232 }
233
234 #[test]
235 fn key_designators_one() {
236 use clap::Parser;
237 use clap::CommandFactory;
238 use clap::FromArgMatches;
239
240 #[derive(Parser, Debug)]
241 #[clap(name = "prog")]
242 struct CLI {
243 #[command(flatten)]
244 pub keys: KeyDesignators<OneValue>,
245 }
246
247 let command = CLI::command();
248
249 // Check if --key is recognized.
250 let m = command.clone().try_get_matches_from(vec![
251 "prog",
252 "--key", "0D45C6A756A038670FDFD85CB1C82E8D27DB23A1",
253 ]);
254 let m = m.expect("valid arguments");
255 let c = CLI::from_arg_matches(&m).expect("ok");
256 assert_eq!(c.keys.designators.len(), 1);
257
258 // Make sure that we can't give it twice.
259 let m = command.clone().try_get_matches_from(vec![
260 "prog",
261 "--key", "0D45C6A756A038670FDFD85CB1C82E8D27DB23A1",
262 "--key", "EB28F26E2739A4870ECC47726F0073F60FD0CBF0",
263 ]);
264 assert!(m.is_err());
265
266 // Make sure that we can't give it zero times.
267 let m = command.clone().try_get_matches_from(vec![
268 "prog",
269 ]);
270 assert!(m.is_err());
271 }
272 }