1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- #[macro_use]
- extern crate lazy_static;
- extern crate regex;
-
- use std::env;
- use std::fs;
- use std::path;
-
- use regex::Regex;
-
- #[derive(Debug)]
- struct Post {
- title: String,
- body: String,
- slug: String,
- }
-
- fn parse_post(path: path::PathBuf) -> Post {
- let contents = fs::read_to_string(&path).expect("Couldn't read post file");
-
- lazy_static! {
- static ref re: Regex = Regex::new(r"^# (?P<title>.*)\n\n(?P<body>.*)").unwrap();
- static ref slug_re: Regex = Regex::new(r"(?P<slug>\S+).md").unwrap();
- }
-
- let title = &re.captures(&contents).expect("Couldn't parse title")["title"];
-
- let body = &re.captures(&contents).expect("Couldn't parse body")["body"];
-
- let filename = &path.file_name().unwrap().to_str().unwrap();
- let slug = &slug_re.captures(filename).expect("Couldn't parse slug")["slug"];
- Post {
- title: String::from(title),
- body: String::from(body),
- slug: String::from(slug),
- }
- }
-
- fn read_posts_dir() -> fs::ReadDir {
- let cwd = env::current_dir()
- .expect("Couldn't read current directory")
- .join("posts");
- match fs::read_dir(cwd) {
- Ok(posts) => posts,
- Err(err) => panic!(err),
- }
- }
-
- fn main() {
- let post_paths = read_posts_dir();
- for path in post_paths {
- match path {
- Ok(p) => {
- let post = parse_post(p.path());
- },
- Err(err) => panic!(err),
- }
- }
- }
|