Skip to main content

tui/app/
report_csv.rs

1//! The category report as CSV: fetched with `x`, shown read-only, copied by OSC 52 or saved locally.
2
3use std::fs::{self, OpenOptions};
4use std::io::{self, ErrorKind, Write};
5use std::path::{Path, PathBuf};
6
7use cli_core::render::{WireValue, parse_wire};
8use cli_core::report_form::csv_call;
9use forms::FormValues;
10use scripting::nomiscript::Value;
11
12use super::App;
13use crate::clipboard::osc52;
14use crate::form::Form;
15use crate::modal::{ConfirmAction, Csv, Modal};
16use crate::route::RouteCtx;
17use crate::tabs::reports::{ReportKind, ReportsTab};
18use crate::view::ViewId;
19use crate::window::WindowId;
20
21impl App {
22    /// Ask for the CSV of the shown category report.
23    pub fn request_report_csv(&mut self) {
24        let Some(window) = self.front_or_say(ViewId::Reports) else {
25            return;
26        };
27        let Some((kind, values)) = self.last_report(window) else {
28            self.set_status("no report run yet");
29            return;
30        };
31        if kind != ReportKind::Breakdown {
32            self.set_status("CSV is only for the category report");
33            return;
34        }
35        let Some(seq) = self
36            .win_mut::<ReportsTab>(window)
37            .map(|tab| tab.csv_seq.advance())
38        else {
39            return;
40        };
41        let ctx = RouteCtx::ReportCsv {
42            seq,
43            file_name: default_file_name(&values),
44        };
45        if self
46            .dispatch_eval(window, ctx, csv_call(kind.descriptor(), &values))
47            .is_none()
48        {
49            self.set_status("console not connected");
50        }
51    }
52
53    pub(super) fn deliver_report_csv(
54        &mut self,
55        window: WindowId,
56        seq: u64,
57        file_name: String,
58        wire: &str,
59    ) {
60        if !self
61            .win::<ReportsTab>(window)
62            .is_some_and(|tab| tab.csv_seq.awaits(seq))
63        {
64            return;
65        }
66        match parse_wire(wire) {
67            Ok(WireValue::Value(Value::String(text))) if self.dialog_free("CSV") => {
68                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            Err(e) => self.set_status(format!("CSV failed: {e}")),
73        }
74    }
75
76    /// Queue the shown CSV for the clipboard of the terminal.
77    pub fn copy_csv(&mut self) {
78        let Some(Modal::Csv(csv)) = self.overlays.top() else {
79            return;
80        };
81        match osc52(&csv.text) {
82            Ok(bytes) => {
83                self.outbound.push(bytes);
84                self.set_status("CSV copied to the clipboard");
85            }
86            Err(e) => self.set_status(e.to_string()),
87        }
88    }
89
90    /// The raw terminal output queued since the last call.
91    pub fn take_outbound(&mut self) -> Vec<Vec<u8>> {
92        std::mem::take(&mut self.outbound)
93    }
94
95    /// Open the save-path prompt; saving files is for the local transport only.
96    pub fn begin_csv_save(&mut self) {
97        if !self.local_files {
98            self.set_status("save is not available over ssh");
99            return;
100        }
101        let Some(Modal::Csv(csv)) = self.overlays.top() else {
102            return;
103        };
104        let form = Form::csv_save(&csv.file_name);
105        self.overlays.push(Modal::Form(form));
106    }
107
108    pub(crate) fn save_csv(&mut self, values: &FormValues) {
109        match values
110            .text("path")
111            .map(str::trim)
112            .filter(|path| !path.is_empty())
113        {
114            Some(path) => self.write_csv(PathBuf::from(path), false),
115            None => self.set_status("no file name given"),
116        }
117    }
118
119    pub(crate) fn overwrite_csv(&mut self, path: PathBuf) {
120        self.write_csv(path, true);
121    }
122
123    fn write_csv(&mut self, path: PathBuf, overwrite: bool) {
124        if !self.local_files {
125            self.set_status("save is not available over ssh");
126            return;
127        }
128        let Some(Modal::Csv(csv)) = self.overlays.top() else {
129            return;
130        };
131        match write_file(&path, &csv.text, overwrite) {
132            Ok(()) => self.set_status(format!("saved {}", path.display())),
133            Err(e) if e.kind() == ErrorKind::AlreadyExists => {
134                let prompt = format!("Overwrite {}?", path.display());
135                self.overlays
136                    .push(Modal::confirm(prompt, ConfirmAction::OverwriteCsv(path)));
137            }
138            Err(e) => self.set_status(format!("save failed: {e}")),
139        }
140    }
141}
142
143fn write_file(path: &Path, text: &str, overwrite: bool) -> io::Result<()> {
144    if !overwrite {
145        return OpenOptions::new()
146            .write(true)
147            .create_new(true)
148            .open(path)?
149            .write_all(text.as_bytes());
150    }
151    let name = path.file_name().unwrap_or_default().to_string_lossy();
152    let staged = path.with_file_name(format!(".{name}.tmp-{}", std::process::id()));
153    let result = fs::write(&staged, text).and_then(|()| fs::rename(&staged, path));
154    if result.is_err() {
155        let _ = fs::remove_file(&staged);
156    }
157    result
158}
159
160fn default_file_name(values: &FormValues) -> String {
161    let part = |key, fallback| {
162        values
163            .text(key)
164            .filter(|text| !text.is_empty())
165            .unwrap_or(fallback)
166            .to_string()
167    };
168    format!(
169        "category-{}-{}.csv",
170        part("from", "start"),
171        part("to", "end")
172    )
173}