radicle_cli/commands/
follow.rs

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
use std::ffi::OsString;

use anyhow::anyhow;

use radicle::node::{policy, Alias, AliasStore, Handle, NodeId};
use radicle::{prelude::*, Node};
use radicle_term::{Element as _, Paint, Table};

use crate::terminal as term;
use crate::terminal::args::{Args, Error, Help};

pub const HELP: Help = Help {
    name: "follow",
    description: "Manage node follow policies",
    version: env!("RADICLE_VERSION"),
    usage: r#"
Usage

    rad follow [<nid>] [--alias <name>] [<option>...]

    The `follow` command will print all nodes being followed, optionally filtered by alias, if no
    Node ID is provided.
    Otherwise, it takes a Node ID, optionally in DID format, and updates the follow policy
    for that peer, optionally giving the peer the alias provided.

Options

    --alias <name>         Associate an alias to a followed peer
    --verbose, -v          Verbose output
    --help                 Print help
"#,
};

#[derive(Debug)]
pub enum Operation {
    Follow { nid: NodeId, alias: Option<Alias> },
    List { alias: Option<Alias> },
}

#[derive(Debug, Default)]
pub enum OperationName {
    Follow,
    #[default]
    List,
}

#[derive(Debug)]
pub struct Options {
    pub op: Operation,
    pub verbose: bool,
}

impl Args for Options {
    fn from_args(args: Vec<OsString>) -> anyhow::Result<(Self, Vec<OsString>)> {
        use lexopt::prelude::*;

        let mut parser = lexopt::Parser::from_args(args);
        let mut verbose = false;
        let mut nid: Option<NodeId> = None;
        let mut alias: Option<Alias> = None;

        while let Some(arg) = parser.next()? {
            match &arg {
                Value(val) if nid.is_none() => {
                    if let Ok(did) = term::args::did(val) {
                        nid = Some(did.into());
                    } else if let Ok(val) = term::args::nid(val) {
                        nid = Some(val);
                    } else {
                        anyhow::bail!("invalid Node ID `{}` specified", val.to_string_lossy());
                    }
                }
                Long("alias") if alias.is_none() => {
                    let name = parser.value()?;
                    let name = term::args::alias(&name)?;

                    alias = Some(name.to_owned());
                }
                Long("verbose") | Short('v') => verbose = true,
                Long("help") | Short('h') => {
                    return Err(Error::Help.into());
                }
                _ => {
                    return Err(anyhow!(arg.unexpected()));
                }
            }
        }

        let op = match nid {
            Some(nid) => Operation::Follow { nid, alias },
            None => Operation::List { alias },
        };
        Ok((Options { op, verbose }, vec![]))
    }
}

pub fn run(options: Options, ctx: impl term::Context) -> anyhow::Result<()> {
    let profile = ctx.profile()?;
    let mut node = radicle::Node::new(profile.socket());

    match options.op {
        Operation::Follow { nid, alias } => follow(nid, alias, &mut node, &profile)?,
        Operation::List { alias } => following(&profile, alias)?,
    }

    Ok(())
}

pub fn follow(
    nid: NodeId,
    alias: Option<Alias>,
    node: &mut Node,
    profile: &Profile,
) -> Result<(), anyhow::Error> {
    let followed = match node.follow(nid, alias.clone()) {
        Ok(updated) => updated,
        Err(e) if e.is_connection_err() => {
            let mut config = profile.policies_mut()?;
            config.follow(&nid, alias.as_deref())?
        }
        Err(e) => return Err(e.into()),
    };
    let outcome = if followed { "updated" } else { "exists" };

    if let Some(alias) = alias {
        term::success!(
            "Follow policy {outcome} for {} ({alias})",
            term::format::tertiary(nid),
        );
    } else {
        term::success!(
            "Follow policy {outcome} for {}",
            term::format::tertiary(nid),
        );
    }

    Ok(())
}

pub fn following(profile: &Profile, alias: Option<Alias>) -> anyhow::Result<()> {
    let store = profile.policies()?;
    let aliases = profile.aliases();
    let mut t = term::Table::new(term::table::TableOptions::bordered());
    t.header([
        term::format::default(String::from("DID")),
        term::format::default(String::from("Alias")),
        term::format::default(String::from("Policy")),
    ]);
    t.divider();

    match alias {
        None => push_policies(&mut t, &aliases, store.follow_policies()?),
        Some(alias) => push_policies(
            &mut t,
            &aliases,
            store
                .follow_policies()?
                .filter(|p| p.alias.as_ref().is_some_and(|alias_| *alias_ == alias)),
        ),
    };
    t.print();

    Ok(())
}

fn push_policies(
    t: &mut Table<3, Paint<String>>,
    aliases: &impl AliasStore,
    policies: impl Iterator<Item = policy::FollowPolicy>,
) {
    for policy::FollowPolicy {
        nid: id,
        alias,
        policy,
    } in policies
    {
        t.push([
            term::format::highlight(Did::from(id).to_string()),
            match alias {
                None => term::format::secondary(fallback_alias(&id, aliases)),
                Some(alias) => term::format::secondary(alias.to_string()),
            },
            term::format::secondary(policy.to_string()),
        ]);
    }
}

fn fallback_alias(nid: &PublicKey, aliases: &impl AliasStore) -> String {
    aliases
        .alias(nid)
        .map_or("n/a".to_string(), |alias| alias.to_string())
}