#![allow(clippy::unused_io_amount)]
use std::{
env::{consts::OS, current_dir},
io::Result,
net::TcpListener,
process::{exit, Command},
thread::spawn,
};
pub mod client;
pub mod consts;
pub mod process_text;
use crate::{
client::handle_client,
consts::{EMPTY, LOCALHOST, URL},
process_text::{process_directory, Html},
};
pub fn main() -> Result<()> {
let mut html: Html = Html::new();
if let Ok(current_dir) = current_dir() {
if let Some(dir_name) = current_dir.file_name() {
let dir_name_str = dir_name.to_string_lossy();
let title = dir_name_str.to_string();
html.add_title(title);
} else {
eprintln!("Error: Getting the dir");
std::process::exit(1);
}
} else {
eprintln!("Error: Its not a dir");
std::process::exit(1);
}
let modifications: String = process_directory().content;
if modifications.is_empty() {
html.content.push_str(EMPTY);
} else {
html.content.push_str(&modifications);
}
let open_a_window_in_your_browser = match OS {
"linux" | "macos" => "xdg-open",
"windows" => "start",
_ => {
eprintln!("OS incompatible");
exit(1);
}
};
Command::new(open_a_window_in_your_browser)
.arg(URL)
.output()?;
let listener = TcpListener::bind(LOCALHOST)?;
for stream in listener.incoming() {
match stream {
Ok(stream) => {
let html = html.clone();
spawn(move || {
handle_client(stream, html.content).expect("Error with the local client");
exit(1);
});
}
Err(e) => eprintln!("Error: {}", e),
}
}
Ok(())
}