1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use clap::Args;
use colorful::Colorful;
use miette::miette;

use ockam_node::Context;

use crate::util::node_rpc;
use crate::{docs, fmt_ok, CommandGlobalOpts};

const LONG_ABOUT: &str = include_str!("./static/default/long_about.txt");
const AFTER_LONG_HELP: &str = include_str!("./static/default/after_long_help.txt");

/// Change the default node
#[derive(Clone, Debug, Args)]
#[command(
long_about = docs::about(LONG_ABOUT),
after_long_help = docs::after_help(AFTER_LONG_HELP)
)]
pub struct DefaultCommand {
    /// Name of the node to set as default
    node_name: Option<String>,
}

impl DefaultCommand {
    pub fn run(self, opts: CommandGlobalOpts) {
        node_rpc(run_impl, (opts, self));
    }
}

async fn run_impl(
    _cxt: Context,
    (opts, cmd): (CommandGlobalOpts, DefaultCommand),
) -> miette::Result<()> {
    if let Some(node_name) = cmd.node_name {
        if opts
            .state
            .get_node(&node_name)
            .await
            .ok()
            .map(|n| n.is_default())
            .unwrap_or(false)
        {
            return Err(miette!("The node '{node_name}' is already the default"));
        } else {
            opts.state.set_default_node(&node_name).await?;
            opts.terminal
                .stdout()
                .plain(fmt_ok!("The node '{node_name}' is now the default"))
                .machine(&node_name)
                .write_line()?;
        }
    } else {
        let default_node_name = opts.state.get_default_node().await?.name();
        let _ = opts
            .terminal
            .stdout()
            .plain(fmt_ok!("The default node is '{default_node_name}'"))
            .write_line();
    }
    Ok(())
}