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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Structs and functions for parsing and generating the Unimarkup configuration.

use std::path::PathBuf;

use clap::{crate_version, ArgEnum, Parser};
use logid::{
    capturing::{LogIdTracing, MappedLogId},
    log_id::LogId,
};
use serde::{Deserialize, Serialize};
use strum_macros::EnumString;

use crate::{
    elements::types::ElementType,
    log_id::{ConfigErrLogId, CORE_LOG_ID_MAP},
};

const UNIMARKUP_NAME: &str = "Unimarkup";

/// Config contains the possible options for the Unimarkup configuration.
#[derive(Debug, PartialEq, Eq, Clone, Parser, Default, Serialize, Deserialize)]
#[clap(name = UNIMARKUP_NAME, version = crate_version!())]
pub struct Config {
    /// The filename of the Unimarkup file that is used as root for rendering.
    #[clap(
        index = 1,
        value_name = "UM-FILE",
        required = true,
        takes_value = true,
        parse(from_os_str)
    )]
    #[serde(skip)]
    pub um_file: PathBuf,

    /// The filename without filetype to be used for output filenames. If a path is part of the filename, output files are saved at the given path.
    #[clap(
        index = 2,
        value_name = "OUTPUT-FILE",
        takes_value = true,
        parse(from_os_str)
    )]
    #[serde(alias = "OUTPUT-FILE")]
    #[serde(default)]
    pub out_file: Option<PathBuf>,

    /// Set output formats the Unimarkup document should be rendered to. Set outputs are also treated as flags inside the Unimarkup document.
    #[clap(
        name = "output-formats",
        display_order = 1,
        long = "output-formats",
        alias = "formats",
        takes_value = true,
        use_value_delimiter = true,
        arg_enum
    )]
    #[serde(alias = "output-formats")]
    #[serde(alias = "formats")]
    #[serde(default)]
    pub out_formats: Option<Vec<OutputFormat>>,

    /// Set paths that are searched for relative file and image inserts.
    #[clap(
        display_order = 2,
        long = "insert-paths",
        takes_value = true,
        use_value_delimiter = true,
        parse(from_os_str)
    )]
    #[serde(alias = "insert-paths")]
    #[serde(default)]
    pub insert_paths: Option<Vec<PathBuf>>,

    /// Set the path to a directory that is used for default preamble and theme settings.
    /// The intermediate form of rendered documents will also be stored at this path.
    #[clap(
        display_order = 3,
        long = "dot-unimarkup",
        alias = "config",
        takes_value = true,
        env = "UNIMARKUP_CONFIG",
        parse(from_os_str)
    )]
    #[serde(alias = "dot-unimarkup")]
    #[serde(alias = "config")]
    #[serde(default)]
    pub dot_unimarkup: Option<PathBuf>,

    /// Set a Unimarkup theme file to be used for rendering.
    #[clap(
        display_order = 5,
        short = 't',
        long = "theme",
        takes_value = true,
        parse(from_os_str)
    )]
    #[serde(alias = "theme")]
    #[serde(default)]
    pub theme: Option<PathBuf>,

    /// Set flags that will be set for rendering.
    #[clap(
        display_order = 6,
        short = 'f',
        long = "flags",
        takes_value = true,
        use_value_delimiter = true
    )]
    #[serde(alias = "flags")]
    #[serde(default)]
    pub flags: Option<Vec<String>>,

    /// Explicitly set Unimarkup block elements that can be used inside the given Unimarkup document.
    /// If this option is set, all Unimarkup elements that are not given are disabled.
    #[clap(
        display_order = 7,
        long = "enable-elements",
        takes_value = true,
        use_value_delimiter = true,
        arg_enum
    )]
    #[serde(alias = "enable-elements")]
    #[serde(default)]
    pub enable_elements: Option<Vec<ElementType>>,

    /// Explicitly set Unimarkup block elements that can NOT be used inside the given Unimarkup document.
    /// If this option is set, all Unimarkup elements that are not given are enabled.
    #[clap(
        display_order = 8,
        long = "disable-elements",
        takes_value = true,
        use_value_delimiter = true,
        arg_enum
    )]
    #[serde(alias = "disable-elements")]
    #[serde(default)]
    pub disable_elements: Option<Vec<ElementType>>,

    /// Set citation style sheet that is used to process referenced literature
    #[clap(
        display_order = 30,
        long = "citation-style",
        alias = "csl",
        takes_value = true,
        requires = "references",
        parse(from_os_str)
    )]
    #[serde(alias = "citation-style")]
    #[serde(alias = "csl")]
    #[serde(default)]
    pub citation_style: Option<PathBuf>,

    /// Set one or more reference files in bibtex or JSON format to use them with literature referencing.
    #[clap(
        display_order = 31,
        long = "references",
        alias = "refs",
        takes_value = true,
        use_value_delimiter = true,
        requires = "citation-style",
        parse(from_os_str)
    )]
    #[serde(alias = "references")]
    #[serde(alias = "refs")]
    #[serde(default)]
    pub references: Option<Vec<PathBuf>>,

    /// Set ttf or woff fonts to be able to use them for rendering
    #[clap(
        display_order = 10,
        long = "fonts",
        alias = "ttf",
        alias = "woff",
        takes_value = true,
        use_value_delimiter = true,
        parse(from_os_str)
    )]
    #[serde(alias = "fonts")]
    #[serde(alias = "ttf")]
    #[serde(alias = "woff")]
    #[serde(default)]
    pub fonts: Option<Vec<PathBuf>>,

    /// Overwrites files set with `out-file` if already existing.
    #[clap(
        display_order = 1,
        short = 'w',
        long = "overwrite-out-files",
        takes_value = false
    )]
    #[serde(alias = "overwrite-out-files")]
    #[serde(default)]
    pub overwrite_out_files: bool,

    /// Deletes all previously rendered documents stored inside the UNIMARKUP_CONFIG path.
    #[clap(display_order = 2, short = 'c', long = "clean", takes_value = false)]
    #[serde(alias = "clean")]
    #[serde(alias = "c")]
    #[serde(default)]
    pub clean: bool,

    /// Ignores all previously rendered documents stored inside the UNIMARKUP_CONFIG path and renders the given Unimarkup file.
    #[clap(display_order = 3, short = 'r', long = "rebuild", takes_value = false)]
    #[serde(alias = "rebuild")]
    #[serde(default)]
    pub rebuild: bool,

    /// Set if preamble of given Unimarkup file is replaced with the given arguments.
    /// If not set, given arguments overwrite the corresponding preamble settings, but other settings are still used.
    #[clap(
        display_order = 20,
        long = "replace-preamble",
        requires = "output-formats",
        takes_value = false
    )]
    #[serde(skip)]
    pub replace_preamble: bool,

    /// This prefix will be set before inserts in the rendered document to inserts that use relative paths.
    /// Note: During rendering, the original relative path is taken.
    #[clap(
        display_order = 20,
        long = "relative-insert-prefix",
        alias = "insert-prefix",
        takes_value = true,
        parse(from_os_str)
    )]
    #[serde(alias = "relative-insert-prefix")]
    #[serde(alias = "insert-prefix")]
    #[serde(default)]
    pub relative_insert_prefix: Option<PathBuf>,

    /// Set a template html file with `{{ head }}` set inside the `head` element and `{{ body }}` set inside the body element.
    /// Styling, fonts and scripts will be inserted at `{{ head }}` and the rendered Unimarkup content is placed inside `{{ body }}`.
    /// Optionally, `{{ toc }}` can be set to get the table of contents (Note: This will not remove a rendered table of contents inside the rendered Unimarkup content if present).
    #[clap(
        display_order = 40,
        long = "html-template",
        takes_value = true,
        parse(from_os_str)
    )]
    #[serde(alias = "html-template")]
    #[serde(default)]
    pub html_template: Option<PathBuf>,

    /// Set the mathmode of MathJax to be used for rendered html documents.
    #[clap(
        display_order = 41,
        long = "html-mathmode",
        takes_value = true,
        arg_enum
    )]
    #[serde(alias = "html-mathmode")]
    #[serde(default)]
    pub html_mathmode: Option<HtmlMathmode>,

    /// Set if svgs should be embedded into html instead of inserted as regular images.
    #[clap(display_order = 40, long = "html-embed-svg", takes_value = false)]
    #[serde(alias = "html-embed-svg")]
    #[serde(default)]
    pub html_embed_svg: bool,
}

/// Possible output formats for a Unimarkup file
#[derive(
    Debug, PartialEq, Eq, Clone, EnumString, ArgEnum, strum_macros::Display, Serialize, Deserialize,
)]
pub enum OutputFormat {
    /// PDF output format
    #[strum(ascii_case_insensitive)]
    Pdf,
    /// HTML output format
    #[strum(ascii_case_insensitive)]
    Html,
    #[strum(ascii_case_insensitive, serialize = "reveal-js")]
    #[clap(alias = "revealjs")]
    /// [revealJs] output format.
    ///
    /// A presentation framework using HTML and Javascript
    ///
    /// [revealJs]: https://revealjs.com/
    RevealJs,
    #[strum(ascii_case_insensitive)]
    /// Intermediate representation of the Unimarkup document.
    Intermediate,
}

/// Possible modes for rendering math formulas in HTML
#[derive(
    Debug, PartialEq, Eq, Clone, EnumString, ArgEnum, strum_macros::Display, Serialize, Deserialize,
)]
pub enum HtmlMathmode {
    /// Render math as SVG
    #[strum(ascii_case_insensitive)]
    Svg,
    /// Embed MathJax
    #[strum(ascii_case_insensitive)]
    Embed,
    /// Use CDN (Content Delivery Network) for MathJax (requires online connection to view math formulas in the output HTML)
    #[strum(ascii_case_insensitive)]
    Cdn,
}

// define extension trait
trait ReplaceIfNone<T> {
    fn replace_none(&mut self, other: Option<T>);
}

// implement for Option<T>
impl<T> ReplaceIfNone<T> for Option<T> {
    fn replace_none(&mut self, other: Option<T>) {
        if self.is_none() {
            *self = other;
        }
    }
}

impl Config {
    /// Merges the fields of two [`Config`]s.
    /// Any field that is `None` is taken from `other` [`Config`] if available.
    ///
    /// In other words, the fields of [`Config`] that this method is called on, take precedence over the
    /// fields of the `other` [`Config`].
    pub fn merge(&mut self, other: Config) {
        self.out_file.replace_none(other.out_file);
        self.out_formats.replace_none(other.out_formats);
        self.insert_paths.replace_none(other.insert_paths);
        self.dot_unimarkup.replace_none(other.dot_unimarkup);
        self.theme.replace_none(other.theme);
        self.flags.replace_none(other.flags);
        self.enable_elements.replace_none(other.enable_elements);
        self.disable_elements.replace_none(other.disable_elements);
        self.citation_style.replace_none(other.citation_style);
        self.references.replace_none(other.references);
        self.fonts.replace_none(other.fonts);

        self.overwrite_out_files |= other.overwrite_out_files;
        self.clean |= other.clean;
        self.rebuild |= other.rebuild;

        self.relative_insert_prefix
            .replace_none(other.relative_insert_prefix);
        self.html_template.replace_none(other.html_template);
        self.html_mathmode.replace_none(other.html_mathmode);

        self.html_embed_svg |= other.html_embed_svg;
    }

    /// [`validate_config`] validates if file and paths exist and if config does not contradict itself
    pub fn validate_config(&mut self) -> Result<(), MappedLogId> {
        if let Some(ref file) = self.out_file {
            if file.exists() && !self.overwrite_out_files {
                return Err((ConfigErrLogId::InvalidConfig as LogId).set_event_with(
                    &CORE_LOG_ID_MAP,
                    "Option `overwrite-out-files` must be `true` if output file exists.",
                    file!(),
                    line!(),
                ));
            }
        }
        if let Some(ref paths) = self.insert_paths {
            for path in paths {
                if !path.exists() {
                    return Err((ConfigErrLogId::InvalidPath as LogId).set_event_with(
                        &CORE_LOG_ID_MAP,
                        &format!("Invalid path given for `insert-paths`: {:?}", path),
                        file!(),
                        line!(),
                    ));
                }
            }
        }
        if let Some(ref path) = self.dot_unimarkup {
            if !path.is_dir() {
                return Err((ConfigErrLogId::InvalidPath as LogId).set_event_with(
                    &CORE_LOG_ID_MAP,
                    &format!("Invalid path given for `dot-unimarkup`: {:?}", path),
                    file!(),
                    line!(),
                ));
            }
        }
        if let Some(ref file) = self.theme {
            if !file.exists() {
                return Err((ConfigErrLogId::InvalidFile as LogId).set_event_with(
                    &CORE_LOG_ID_MAP,
                    &format!("Invalid file given for `theme`: {:?}", file),
                    file!(),
                    line!(),
                ));
            }
        }
        if let Some(ref file) = self.citation_style {
            if !file.exists() {
                return Err((ConfigErrLogId::InvalidFile as LogId).set_event_with(
                    &CORE_LOG_ID_MAP,
                    &format!("Invalid file given for `citation-style`: {:?}", file),
                    file!(),
                    line!(),
                ));
            }
        }
        if let Some(ref files) = self.references {
            for file in files {
                if !file.exists() {
                    return Err((ConfigErrLogId::InvalidFile as LogId).set_event_with(
                        &CORE_LOG_ID_MAP,
                        &format!("Invalid file given for `references`: {:?}", file),
                        file!(),
                        line!(),
                    ));
                }
            }
        }
        if let Some(ref files) = self.fonts {
            for file in files {
                if !file.exists() {
                    return Err((ConfigErrLogId::InvalidFile as LogId).set_event_with(
                        &CORE_LOG_ID_MAP,
                        &format!("Invalid file given for `fonts`: {:?}", file),
                        file!(),
                        line!(),
                    ));
                }
            }
        }
        if let Some(ref file) = self.html_template {
            if !file.exists() {
                return Err((ConfigErrLogId::InvalidFile as LogId).set_event_with(
                    &CORE_LOG_ID_MAP,
                    &format!("Invalid file given for `html-template`: {:?}", file),
                    file!(),
                    line!(),
                ));
            }
        }
        if !self.um_file.exists() {
            return Err((ConfigErrLogId::InvalidFile as LogId).set_event_with(
                &CORE_LOG_ID_MAP,
                "Set `um-file` does not exist!",
                file!(),
                line!(),
            ));
        }

        Ok(())
    }
}

#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test__validate__valid_config() {
        let mut cfg: Config = Config::parse_from(vec![
            "unimarkup",
            "--output-formats=html",
            "--dot-unimarkup=tests/test_files/",
            "tests/test_files/frontend/heading1.um",
        ]);

        let result = cfg.validate_config();
        assert!(result.is_ok(), "Cause: {:?}", result.unwrap_err());
    }

    #[should_panic]
    #[test]
    fn test__validate__invalid_config() {
        let mut cfg: Config = Config::parse_from(vec![
            "unimarkup",
            "--output-formats=html",
            //invalid attribute "shouldfail" on purpose
            "--dot-unimarkup=shouldfail",
            "tests/test_files/frontend/heading1.um",
        ]);

        cfg.validate_config().unwrap();
    }

    #[test]
    fn test__validate__valid_multi_path_config() {
        let mut cfg: Config = Config::parse_from(vec![
            "unimarkup",
            "--output-formats=html",
            "--dot-unimarkup=tests/test_files/",
            "--insert-paths=tests/test_files/,tests/test_files/",
            "tests/test_files/frontend/heading1.um",
        ]);

        let result = cfg.validate_config();
        assert!(result.is_ok(), "Cause: {:?}", result.unwrap_err());
    }

    #[should_panic]
    #[test]
    fn test__validate__invalid_multi_path_config() {
        let mut cfg: Config = Config::parse_from(vec![
            "unimarkup",
            "--output-formats=html",
            "--dot-unimarkup=tests/test_files/",
            //invalid attribute "shouldfail" on purpose
            "--insert-paths=shouldfail,tests/test_files/",
            "tests/test_files/frontend/heading1.um",
        ]);

        cfg.validate_config().unwrap();
    }
}