1
use cli_core::{CliRunnable, CommandError};
2
use server::command::data_findings::DataFinding;
3
use server::command::{Argument, CmdResult, FinanceEntity};
4
use std::collections::HashMap;
5

            
6
/// Run a `CliRunnable` with the given argument map and render its result
7
/// to stdout in a script-friendly format. Returns the same `CommandError`
8
/// the runnable raised; the caller decides the exit code.
9
3
pub async fn run_and_print(
10
3
    runnable: &dyn CliRunnable,
11
3
    args: HashMap<&str, Argument>,
12
3
) -> Result<(), CommandError> {
13
3
    let args_ref: HashMap<&str, &Argument> = args.iter().map(|(k, v)| (*k, v)).collect();
14
3
    let result = runnable.run(&args_ref).await?;
15
2
    if let Some(r) = result {
16
1
        print_result(r);
17
1
    }
18
2
    Ok(())
19
3
}
20

            
21
fn entity_identifier(entity: &FinanceEntity) -> String {
22
    match entity {
23
        FinanceEntity::Tag(t) => t.tag_value.clone(),
24
        FinanceEntity::Commodity(c) => c.id.to_string(),
25
        FinanceEntity::Account(a) => a.id.to_string(),
26
        FinanceEntity::Transaction(t) => t.id.to_string(),
27
        FinanceEntity::Split(s) => s.id.to_string(),
28
        FinanceEntity::Price(p) => p.id.to_string(),
29
    }
30
}
31

            
32
fn tag_fields(tags: &HashMap<String, FinanceEntity>) -> Vec<String> {
33
    tags.iter()
34
        .filter_map(|(k, v)| match v {
35
            FinanceEntity::Tag(t) => Some(format!("{k}={}", t.tag_value)),
36
            _ => None,
37
        })
38
        .collect()
39
}
40

            
41
2
fn finding_lines(findings: &[DataFinding]) -> Vec<String> {
42
2
    if findings.is_empty() {
43
1
        return vec!["no findings".to_string()];
44
1
    }
45
1
    let mut lines = Vec::new();
46
1
    let mut current_kind: Option<&str> = None;
47
1
    for finding in findings {
48
3
        if current_kind != Some(finding.kind.as_str()) {
49
6
            let count = findings.iter().filter(|f| f.kind == finding.kind).count();
50
2
            lines.push(format!("{} ({count})", finding.kind));
51
2
            current_kind = Some(finding.kind.as_str());
52
1
        }
53
3
        let subjects = finding
54
3
            .subjects
55
3
            .iter()
56
3
            .map(ToString::to_string)
57
3
            .collect::<Vec<_>>()
58
3
            .join(",");
59
3
        lines.push(format!(
60
3
            "  {}\t{subjects}\t{}\t{}",
61
3
            finding.id,
62
3
            finding.detail,
63
3
            finding.created_at.to_rfc3339()
64
3
        ));
65
    }
66
1
    lines
67
2
}
68

            
69
1
fn merged_line(into: sqlx::types::Uuid, moved: i64) -> String {
70
1
    format!("{into}\t{moved}")
71
1
}
72

            
73
1
fn print_result(result: CmdResult) {
74
1
    match result {
75
        CmdResult::Lines(lines) => {
76
1
            for line in lines {
77
2
                println!("{line}");
78
            }
79
        }
80
        CmdResult::String(s) => println!("{s}"),
81
        CmdResult::Rational(r) => println!("{r}"),
82
        CmdResult::Timezone(zone) => println!("{zone}"),
83
        CmdResult::ScriptRun(run) => println!("{run}"),
84
        CmdResult::Data(bytes) => {
85
            use std::io::Write;
86
            let _ = std::io::stdout().write_all(&bytes);
87
        }
88
        CmdResult::Entity(entity) => println!("{}", entity_identifier(&entity)),
89
        CmdResult::Entities(entities) => {
90
            for entity in entities {
91
                println!("{}", entity_identifier(&entity));
92
            }
93
        }
94
        CmdResult::MultiCurrencyBalance(items) => {
95
            for (commodity, balance) in items {
96
                println!("{balance} {}", commodity.id);
97
            }
98
        }
99
        CmdResult::CommodityInfoList(items) => {
100
            for info in items {
101
                println!("{}\t{}\t{}", info.commodity_id, info.symbol, info.name);
102
            }
103
        }
104
        CmdResult::SingleCommodities(held) => {
105
            for (account, commodity) in held {
106
                println!("{account}\t{commodity}");
107
            }
108
        }
109
        CmdResult::Templates(templates) => {
110
            for template in templates {
111
                println!("{}\t{}", template.id, template.name.unwrap_or_default());
112
            }
113
        }
114
        CmdResult::TaggedEntities { entities, .. } => {
115
            for (entity, tags) in entities {
116
                let name = entity_identifier(&entity);
117
                let fields = tag_fields(&tags);
118
                if fields.is_empty() {
119
                    println!("{name}");
120
                } else {
121
                    println!("{name}\t{}", fields.join("\t"));
122
                }
123
            }
124
        }
125
        CmdResult::TaggedSplits { entities } => {
126
            for (split, tags) in entities {
127
                let fields: Vec<String> = tags
128
                    .iter()
129
                    .map(|t| format!("{}={}", t.tag_name, t.tag_value))
130
                    .collect();
131
                if fields.is_empty() {
132
                    println!("{}", split.id);
133
                } else {
134
                    println!("{}\t{}", split.id, fields.join("\t"));
135
                }
136
            }
137
        }
138
        CmdResult::TaggedTransactions { entities, .. } => {
139
            for (entity, tags, amount) in entities {
140
                let name = entity_identifier(&entity);
141
                let mut fields = tag_fields(&tags);
142
                if let Some(amount) = amount {
143
                    fields.push(format!("amount={amount}"));
144
                }
145
                if fields.is_empty() {
146
                    println!("{name}");
147
                } else {
148
                    println!("{name}\t{}", fields.join("\t"));
149
                }
150
            }
151
        }
152
        CmdResult::Report(_) | CmdResult::Activity(_) | CmdResult::Breakdown(_) => {
153
            eprintln!("(structured report; use `reports` subcommand for rendered output)");
154
        }
155
        CmdResult::Uuid(id) => println!("{id}"),
156
        CmdResult::Bool(b) => println!("{b}"),
157
        CmdResult::Count(n) => println!("{n}"),
158
        CmdResult::Merged { into, moved } => println!("{}", merged_line(into, moved)),
159
        CmdResult::DataFindings(findings) => {
160
            for line in finding_lines(&findings) {
161
                println!("{line}");
162
            }
163
        }
164
        CmdResult::ConfigEntries(entries) => {
165
            for (name, value) in entries {
166
                println!("{name}\t{value}");
167
            }
168
        }
169
        CmdResult::SshKeys(keys) => {
170
            for k in keys {
171
                let last_used = k
172
                    .last_used_at
173
                    .map_or_else(|| "never".to_string(), |d| d.to_rfc3339());
174
                println!(
175
                    "{}\t{}\t{}\t{}\t{}",
176
                    k.fingerprint, k.key_type, k.annotation, k.created_at, last_used
177
                );
178
            }
179
        }
180
    }
181
1
}
182

            
183
#[cfg(test)]
184
#[path = "dispatch_tests.rs"]
185
mod tests;