Skip to content

Commit

Permalink
improve an MPV of the plugin system and create first plugin to conver…
Browse files Browse the repository at this point in the history
…t mermaid schemes
  • Loading branch information
daynin committed Mar 29, 2023
1 parent 1bbb246 commit 7bf7d33
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 40 deletions.
13 changes: 8 additions & 5 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ pub fn read_config(path: Option<&str>) -> Option<Config> {
config
}

pub fn create_default_config() {
pub fn create_default_config() -> Config {
let theme = ColorfulTheme {
values_style: Style::new().cyan(),
..ColorfulTheme::default()
Expand Down Expand Up @@ -172,7 +172,7 @@ pub fn create_default_config() {
gh_username, gh_repo
));

let config = serde_json::to_string_pretty(&Config {
let config = Config {
docs_folder,
project_path,
repository_host,
Expand All @@ -185,14 +185,17 @@ pub fn create_default_config() {
comment_end_string: None,
comment_prefix: None,
plugins_dir: Some(String::from("./plugins")),
})
.unwrap();
};

let config_str = serde_json::to_string_pretty(&config).unwrap();

match File::create("./fundoc.json") {
Ok(mut file) => match file.write_all(config.as_bytes()) {
Ok(mut file) => match file.write_all(config_str.as_bytes()) {
Ok(_) => println!("Initialization is completed!",),
Err(_) => println!("Cannot create the config file"),
},
Err(e) => println!("{:?}", e),
}

config
}
28 changes: 20 additions & 8 deletions src/lua_runtime.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use rlua::{Function, Lua, MetaMethod, Result, UserData, UserDataMethods, Variadic, Context};
use rlua::{Function, Lua, Result};

pub struct LuaRuntime {
runtime: Lua,
Expand All @@ -14,21 +14,33 @@ impl LuaRuntime {
pub fn exec(&self, lua_code: String) {
self.runtime.context(|ctx| {
let globals = ctx.globals();
let log = ctx.create_function(|_, msg: String| {
eprintln!("{:#?}", msg);
Ok(())
}).unwrap();
let log = ctx
.create_function(|_, msg: String| {
eprintln!("{:#?}", msg);
Ok(())
})
.unwrap();

globals.set("log", log);
match globals.set("log", log) {
Err(err) => eprintln!("{:#?}", err),
_ => {}
};

ctx.load(&lua_code).exec();
match ctx.load(&lua_code).exec() {
Err(err) => eprintln!("{:#?}", err),
_ => {}
};
});
}

pub fn call_transform(&self, text: String) -> Result<String> {
self.runtime.context(|ctx| {
let transform: Function = ctx.globals().get("transform")?;
transform.call::<_, ()>(text);

match transform.call::<_, ()>(text) {
Err(err) => eprintln!("{:#?}", err),
_ => {}
}

ctx.globals().get::<_, String>("result")
})
Expand Down
20 changes: 9 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ mod parser;
mod plugins;

use ansi_term::Colour;
use plugins::Plugins;
use std::fs;

fn parse_articles(config: config::Config, root: &str) -> Vec<parser::Article> {
Expand Down Expand Up @@ -39,23 +38,22 @@ fn parse_articles(config: config::Config, root: &str) -> Vec<parser::Article> {
result.articles
}

fn generate_book(config: config::Config) {
/* book::init_book(config); */
book::build_book();
}

fn main() {
let args = cli::create_cli();

if let Some(true) = args.get_one::<bool>("init") {
config::create_default_config()
let config = config::create_default_config();
book::init_book(config);
} else if let Some(true) = args.get_one::<bool>("extension") {
match config::read_config(None) {
Some(config) => {
let plugins = plugins::Plugins::new(lua_runtime::LuaRuntime::new(), config);
plugins.run_as_plugin();
},
_ => {},
match plugins.run_as_plugin() {
Err(err) => eprintln!("{:#?}", err),
_ => {}
}
}
_ => {}
}
} else {
match config::read_config(None) {
Expand All @@ -74,7 +72,7 @@ fn main() {
generator::generate_docs(articles, config.clone());

if config.mdbook.unwrap() {
generate_book(config.clone());
book::build_book();

fs::remove_dir_all(config.docs_folder.unwrap()).ok();
}
Expand Down
64 changes: 48 additions & 16 deletions src/plugins.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use mdbook::book::{BookItem, Chapter};
use mdbook::preprocess::CmdPreprocessor;
use regex::Regex;
use serde_json::Error;
use std::{env, fs, io, process};

use crate::config;
Expand All @@ -13,10 +14,13 @@ pub struct Plugins {

impl Plugins {
pub fn new(lua_runtime: lua_runtime::LuaRuntime, config: config::Config) -> Self {
Self { lua_runtime, config }
Self {
lua_runtime,
config,
}
}

pub fn run_as_plugin(&self) {
pub fn run_as_plugin(&self) -> Result<(), Error> {
if self.config.plugins_dir.is_none() {
()
}
Expand All @@ -29,48 +33,76 @@ impl Plugins {
}

let (ctx, mut book) = CmdPreprocessor::parse_input(io::stdin()).unwrap();
eprintln!("{:?}", ctx);
let preprocessor = self.parse_private_preprocessor_value(format!("{:?}", ctx));

let re = Regex::new(r"\{\{ #mermaid[\w\W]*\}\}").unwrap();

for file in paths.unwrap() {
match file {
Ok(file) => {
let plugin_src = fs::read_to_string(&file.path()).unwrap();
book.sections = book.sections.iter().map(|section| {
match section {
let file_path = file.path();
let (Some(preprocessor_value), Some(path_str)) = (&preprocessor, file_path.to_str()) else {
serde_json::to_writer(io::stdout(), &book)?;
break;
};

if !path_str.contains(preprocessor_value) {
serde_json::to_writer(io::stdout(), &book)?;
break;
};
let regex_str = String::from(r"\{\{ #") + preprocessor_value + r"[\w\W]*\}\}";
let re = Regex::new(&regex_str).unwrap();

let plugin_src = fs::read_to_string(file_path).unwrap();
book.sections = book
.sections
.iter()
.map(|section| match section {
BookItem::Chapter(chapter) => {
let mut content = chapter.content.clone();

for capture in re.captures(&content.clone()) {
for capture in re.captures_iter(&content.clone()) {
let src_text =
capture.get(0).map_or("", |c| c.as_str()).to_string();

let parsed_fragment = self.parse_chapter(plugin_src.clone(), src_text.clone());
let parsed_fragment =
self.parse_chapter(preprocessor_value.to_string(), plugin_src.clone(), src_text.clone());
content = content.replace(&src_text, &parsed_fragment);

}

BookItem::Chapter(Chapter {
content,
..chapter.clone()
})
}
_ => section.clone()
}
}).collect();
_ => section.clone(),
})
.collect();

serde_json::to_writer(io::stdout(), &book);
serde_json::to_writer(io::stdout(), &book)?;
}
_ => {}
}
}

Ok(())
}

fn parse_private_preprocessor_value(&self, stringified_ctx: String) -> Option<String> {
let re = Regex::new(r#""preprocessor": Table\(\{"*(.*?) *":"#).unwrap();

match re.captures(&stringified_ctx) {
Some(captures) => captures
.get(1)
.map_or(None, |c| Some(String::from(c.as_str()))),
_ => None,
}
}

fn parse_chapter(&self, lua_src: String, src_text: String) -> String {
fn parse_chapter(&self, preprocessor: String, lua_src: String, src_text: String) -> String {
self.lua_runtime.exec(lua_src);

let mut extracted_text = src_text.replace("{{ #mermaid", "");
let preprocessor_header = String::from("{{ #") + &preprocessor;
let mut extracted_text = src_text.replace(&preprocessor_header, "");
extracted_text = extracted_text.replace("}}", "");

let result = self.lua_runtime.call_transform(extracted_text).unwrap();
Expand Down

0 comments on commit 7bf7d33

Please sign in to comment.