62 lines
1.4 KiB
Rust
62 lines
1.4 KiB
Rust
use std::collections::HashMap;
|
|
use std::io::{BufRead, BufReader};
|
|
use std::fs::File;
|
|
|
|
pub struct Marky {
|
|
pub metadata: HashMap<String, String>,
|
|
pub content: String,
|
|
}
|
|
|
|
impl Marky {
|
|
pub fn from_file(file: &File) -> Marky {
|
|
let reader = BufReader::new(file);
|
|
|
|
let mut is_metadata = false;
|
|
let mut metadata = HashMap::new();
|
|
let mut content = String::new();
|
|
|
|
for line in reader.lines() {
|
|
let line = match line {
|
|
Err(error) => panic!("Could not read line: {}", error),
|
|
Ok(line) => line,
|
|
};
|
|
|
|
match line.trim() {
|
|
"---" => {
|
|
if metadata.len() != 0 && !is_metadata {
|
|
is_metadata = false;
|
|
content.push_str(&line);
|
|
} else {
|
|
is_metadata = !is_metadata;
|
|
}
|
|
}
|
|
_ => {
|
|
if is_metadata {
|
|
if let Some(metadata_entry) = line_to_metadata(line) {
|
|
metadata.insert(metadata_entry.0, metadata_entry.1);
|
|
}
|
|
} else {
|
|
content.push_str(&line);
|
|
content.push_str("\n");
|
|
}
|
|
},
|
|
}
|
|
}
|
|
|
|
Marky {
|
|
metadata,
|
|
content
|
|
}
|
|
}
|
|
}
|
|
|
|
fn line_to_metadata(line: String) -> Option<(String, String)> {
|
|
let separator_index = match line.find(":") {
|
|
None => return None,
|
|
Some(index) => index,
|
|
};
|
|
|
|
let (key, value) = line.split_at(separator_index);
|
|
|
|
return Some((String::from(key), String::from(value.trim_start_matches(":").trim())));
|
|
} |