git_editor/utils/
prompt.rs1use crate::utils::types::Result;
2use colored::*;
3use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
4use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
5use std::io::{self, IsTerminal, Write};
6
7pub const CANCELLED: &str = "CANCELLED";
9
10pub const EXIT_CANCELLED: i32 = 130;
12
13pub fn is_cancelled(err: &dyn std::error::Error) -> bool {
14 err.to_string() == CANCELLED
15}
16
17pub fn exit_code_for_error(err: &dyn std::error::Error) -> i32 {
19 if is_cancelled(err) {
20 EXIT_CANCELLED
21 } else {
22 1
23 }
24}
25
26pub fn cancelled() -> Box<dyn std::error::Error> {
28 cancelled_msg();
29 CANCELLED.into()
30}
31
32fn print_esc_hint() {
33 crate::say_inline!(" {}", "(Esc to cancel)".bright_black());
34}
35
36pub fn read_line_allow_esc() -> Result<Option<String>> {
41 if !io::stdin().is_terminal() {
42 let mut line = String::new();
43 if io::stdin().read_line(&mut line)? == 0 {
44 crate::say!();
45 return Err(
46 "No input available (stdin is not a terminal and is closed); pass the values as flags and --yes to confirm"
47 .into(),
48 );
49 }
50 crate::say!("{}", line.trim_end());
51 return Ok(Some(line.trim_end_matches(['\r', '\n']).to_string()));
52 }
53
54 enable_raw_mode().map_err(|e| format!("Failed to enable raw mode: {e}"))?;
55
56 let result = (|| -> Result<Option<String>> {
57 let mut buffer = String::new();
58 loop {
59 let Event::Key(key) = event::read().map_err(|e| format!("Failed to read key: {e}"))?
60 else {
61 continue;
62 };
63 if key.kind != KeyEventKind::Press {
64 continue;
65 }
66
67 match key.code {
68 KeyCode::Esc => {
69 crate::say_inline!("\r\n");
70 let _ = io::stdout().flush();
71 return Ok(None);
72 }
73 KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
74 crate::say_inline!("\r\n");
75 let _ = io::stdout().flush();
76 return Ok(None);
77 }
78 KeyCode::Enter => {
79 crate::say_inline!("\r\n");
80 let _ = io::stdout().flush();
81 return Ok(Some(buffer));
82 }
83 KeyCode::Backspace => {
84 if buffer.pop().is_some() {
85 crate::say_inline!("\x08 \x08");
86 let _ = io::stdout().flush();
87 }
88 }
89 KeyCode::Char(c) => {
90 buffer.push(c);
91 crate::say_inline!("{c}");
92 let _ = io::stdout().flush();
93 }
94 _ => {}
95 }
96 }
97 })();
98
99 let _ = disable_raw_mode();
100 result
101}
102
103fn cancelled_msg() {
104 crate::say!("{}", "Operation cancelled.".yellow());
105}
106
107pub fn prompt_for_input(prompt: &str) -> Result<String> {
108 crate::say_inline!("{prompt}");
109 print_esc_hint();
110 crate::say_inline!(": ");
111 io::stdout()
112 .flush()
113 .map_err(|e| format!("Failed to flush stdout: {e}"))?;
114
115 match read_line_allow_esc()? {
116 Some(input) => Ok(input.trim().to_string()),
117 None => {
118 cancelled_msg();
119 Err(CANCELLED.into())
120 }
121 }
122}
123
124pub fn prompt_for_missing_arg(arg_name: &str) -> Result<String> {
125 let hint = format!(
126 "{} '{}'",
127 "Please provide a value for".yellow(),
128 arg_name.yellow().bold()
129 );
130 prompt_for_input(&hint)
131}
132
133pub fn prompt_with_default(prompt: &str, default_value: &str) -> Result<String> {
135 crate::say_inline!(
136 "{}: {} ",
137 prompt.yellow().bold(),
138 format!("({default_value})").bright_black()
139 );
140 print_esc_hint();
141 crate::say_inline!(" ");
142 io::stdout()
143 .flush()
144 .map_err(|e| format!("Failed to flush stdout: {e}"))?;
145
146 match read_line_allow_esc()? {
147 Some(input) => {
148 let input = input.trim();
149 if input.is_empty() {
150 Ok(default_value.to_string())
151 } else {
152 Ok(input.to_string())
153 }
154 }
155 None => {
156 cancelled_msg();
157 Err(CANCELLED.into())
158 }
159 }
160}
161
162pub fn confirm(question: &str, assume_yes: bool) -> Result<bool> {
165 if assume_yes {
166 crate::say!("{question} {}", "yes (--yes)".green());
167 return Ok(true);
168 }
169 let answer = prompt_for_input(&format!("{question} (yes/no)"))?;
170 Ok(is_yes(&answer))
171}
172
173fn is_yes(answer: &str) -> bool {
174 matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes")
175}
176
177pub fn read_prompted_line_raw() -> Result<String> {
179 match read_line_allow_esc()? {
180 Some(input) => Ok(input),
181 None => {
182 cancelled_msg();
183 Err(CANCELLED.into())
184 }
185 }
186}
187
188pub fn read_prompted_line() -> Result<String> {
190 match read_line_allow_esc()? {
191 Some(input) => Ok(input.trim().to_string()),
192 None => {
193 cancelled_msg();
194 Err(CANCELLED.into())
195 }
196 }
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202
203 #[test]
204 fn test_is_yes_accepts_y_and_yes_only() {
205 for yes in ["y", "Y", "yes", "YES", " yes "] {
206 assert!(is_yes(yes), "{yes}");
207 }
208 for no in ["", "n", "no", "yep", "yess"] {
209 assert!(!is_yes(no), "{no}");
210 }
211 }
212
213 #[test]
214 fn test_confirm_with_assume_yes_does_not_prompt() {
215 assert!(confirm("Proceed?", true).unwrap());
216 }
217
218 #[test]
219 fn test_is_cancelled() {
220 let err: Box<dyn std::error::Error> = CANCELLED.into();
221 assert!(is_cancelled(err.as_ref()));
222 let other: Box<dyn std::error::Error> = "boom".into();
223 assert!(!is_cancelled(other.as_ref()));
224 }
225
226 #[test]
227 fn test_exit_code_for_cancelled_vs_error() {
228 let cancelled: Box<dyn std::error::Error> = CANCELLED.into();
229 assert_eq!(exit_code_for_error(cancelled.as_ref()), 130);
230
231 let failed: Box<dyn std::error::Error> = "Invalid number".into();
232 assert_eq!(exit_code_for_error(failed.as_ref()), 1);
233 }
234
235 #[test]
236 fn test_cancelled_constant_stable() {
237 assert_eq!(CANCELLED, "CANCELLED");
239 let err: Box<dyn std::error::Error> = CANCELLED.into();
240 assert_eq!(exit_code_for_error(err.as_ref()), 130);
241 }
242}