Skip to main content

rocketmq_admin_cli/ui/
progress.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 indicatif::ProgressBar;
16use indicatif::ProgressStyle;
17
18pub fn create_spinner(message: &str) -> ProgressBar {
19    let pb = ProgressBar::new_spinner();
20    pb.set_style(
21        ProgressStyle::default_spinner()
22            .tick_strings(&["-", "\\", "|", "/"])
23            .template("{spinner:.blue} {msg}")
24            .expect("valid spinner template"),
25    );
26    pb.set_message(message.to_string());
27    pb.enable_steady_tick(std::time::Duration::from_millis(80));
28    pb
29}
30
31pub fn create_progress_bar(total: u64, message: &str) -> ProgressBar {
32    let pb = ProgressBar::new(total);
33    pb.set_style(
34        ProgressStyle::default_bar()
35            .template("{msg} [{bar:40.cyan/blue}] {pos}/{len} ({eta})")
36            .expect("valid progress bar template")
37            .progress_chars("=>-"),
38    );
39    pb.set_message(message.to_string());
40    pb
41}
42
43pub fn finish_progress_success(pb: &ProgressBar, message: &str) {
44    pb.finish_with_message(format!("[OK] {message}"));
45}
46
47pub fn finish_progress_error(pb: &ProgressBar, message: &str) {
48    pb.finish_with_message(format!("[ERROR] {message}"));
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn progress_helpers_do_not_panic() {
57        let spinner = create_spinner("Loading");
58        spinner.finish_and_clear();
59
60        let pb = create_progress_bar(10, "Counting");
61        for _ in 0..10 {
62            pb.inc(1);
63        }
64        finish_progress_success(&pb, "Done");
65
66        let pb = create_progress_bar(1, "Failing");
67        finish_progress_error(&pb, "Failed");
68    }
69}