create source dir, output dir and template file if missing

This commit is contained in:
Crispy 2024-04-26 20:05:33 +02:00
parent c785aa3ac8
commit 8736fa8638
2 changed files with 33 additions and 3 deletions

View file

@ -1,7 +1,7 @@
use std::{ use std::{
error::Error, error::Error,
ffi::OsStr, ffi::OsStr,
fs::{read_dir, read_to_string, File}, fs::{read_dir, read_to_string, DirBuilder, File},
io::Write, io::Write,
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
@ -10,15 +10,31 @@ const SRC_DIR: &str = "write";
const OUT_DIR: &str = "site"; const OUT_DIR: &str = "site";
const CONTENT_MARKER: &str = "CONTENT HERE"; const CONTENT_MARKER: &str = "CONTENT HERE";
const TEMPLATE_FILE: &str = "template.html";
const DEFAULT_TEMPLATE: &[u8] = include_bytes!("../template.html");
type Result = core::result::Result<(), Box<dyn Error>>; type Result = core::result::Result<(), Box<dyn Error>>;
fn main() -> Result { fn main() -> Result {
if !PathBuf::from(TEMPLATE_FILE).is_file() {
File::create(TEMPLATE_FILE)?.write_all(DEFAULT_TEMPLATE)?;
println!("created {TEMPLATE_FILE}");
}
if !PathBuf::from(SRC_DIR).is_dir() {
DirBuilder::new().create(SRC_DIR)?;
println!("created {SRC_DIR}/");
}
if !PathBuf::from(OUT_DIR).is_dir() {
DirBuilder::new().create(OUT_DIR)?;
println!("created {OUT_DIR}/");
}
let src_dir = PathBuf::from(SRC_DIR); let src_dir = PathBuf::from(SRC_DIR);
build_dir(&src_dir) build_dir(&src_dir)
} }
fn build_dir(dir: &Path) -> Result { fn build_dir(dir: &Path) -> Result {
for entry in read_dir(dir).unwrap().flatten() { for entry in read_dir(dir)?.flatten() {
let ftype = entry.file_type()?; let ftype = entry.file_type()?;
if ftype.is_dir() { if ftype.is_dir() {
build_dir(&entry.path())?; build_dir(&entry.path())?;
@ -99,7 +115,7 @@ fn convert_file(path: &Path) -> Result {
} }
} }
let template = read_to_string("template.html")?; let template = read_to_string(TEMPLATE_FILE)?;
let html = template.replacen(CONTENT_MARKER, &html, 1); let html = template.replacen(CONTENT_MARKER, &html, 1);
let mut file = File::create(&out_path)?; let mut file = File::create(&out_path)?;

14
template.html Normal file
View file

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TITLE HERE</title>
</head>
<body>
CONTENT HERE
</body>
</html>