1
//! The category report as CSV: fetched with `x`, shown read-only, copied by OSC 52 or saved locally.
2

            
3
use std::fs::{self, OpenOptions};
4
use std::io::{self, ErrorKind, Write};
5
use std::path::{Path, PathBuf};
6

            
7
use cli_core::render::{WireValue, parse_wire};
8
use cli_core::report_form::csv_call;
9
use forms::FormValues;
10
use scripting::nomiscript::Value;
11

            
12
use super::App;
13
use crate::clipboard::osc52;
14
use crate::form::Form;
15
use crate::modal::{ConfirmAction, Csv, Modal};
16
use crate::route::RouteCtx;
17
use crate::tabs::reports::{ReportKind, ReportsTab};
18
use crate::view::ViewId;
19
use crate::window::WindowId;
20

            
21
impl App {
22
    /// Ask for the CSV of the shown category report.
23
14
    pub fn request_report_csv(&mut self) {
24
14
        let Some(window) = self.front_or_say(ViewId::Reports) else {
25
1
            return;
26
        };
27
13
        let Some((kind, values)) = self.last_report(window) else {
28
1
            self.set_status("no report run yet");
29
1
            return;
30
        };
31
12
        if kind != ReportKind::Breakdown {
32
1
            self.set_status("CSV is only for the category report");
33
1
            return;
34
11
        }
35
11
        let Some(seq) = self
36
11
            .win_mut::<ReportsTab>(window)
37
11
            .map(|tab| tab.csv_seq.advance())
38
        else {
39
            return;
40
        };
41
11
        let ctx = RouteCtx::ReportCsv {
42
11
            seq,
43
11
            file_name: default_file_name(&values),
44
11
        };
45
11
        if self
46
11
            .dispatch_eval(window, ctx, csv_call(kind.descriptor(), &values))
47
11
            .is_none()
48
        {
49
            self.set_status("console not connected");
50
11
        }
51
14
    }
52

            
53
11
    pub(super) fn deliver_report_csv(
54
11
        &mut self,
55
11
        window: WindowId,
56
11
        seq: u64,
57
11
        file_name: String,
58
11
        wire: &str,
59
11
    ) {
60
11
        if !self
61
11
            .win::<ReportsTab>(window)
62
11
            .is_some_and(|tab| tab.csv_seq.awaits(seq))
63
        {
64
2
            return;
65
9
        }
66
9
        match parse_wire(wire) {
67
8
            Ok(WireValue::Value(Value::String(text))) if self.dialog_free("CSV") => {
68
8
                self.open_dialog_in(window, Modal::Csv(Csv::new(file_name, text)));
69
            }
70
            Ok(WireValue::Value(Value::String(_))) => {}
71
            Ok(WireValue::Value(_)) => self.set_status("the CSV reply is not text"),
72
1
            Err(e) => self.set_status(format!("CSV failed: {e}")),
73
        }
74
11
    }
75

            
76
    /// Queue the shown CSV for the clipboard of the terminal.
77
3
    pub fn copy_csv(&mut self) {
78
3
        let Some(Modal::Csv(csv)) = self.overlays.top() else {
79
            return;
80
        };
81
3
        match osc52(&csv.text) {
82
            Ok(bytes) => {
83
2
                self.outbound.push(bytes);
84
2
                self.set_status("CSV copied to the clipboard");
85
            }
86
1
            Err(e) => self.set_status(e.to_string()),
87
        }
88
3
    }
89

            
90
    /// The raw terminal output queued since the last call.
91
635
    pub fn take_outbound(&mut self) -> Vec<Vec<u8>> {
92
635
        std::mem::take(&mut self.outbound)
93
635
    }
94

            
95
    /// Open the save-path prompt; saving files is for the local transport only.
96
2
    pub fn begin_csv_save(&mut self) {
97
2
        if !self.local_files {
98
1
            self.set_status("save is not available over ssh");
99
1
            return;
100
1
        }
101
1
        let Some(Modal::Csv(csv)) = self.overlays.top() else {
102
            return;
103
        };
104
1
        let form = Form::csv_save(&csv.file_name);
105
1
        self.overlays.push(Modal::Form(form));
106
2
    }
107

            
108
3
    pub(crate) fn save_csv(&mut self, values: &FormValues) {
109
3
        match values
110
3
            .text("path")
111
3
            .map(str::trim)
112
3
            .filter(|path| !path.is_empty())
113
        {
114
3
            Some(path) => self.write_csv(PathBuf::from(path), false),
115
            None => self.set_status("no file name given"),
116
        }
117
3
    }
118

            
119
1
    pub(crate) fn overwrite_csv(&mut self, path: PathBuf) {
120
1
        self.write_csv(path, true);
121
1
    }
122

            
123
4
    fn write_csv(&mut self, path: PathBuf, overwrite: bool) {
124
4
        if !self.local_files {
125
1
            self.set_status("save is not available over ssh");
126
1
            return;
127
3
        }
128
3
        let Some(Modal::Csv(csv)) = self.overlays.top() else {
129
            return;
130
        };
131
3
        match write_file(&path, &csv.text, overwrite) {
132
2
            Ok(()) => self.set_status(format!("saved {}", path.display())),
133
1
            Err(e) if e.kind() == ErrorKind::AlreadyExists => {
134
1
                let prompt = format!("Overwrite {}?", path.display());
135
1
                self.overlays
136
1
                    .push(Modal::confirm(prompt, ConfirmAction::OverwriteCsv(path)));
137
            }
138
            Err(e) => self.set_status(format!("save failed: {e}")),
139
        }
140
4
    }
141
}
142

            
143
3
fn write_file(path: &Path, text: &str, overwrite: bool) -> io::Result<()> {
144
3
    if !overwrite {
145
2
        return OpenOptions::new()
146
2
            .write(true)
147
2
            .create_new(true)
148
2
            .open(path)?
149
1
            .write_all(text.as_bytes());
150
1
    }
151
1
    let name = path.file_name().unwrap_or_default().to_string_lossy();
152
1
    let staged = path.with_file_name(format!(".{name}.tmp-{}", std::process::id()));
153
1
    let result = fs::write(&staged, text).and_then(|()| fs::rename(&staged, path));
154
1
    if result.is_err() {
155
        let _ = fs::remove_file(&staged);
156
1
    }
157
1
    result
158
3
}
159

            
160
11
fn default_file_name(values: &FormValues) -> String {
161
22
    let part = |key, fallback| {
162
22
        values
163
22
            .text(key)
164
22
            .filter(|text| !text.is_empty())
165
22
            .unwrap_or(fallback)
166
            .to_string()
167
22
    };
168
11
    format!(
169
        "category-{}-{}.csv",
170
11
        part("from", "start"),
171
11
        part("to", "end")
172
    )
173
11
}