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
use enum_iterator_derive::IntoEnumIterator;
use getset::{Getters, Setters};

use crate::{error::Error, Adapter};

pub type MarkdownResult = Result<Markdown, Error>;

/// Markdown
/// it is a struct refer a true md file
///
/// including `format`,`content` and `front_matter`
#[derive(Debug, Getters, Setters, Clone)]
pub struct Markdown {
    #[getset(get = "pub", set = "pub")]
    content: String,
    #[getset(get = "pub", set = "pub")]
    front_matter: String,
    #[getset(get = "pub", set = "pub")]
    format: Format,
}

impl Markdown {
    #[inline]
    pub fn new(content: String, front_matter: String, format: Format) -> Self {
        Markdown {
            format,
            content,
            front_matter,
        }
    }

    /// write data into a file
    /// # Examples
    /// ```
    /// use md_parser::*;
    /// Markdown::write_file("to.md").unwrap();
    /// ```
    pub fn write_file<P>(&self, path: P) -> Result<(), crate::error::Error>
    where
        P: AsRef<std::path::Path>,
    {
        crate::fs::write_file(self, path)
    }

    #[inline]
    /// write data into `Vec<u8>`
    pub fn bytes(&self) -> Vec<u8> {
        let mut v = vec![];
        let sp = self.format().separator();
        v.extend_from_slice(sp.as_bytes());
        v.extend_from_slice(self.front_matter().as_bytes());
        v.extend_from_slice(b"\n");
        v.extend_from_slice(sp.as_bytes());
        v.extend_from_slice(b"\n");
        v.extend_from_slice(self.content().as_bytes());

        v
    }

    #[inline]
    /// display all data as md format into a String
    pub fn display(&self) -> String {
        unsafe { String::from_utf8_unchecked(self.bytes()) }
    }

    /// transform a Markdown struct into another format
    ///
    /// require two types: Data Object and Adapter
    /// # Examples
    ///```
    /// use markdown_parser::*;
    /// use markdown_parser::adapt::{SafeFM, JsonAdapter};
    /// let origin = read_file("toml.md").unwrap();
    /// let md = origin.adapt::<JsonAdapter, SafeFM>().unwrap();
    ///```
    ///
    #[cfg(feature = "adapt")]
    pub fn adapt<A, T>(self) -> MarkdownResult
    where
        A: Adapter + Default,
        T: serde::ser::Serialize + serde::de::DeserializeOwned,
    {
        A::default().adapt::<T>(self)
    }
}

/// format of format matters
///
/// - json
/// - yaml
/// - toml
#[derive(Debug, Clone, IntoEnumIterator, PartialEq)]
pub enum Format {
    JSON,
    YAML,
    TOML,
}

impl Format {
    #[inline]
    /// internal format separator
    fn separator(&self) -> &str {
        match self {
            Format::YAML => "---\n",
            Format::TOML => "+++\n",
            _ => "",
        }
    }

    #[inline]
    /// internal format regex patten
    fn regex_patten(&self) -> &str {
        match self {
            Format::YAML => r"^[[:space:]]*\-\-\-\r?\n((?s).*?(?-s))\-\-\-\r?\n((?s).*(?-s))$",
            Format::TOML => r"^[[:space:]]*\+\+\+\r?\n((?s).*?(?-s))\+\+\+\r?\n((?s).*(?-s))$",
            Format::JSON => r"^[[:space:]]*\{\r?\n((?s).*?(?-s))\}\r?\n((?s).*(?-s))$",
        }
    }
}

/// parse data and guess the `Format`
pub fn parse(input: &str) -> MarkdownResult {
    use enum_iterator::IntoEnumIterator;
    for format in Format::into_enum_iter() {
        let md = parse_format(input, format);
        if md.is_ok() {
            return md;
        }
    }

    Err(crate::ParseError::MissingAllFormat.into())
}

/// parse data to the given `Format`
pub fn parse_format(input: &str, format: Format) -> MarkdownResult {
    let cap = regex::Regex::new(format.regex_patten())?
        .captures(input)
        .ok_or(crate::ParseError::BadFormat(format.clone()))?;

    // json should have `{` and `}`
    let front_matter = if Format::JSON.eq(&format) {
        format!("{{\n{0}\n}}", cap[1].trim())
    } else {
        cap[1].trim().to_string()
    };

    Ok(Markdown {
        format,
        front_matter,
        content: cap[2].trim().to_string(),
    })
}