Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 69 additions & 55 deletions src/io_util.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{
fs,
io::{self, Read},
path::PathBuf,
path::{Path, PathBuf},
process::exit,
};

Expand Down Expand Up @@ -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))
};
Expand All @@ -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<PathBuf> {
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<Vec<PathBuf>, 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<PathBuf> = 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<PathBuf> = 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<PathBuf> {
fn read_dir_html_files(dir: &Path) -> io::Result<Vec<PathBuf>> {
let mut files: Vec<PathBuf> = 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"
)
}
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
119 changes: 110 additions & 9 deletions tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,14 +204,94 @@ mod tests {
assert_eq!(result.stdout.trim(), "<https://example.com>");
}

#[test]
fn glob_in_xhtml_files() {
let result = exec_with_temp_fs_and_setup(
|dir| {
fs::write(dir.join("page1.xhtml"), "<h1>Page 1</h1>").unwrap();
fs::write(dir.join("page2.xhtml"), "<h2>Page 2</h2>").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"), "<h1>Single XHTML</h1>").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"), "<p>Doc</p>").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())
Expand All @@ -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");
Expand All @@ -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");
Expand All @@ -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())
Expand All @@ -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");
Expand Down
Loading