Skip to main content

indodax_cli/commands/
utility.rs

1use std::collections::HashMap;
2use crate::client::IndodaxClient;
3use crate::config::ResolvedCredentials;
4use crate::output::CommandOutput;
5use anyhow::Result;
6
7#[derive(Debug, clap::Subcommand)]
8pub enum UtilityCommand {
9    #[command(name = "setup", about = "Interactive setup wizard")]
10    Setup,
11
12    #[command(name = "shell", about = "Start interactive REPL")]
13    Shell,
14}
15
16pub async fn execute(
17    client: &IndodaxClient,
18    creds: &Option<ResolvedCredentials>,
19    cmd: &UtilityCommand,
20) -> Result<CommandOutput> {
21    match cmd {
22        UtilityCommand::Setup => setup().await,
23        UtilityCommand::Shell => shell(client, creds).await,
24    }
25}
26
27async fn test_credentials(api_key: &str, api_secret: &str) {
28    use crate::auth::Signer;
29    let signer = Signer::new(api_key, api_secret);
30    match IndodaxClient::new(Some(signer)) {
31        Ok(client) => {
32            match client.private_post_v1::<serde_json::Value>("getInfo", &HashMap::new()).await {
33                Ok(info) => {
34                    let name = info.get("name").and_then(|v| v.as_str()).unwrap_or("unknown");
35                    let user_id = info.get("user_id").and_then(|v| v.as_str()).unwrap_or("unknown");
36                    eprintln!("  Credentials validated: logged in as '{}' (user ID: {})", name, user_id);
37                }
38                Err(e) => {
39                    eprintln!("  Warning: Credentials saved but validation failed: {}", e);
40                    eprintln!("  Check that your API key and secret are correct.");
41                }
42            }
43        }
44        Err(e) => {
45            eprintln!("  Warning: Could not create client for validation: {}", e);
46        }
47    }
48}
49
50async fn setup() -> Result<CommandOutput> {
51    use dialoguer::{Confirm, Input, Password};
52
53    eprintln!("=== Indodax CLI Setup Wizard ===\n");
54
55    let api_key: String = Input::new()
56        .with_prompt("Enter your Indodax API key")
57        .interact_text()?;
58
59    let api_secret: String = Password::new()
60        .with_prompt("Enter your Indodax API secret")
61        .interact()?;
62
63    let callback_url: String = Input::new()
64        .with_prompt("Enter your Indodax Callback URL (optional, e.g., https://indodax.tep2.in/)")
65        .allow_empty(true)
66        .interact_text()?;
67
68    let save: bool = Confirm::new()
69        .with_prompt("Save configuration to config?")
70        .default(true)
71        .interact()?;
72
73    if save {
74        let mut config = crate::config::IndodaxConfig::load()?;
75        config.api_key = Some(crate::config::SecretValue::new(&api_key));
76        config.api_secret = Some(crate::config::SecretValue::new(&api_secret));
77        if !callback_url.is_empty() {
78            config.callback_url = Some(callback_url);
79        }
80        config.save()?;
81        eprintln!("\nConfiguration saved to {:?}", crate::config::IndodaxConfig::config_path());
82    }
83
84    eprintln!("\nValidating credentials...");
85    test_credentials(&api_key, &api_secret).await;
86
87    let data = serde_json::json!({
88        "status": "ok",
89        "message": "Setup complete"
90    });
91    Ok(CommandOutput::json(data))
92}
93
94async fn shell(client: &IndodaxClient, _creds: &Option<ResolvedCredentials>) -> Result<CommandOutput> {
95    use crate::Cli;
96    use clap::Parser;
97    use rustyline::DefaultEditor;
98
99    println!("Indodax CLI interactive shell");
100    println!("Type commands without 'indodax' prefix (e.g. 'market ticker btc_idr')");
101    println!("Type 'help' for available commands, 'exit' to quit\n");
102
103    let mut rl = DefaultEditor::new()?;
104    let mut config = crate::config::IndodaxConfig::load()?;
105    let client_ref = client;
106
107    loop {
108        let line = rl.readline("indodax> ");
109        match line {
110            Ok(input) if input.trim().is_empty() => continue,
111            Ok(input) if input.trim() == "exit" || input.trim() == "quit" => break,
112            Ok(input) => {
113                let _ = rl.add_history_entry(&input);
114                let args = format!("indodax {}", input);
115                let args: Vec<String> = shell_parse(&args);
116                match Cli::try_parse_from(args) {
117                    Ok(cli) => {
118                        if matches!(cli.command, crate::Command::Shell) {
119                            println!("Already in shell mode");
120                            continue;
121                        }
122                        if matches!(cli.command, crate::Command::Setup) {
123                            println!("Setup is only available from the command line, not inside the shell");
124                            continue;
125                        }
126                        match crate::dispatch(cli, client_ref, &mut config).await {
127                            Ok(output) => println!("{}", output.render()),
128                            Err(e) => {
129                                eprintln!("Error: {}", e);
130                            }
131                        }
132                    }
133                    Err(e) => eprintln!("{}", e.render()),
134                }
135            }
136            Err(_) => break,
137        }
138    }
139
140    let data = serde_json::json!({"status": "exited"});
141    Ok(CommandOutput::json(data))
142}
143
144/// Splits a shell-style command line into argv-like tokens using shlex.
145fn shell_parse(input: &str) -> Vec<String> {
146    shlex::split(input).unwrap_or_default()
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn test_shell_parse_simple() {
155        let result = shell_parse("market ticker btc_idr");
156        assert_eq!(result, vec!["market", "ticker", "btc_idr"]);
157    }
158
159    #[test]
160    fn test_shell_parse_single_word() {
161        let result = shell_parse("help");
162        assert_eq!(result, vec!["help"]);
163    }
164
165    #[test]
166    fn test_shell_parse_empty() {
167        let result = shell_parse("");
168        assert!(result.is_empty());
169    }
170
171    #[test]
172    fn test_shell_parse_with_quotes() {
173        let result =
174            shell_parse(r#"auth set --api-key "my key" --api-secret "my secret""#);
175        assert_eq!(
176            result,
177            vec![
178                "auth", "set", "--api-key", "my key", "--api-secret", "my secret",
179            ]
180        );
181    }
182
183    #[test]
184    fn test_shell_parse_quoted_value_with_dash() {
185        let result = shell_parse(r#"market ticker --pair "btc_idr""#);
186        assert_eq!(result, vec!["market", "ticker", "--pair", "btc_idr"]);
187    }
188
189    #[test]
190    fn test_shell_parse_multiple_spaces() {
191        let result = shell_parse("market   ticker   btc_idr");
192        assert_eq!(result, vec!["market", "ticker", "btc_idr"]);
193    }
194
195    #[test]
196    fn test_shell_parse_leading_trailing_spaces() {
197        let result = shell_parse("  market ticker btc_idr  ");
198        assert_eq!(result, vec!["market", "ticker", "btc_idr"]);
199    }
200
201    #[test]
202    fn test_shell_parse_only_whitespace() {
203        let result = shell_parse("    ");
204        assert!(result.is_empty());
205    }
206
207    #[test]
208    fn test_shell_parse_quoted_empty_string() {
209        let result = shell_parse(r#"set key """#);
210        assert_eq!(result, vec!["set", "key", ""]);
211    }
212
213    #[test]
214    fn test_shell_parse_quoted_whitespace_only() {
215        let result = shell_parse(r#"echo "   ""#);
216        assert_eq!(result, vec!["echo", "   "]);
217    }
218
219    #[test]
220    fn test_shell_parse_escaped_quote_inside_quotes() {
221        let result = shell_parse(r#"echo "he said \"hi\"""#);
222        assert_eq!(result, vec!["echo", r#"he said "hi""#]);
223    }
224
225    #[test]
226    fn test_shell_parse_escaped_backslash_inside_quotes() {
227        let result = shell_parse(r#"path "a\\b""#);
228        assert_eq!(result, vec!["path", r#"a\b"#]);
229    }
230
231    #[test]
232    fn test_shell_parse_unclosed_quote_returns_empty() {
233        let result = shell_parse(r#"foo "bar baz"#);
234        // shlex returns None on parse error (unclosed quotes), unwrap_or_default gives empty vec
235        assert!(result.is_empty());
236    }
237
238    #[test]
239    fn test_shell_parse_adjacent_quoted_and_bare() {
240        let result = shell_parse(r#"x="hello world""#);
241        assert_eq!(result, vec!["x=hello world"]);
242    }
243
244    #[test]
245    fn test_shell_parse_tab_separator() {
246        let result = shell_parse("a\tb\tc");
247        assert_eq!(result, vec!["a", "b", "c"]);
248    }
249
250    #[test]
251    fn test_utility_command_variants() {
252        let _cmd1 = UtilityCommand::Setup;
253        let _cmd2 = UtilityCommand::Shell;
254    }
255
256    #[test]
257    fn test_shell_parse_with_dash_args() {
258        let result = shell_parse("account balance -v");
259        assert_eq!(result, vec!["account", "balance", "-v"]);
260    }
261}