1use anyhow::{bail, Result};
4use clap::Parser;
5use derive_more::FromStr;
6use futures_lite::StreamExt;
7
8use super::{AuthorsClient, ConsoleEnv};
9use crate::{cli::fmt_short, Author, AuthorId};
10
11#[allow(missing_docs)]
12#[derive(Debug, Clone, Parser)]
14pub enum AuthorCommands {
15 Switch { author: AuthorId },
17 Create {
19 #[clap(long)]
21 switch: bool,
22 },
23 Delete { author: AuthorId },
25 Export { author: AuthorId },
27 Import { author: String },
29 Default {
31 #[clap(long)]
33 switch: bool,
34 },
35 #[clap(alias = "ls")]
37 List,
38}
39
40impl AuthorCommands {
41 pub async fn run(self, authors: &AuthorsClient, env: &ConsoleEnv) -> Result<()> {
43 match self {
44 Self::Switch { author } => {
45 env.set_author(author)?;
46 println!("Active author is now {}", fmt_short(author.as_bytes()));
47 }
48 Self::List => {
49 let mut stream = authors.list().await?;
50 while let Some(author_id) = stream.try_next().await? {
51 println!("{}", author_id);
52 }
53 }
54 Self::Default { switch } => {
55 if switch && !env.is_console() {
56 bail!("The --switch flag is only supported within the Iroh console.");
57 }
58 let author_id = authors.default().await?;
59 println!("{}", author_id);
60 if switch {
61 env.set_author(author_id)?;
62 println!("Active author is now {}", fmt_short(author_id.as_bytes()));
63 }
64 }
65 Self::Create { switch } => {
66 if switch && !env.is_console() {
67 bail!("The --switch flag is only supported within the Iroh console.");
68 }
69
70 let author_id = authors.create().await?;
71 println!("{}", author_id);
72
73 if switch {
74 env.set_author(author_id)?;
75 println!("Active author is now {}", fmt_short(author_id.as_bytes()));
76 }
77 }
78 Self::Delete { author } => {
79 authors.delete(author).await?;
80 println!("Deleted author {}", fmt_short(author.as_bytes()));
81 }
82 Self::Export { author } => match authors.export(author).await? {
83 Some(author) => {
84 println!("{}", author);
85 }
86 None => {
87 println!("No author found {}", fmt_short(author.as_bytes()));
88 }
89 },
90 Self::Import { author } => match Author::from_str(&author) {
91 Ok(author) => {
92 let id = author.id();
93 authors.import(author).await?;
94 println!("Imported {}", fmt_short(id.as_bytes()));
95 }
96 Err(err) => {
97 eprintln!("Invalid author key: {}", err);
98 }
99 },
100 }
101 Ok(())
102 }
103}