summaryrefslogtreecommitdiff
path: root/cli/fs_util.rs
diff options
context:
space:
mode:
Diffstat (limited to 'cli/fs_util.rs')
-rw-r--r--cli/fs_util.rs62
1 files changed, 62 insertions, 0 deletions
diff --git a/cli/fs_util.rs b/cli/fs_util.rs
index 54bb8f3c6..20b20cccd 100644
--- a/cli/fs_util.rs
+++ b/cli/fs_util.rs
@@ -350,6 +350,37 @@ pub fn specifier_to_file_path(
}
}
+/// Ensures a specifier that will definitely be a directory has a trailing slash.
+pub fn ensure_directory_specifier(
+ mut specifier: ModuleSpecifier,
+) -> ModuleSpecifier {
+ let path = specifier.path();
+ if !path.ends_with('/') {
+ let new_path = format!("{}/", path);
+ specifier.set_path(&new_path);
+ }
+ specifier
+}
+
+/// Gets the parent of this module specifier.
+pub fn specifier_parent(specifier: &ModuleSpecifier) -> ModuleSpecifier {
+ let mut specifier = specifier.clone();
+ // don't use specifier.segments() because it will strip the leading slash
+ let mut segments = specifier.path().split('/').collect::<Vec<_>>();
+ if segments.iter().all(|s| s.is_empty()) {
+ return specifier;
+ }
+ if let Some(last) = segments.last() {
+ if last.is_empty() {
+ segments.pop();
+ }
+ segments.pop();
+ let new_path = format!("{}/", segments.join("/"));
+ specifier.set_path(&new_path);
+ }
+ specifier
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -688,4 +719,35 @@ mod tests {
assert_eq!(result, PathBuf::from(expected_path));
}
}
+
+ #[test]
+ fn test_ensure_directory_specifier() {
+ run_test("file:///", "file:///");
+ run_test("file:///test", "file:///test/");
+ run_test("file:///test/", "file:///test/");
+ run_test("file:///test/other", "file:///test/other/");
+ run_test("file:///test/other/", "file:///test/other/");
+
+ fn run_test(specifier: &str, expected: &str) {
+ let result =
+ ensure_directory_specifier(ModuleSpecifier::parse(specifier).unwrap());
+ assert_eq!(result.to_string(), expected);
+ }
+ }
+
+ #[test]
+ fn test_specifier_parent() {
+ run_test("file:///", "file:///");
+ run_test("file:///test", "file:///");
+ run_test("file:///test/", "file:///");
+ run_test("file:///test/other", "file:///test/");
+ run_test("file:///test/other.txt", "file:///test/");
+ run_test("file:///test/other/", "file:///test/");
+
+ fn run_test(specifier: &str, expected: &str) {
+ let result =
+ specifier_parent(&ModuleSpecifier::parse(specifier).unwrap());
+ assert_eq!(result.to_string(), expected);
+ }
+ }
}