From cdaf9a626589825edb857362457088e39fd1984e Mon Sep 17 00:00:00 2001 From: letmutex <155220925+letmutex@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:12:25 +0800 Subject: [PATCH] Support .xhtml and .xhtm files --- src/io_util.rs | 124 +++++++++++++++++++++++++++---------------------- src/main.rs | 2 +- tests/mod.rs | 119 +++++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 180 insertions(+), 65 deletions(-) diff --git a/src/io_util.rs b/src/io_util.rs index 604e768..833acaa 100644 --- a/src/io_util.rs +++ b/src/io_util.rs @@ -1,7 +1,7 @@ use std::{ fs, io::{self, Read}, - path::PathBuf, + path::{Path, PathBuf}, process::exit, }; @@ -38,12 +38,13 @@ pub(crate) fn resolve_input(matches: &ArgMatches) -> Input { return Some(read_stdin()); } - let files = get_html_files_from_input(&input_arg); - - if files.is_empty() { - eprintln!("File or directory does not exists: {}", input_arg); - exit(1); - } + let files = match get_html_files_from_input(&input_arg) { + Ok(files) => files, + Err(e) => { + eprintln!("{}", e); + exit(1); + } + }; Some(Input::Fs(files)) }; @@ -69,66 +70,79 @@ pub(crate) fn resolve_output(matches: &ArgMatches) -> Output { Output::Fs(PathBuf::from(output)) } -fn get_html_files_from_input(pattern: &str) -> Vec { - if pattern == "." || pattern == "./" { - // Fast path for the current dir - return read_dir_html_files(&std::env::current_dir().unwrap()); +fn is_glob_pattern(pattern: &str) -> bool { + pattern.contains('*') || pattern.contains('?') || pattern.contains('[') +} + +fn get_html_files_from_input(input: &str) -> Result, String> { + let path = if input == "." || input == "./" { + std::env::current_dir().unwrap_or_else(|_| PathBuf::from(input)) + } else { + PathBuf::from(input) + }; + + // 1. Literal file: trust explicit file inputs directly + if path.is_file() { + return Ok(vec![path]); } - // Parse input as glob - let mut files: Vec = Vec::new(); - for entry in glob(pattern).expect("Failed to read input") { - match entry { - Ok(path) => { - let Some(ext) = path.extension() else { - continue; - }; - let Some(etx) = ext.to_str() else { - continue; - }; - let ext = etx.to_lowercase(); - if ext == "html" || ext == "htm" { - files.push(path); + + // 2. Literal directory: scan for all HTML/XHTML files + if path.is_dir() { + let files = read_dir_html_files(&path) + .map_err(|e| format!("Cannot read directory '{}': {}", input, e))?; + if files.is_empty() { + return Err(format!("No HTML files found in directory: {}", input)); + } + return Ok(files); + } + + // 3. Glob pattern + if is_glob_pattern(input) { + let mut files: Vec = Vec::new(); + let entries = glob(input).map_err(|e| format!("Invalid glob pattern '{}': {}", input, e))?; + for entry in entries { + match entry { + Ok(p) => { + if possible_html_file(&p) { + files.push(p); + } } + Err(e) => eprintln!("Error while matching file: {}", e), } - Err(e) => eprintln!("Error while matching file: {}", e), } + if files.is_empty() { + return Err(format!("No matching HTML files found for pattern: {}", input)); + } + files.sort(); + return Ok(files); } - if !files.is_empty() { - return files; - } - // Treat the input as a file or a directory - let file = PathBuf::from(pattern); - if !file.exists() { - eprintln!("File or directory does not exist: {:?}", file); - exit(1); - } - if file.is_dir() { - read_dir_html_files(&file) - } else { - vec![file] - } + + Err(format!("File or directory does not exist: {}", input)) } -fn read_dir_html_files(dir: &PathBuf) -> Vec { +fn read_dir_html_files(dir: &Path) -> io::Result> { let mut files: Vec = Vec::new(); - for entry in fs::read_dir(dir).unwrap() { - if let Ok(entry) = entry { - let child = entry.path(); - if possible_html_file(&child) { - files.push(child); - } + for entry in fs::read_dir(dir)? { + let entry = entry?; + let child = entry.path(); + if possible_html_file(&child) { + files.push(child); } } - files + files.sort(); + Ok(files) } -fn possible_html_file(path: &PathBuf) -> bool { - let Some(ext) = path.extension() else { - return false; - }; - let Some(ext) = ext.to_str() else { +fn possible_html_file(path: &Path) -> bool { + path.is_file() && is_html_extension(path) +} + +fn is_html_extension(path: &Path) -> bool { + let Some(ext) = path.extension().and_then(|e| e.to_str()) else { return false; }; - let ext = ext.to_lowercase(); - ext == "html" || ext == "htm" + matches!( + ext.to_ascii_lowercase().as_str(), + "html" | "htm" | "xhtml" | "xhtm" + ) } diff --git a/src/main.rs b/src/main.rs index 29bb05e..73b4731 100644 --- a/src/main.rs +++ b/src/main.rs @@ -97,7 +97,7 @@ fn convert_files( exit(0); } else if len == 1 { let file = &files[0]; - let output_as_dir = !output.extension().is_some(); + let output_as_dir = output.is_dir() || output.extension().is_none(); let base_dir = &file.parent().unwrap().to_path_buf(); convert_file( file, diff --git a/tests/mod.rs b/tests/mod.rs index c8950d1..7b394be 100644 --- a/tests/mod.rs +++ b/tests/mod.rs @@ -204,14 +204,94 @@ mod tests { assert_eq!(result.stdout.trim(), ""); } + #[test] + fn glob_in_xhtml_files() { + let result = exec_with_temp_fs_and_setup( + |dir| { + fs::write(dir.join("page1.xhtml"), "

Page 1

").unwrap(); + fs::write(dir.join("page2.xhtml"), "

Page 2

").unwrap(); + }, + vec!["--ignored-tags", "title,style", "-i", "*.xhtml", "-o", "./"], + |dir| { + assert!(dir.join("page1.md").exists()); + assert!(dir.join("page2.md").exists()); + assert_eq!( + "# Page 1", + fs::read_to_string(dir.join("page1.md")).unwrap().trim() + ); + assert_eq!( + "## Page 2", + fs::read_to_string(dir.join("page2.md")).unwrap().trim() + ); + }, + ); + assert_eq!(result.exit_code, 0); + } + + #[test] + fn single_xhtml_file_in_folder_out() { + let result = exec_with_temp_fs_and_setup( + |dir| { + fs::write(dir.join("single.xhtml"), "

Single XHTML

").unwrap(); + }, + vec!["single.xhtml", "--output", "./"], + |dir| { + assert!(dir.join("single.md").exists()); + assert_eq!( + "# Single XHTML", + fs::read_to_string(dir.join("single.md")).unwrap().trim() + ); + }, + ); + assert_eq!(result.exit_code, 0); + } + + #[test] + fn folder_in_with_xhtml_files() { + let result = exec_with_temp_fs_and_setup( + |dir| { + let xhtml_dir = dir.join("xhtml-folder"); + fs::create_dir_all(&xhtml_dir).unwrap(); + fs::write(xhtml_dir.join("doc.xhtml"), "

Doc

").unwrap(); + }, + vec!["-i", "./xhtml-folder", "--output", "./output"], + |dir| { + assert!(dir.join("output").join("doc.md").exists()); + }, + ); + assert_eq!(result.exit_code, 0); + } + + #[test] + fn glob_no_matches_error() { + let result = exec_with_temp_fs(vec!["-i", "*.xhtml", "--output", "./"], |_| {}); + assert_eq!(result.exit_code, 1); + assert!(result + .stderr + .contains("No matching HTML files found for pattern: *.xhtml")); + } + + #[test] + fn empty_dir_error() { + let result = exec_with_temp_fs_and_setup( + |dir| { + fs::create_dir_all(dir.join("empty-folder")).unwrap(); + }, + vec!["-i", "./empty-folder", "--output", "./"], + |_| {}, + ); + assert_eq!(result.exit_code, 1); + assert!(result + .stderr + .contains("No HTML files found in directory: ./empty-folder")); + } + fn exec(args: Vec<&str>) -> ExecResult { exec_with_input(None, args) } fn exec_with_input(input_text: Option<&str>, args: Vec<&str>) -> ExecResult { - let mut child = Command::new("cargo") - .arg("run") - .arg("--") + let mut child = Command::new(env!("CARGO_BIN_EXE_htmd")) .args(args) .stdin(Stdio::piped()) .stdout(Stdio::piped()) @@ -225,6 +305,8 @@ mod tests { .write_all(input_text.as_bytes()) .expect("Failed to write to stdin"); } + } else { + drop(child.stdin.take()); } let output = child.wait_with_output().expect("Failed to read stdout"); @@ -236,14 +318,31 @@ mod tests { } } - fn exec_with_temp_fs(args: Vec<&str>, verify: impl FnOnce(PathBuf) -> ()) -> ExecResult { - exec_with_temp_fs_and_input(None, args, verify) + fn exec_with_temp_fs(args: Vec<&str>, verify: impl FnOnce(PathBuf)) -> ExecResult { + exec_with_temp_fs_and_setup(|_| {}, args, verify) + } + + fn exec_with_temp_fs_and_setup( + setup: impl FnOnce(&Path), + args: Vec<&str>, + verify: impl FnOnce(PathBuf), + ) -> ExecResult { + exec_with_temp_fs_and_input_and_setup(None, setup, args, verify) } fn exec_with_temp_fs_and_input( input_text: Option<&str>, args: Vec<&str>, - verify: impl FnOnce(PathBuf) -> (), + verify: impl FnOnce(PathBuf), + ) -> ExecResult { + exec_with_temp_fs_and_input_and_setup(input_text, |_| {}, args, verify) + } + + fn exec_with_temp_fs_and_input_and_setup( + input_text: Option<&str>, + setup: impl FnOnce(&Path), + args: Vec<&str>, + verify: impl FnOnce(PathBuf), ) -> ExecResult { let tests_dir = env::current_dir().unwrap().join("tests"); let html_dir = tests_dir.join("html"); @@ -259,9 +358,9 @@ mod tests { ) .unwrap(); - let mut child = Command::new("cargo") - .arg("run") - .arg("--") + setup(&temp_dir); + + let mut child = Command::new(env!("CARGO_BIN_EXE_htmd")) .args(args) .current_dir(&temp_dir) .stdin(Stdio::piped()) @@ -276,6 +375,8 @@ mod tests { .write_all(input_text.as_bytes()) .expect("Failed to write to stdin"); } + } else { + drop(child.stdin.take()); } let output = child.wait_with_output().expect("Failed to read stdout");