Created
March 1, 2024 18:35
-
-
Save RyanParsley/69e179dce54fd08b84a54642b0fc433f to your computer and use it in GitHub Desktop.
A small rust script to parse markdown and set a yaml property to true.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use color_eyre::Result; | |
use gray_matter::engine::YAML; | |
use gray_matter::{Matter, Pod}; | |
use std::env::args; | |
use std::fs::{create_dir_all, write, File}; | |
use std::io::prelude::*; | |
fn main() -> Result<()> { | |
color_eyre::install()?; | |
let args: Vec<String> = args().collect(); | |
let source_path = &args[1]; | |
let directory_path = "dist"; | |
let filepath = "dist/output.md"; | |
let mut file = File::open(source_path)?; | |
let mut contents = String::new(); | |
file.read_to_string(&mut contents)?; | |
let has_complete_property = contents.lines().fold(false, |acc, line| { | |
if line.starts_with("complete") { | |
return true; | |
} | |
acc | |
}); | |
contents = match has_complete_property { | |
true => replace_property(contents), | |
false => add_property(contents), | |
}; | |
fn replace_property(body: String) -> String { | |
body.lines() | |
.map(|line| { | |
if line.starts_with("complete") { | |
return "complete: true".to_string(); | |
} | |
line.to_string() | |
}) | |
.collect::<Vec<String>>() | |
.join("\n") | |
} | |
fn add_property(body: String) -> String { | |
let matter = Matter::<YAML>::new(); | |
let parsed = matter.parse(&body); | |
let mut data = parsed.data.unwrap().as_vec(); | |
data.push(Pod::String("complete: true".to_string())); | |
let data = data?.join("\n"); | |
format!("---\n{}---\n{}", data, parsed.content) | |
} | |
create_dir_all(directory_path)?; | |
write(filepath, contents)?; | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment