asimov_readwise_module/
output.rs

1// This is free and unencumbered software released into the public domain.
2
3use clap::ValueEnum;
4use serde::Serialize;
5
6#[derive(Debug, Clone, ValueEnum)]
7pub enum OutputFormat {
8    Json,
9    Jsonl,
10}
11
12impl Default for OutputFormat {
13    fn default() -> Self {
14        OutputFormat::Json
15    }
16}
17
18pub fn write_json_output<T: Serialize>(data: &T) -> Result<(), Box<dyn std::error::Error>> {
19    let response = serde_json::to_string(data)?;
20    println!("{}", response);
21    Ok(())
22}
23
24pub fn write_jsonl_from_results<T: Serialize>(
25    results: Option<&Vec<T>>,
26) -> Result<(), Box<dyn std::error::Error>> {
27    if let Some(results) = results {
28        for item in results {
29            let line = serde_json::to_string(item)?;
30            println!("{}", line);
31        }
32    }
33    Ok(())
34}
35
36pub fn write_jsonl_from_jsonld(
37    json_ld: &serde_json::Value,
38    provider_id: &str,
39) -> Result<(), Box<dyn std::error::Error>> {
40    use crate::api::types::ReadwiseType;
41
42    let items = match provider_id {
43        ReadwiseType::HIGHLIGHTS_ID => json_ld
44            .get("highlights")
45            .and_then(|h| h.get("items"))
46            .and_then(|i| i.as_array()),
47        ReadwiseType::BOOKLIST_ID => json_ld
48            .get("books")
49            .and_then(|b| b.get("items"))
50            .and_then(|i| i.as_array()),
51        ReadwiseType::TAGS_ID => json_ld
52            .get("tags")
53            .and_then(|t| t.get("items"))
54            .and_then(|i| i.as_array()),
55        _ => None,
56    };
57
58    if let Some(items_array) = items {
59        for item in items_array {
60            let line = serde_json::to_string(item)?;
61            println!("{}", line);
62        }
63    } else {
64        eprintln!(
65            "Warning: Expected items array not found in JSON-LD structure for JSONL output. No data will be produced."
66        );
67    }
68
69    Ok(())
70}