summaryrefslogtreecommitdiff
path: root/src/metadata.rs
blob: 3f4916a1728762e790c941eaa43156f17fae5ad7 (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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
use crate::{resource, Result};
use crate::{Bindings, TemplateSpec};

use std::ops::Deref;
use std::path::{Path, PathBuf};

use pandoc_ast::{Inline, Map, MetaValue, Pandoc};

/// Metadata of a document, as needed by Subplot.
#[derive(Debug)]
pub struct Metadata {
    title: String,
    date: Option<String>,
    bindings_filenames: Vec<PathBuf>,
    bindings: Bindings,
    functions_filenames: Vec<PathBuf>,
    template: Option<String>,
    spec: Option<TemplateSpec>,
    bibliographies: Vec<PathBuf>,
    /// Extra class names which should be considered 'correct' for this document
    classes: Vec<String>,
}

impl Metadata {
    /// Construct a Metadata from a Document, if possible.
    pub fn new<P>(basedir: P, doc: &Pandoc) -> Result<Metadata>
    where
        P: AsRef<Path>,
    {
        let title = get_title(&doc.meta);
        let date = get_date(&doc.meta);
        let bindings_filenames = get_bindings_filenames(basedir.as_ref(), &doc.meta);
        let functions_filenames = get_functions_filenames(basedir.as_ref(), &doc.meta);
        let (template, spec) = if let Some((template, spec)) = get_template_spec(&doc.meta)? {
            resource::set_template(&template);
            (Some(template), Some(spec))
        } else {
            (None, None)
        };
        let mut bindings = Bindings::new();

        let bibliographies = get_bibliographies(basedir.as_ref(), &doc.meta);
        let classes = get_classes(&doc.meta);

        get_bindings(&bindings_filenames, &mut bindings)?;
        Ok(Metadata {
            title,
            date,
            bindings_filenames,
            bindings,
            functions_filenames,
            template,
            spec,
            bibliographies,
            classes,
        })
    }

    /// Return title of document.
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Return date of document, if any.
    pub fn date(&self) -> Option<&str> {
        if let Some(date) = &self.date {
            Some(&date)
        } else {
            None
        }
    }

    /// Return filename where bindings are specified.
    pub fn bindings_filenames(&self) -> Vec<&Path> {
        self.bindings_filenames.iter().map(|f| f.as_ref()).collect()
    }

    /// Return filename where functions are specified.
    pub fn functions_filenames(&self) -> Vec<&Path> {
        self.functions_filenames
            .iter()
            .map(|f| f.as_ref())
            .collect()
    }

    /// Return the name of the code template, if specified.
    pub fn template_name(&self) -> Option<&str> {
        match &self.template {
            Some(x) => Some(&x),
            None => None,
        }
    }

    /// Return the bindings.
    pub fn bindings(&self) -> &Bindings {
        &self.bindings
    }

    /// Return the bibliographies.
    pub fn bibliographies(&self) -> Vec<&Path> {
        self.bibliographies.iter().map(|x| x.as_path()).collect()
    }

    /// The classes which this document also claims are valid
    pub fn classes(&self) -> impl Iterator<Item = &str> {
        self.classes.iter().map(Deref::deref)
    }
}

type Mapp = Map<String, MetaValue>;

fn get_title(map: &Mapp) -> String {
    if let Some(s) = get_string(map, "title") {
        s
    } else {
        "".to_string()
    }
}

fn get_date(map: &Mapp) -> Option<String> {
    if let Some(s) = get_string(map, "date") {
        Some(s)
    } else {
        None
    }
}

fn get_bindings_filenames<P>(basedir: P, map: &Mapp) -> Vec<PathBuf>
where
    P: AsRef<Path>,
{
    get_paths(basedir, map, "bindings")
}

fn get_functions_filenames<P>(basedir: P, map: &Mapp) -> Vec<PathBuf>
where
    P: AsRef<Path>,
{
    get_paths(basedir, map, "functions")
}

fn get_template_spec(map: &Mapp) -> Result<Option<(String, TemplateSpec)>> {
    match get_string(map, "template") {
        Some(s) => {
            let mut spec_path = PathBuf::from(&s);
            spec_path.push("template");
            spec_path.push("template.yaml");
            let spec = TemplateSpec::from_file(&spec_path)?;
            Ok(Some((s, spec)))
        }
        None => Ok(None),
    }
}

fn get_paths<P>(basedir: P, map: &Mapp, field: &str) -> Vec<PathBuf>
where
    P: AsRef<Path>,
{
    match map.get(field) {
        None => vec![],
        Some(v) => pathbufs(basedir, v),
    }
}

fn get_string(map: &Mapp, field: &str) -> Option<String> {
    let v = match map.get(field) {
        None => return None,
        Some(s) => s,
    };
    let v = match v {
        pandoc_ast::MetaValue::MetaString(s) => s.to_string(),
        pandoc_ast::MetaValue::MetaInlines(vec) => join(&vec),
        _ => panic!("don't know how to handle: {:?}", v),
    };
    Some(v)
}

fn get_bibliographies<P>(basedir: P, map: &Mapp) -> Vec<PathBuf>
where
    P: AsRef<Path>,
{
    let v = match map.get("bibliography") {
        None => return vec![],
        Some(s) => s,
    };
    pathbufs(basedir, v)
}

fn pathbufs<P>(basedir: P, v: &MetaValue) -> Vec<PathBuf>
where
    P: AsRef<Path>,
{
    let mut bufs = vec![];
    push_pathbufs(basedir, v, &mut bufs);
    bufs
}

fn get_classes(map: &Mapp) -> Vec<String> {
    let mut ret = Vec::new();
    if let Some(classes) = map.get("classes") {
        push_strings(classes, &mut ret);
    }
    ret
}

fn push_strings(v: &MetaValue, strings: &mut Vec<String>) {
    match v {
        MetaValue::MetaString(s) => strings.push(s.to_string()),
        MetaValue::MetaInlines(vec) => strings.push(join(&vec)),
        MetaValue::MetaList(values) => {
            for value in values {
                push_strings(value, strings);
            }
        }
        _ => panic!("don't know how to handle: {:?}", v),
    };
}

fn push_pathbufs<P>(basedir: P, v: &MetaValue, bufs: &mut Vec<PathBuf>)
where
    P: AsRef<Path>,
{
    match v {
        MetaValue::MetaString(s) => bufs.push(basedir.as_ref().join(Path::new(s))),
        MetaValue::MetaInlines(vec) => bufs.push(basedir.as_ref().join(Path::new(&join(&vec)))),
        MetaValue::MetaList(values) => {
            for value in values {
                push_pathbufs(basedir.as_ref(), value, bufs);
            }
        }
        _ => panic!("don't know how to handle: {:?}", v),
    };
}

fn join(vec: &[Inline]) -> String {
    let mut buf = String::new();
    join_into_buffer(vec, &mut buf);
    buf
}

fn join_into_buffer(vec: &[Inline], buf: &mut String) {
    for item in vec {
        match item {
            pandoc_ast::Inline::Str(s) => buf.push_str(&s),
            pandoc_ast::Inline::Emph(v) => join_into_buffer(v, buf),
            pandoc_ast::Inline::Strong(v) => join_into_buffer(v, buf),
            pandoc_ast::Inline::Strikeout(v) => join_into_buffer(v, buf),
            pandoc_ast::Inline::Superscript(v) => join_into_buffer(v, buf),
            pandoc_ast::Inline::Subscript(v) => join_into_buffer(v, buf),
            pandoc_ast::Inline::SmallCaps(v) => join_into_buffer(v, buf),
            pandoc_ast::Inline::Space => buf.push(' '),
            pandoc_ast::Inline::SoftBreak => buf.push(' '),
            pandoc_ast::Inline::LineBreak => buf.push(' '),
            pandoc_ast::Inline::Quoted(qtype, v) => {
                let quote = match qtype {
                    pandoc_ast::QuoteType::SingleQuote => '\'',
                    pandoc_ast::QuoteType::DoubleQuote => '"',
                };
                buf.push(quote);
                join_into_buffer(v, buf);
                buf.push(quote);
            }
            _ => panic!("unknown pandoc_ast::Inline component {:?}", item),
        }
    }
}

#[cfg(test)]
mod test_join {
    use super::join;
    use pandoc_ast::{Inline, QuoteType};

    #[test]
    fn join_all_kinds() {
        let v = vec![
            Inline::Str("a".to_string()),
            Inline::Emph(vec![Inline::Str("b".to_string())]),
            Inline::Strong(vec![Inline::Str("c".to_string())]),
            Inline::Strikeout(vec![Inline::Str("d".to_string())]),
            Inline::Superscript(vec![Inline::Str("e".to_string())]),
            Inline::Subscript(vec![Inline::Str("f".to_string())]),
            Inline::SmallCaps(vec![Inline::Str("g".to_string())]),
            Inline::Space,
            Inline::SoftBreak,
            Inline::Quoted(QuoteType::SingleQuote, vec![Inline::Str("h".to_string())]),
            Inline::LineBreak,
            Inline::Quoted(QuoteType::DoubleQuote, vec![Inline::Str("i".to_string())]),
        ];
        assert_eq!(join(&v), r#"abcdefg  'h' "i""#);
    }
}

fn get_bindings<P>(filenames: &[P], bindings: &mut Bindings) -> Result<()>
where
    P: AsRef<Path>,
{
    for filename in filenames {
        bindings.add_from_file(filename)?;
    }
    Ok(())
}