cli/command/
key.rs

1// SPDX-License-Identifier: GPL-3-0-or-later
2// Copyright (c) 2025 Opinsys Oy
3
4use crate::{
5    cli::SubCommand,
6    command::CommandError,
7    context::{ContextCache, ContextItem},
8    device::{Device, DeviceError},
9    key,
10};
11use argh::FromArgs;
12use std::{cell::RefCell, rc::Rc};
13use tabled::Tabled;
14
15#[derive(Tabled)]
16struct KeyRow {
17    #[tabled(rename = "GRIP")]
18    grip: String,
19    #[tabled(rename = "DETAILS")]
20    details: String,
21}
22
23/// Lists cached keys.
24#[derive(FromArgs, Debug)]
25#[argh(subcommand, name = "key", note = "Lists keys from local cache.")]
26pub struct Key {}
27
28impl SubCommand for Key {
29    fn run(
30        &self,
31        device: Option<Rc<RefCell<Device>>>,
32        context: &mut ContextCache,
33        plain: bool,
34    ) -> Result<(), CommandError> {
35        let device_rc = device.ok_or(DeviceError::NotAvailable)?;
36        let mut rows: Vec<KeyRow> = Vec::new();
37
38        for item_result in context.loaded_contexts(device_rc) {
39            match item_result? {
40                ContextItem::Loaded(loaded_context) => {
41                    let grip = loaded_context.grip.clone();
42                    let alg_string = key::format_alg_from_public(&loaded_context.public);
43                    rows.push(KeyRow {
44                        grip,
45                        details: alg_string,
46                    });
47                }
48                ContextItem::Stale(grip) => {
49                    log::warn!("key://{grip} stale");
50                }
51            }
52        }
53
54        rows.sort_unstable_by(|a, b| a.grip.cmp(&b.grip));
55
56        super::print_table(&mut context.writer, rows, plain)?;
57
58        Ok(())
59    }
60}