mdmodels 0.2.9

A tool to generate models, code and schemas from markdown files
Documentation
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
/*
 * Copyright (c) 2025 Jan Range
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

use crate::{datamodel::DataModel, exporters::Templates};
use colored::Colorize;
use convert_case::Casing;
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    error::Error,
    fs,
    path::{Path, PathBuf},
    str::FromStr,
};

/// Represents a template with metadata and generation specifications.
#[derive(Debug, Serialize, Deserialize)]
struct GenTemplate {
    meta: Meta,
    generate: HashMap<String, GenSpecs>,
}

impl GenTemplate {
    pub fn prepend_root(&mut self, path: &Path) {
        for (_, specs) in self.generate.iter_mut() {
            specs.prepend_root(path);
        }

        self.meta.paths = self
            .meta
            .paths
            .iter_mut()
            .map(|spec| path.join(spec))
            .collect();
    }
}

/// Represents metadata for the template.
#[derive(Debug, Serialize, Deserialize)]
struct Meta {
    name: Option<String>,
    description: Option<String>,
    paths: Vec<PathBuf>,
}

/// Represents generation specifications for a template.
#[derive(Debug, Serialize, Deserialize)]
struct GenSpecs {
    description: Option<String>,
    out: PathBuf,
    root: Option<String>,
    #[serde(rename = "per-spec")]
    per_spec: Option<bool>,
    #[serde(flatten)]
    #[serde(deserialize_with = "deserialize_config_map")]
    config: HashMap<String, String>,
    #[serde(rename = "fname-case", default)]
    fname_case: Option<NameCase>,
}

fn deserialize_config_map<'de, D>(deserializer: D) -> Result<HashMap<String, String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let map: HashMap<String, toml::Value> = HashMap::deserialize(deserializer)?;
    Ok(map.into_iter().map(|(k, v)| (k, v.to_string())).collect())
}

impl GenSpecs {
    pub fn prepend_root(&mut self, path: &Path) {
        if path.is_file() {
            panic!("Root to prepend is not a directory.");
        }

        self.out = path.join(&self.out);
    }
}

/// Sate that determines whether objects are merged or not.
#[derive(Debug)]
enum MergeState {
    Merge,
    NoMerge,
}

impl From<bool> for MergeState {
    fn from(value: bool) -> Self {
        if value {
            MergeState::NoMerge
        } else {
            MergeState::Merge
        }
    }
}

/// Processes the pipeline by reading the template file, building the data model, and generating files based on the specifications.
///
/// # Arguments
///
/// * `path` - Path to the template file.
///
/// # Returns
///
/// A Result indicating success or failure.
pub fn process_pipeline(path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    let content = std::fs::read_to_string(path)?;
    let mut gen_template: GenTemplate = toml::from_str(content.as_str()).unwrap();

    if let Some(parent) = path.parent() {
        gen_template.prepend_root(parent);
    }

    let paths = gen_template.meta.paths.as_slice();

    for (name, mut specs) in gen_template.generate.into_iter() {
        let template = Templates::from_str(name.as_str())?;
        let merge_state = MergeState::from(specs.per_spec.unwrap_or(false));

        match template {
            Templates::JsonSchema => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::JsonSchemaAll => {
                serialize_all_json_schemes(&specs.out, paths, &merge_state)?;
            }
            Templates::JsonLd => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Linkml => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Shex => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Shacl => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Markdown => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Owl => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::CompactMarkdown => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::PythonDataclass => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::PythonPydantic => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::PythonPydanticXML => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::XmlSchema => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Typescript => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::TypescriptZod => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Rust => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Golang => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Julia => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Protobuf => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Graphql => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::MkDocs => {
                // If the template is not set to merge, then disable the navigation.
                if let MergeState::Merge = merge_state {
                    if !specs.config.contains_key("nav") {
                        specs.config.insert("nav".to_string(), "false".to_string());
                    }
                }

                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Mermaid => {
                serialize_by_template(
                    &specs.out,
                    paths,
                    &merge_state,
                    &template,
                    &specs.config,
                    &specs.fname_case,
                )?;
            }
            Templates::Internal => {
                let model = build_models(paths)?;
                serialize_to_internal_schema(model, &specs.out, &merge_state)?;
            }
        }
    }

    Ok(())
}

/// Builds the data model by reading and merging multiple paths.
///
/// # Arguments
///
/// * `paths` - A slice of PathBuf representing the paths to read.
///
/// # Returns
///
/// A Result containing the DataModel or an error.
fn build_models(paths: &[PathBuf]) -> Result<DataModel, Box<dyn Error>> {
    let first_path = paths.first().unwrap();
    path_exists(first_path)?;

    let mut model = DataModel::from_markdown(first_path).map_err(|e| {
        e.log_result();
        format!("Error parsing markdown content: {e:#?}")
    })?;

    if paths.len() == 1 {
        return Ok(model);
    }

    for path in paths.iter().skip(1) {
        path_exists(path)?;
        let new_model = DataModel::from_markdown(path)?;
        model.merge(&new_model);
    }

    Ok(model)
}

/// Checks if the given path exists.
///
/// # Arguments
///
/// * `path` - A reference to a PathBuf to check.
///
/// # Returns
///
/// A Result indicating success or failure.
fn path_exists(path: &PathBuf) -> Result<(), Box<dyn Error>> {
    if !path.exists() {
        return Err(format!("Path does not exist: {path:?}").into());
    }
    Ok(())
}

/// Serializes the data model to the internal schema.
///
/// Please note, this format may only be used for internal purposes.
///
/// # Arguments
///
/// * `model` - The DataModel to serialize.
/// * `out` - The output path for the internal schema file.
///
/// # Returns
///
/// A Result indicating success or failure.
fn serialize_to_internal_schema(
    model: DataModel,
    out: &PathBuf,
    merge_state: &MergeState,
) -> Result<(), Box<dyn Error>> {
    match merge_state {
        MergeState::Merge => {
            let schema = model.internal_schema();
            save_to_file(out, &schema)?;
            print_render_msg(out, &Templates::Internal);
            Ok(())
        }
        MergeState::NoMerge => {
            Err("Per spec is not supported for internal schema generation at the moment.".into())
        }
    }
}

/// Serializes all JSON schemas for the data model to the specified output directory.
///
/// # Arguments
///
/// * `model` - The DataModel to serialize.
/// * `out` - The output directory for the JSON schema files.
///
/// # Returns
///
/// A Result indicating success or failure.
fn serialize_all_json_schemes(
    out: &PathBuf,
    specs: &[PathBuf],
    merge_state: &MergeState,
) -> Result<(), Box<dyn Error>> {
    if out.is_file() {
        return Err("Output path is a file".into());
    }
    if !out.exists() {
        fs::create_dir_all(out)?;
    }

    match merge_state {
        MergeState::Merge => {
            let model = build_models(specs)?;
            model.json_schema_all(out.to_path_buf(), false)?;
            print_render_msg(out, &Templates::JsonSchemaAll);
            Ok(())
        }
        MergeState::NoMerge => {
            for spec in specs {
                let model = DataModel::from_markdown(spec)?;
                let path = out.join(get_file_name(spec));
                model.json_schema_all(path.to_path_buf(), false)?;
                print_render_msg(&path, &Templates::JsonSchemaAll);
            }
            Ok(())
        }
    }
}

/// Serializes the data model by the specified template.
///
/// # Arguments
///
/// * `out` - The output path for the serialized data model.
/// * `specs` - A slice of PathBuf representing the paths to read.
/// * `merge_state` - The merge state.
/// * `template` - The template to use for serialization.
///
/// # Returns
///
/// A Result indicating success or failure.
fn serialize_by_template(
    out: &PathBuf,
    specs: &[PathBuf],
    merge_state: &MergeState,
    template: &Templates,
    config: &HashMap<String, String>,
    case: &Option<NameCase>,
) -> Result<(), Box<dyn Error>> {
    match merge_state {
        MergeState::Merge => {
            print_render_msg(out, template);

            let mut model = build_models(specs)?;
            let content = model.convert_to(template, Some(config))?;

            return save_to_file(out, content.as_str());
        }
        MergeState::NoMerge => {
            if !has_wildcard_fname(out) {
                return Err("
                    Output file name must contain a wildcard.
                    For example, a valid wildcard is 'path/to/*.json'"
                    .into());
            }

            for spec in specs {
                if !spec.exists() {
                    return Err(format!("Path does not exist: {spec:?}").into());
                }

                let mut fname = get_file_name(spec);

                if let Some(case) = case {
                    fname = casify_filename(fname, case.into());
                }

                let path = replace_wildcard(out, &fname);
                print_render_msg(&path, template);

                let mut model = DataModel::from_markdown(spec)?;
                let content = model.convert_to(template, Some(config))?;

                save_to_file(&path, content.as_str())?;
            }
        }
    }

    Ok(())
}

/// Converts a filename to the specified case format.
///
/// # Arguments
///
/// * `name` - The filename to convert
/// * `case` - The case format to convert to
///
/// # Returns
///
/// The converted filename as a String
fn casify_filename(name: String, case: Option<convert_case::Case>) -> String {
    if let Some(c) = case {
        let (name, _) = name.split_once('.').unwrap_or((name.as_str(), ""));
        let new_name = name.to_case(c);

        new_name.to_string()
    } else {
        name
    }
}

/// Checks if the given path has a wildcard file name.
///
/// # Arguments
///
/// * `path` - The path to check.
///
/// # Returns
///
/// A boolean indicating if the path has a wildcard file name.
fn has_wildcard_fname(path: &Path) -> bool {
    let path_str = path.to_str().unwrap();
    path_str.contains("*")
}

/// Replaces the wildcard in the given path with the given name.
///
/// # Arguments
///
/// * `path` - The path to replace the wildcard file name.
/// * `name` - The name to replace the wildcard file name with.
///
/// # Returns
///
/// A PathBuf with the wildcard replaced.
fn replace_wildcard(path: &Path, name: &str) -> PathBuf {
    let path_str = path.to_str().unwrap();
    let new_path = path_str.replace('*', name);
    PathBuf::from(new_path)
}

/// Gets the file name without the extension.
///
/// # Arguments
///
/// * `path` - The path to get the file name from.
///
/// # Returns
///
/// A string containing the file name without the extension.
fn get_file_name(path: &Path) -> String {
    // Get the filename without the extension
    let file_name = path.file_name().unwrap().to_str().unwrap();
    let file_name = file_name.split('.').collect::<Vec<&str>>()[0];
    file_name.to_string()
}

/// Saves the given content to the specified file.
///
/// # Arguments
///
/// * `out` - The output path for the file.
/// * `content` - The content to write to the file.
///
/// # Returns
///
/// A Result indicating success or failure.
fn save_to_file(out: &PathBuf, content: &str) -> Result<(), Box<dyn Error>> {
    let dir = out.parent().unwrap();
    if !dir.exists() {
        fs::create_dir_all(dir)?;
    }

    fs::write(out, content.trim()).map_err(|e| format!("Error writing to file: {e:#?}"))?;
    Ok(())
}

fn print_render_msg(out: &Path, template: &Templates) {
    println!(
        " [{}] Writing to '{}'",
        template.to_string().green().bold(),
        out.to_str().unwrap().to_string().bold(),
    );
}

/// Represents different case styles for naming files.
///
/// Supports common case conventions used in programming:
/// - Pascal case (e.g. "MyFileName")
/// - Snake case (e.g. "my_file_name")
/// - Kebab case (e.g. "my-file-name")
/// - Camel case (e.g. "myFileName")
/// - None (no case transformation)
#[derive(Debug, Deserialize, Serialize)]
enum NameCase {
    Pascal,
    Snake,
    Kebab,
    Camel,
    None,
}

impl FromStr for NameCase {
    type Err = String;

    /// Converts a string to a NameCase variant.
    ///
    /// # Arguments
    ///
    /// * `s` - The string to convert
    ///
    /// # Returns
    ///
    /// A Result containing the NameCase variant or an error string if invalid.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "pascal" => Ok(NameCase::Pascal),
            "snake" => Ok(NameCase::Snake),
            "kebab" => Ok(NameCase::Kebab),
            "camel" => Ok(NameCase::Camel),
            _ => Err("Invalid name case".to_string()),
        }
    }
}

impl<'a> From<&'a NameCase> for Option<convert_case::Case<'a>> {
    /// Converts a NameCase variant to the corresponding convert_case::Case variant.
    ///
    /// # Arguments
    ///
    /// * `value` - The NameCase variant to convert
    ///
    /// # Returns
    ///
    /// An Option containing the convert_case::Case variant, or None if no transformation needed.
    fn from(value: &NameCase) -> Self {
        match value {
            NameCase::Pascal => Some(convert_case::Case::Pascal),
            NameCase::Snake => Some(convert_case::Case::Snake),
            NameCase::Kebab => Some(convert_case::Case::Kebab),
            NameCase::Camel => Some(convert_case::Case::Camel),
            NameCase::None => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn test_has_wildcard_fname() {
        let path = PathBuf::from("path/to/*.json");
        let result = has_wildcard_fname(&path);
        assert!(result);
    }

    #[test]
    fn test_has_wildcard_fname_no_wildcard() {
        let path = PathBuf::from("path/to/file.json");
        let result = has_wildcard_fname(&path);
        assert!(!result);
    }

    #[test]
    fn test_build_models() {
        let specs = vec![
            PathBuf::from("tests/data/model.md"),
            PathBuf::from("tests/data/model_merge.md"),
        ];
        let result = build_models(&specs);
        assert!(result.is_ok());
    }

    #[test]
    fn test_prepend_root() {
        let mut gen_template = GenTemplate {
            meta: Meta {
                name: None,
                description: None,
                paths: vec![PathBuf::from("model.md")],
            },
            generate: HashMap::from_iter(vec![(
                "json-schema".to_string(),
                GenSpecs {
                    description: None,
                    out: PathBuf::from("schema.json"),
                    root: None,
                    per_spec: None,
                    config: HashMap::new(),
                    fname_case: None,
                },
            )]),
        };

        let path = PathBuf::from("tests/data");
        gen_template.prepend_root(&path);

        assert_eq!(
            gen_template.meta.paths[0],
            PathBuf::from("tests/data/model.md")
        );
        assert_eq!(
            gen_template.generate["json-schema"].out,
            PathBuf::from("tests/data/schema.json")
        );
    }
}