Here's the refactored and improved code, incorporating the requested functionality:
main.rs:
#![allow(warnings)]
use base64::encode;
use std::fs::File;
use std::io::{self, Read, Write};
use std::path::PathBuf;
use clap::Parser;
use pulldown_cmark::{html, Event, Options, Parser as MdParser};
use tokio::sync::{broadcast, RwLock};
use warp::Filter;
use std::sync::Arc;
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
#[arg(value_name = "FILE")]
file: Option<PathBuf>,
#[arg(short, long)]
static_mode: bool,
}
#[tokio::main]
async fn main() -> io::Result<()> {
// Parse command-line arguments
let args = Args::parse();
if args.static_mode {
run_static_mode(&args)?;
} else {
run_server_mode(&args).await?;
}
Ok(())
}
fn run_static_mode(args: &Args) -> io::Result<()> {
// Read Markdown content
let (file_name, markdown_input) = match &args.file {
Some(file_path) => {
let mut file = File::open(&file_path).unwrap_or_else(|err| {
eprintln!("Error opening file {}: {}", file_path.display(), err);
std::process::exit(1);
});
let mut content = String::new();
file.read_to_string(&mut content)?;
(
file_path.file_name().unwrap().to_string_lossy().to_string(),
content,
)
}
None => {
// Read from stdin if no file is provided
let mut content = String::new();
io::stdin().read_to_string(&mut content)?;
(String::from("New file"), content)
}
};
let html_output = render_markdown_to_html(&markdown_input);
let style = read_style_css();
let fonts = read_fonts();
let html_content = build_full_html(&file_name, &html_output, &style, &fonts, false);
// Create a temporary file with .html extension
let temp_file = tempfile::Builder::new()
.prefix("markdown_preview_")
.suffix(".html")
.rand_bytes(5)
.tempfile()?;
let temp_path = temp_file.path().to_string_lossy().to_string();
// Write HTML content to the temporary file
let mut file = temp_file.as_file();
file.write_all(html_content.as_bytes())?;
file.flush()?;
// Open the default browser
#[cfg(target_os = "macos")]
{
std::process::Command::new("open")
.arg(&temp_path)
.spawn()
.expect("Failed to open browser");
}
#[cfg(target_os = "windows")]
{
std::process::Command::new("cmd")
.args(&["/C", "start", &temp_path])
.spawn()
.expect("Failed to open browser");
}
#[cfg(target_os = "linux")]
{
std::process::Command::new("xdg-open")
.arg(&temp_path)
.spawn()
.expect("Failed to open browser");
}
// Keep the program running to prevent the temporary file from being deleted
println!("Press Enter to exit...");
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(())
}
async fn run_server_mode(args: &Args) -> io::Result<()> {
let file_path = match &args.file {
Some(path) => path.clone(),
None => {
eprintln!("Error: No input file specified in server mode.");
std::process::exit(1);
}
};
let file_name = file_path
.file_name()
.unwrap()
.to_string_lossy()
.to_string();
let markdown_input = read_markdown_input(&file_path)?;
let html_output = render_markdown_to_html(&markdown_input);
let style = read_style_css();
let fonts = read_fonts();
let (tx, _rx) = broadcast::channel::<()>(100);
let app_state = Arc::new(AppState {
html_content: Arc::new(RwLock::new(html_output)),
css_content: style,
fonts,
file_path: file_path.clone(),
notifier: tx.clone(),
file_name,
});
// Start the file watcher task
let app_state_clone = app_state.clone();
tokio::task::spawn_blocking(move || {
if let Err(e) = watch_markdown_file(app_state_clone) {
eprintln!("Error in file watcher: {:?}", e);
}
});
// Set up the routes
let state_filter = warp::any().map(move || app_state.clone());
let html_route = warp::path::end()
.and(state_filter.clone())
.and_then(serve_html);
let sse_route = warp::path("events")
.and(warp::sse())
.and(state_filter.clone())
.and_then(sse_handler);
// Start the server
println!("Server running at http://localhost:3030/");
if let Err(e) = warp::serve(html_route.or(sse_route))
.run(([127, 0, 0, 1], 3030))
.await
{
eprintln!("Server error: {:?}", e);
}
Ok(())
}
fn read_markdown_input(file_path: &PathBuf) -> io::Result<String> {
let mut file = File::open(&file_path)?;
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
}
fn render_markdown_to_html(markdown_input: &str) -> String {
let mut options = Options::empty();
options.insert(Options::ENABLE_STRIKETHROUGH);
options.insert(Options::ENABLE_TABLES);
options.insert(Options::ENABLE_FOOTNOTES);
options.insert(Options::ENABLE_TASKLISTS);
options.insert(Options::ENABLE_SMART_PUNCTUATION);
let parser = MdParser::new_ext(&markdown_input, options);
let mut html_output = String::new();
html::push_html(
&mut html_output,
parser.map(|event| match event {
Event::SoftBreak => Event::Html("<br>".into()),
_ => event,
}),
);
html_output
}
fn read_style_css() -> String {
let default_css = r#"
body { font-family: Arial, sans-serif; line-height: 1.6; padding: 20px; max-width: 800px; margin: 0 auto; }
pre { background-color: #f4f4f4; padding: 10px; border-radius: 5px; }
code { background-color: #f4f4f4; padding: 2px 4px; border-radius: 3px; }
"#
.to_string();
let mut contents = String::new();
// Try to open and read the file
if let Ok(mut file) = File::open("./src/style.css") {
if let Err(_) = file.read_to_string(&mut contents) {
// If reading the file fails, use default CSS
contents = default_css;
}
} else {
// If opening the file fails, use default CSS
contents = default_css;
}
contents
}
struct Fonts {
font_regular: String,
font_medium: String,
font_light: String,
favicon: String,
}
fn read_fonts() -> Fonts {
Fonts {
font_regular: encode(include_bytes!("./fonts/Oswald/Oswald-Regular.ttf")),
font_medium: encode(include_bytes!("./fonts/Oswald/Oswald-Regular.ttf")),
font_light: encode(include_bytes!("./fonts/Oswald/Oswald-Light.ttf")),
favicon: encode(include_bytes!("./favicon.ico")),
}
}
struct AppState {
html_content: Arc<RwLock<String>>,
css_content: String,
fonts: Fonts,
file_path: PathBuf,
notifier: broadcast::Sender<()>,
file_name: String,
}
fn watch_markdown_file(app_state: Arc<AppState>) -> io::Result<()> {
use notify::{DebouncedEvent, RecursiveMode, Watcher};
use std::sync::mpsc::channel;
use std::time::Duration;
let (tx, rx) = channel();
let mut watcher = notify::watcher(tx, Duration::from_secs(1))?;
watcher.watch(&app_state.file_path, RecursiveMode::NonRecursive)?;
loop {
match rx.recv() {
Ok(event) => match event {
DebouncedEvent::Write(_) | DebouncedEvent::Create(_) => {
println!("File changed, reloading...");
// Re-render markdown
match read_markdown_input(&app_state.file_path) {
Ok(markdown_input) => {
let html_output = render_markdown_to_html(&markdown_input);
{
let mut html_content = app_state.html_content.blocking_write();
*html_content = html_output;
}
// Send notification
let _ = app_state.notifier.send(());
}
Err(e) => {
eprintln!("Error reading file: {:?}", e);
}
}
}
_ => {}
},
Err(e) => {
println!("Watch error: {:?}", e);
}
}
}
}
async fn serve_html(app_state: Arc<AppState>) -> Result<impl warp::Reply, warp::Rejection> {
let html_content = {
let html = app_state.html_content.read().await;
html.clone()
};
let full_html = build_full_html(
&app_state.file_name,
&html_content,
&app_state.css_content,
&app_state.fonts,
true,
);
Ok(warp::reply::html(full_html))
}
async fn sse_handler(
sse: warp::sse::Sse,
app_state: Arc<AppState>,
) -> Result<impl warp::Reply, warp::Rejection> {
let mut rx = app_state.notifier.subscribe();
let event_stream = async_stream::stream! {
while let Ok(_) = rx.recv().await {
yield warp::sse::Event::default().data("reload");
}
};
Ok(sse.reply(warp::sse::keep_alive().stream(event_stream)))
}
fn build_full_html(
file_name: &str,
html_output: &str,
style: &str,
fonts: &Fonts,
enable_reload: bool,
) -> String {
let reload_script = if enable_reload {
r#"
<script>
var evtSource = new EventSource("/events");
evtSource.onmessage = function(e) {
if (e.data === "reload") {
location.reload();
}
};
</script>
"#
} else {
""
};
format!(
r#"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="data:image/x-icon;base64,{}">
<style>
@font-face {{
font-family: 'Oswald';
src: url(data:font/truetype;charset=utf-8;base64,{}) format('truetype');
font-weight: 400;
font-style: normal;
}}
@font-face {{
font-family: 'Oswald';
src: url(data:font/truetype;charset=utf-8;base64,{}) format('truetype');
font-weight: 700;
font-style: normal;
}}
@font-face {{
font-family: 'Oswald';
src: url(data:font/truetype;charset=utf-8;base64,{}) format('truetype');
font-weight: 300;
font-style: normal;
}}
{}
</style>
<title>
{}
</title>
</head>
<body>
{}
{}
</body>
</html>
"#,
fonts.favicon,
fonts.font_regular,
fonts.font_medium,
fonts.font_light,
style,
file_name,
html_output,
reload_script
)
}
Cargo.toml:
[package]
name = "omd"
version = "0.1.0"
edition = "2021"
[dependencies]
pulldown-cmark = "0.9.1"
tempfile = "3.5.0"
clap = { version = "4.4.0", features = ["derive"] }
base64 = "0.22.1"
tokio = { version = "1.28.1", features = ["full"] }
notify = "5.1.0"
warp = "0.3.3"
async-stream = "0.3.4"
Explanation:
-
Refactoring and Modularity:
- The code has been refactored into smaller, reusable functions such as
read_markdown_input, render_markdown_to_html, read_style_css, read_fonts, and build_full_html to improve readability and maintainability.
-
Command-Line Argument Parsing:
- The
--static flag (-s shorthand) has been added using clap. The Args struct now includes a static_mode boolean to determine the mode of operation.
-
Static Mode (--static):
- When the
--static flag is used, the program behaves as before. It reads the Markdown file, converts it to HTML, writes it to a temporary HTML file, and opens it in the default browser.
- The
run_static_mode function encapsulates this functionality.
-
Server Mode (Live Reload):
- When not using the
--static flag, the program starts a web server that serves the converted HTML content.
- The server watches the Markdown file for changes using the
notify crate. Any changes trigger a re-rendering of the HTML content.
- The
run_server_mode function handles starting the server and file watcher.
-
Web Server Setup:
- The
warp web framework is used to set up the server and handle routes.
- The root route (
/) serves the latest HTML content.
- An
/events route is set up to handle Server-Sent Events (SSE) for live reloading.
-
Live Reloading Mechanism:
- The program uses SSE to notify connected clients (browsers) when the Markdown file changes.
- Clients connect to the
/events endpoint and listen for "reload" events.
- Upon receiving a "reload" event, the client reloads the page to display the updated content.
- This is facilitated by a small JavaScript snippet injected into the served HTML.
-
Concurrency and State Management:
- Shared application state is managed using
Arc and tokio::sync::RwLock to allow safe concurrent access across tasks and threads.
Note:
- This code assumes the presence of the font files and favicon as specified in the original code (
./fonts/Oswald/Oswald-Regular.ttf, ./fonts/Oswald/Oswald-Light.ttf, and ./favicon.ico). Ensure these files are in the correct paths or adjust the paths as needed.
- Make sure to handle any potential errors when reading files or rendering markdown to prevent the application from crashing due to unexpected inputs or missing files.
- The server runs on
http://localhost:3030/. You can change the port or IP address in the run method of warp::serve if needed.
- The code uses the
tokio runtime for asynchronous operations, which is appropriate for the asynchronous nature of web servers and file I/O in this context.
- The
async-stream crate is used to create an async stream for SSE events in a convenient way.