Skip to main content

cli/
reports.rs

1//! `reports` subcommands, built from the compiled-in report descriptors.
2
3use std::io::IsTerminal;
4use std::path::{Path, PathBuf};
5
6use clap::error::ErrorKind;
7use clap::{Arg, ArgAction, ArgMatches, Command, Error, FromArgMatches, Subcommand};
8use cli_core::CommandError;
9use cli_core::eval::Rendered;
10use cli_core::report_form::{self, ChartRequest, ChartSize};
11use forms::{Form, FormValues};
12use rpc::Session;
13use rpc::chart::{ChartFormat, ChartLook, DEFAULT_HEIGHT, DEFAULT_WIDTH, MAX_SIDE, parse_kind};
14
15use crate::eval::print_rendered;
16use crate::transaction::{form_command, values_of};
17
18const CHART: &str = "chart";
19const PNG: &str = "png";
20const SVG: &str = "svg";
21const SIZE: &str = "size";
22const CSV: &str = "csv";
23const DEFAULT_CHART: &str = "bar";
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26enum Report {
27    Balance,
28    Activity,
29    Breakdown,
30}
31
32const REPORTS: [(Report, &str, &str); 3] = [
33    (
34        Report::Balance,
35        "balance",
36        "Balance chart (top-level accounts by magnitude)",
37    ),
38    (
39        Report::Activity,
40        "activity",
41        "Activity chart (Income vs Expense over a period)",
42    ),
43    (
44        Report::Breakdown,
45        "breakdown",
46        "Category breakdown chart (top-N tag values)",
47    ),
48];
49
50impl Report {
51    fn form(self) -> &'static Form {
52        match self {
53            Self::Balance => &forms::REPORT_BALANCE,
54            Self::Activity => &forms::REPORT_ACTIVITY,
55            Self::Breakdown => &forms::REPORT_CATEGORY,
56        }
57    }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61enum Renderer {
62    Text,
63    Kitty,
64}
65
66/// What `--chart` names: a chart shape, or a terminal renderer drawing the bar chart.
67#[derive(Debug, PartialEq, Eq)]
68struct ChartChoice {
69    kind: String,
70    renderer: Option<Renderer>,
71}
72
73impl ChartChoice {
74    fn parse(name: &str) -> Result<Self, Error> {
75        let renderer = match name.to_ascii_lowercase().as_str() {
76            "text" | "ascii" => Some(Renderer::Text),
77            "kitty" | "graphic" => Some(Renderer::Kitty),
78            _ => None,
79        };
80        if renderer.is_none() && parse_kind(name).is_none() {
81            return Err(Error::raw(
82                ErrorKind::InvalidValue,
83                format!("unknown chart '{name}': use bar, line, stacked, text or kitty"),
84            ));
85        }
86        let kind = if renderer.is_some() { "bar" } else { name };
87        Ok(Self {
88            kind: kind.to_string(),
89            renderer,
90        })
91    }
92}
93
94#[derive(Debug)]
95pub struct ReportsCmd {
96    report: Report,
97    values: FormValues,
98    chart: ChartChoice,
99    png: Option<PathBuf>,
100    svg: Option<PathBuf>,
101    size: ChartSize,
102    csv: bool,
103}
104
105fn defaulted<'a, T: Clone + Send + Sync + 'static>(
106    matches: &'a ArgMatches,
107    id: &str,
108) -> Result<&'a T, Error> {
109    matches.get_one::<T>(id).ok_or_else(|| {
110        Error::raw(
111            ErrorKind::MissingRequiredArgument,
112            format!("--{id} has no value"),
113        )
114    })
115}
116
117fn parse_side(text: &str) -> Result<u32, String> {
118    text.parse::<u32>()
119        .ok()
120        .filter(|side| (1..=MAX_SIDE).contains(side))
121        .ok_or_else(|| format!("'{text}' is not a size from 1 to {MAX_SIDE}"))
122}
123
124fn parse_size(text: &str) -> Result<ChartSize, String> {
125    let (width, height) = text
126        .split_once('x')
127        .ok_or_else(|| format!("'{text}' is not WIDTHxHEIGHT"))?;
128    Ok((parse_side(width)?, parse_side(height)?))
129}
130
131fn report_command(report: Report, name: &'static str, about: &'static str) -> Command {
132    let command = form_command(name, about, report.form());
133    let command = match report {
134        Report::Breakdown => command.arg(
135            Arg::new(CSV)
136                .long(CSV)
137                .action(ArgAction::SetTrue)
138                .conflicts_with_all([CHART, PNG, SVG, SIZE])
139                .help("Print the report as CSV on stdout instead of a chart"),
140        ),
141        Report::Balance | Report::Activity => command,
142    };
143    command
144        .arg(
145            Arg::new(CHART)
146                .long(CHART)
147                .default_value(DEFAULT_CHART)
148                .help("Chart shape or renderer: bar, line, stacked, text, kitty"),
149        )
150        .arg(
151            Arg::new(PNG)
152                .long(PNG)
153                .value_name("FILE")
154                .value_parser(clap::value_parser!(PathBuf))
155                .help("Write the chart as a PNG file; nothing is printed"),
156        )
157        .arg(
158            Arg::new(SVG)
159                .long(SVG)
160                .value_name("FILE")
161                .value_parser(clap::value_parser!(PathBuf))
162                .help("Write the chart as an SVG file; nothing is printed"),
163        )
164        .arg(
165            Arg::new(SIZE)
166                .long(SIZE)
167                .value_name("WxH")
168                .default_value(format!("{DEFAULT_WIDTH}x{DEFAULT_HEIGHT}"))
169                .value_parser(parse_size)
170                .help("Chart size in pixels, each side 1 to 2048"),
171        )
172}
173
174impl Subcommand for ReportsCmd {
175    fn augment_subcommands(cmd: Command) -> Command {
176        REPORTS.iter().fold(
177            cmd.subcommand_required(true).arg_required_else_help(true),
178            |cmd, (report, name, about)| cmd.subcommand(report_command(*report, name, about)),
179        )
180    }
181
182    fn augment_subcommands_for_update(cmd: Command) -> Command {
183        Self::augment_subcommands(cmd)
184    }
185
186    fn has_subcommand(name: &str) -> bool {
187        REPORTS.iter().any(|(_, known, _)| *known == name)
188    }
189}
190
191impl FromArgMatches for ReportsCmd {
192    fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
193        let (name, sub) = matches
194            .subcommand()
195            .ok_or_else(|| Error::raw(ErrorKind::MissingSubcommand, "a report name is required"))?;
196        let (report, ..) = REPORTS
197            .iter()
198            .find(|(_, known, _)| *known == name)
199            .ok_or_else(|| {
200                Error::raw(
201                    ErrorKind::InvalidSubcommand,
202                    format!("unknown report '{name}'"),
203                )
204            })?;
205        let chart = ChartChoice::parse(sub.get_one::<String>(CHART).map_or("bar", String::as_str))?;
206        let (png, svg) = (
207            sub.get_one::<PathBuf>(PNG).cloned(),
208            sub.get_one::<PathBuf>(SVG).cloned(),
209        );
210        if chart.renderer.is_some() && (png.is_some() || svg.is_some()) {
211            return Err(Error::raw(
212                ErrorKind::ArgumentConflict,
213                "--png and --svg draw a bar, line or stacked chart, not text or kitty".to_string(),
214            ));
215        }
216        Ok(Self {
217            report: *report,
218            values: values_of(report.form(), sub),
219            chart,
220            png,
221            svg,
222            size: *defaulted::<ChartSize>(sub, SIZE)?,
223            csv: sub.try_get_one::<bool>(CSV).ok().flatten() == Some(&true),
224        })
225    }
226
227    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
228        *self = Self::from_arg_matches(matches)?;
229        Ok(())
230    }
231}
232
233fn wants_kitty(
234    renderer: Option<Renderer>,
235    tty: bool,
236    env: impl Fn(&str) -> Option<String>,
237) -> bool {
238    match renderer {
239        Some(Renderer::Kitty) => tty,
240        Some(Renderer::Text) => false,
241        None => tty && rpc::chart::env_speaks_kitty(env),
242    }
243}
244
245fn use_kitty(renderer: Option<Renderer>) -> bool {
246    wants_kitty(renderer, std::io::stdout().is_terminal(), |name| {
247        std::env::var(name).ok()
248    })
249}
250
251fn write_file(path: &Path, bytes: &[u8]) -> Result<(), CommandError> {
252    std::fs::write(path, bytes)
253        .map_err(|e| CommandError::Command(format!("{}: {e}", path.display())))
254}
255
256async fn write_files(session: &mut Session, cmd: &ReportsCmd) -> Result<(), CommandError> {
257    let (form, kind) = (cmd.report.form(), cmd.chart.kind.as_str());
258    if let Some(path) = &cmd.png {
259        let png = report_form::chart_png(session, form, &cmd.values, kind, cmd.size).await?;
260        write_file(path, &png)?;
261    }
262    if let Some(path) = &cmd.svg {
263        let request = ChartRequest {
264            kind,
265            format: ChartFormat::Svg,
266            size: cmd.size,
267            look: ChartLook::default(),
268        };
269        let svg = report_form::chart(session, form, &cmd.values, &request).await?;
270        write_file(path, svg.as_bytes())?;
271    }
272    Ok(())
273}
274
275async fn render(session: &mut Session, cmd: &ReportsCmd) -> Result<Rendered, CommandError> {
276    if cmd.csv {
277        let csv = report_form::csv(session, cmd.report.form(), &cmd.values).await?;
278        return Ok(Rendered::Bytes(csv.into_bytes()));
279    }
280    if cmd.png.is_some() || cmd.svg.is_some() {
281        write_files(session, cmd).await?;
282        return Ok(Rendered::Nothing);
283    }
284    report_form::terminal_chart(
285        session,
286        cmd.report.form(),
287        &cmd.values,
288        &cmd.chart.kind,
289        use_kitty(cmd.chart.renderer),
290        cmd.size,
291    )
292    .await
293}
294
295pub async fn run(session: &mut Session, cmd: ReportsCmd) -> Result<(), CommandError> {
296    print_rendered(render(session, &cmd).await?)
297}
298
299#[cfg(test)]
300mod chart_tests;
301#[cfg(test)]
302mod tests;