From cc095223b29b95287399476fc1dc58e32c303f60 Mon Sep 17 00:00:00 2001 From: Jan Range Date: Tue, 4 Jun 2024 14:11:38 +0200 Subject: [PATCH] parse md from string rather than path --- src/datamodel.rs | 3 ++- src/exporters.rs | 5 ++++- src/markdown/parser.rs | 12 ++---------- 3 files changed, 8 insertions(+), 12 deletions(-) diff --git a/src/datamodel.rs b/src/datamodel.rs index 3216167..19c7e8a 100644 --- a/src/datamodel.rs +++ b/src/datamodel.rs @@ -229,7 +229,8 @@ impl DataModel { /// # Returns /// A data model pub fn from_markdown(path: &Path) -> Result> { - parse_markdown(path) + let content = fs::read_to_string(path)?; + parse_markdown(&content) } /// Parse a JSON schema and create a data model diff --git a/src/exporters.rs b/src/exporters.rs index e830089..0997a39 100644 --- a/src/exporters.rs +++ b/src/exporters.rs @@ -2,6 +2,7 @@ use crate::datamodel::DataModel; use clap::ValueEnum; use lazy_static::lazy_static; use minijinja::{context, Environment}; +use pyo3::prelude::*; lazy_static! { /// Maps generic type names to Python-specific type names. @@ -30,6 +31,7 @@ lazy_static! { } /// Enumeration of available templates. +#[pyclass] #[derive(Debug, ValueEnum, Clone)] pub enum Templates { PythonDataclass, @@ -192,7 +194,8 @@ mod tests { /// A string containing the rendered template. fn build_and_convert(template: Templates) -> String { let path = Path::new("tests/data/model.md"); - let mut model = parse_markdown(path).expect("Failed to parse markdown file"); + let content = fs::read_to_string(path).expect("Could not read markdown file"); + let mut model = parse_markdown(&content).expect("Failed to parse markdown file"); render_jinja_template(&template, &mut model) .expect("Could not render template") .trim() diff --git a/src/markdown/parser.rs b/src/markdown/parser.rs index 25c4dee..d0796a2 100644 --- a/src/markdown/parser.rs +++ b/src/markdown/parser.rs @@ -1,7 +1,5 @@ use std::collections::BTreeMap; use std::error::Error; -use std::fs; -use std::path::Path; use pulldown_cmark::{Event, Parser, Tag}; use regex::Regex; @@ -28,16 +26,10 @@ enum ParserState { /// # Returns /// /// A `Result` containing a `DataModel` on success or an error on failure. -pub fn parse_markdown(path: &Path) -> Result> { - if !path.exists() { - return Err("File does not exist".into()); - } - - let content = fs::read_to_string(path).expect("Could not read file"); - +pub fn parse_markdown(content: &str) -> Result> { // Remove all html tags let re = Regex::new(r"<[^>]*>").unwrap(); - let content = re.replace_all(&content, "").to_string(); + let content = re.replace_all(content, "").to_string(); // Parse the frontmatter let config = parse_frontmatter(content.as_str());