summaryrefslogtreecommitdiff
path: root/src/bin/cli/mod.rs
blob: c53da0f2482ea0ffb359cfcad911df6900eb3926 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
//! CLI Functionality abstractions

#![allow(unused)]

use anyhow::Result;
use serde::Serialize;
use std::convert::TryFrom;
use std::fmt::Debug;
use std::path::Path;
use std::str::FromStr;
use subplot::{DataFile, Document, Style, SubplotError};
use tracing::{event, instrument, Level};

#[instrument(level = "trace")]
pub fn load_document<P>(filename: P, style: Style) -> Result<Document>
where
    P: AsRef<Path> + Debug,
{
    let filename = filename.as_ref();
    let base_path = subplot::get_basedir_from(filename);
    event!(
        Level::TRACE,
        ?filename,
        ?base_path,
        "Loading document based at `{}` called `{}` with {:?}",
        base_path.display(),
        filename.display(),
        style
    );
    let doc = Document::from_file(&base_path, filename, style)?;
    event!(Level::TRACE, "Loaded doc from file OK");

    Ok(doc)
}

#[instrument(level = "trace")]
pub fn load_document_with_pullmark<P>(filename: P, style: Style) -> Result<Document>
where
    P: AsRef<Path> + Debug,
{
    let filename = filename.as_ref();
    let base_path = subplot::get_basedir_from(filename);
    event!(
        Level::TRACE,
        ?filename,
        ?base_path,
        "Loading document based at `{}` called `{}` with {:?} using pullmark-cmark",
        base_path.display(),
        filename.display(),
        style
    );
    let doc = Document::from_file_with_pullmark(&base_path, filename, style)?;
    event!(Level::TRACE, "Loaded doc from file OK");

    Ok(doc)
}

pub fn extract_file<'a>(doc: &'a Document, filename: &str) -> Result<&'a DataFile> {
    for file in doc.files() {
        if file.filename() == filename {
            return Ok(file);
        }
    }
    Err(SubplotError::EmbeddedFileNotFound(filename.to_owned()).into())
}

#[derive(Serialize)]
pub struct Metadata {
    sources: Vec<String>,
    title: String,
    binding_files: Vec<String>,
    function_files: Vec<String>,
    bibliographies: Vec<String>,
    scenarios: Vec<String>,
    files: Vec<String>,
}

impl TryFrom<&mut Document> for Metadata {
    type Error = subplot::SubplotError;
    fn try_from(doc: &mut Document) -> std::result::Result<Self, Self::Error> {
        let mut sources: Vec<_> = doc
            .sources()
            .into_iter()
            .map(|p| filename(Some(&p)))
            .collect();
        sources.sort_unstable();
        let title = doc.meta().title().to_owned();
        let mut binding_files: Vec<_> = doc
            .meta()
            .bindings_filenames()
            .into_iter()
            .map(|p| filename(Some(p)))
            .collect();
        binding_files.sort_unstable();
        let mut function_files: Vec<_> = doc
            .meta()
            .functions_filenames()
            .into_iter()
            .map(|p| filename(Some(p)))
            .collect();
        function_files.sort_unstable();
        let mut bibliographies: Vec<_> = doc
            .meta()
            .bibliographies()
            .into_iter()
            .map(|p| filename(Some(p)))
            .collect();
        bibliographies.sort_unstable();
        let mut scenarios: Vec<_> = doc
            .scenarios()?
            .into_iter()
            .map(|s| s.title().to_owned())
            .collect();
        scenarios.sort_unstable();
        let mut files: Vec<_> = doc
            .files()
            .iter()
            .map(|f| f.filename().to_owned())
            .collect();
        files.sort_unstable();
        Ok(Self {
            sources,
            title,
            binding_files,
            function_files,
            bibliographies,
            scenarios,
            files,
        })
    }
}

impl Metadata {
    fn write_list(v: &[String], prefix: &str) {
        v.iter().for_each(|entry| println!("{}: {}", prefix, entry))
    }

    pub fn write_out(&self) {
        Self::write_list(&self.sources, "source");
        println!("title: {}", self.title);
        Self::write_list(&self.binding_files, "bindings");
        Self::write_list(&self.function_files, "functions");
        Self::write_list(&self.bibliographies, "bibliography");
        Self::write_list(&self.files, "file");
        Self::write_list(&self.scenarios, "scenario");
    }
}

fn filename(name: Option<&Path>) -> String {
    let path = match name {
        None => return "".to_string(),
        Some(x) => x,
    };
    match path.to_str() {
        None => "non-UTF8 filename".to_string(),
        Some(x) => x.to_string(),
    }
}

#[derive(Debug)]
pub enum OutputFormat {
    Plain,
    Json,
}

impl FromStr for OutputFormat {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_ref() {
            "plain" => Ok(OutputFormat::Plain),
            "json" => Ok(OutputFormat::Json),
            _ => Err(format!("Unknown output format: `{}`", s)),
        }
    }
}