Skip to main content

hashiverse_cli/
cli_args.rs

1//! Command-line argument definitions.
2//!
3//! Secrets (the keyphrase and the key-file password) are deliberately NOT accepted as argv
4//! flags: argv is visible to other users via `ps` and lands in shell history. They come from
5//! the `HASHIVERSE_KEYPHRASE` / `HASHIVERSE_PASSWORD` environment variables only; the CLI never
6//! prompts. See [`crate::unlock`].
7
8use clap::{Parser, Subcommand};
9use std::path::PathBuf;
10
11pub const ENV_KEYPHRASE: &str = "HASHIVERSE_KEYPHRASE";
12pub const ENV_PASSWORD: &str = "HASHIVERSE_PASSWORD";
13pub const ENV_PROFILE: &str = "HASHIVERSE_PROFILE";
14pub const ENV_DATA_DIR: &str = "HASHIVERSE_DATA_DIR";
15
16#[derive(Parser, Debug)]
17#[command(name = "hashiverse-cli", version, about = "Command-line client for Hashiverse")]
18pub struct CliArgs {
19    /// Directory holding the stored keys and client storage. Defaults to the platform data dir.
20    #[arg(long, env = ENV_DATA_DIR, global = true)]
21    pub data_dir: Option<PathBuf>,
22
23    /// Client id (hex) of a key previously stored in the data dir. Requires HASHIVERSE_PASSWORD.
24    #[arg(long, env = ENV_PROFILE, global = true)]
25    pub profile: Option<String>,
26
27    /// Override the bootstrap peers with a comma-separated list of host:port.
28    #[arg(long, value_delimiter = ',', global = true)]
29    pub bootstrap: Vec<String>,
30
31    /// Emit machine-readable JSON instead of text.
32    #[arg(long, global = true)]
33    pub json: bool,
34
35    /// Log level for the underlying client (error, warn, info, debug, trace).
36    #[arg(long, default_value = "warn", global = true)]
37    pub log_level: String,
38
39    #[command(subcommand)]
40    pub command: Option<Command>,
41}
42
43pub const DEFAULT_TRENDING_LIMIT: u16 = 20;
44
45#[derive(Subcommand, Debug, PartialEq, Eq, Clone)]
46pub enum Command {
47    /// Submit a plain-text post. #hashtags and @<64-hex client id> mentions are recognised.
48    ///
49    /// Options (e.g. --json) must come before the text: everything after the first word of text
50    /// is part of the post, so `post hi --json` posts "hi --json".
51    Post {
52        /// The post text. Multiple words are joined with spaces, so quoting is optional.
53        #[arg(required = true, num_args = 1.., trailing_var_arg = true, allow_hyphen_values = true)]
54        text: Vec<String>,
55    },
56    /// List posts by a user. Repeating this in the REPL fetches progressively older posts.
57    ///
58    /// Switching to a different timeline starts that one from the newest again.
59    User {
60        /// The user's client id (hex).
61        client_id_hex: String,
62        /// How many batches of posts to fetch.
63        #[arg(long, default_value_t = 1)]
64        pages: u32,
65    },
66    /// List posts with a hashtag. Repeating this in the REPL fetches progressively older posts.
67    ///
68    /// Switching to a different timeline starts that one from the newest again.
69    Hashtag {
70        /// The hashtag, with or without the leading '#'.
71        hashtag: String,
72        /// How many batches of posts to fetch.
73        #[arg(long, default_value_t = 1)]
74        pages: u32,
75    },
76    /// Show trending hashtags.
77    Trending {
78        /// Maximum number of hashtags to show.
79        #[arg(long, default_value_t = DEFAULT_TRENDING_LIMIT)]
80        limit: u16,
81    },
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use clap::CommandFactory;
88
89    #[test]
90    fn cli_args_definition_is_valid() {
91        CliArgs::command().debug_assert();
92    }
93
94    #[test]
95    fn bootstrap_is_comma_separated() {
96        let cli_args = CliArgs::try_parse_from(["hashiverse-cli", "--bootstrap", "1.2.3.4:443,5.6.7.8:443"]).unwrap();
97        assert_eq!(cli_args.bootstrap, vec!["1.2.3.4:443".to_string(), "5.6.7.8:443".to_string()]);
98    }
99
100    fn parse_command(argv: &[&str]) -> Command {
101        let mut full_argv = vec!["hashiverse-cli"];
102        full_argv.extend_from_slice(argv);
103        CliArgs::try_parse_from(full_argv).unwrap().command.unwrap()
104    }
105
106    #[test]
107    fn no_subcommand_is_none() {
108        assert_eq!(CliArgs::try_parse_from(["hashiverse-cli"]).unwrap().command, None);
109    }
110
111    #[test]
112    fn post_joins_unquoted_words_and_keeps_hyphens() {
113        assert_eq!(parse_command(&["post", "hello", "#world", "-", "--json-ish"]), Command::Post { text: vec!["hello".into(), "#world".into(), "-".into(), "--json-ish".into()] });
114    }
115
116    #[test]
117    fn post_options_before_text_are_parsed_as_options() {
118        let cli_args = CliArgs::try_parse_from(["hashiverse-cli", "post", "--json", "hello", "world"]).unwrap();
119        assert!(cli_args.json);
120        assert_eq!(cli_args.command, Some(Command::Post { text: vec!["hello".into(), "world".into()] }));
121    }
122
123    #[test]
124    fn post_requires_text() {
125        assert!(CliArgs::try_parse_from(["hashiverse-cli", "post"]).is_err());
126    }
127
128    #[test]
129    fn global_json_flag_works_after_subcommand() {
130        let cli_args = CliArgs::try_parse_from(["hashiverse-cli", "trending", "--json"]).unwrap();
131        assert!(cli_args.json);
132        assert_eq!(cli_args.command, Some(Command::Trending { limit: DEFAULT_TRENDING_LIMIT }));
133    }
134
135    #[test]
136    fn user_and_hashtag_pages() {
137        assert_eq!(parse_command(&["user", "abcd"]), Command::User { client_id_hex: "abcd".into(), pages: 1 });
138        assert_eq!(parse_command(&["hashtag", "#rust", "--pages", "3"]), Command::Hashtag { hashtag: "#rust".into(), pages: 3 });
139        assert_eq!(parse_command(&["trending", "--limit", "5"]), Command::Trending { limit: 5 });
140    }
141
142    #[test]
143    fn no_secret_flags_exist() {
144        assert!(CliArgs::try_parse_from(["hashiverse-cli", "--keyphrase", "x"]).is_err());
145        assert!(CliArgs::try_parse_from(["hashiverse-cli", "--password", "x"]).is_err());
146    }
147}