Skip to content

Instantly share code, notes, and snippets.

@jesselawson
Last active October 22, 2019 00:01
Show Gist options
  • Save jesselawson/f2833e1aa02ed9320792291bbd2a1457 to your computer and use it in GitHub Desktop.
Save jesselawson/f2833e1aa02ed9320792291bbd2a1457 to your computer and use it in GitHub Desktop.
parse_markdown_file() function testing
use std::path::Path;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::io::Write;
fn parse_markdown_file(_filename: &str) {
print_short_banner();
println!("[ INFO ] Starting parser!");
// Create a path variable from the filename
let input_filename = Path::new(_filename);
// Try to open the file
let file = File::open(&input_filename).expect("[ ERROR ] Failed to open file!");
// Create a place to store all our tokens
let mut tokens: Vec<String> = Vec::new();
// Read the file line-by-line
let reader = BufReader::new(file);
let mut _ptag: bool = false; // keep track of paragraph enclosures
let mut _htag: bool = false;
for line in reader.lines() {
let line_contents = line.unwrap();
let mut first_char: Vec<char> = line_contents.chars().take(1).collect();
// Now check the first character to for headings
let mut s = String::new();
let slice = &line_contents.to_string();
match first_char.pop() {
Some('#') => {
if _ptag {
_ptag = false;
s.push_str("</p>\n"); // adding \n for instructional clarity
}
if _htag {
_htag = false;
s.push_str("</h1>\n"); // close it if we're already open
}
_htag = true;
s.push_str("<h1>");
s.push_str(&slice[2..]); // Get all but the first two characters
},
_ => {
if _htag {
_htag = false;
s.push_str("</h1>\n");
}
if !_ptag {
_ptag = true;
s.push_str("<p>");
}
s.push_str(&slice);
}
};
// At the very end, check if any of the tag bools are still open. If so,
// close them.
if _htag {
htag = false;
s.push_str("</h1>\n");
}
if _ptag {
_ptag = false;
s.push_str("</p>\n");
}
// Don't push blank lines
if s != "<p></p>\n" {
tokens.push(s);
}
}
// To test if our markdown parser works, let's just output the raw html to the console window
for t in &tokens {
println!("{}", t);
}
}
fn get_title() -> String {
let mut the_title = String::from(env!("CARGO_PKG_NAME"));
the_title.push_str(" (v");
the_title.push_str(env!("CARGO_PKG_VERSION"));
the_title.push_str("), ");
the_title.push_str(env!("CARGO_PKG_DESCRIPTION"));
return the_title;
}
fn print_short_banner() {
println!("{}", get_title());
}
fn print_long_banner() {
print_short_banner();
println!("Written by: {}\nHomepage: {}\nUsage: tinymd <somefile>.md\n",
env!("CARGO_PKG_AUTHORS"),
env!("CARGO_PKG_HOMEPAGE")
);
}
fn usage() {
print_long_banner();
}
fn main() {
let args: Vec<String> = std::env::args().collect();
match args.len() {
2 => parse_markdown_file(&args[1]),
_ => {
println!("[ ERROR ] No input file specified!");
usage();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment