Skip to content

Commit 480ddb5

Browse files
committed
Handle empty directory or template_name as cwd
Django converts empty relative paths to the current working directory via `os.path.abspath`, so we need to match this behaviour in Rust.
1 parent 13772fb commit 480ddb5

File tree

1 file changed

+26
-8
lines changed

1 file changed

+26
-8
lines changed

src/loaders.rs

+26-8
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,16 @@ pub struct LoaderError {
1313
pub tried: Vec<(String, String)>,
1414
}
1515

16+
fn absolute(path: &Path) -> Option<PathBuf> {
17+
match path.as_os_str().is_empty() {
18+
false => std::path::absolute(path).ok(),
19+
true => std::env::current_dir().ok(),
20+
}
21+
}
22+
1623
fn safe_join(directory: &Path, template_name: &str) -> Option<PathBuf> {
17-
let final_path = match std::path::absolute(directory.join(template_name)) {
18-
Ok(path) => path.normalize(),
19-
Err(_) => return None,
20-
};
21-
let directory = match std::path::absolute(directory) {
22-
Ok(directory) => directory,
23-
Err(_) => return None,
24-
};
24+
let final_path = absolute(&directory.join(template_name))?.normalize();
25+
let directory = absolute(directory)?;
2526
if final_path.starts_with(directory) {
2627
Some(final_path)
2728
} else {
@@ -307,4 +308,21 @@ mod tests {
307308
let joined = safe_join(&path, "/../directory");
308309
assert_eq!(joined, None);
309310
}
311+
312+
#[test]
313+
fn test_safe_join_empty_path() {
314+
let path = PathBuf::from("");
315+
let joined = safe_join(&path, "directory").unwrap();
316+
let mut expected = std::env::current_dir().unwrap();
317+
expected.push("directory");
318+
assert_eq!(joined, expected);
319+
}
320+
321+
#[test]
322+
fn test_safe_join_empty_path_and_template_name() {
323+
let path = PathBuf::from("");
324+
let joined = safe_join(&path, "").unwrap();
325+
let expected = std::env::current_dir().unwrap();
326+
assert_eq!(joined, expected);
327+
}
310328
}

0 commit comments

Comments
 (0)