1
//! The `ssh-key add` command over the `ssh-key-add` form.
2

            
3
use cli_core::{CommandError, ssh_key};
4
use rpc::Session;
5

            
6
/// The key line from the file or the inline argument.
7
6
fn key_text(key_file: Option<String>, public_key: Option<String>) -> Result<String, CommandError> {
8
6
    match (key_file, public_key) {
9
2
        (Some(path), None) => std::fs::read_to_string(&path)
10
1
            .map_err(|e| CommandError::Argument(format!("ssh-key file {path}: {e}"))),
11
3
        (None, Some(line)) => Ok(line),
12
1
        _ => Err(CommandError::Argument(
13
1
            "either --key-file or --public-key is required".to_string(),
14
1
        )),
15
    }
16
6
}
17

            
18
/// Registers the key and prints the id of the stored one.
19
3
pub async fn add(
20
3
    session: &mut Session,
21
3
    key_file: Option<String>,
22
3
    public_key: Option<String>,
23
3
    annotation: Option<String>,
24
3
) -> Result<(), CommandError> {
25
3
    let key = key_text(key_file, public_key)?;
26
3
    println!(
27
        "{}",
28
3
        ssh_key::add(session, &key, annotation.as_deref()).await?
29
    );
30
2
    Ok(())
31
3
}
32

            
33
#[cfg(test)]
34
mod tests;