taskfast_cli/cmd/
init_tui.rs1use std::io::{self, IsTerminal};
14
15use dialoguer::console::{Key, Term};
16use dialoguer::theme::{ColorfulTheme, Theme};
17use dialoguer::{Input, Password, Select};
18use taskfast_client::UserProfile;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum WalletMode {
25 Byow,
27 Generate,
29 Skip,
31}
32
33pub trait Prompter {
37 fn pat(&self, accounts_url: &str) -> io::Result<String>;
40 fn wallet_mode(&self) -> io::Result<WalletMode>;
42 fn wallet_address(&self) -> io::Result<String>;
44 fn wallet_password(&self) -> io::Result<String>;
46}
47
48pub struct DialoguerPrompter;
52
53impl Prompter for DialoguerPrompter {
54 fn pat(&self, accounts_url: &str) -> io::Result<String> {
55 eprintln!("Get a PAT at: {accounts_url}");
58 read_masked("Paste your PAT")
59 }
60
61 fn wallet_mode(&self) -> io::Result<WalletMode> {
62 let choices = [
63 "Use existing wallet (BYOW)",
64 "Generate new wallet",
65 "Skip for now",
66 ];
67 let idx = Select::with_theme(&ColorfulTheme::default())
68 .with_prompt("Wallet setup")
69 .items(&choices)
70 .default(0)
71 .interact()
72 .map_err(dialoguer_err)?;
73 Ok(match idx {
74 0 => WalletMode::Byow,
75 1 => WalletMode::Generate,
76 _ => WalletMode::Skip,
77 })
78 }
79
80 fn wallet_address(&self) -> io::Result<String> {
81 Input::<String>::with_theme(&ColorfulTheme::default())
82 .with_prompt("Wallet address")
83 .validate_with(|s: &String| validate_wallet_address(s))
84 .interact_text()
85 .map_err(dialoguer_err)
86 }
87
88 fn wallet_password(&self) -> io::Result<String> {
89 Password::with_theme(&ColorfulTheme::default())
90 .with_prompt("Keystore password")
91 .with_confirmation("Confirm password", "Passwords don't match")
92 .interact()
93 .map_err(dialoguer_err)
94 }
95}
96
97fn read_masked(prompt: &str) -> io::Result<String> {
101 let term = Term::stderr();
102 if !term.is_term() {
103 return Err(io::Error::other("stderr is not a terminal"));
105 }
106 let theme = ColorfulTheme::default();
107 let mut line = String::new();
108 theme
109 .format_password_prompt(&mut line, prompt)
110 .map_err(io::Error::other)?;
111 term.write_str(&line)?;
112 let mut secret = String::new();
113 loop {
114 match term.read_key()? {
115 Key::Enter if !secret.is_empty() => break,
116 Key::Char('\u{15}') => {
119 term.clear_chars(secret.chars().count())?;
120 secret.clear();
121 }
122 Key::Char(c) if !c.is_control() => {
123 secret.push(c);
124 term.write_str("*")?;
125 }
126 Key::Backspace if secret.pop().is_some() => term.clear_chars(1)?,
127 _ => {}
128 }
129 }
130 term.write_line("")?;
133 Ok(secret)
134}
135
136fn dialoguer_err(e: dialoguer::Error) -> io::Error {
137 match e {
138 dialoguer::Error::IO(io) => io,
139 }
140}
141
142fn validate_wallet_address(s: &str) -> Result<(), &'static str> {
145 let trimmed = s.trim();
146 let rest = trimmed
147 .strip_prefix("0x")
148 .ok_or("address must start with 0x")?;
149 if rest.len() != 40 {
150 return Err("address must be 0x + 40 hex characters");
151 }
152 if !rest.bytes().all(|b| b.is_ascii_hexdigit()) {
153 return Err("address must be hexadecimal");
154 }
155 Ok(())
156}
157
158pub fn is_interactive() -> bool {
162 io::stdin().is_terminal() && io::stdout().is_terminal()
163}
164
165pub fn greeting(profile: Option<&UserProfile>) -> String {
169 match profile {
170 Some(p) => format!("Hi {} <{}>", p.name, p.email),
171 None => "Hi there — authenticated.".to_string(),
172 }
173}
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178
179 #[test]
180 fn greeting_with_profile() {
181 let p = UserProfile {
182 name: "Alice Smith".into(),
183 email: "alice@example.com".into(),
184 };
185 assert_eq!(greeting(Some(&p)), "Hi Alice Smith <alice@example.com>");
186 }
187
188 #[test]
189 fn greeting_without_profile_is_neutral() {
190 assert_eq!(greeting(None), "Hi there — authenticated.");
191 }
192
193 #[test]
194 fn valid_wallet_address_accepted() {
195 assert!(validate_wallet_address("0x0123456789abcdef0123456789ABCDEF01234567").is_ok());
196 }
197
198 #[test]
199 fn wallet_address_missing_0x_rejected() {
200 assert!(validate_wallet_address("0123456789abcdef0123456789ABCDEF01234567").is_err());
201 }
202
203 #[test]
204 fn wallet_address_wrong_length_rejected() {
205 assert!(validate_wallet_address("0xabc").is_err());
206 }
207
208 #[test]
209 fn wallet_address_non_hex_rejected() {
210 assert!(validate_wallet_address("0xGGGG456789abcdef0123456789ABCDEF01234567").is_err());
211 }
212
213 #[test]
214 fn wallet_address_trims_whitespace() {
215 assert!(validate_wallet_address(" 0x0123456789abcdef0123456789ABCDEF01234567\n").is_ok());
216 }
217}