duplicate_finder/
output.rs

1use crate::{
2    convert, file_info::FileInfo, output_type::OutputType, progress_line::ProgressLine,
3    tty::move_cursor_up,
4};
5use std::{io::Write, path::PathBuf};
6
7pub struct Output<TWrite: Write> {
8    top_line: ProgressLine,
9    bottom_line: ProgressLine,
10    writer: TWrite,
11    duplicates: Option<String>,
12    pub is_called: bool,
13}
14
15impl<TWrite: Write> Output<TWrite> {
16    pub fn new(writer: TWrite, total_files_count: u64) -> Output<TWrite> {
17        Output {
18            top_line: ProgressLine {
19                current: 0,
20                message: String::new(),
21                show_counters: false,
22                show_message: true,
23                total: 100,
24                width: None,
25            },
26            bottom_line: ProgressLine {
27                current: 0,
28                message: String::new(),
29                show_counters: true,
30                show_message: false,
31                total: total_files_count,
32                width: None,
33            },
34            writer,
35            duplicates: None,
36            is_called: false,
37        }
38    }
39
40    pub fn update_summary_progress(&mut self) {
41        self.bottom_line.current += 1;
42    }
43
44    pub fn update_file_progress(&mut self, percent: u64, message: &PathBuf) {
45        self.top_line.current = percent;
46        self.top_line.message =
47            convert::to_string_of_length(message, crate::constants::OUTPUT_PADDING);
48    }
49
50    pub fn set_finish(&mut self, duplicates: Vec<Vec<FileInfo>>, output_type: OutputType) {
51        let string = convert::to_string_by_output_type(duplicates, output_type);
52        self.duplicates = Some(string);
53    }
54
55    pub fn redraw(&mut self) {
56        let mut out = String::new();
57
58        if self.is_called {
59            out += &move_cursor_up(2);
60        }
61        self.is_called = true;
62
63        if let Some(duplicates) = &self.duplicates {
64            out.push_str(&format!("\r{}\n", &self.top_line.to_empty_string()));
65            out.push_str(&format!("\r{}\n", &self.bottom_line.to_empty_string()));
66
67            out += &move_cursor_up(2);
68            out.push_str(&format!("\r{}\n", duplicates))
69        } else {
70            out.push_str(&format!("\r{}\n", &self.top_line.to_string()));
71            out.push_str(&format!("\r{}\n", &self.bottom_line.to_string()));
72        }
73        self.writer
74            .write(out.as_bytes())
75            .ok()
76            .expect("write() fail");
77
78        self.writer.flush().ok().expect("flush() fail");
79    }
80}