Debian Codegraph @

src/commands/cert/export.rs

raw
1 use anyhow::Context;
2
3 use sequoia_openpgp as openpgp;
4 use openpgp::{
5 armor,
6 Result,
7 serialize::Serialize,
8 };
9
10 use sequoia_cert_store as cert_store;
11 use cert_store::Store;
12
13 use crate::{
14 Sq,
15 print_error_chain,
16 utils::cert_exportable,
17 };
18
19 use crate::cli::cert::export;
20 use crate::sq::TrustThreshold;
21
22 pub fn dispatch(sq: Sq, cmd: export::Command) -> Result<()> {
23 let cert_store = sq.cert_store_or_else()?;
24
25 if cmd.certs.is_empty() && ! cmd.all {
26 sq.hint(format_args!(
27 "Use --all to export all certs, or give a query."));
28 return Err(anyhow::anyhow!("no query given"));
29 }
30
31 let mut sink = cmd.output.create_pgp_safe(
32 &sq,
33 false,
34 armor::Kind::PublicKey,
35 )?;
36
37 let mut exported_something = false;
38
39 if cmd.all {
40 // Export everything.
41 for cert in cert_store.certs()
42 .filter(|c| cmd.local
43 || c.to_cert().map(cert_exportable).unwrap_or(false))
44 {
45 // Turn parse errors into warnings: we want users to be
46 // able to recover as much of their data as possible.
47 let result = cert.to_cert()
48 .with_context(|| {
49 format!("Parsing {} from certificate directory",
50 cert.fingerprint())
51 });
52 match result {
53 Ok(cert) => if cmd.local {
54 cert.serialize(&mut sink)?;
55 } else {
56 cert.export(&mut sink)?;
57 },
58 Err(err) => {
59 print_error_chain(&err);
60 continue;
61 }
62 }
63 }
64
65 // When specifying `--all`, if we have nothing and we export
66 // nothing, that is fine.
67 exported_something = true;
68 } else {
69 let (certs, errors)
70 = sq.resolve_certs(&cmd.certs, TrustThreshold::Full)?;
71 for error in errors.iter() {
72 print_error_chain(error);
73 }
74 if ! errors.is_empty() {
75 return Err(anyhow::anyhow!("Failed to resolve certificates"));
76 }
77
78 for cert in certs.into_iter() {
79 if cmd.local {
80 cert.serialize(&mut sink)?;
81 } else {
82 cert.export(&mut sink)?;
83 }
84 exported_something = true;
85 }
86 }
87
88 sink.finalize().context("Failed to export certificates")?;
89
90 if exported_something {
91 Ok(())
92 } else {
93 Err(anyhow::anyhow!("Search terms did not match any certificates"))
94 }
95 }