Skip to main content

rocketmq_admin_cli/ui/
prompt.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use dialoguer::Confirm;
16use dialoguer::Input;
17use dialoguer::Select;
18use dialoguer::theme::ColorfulTheme;
19
20pub fn confirm(message: &str) -> bool {
21    Confirm::with_theme(&ColorfulTheme::default())
22        .with_prompt(message)
23        .default(false)
24        .interact()
25        .unwrap_or(false)
26}
27
28pub fn confirm_default_yes(message: &str) -> bool {
29    Confirm::with_theme(&ColorfulTheme::default())
30        .with_prompt(message)
31        .default(true)
32        .interact()
33        .unwrap_or(true)
34}
35
36pub fn input(message: &str) -> Option<String> {
37    Input::with_theme(&ColorfulTheme::default())
38        .with_prompt(message)
39        .interact_text()
40        .ok()
41}
42
43pub fn input_with_default(message: &str, default: &str) -> String {
44    Input::with_theme(&ColorfulTheme::default())
45        .with_prompt(message)
46        .default(default.to_string())
47        .interact_text()
48        .unwrap_or_else(|_| default.to_string())
49}
50
51pub fn select(message: &str, items: &[String]) -> Option<usize> {
52    if items.is_empty() {
53        return None;
54    }
55
56    Select::with_theme(&ColorfulTheme::default())
57        .with_prompt(message)
58        .items(items)
59        .interact()
60        .ok()
61}
62
63pub fn dangerous_operation_message(operation: &str, target: &str) -> String {
64    format!("[WARNING] This will {operation} {target}. This action cannot be undone. Continue?")
65}
66
67pub fn confirm_dangerous_operation(operation: &str, target: &str) -> bool {
68    confirm(&dangerous_operation_message(operation, target))
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn formats_dangerous_operation_messages() {
77        let message = dangerous_operation_message("delete", "topic 'Test'");
78        assert_eq!(
79            message,
80            "[WARNING] This will delete topic 'Test'. This action cannot be undone. Continue?"
81        );
82    }
83
84    #[test]
85    fn empty_selection_returns_none() {
86        assert_eq!(select("Choose", &[]), None);
87    }
88}