-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
path.rs
343 lines (321 loc) · 10.4 KB
/
path.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use std::borrow::Cow;
use std::path::Path;
use std::path::PathBuf;
use deno_ast::MediaType;
use deno_ast::ModuleSpecifier;
use deno_config::glob::PathGlobMatch;
use deno_config::glob::PathOrPattern;
use deno_config::glob::PathOrPatternSet;
/// Checks if the path has an extension Deno supports for script execution.
pub fn is_script_ext(path: &Path) -> bool {
if let Some(ext) = get_extension(path) {
matches!(
ext.as_str(),
"ts" | "tsx" | "js" | "jsx" | "mjs" | "mts" | "cjs" | "cts"
)
} else {
false
}
}
/// Checks if the path has an extension Deno supports for importing.
pub fn is_importable_ext(path: &Path) -> bool {
if let Some(ext) = get_extension(path) {
matches!(
ext.as_str(),
"ts" | "tsx" | "js" | "jsx" | "mjs" | "mts" | "cjs" | "cts" | "json"
)
} else {
false
}
}
/// Get the extension of a file in lowercase.
pub fn get_extension(file_path: &Path) -> Option<String> {
return file_path
.extension()
.and_then(|e| e.to_str())
.map(|e| e.to_lowercase());
}
pub fn get_atomic_dir_path(file_path: &Path) -> PathBuf {
let rand = gen_rand_path_component();
let new_file_name = format!(
".{}_{}",
file_path
.file_name()
.map(|f| f.to_string_lossy())
.unwrap_or(Cow::Borrowed("")),
rand
);
file_path.with_file_name(new_file_name)
}
pub fn get_atomic_file_path(file_path: &Path) -> PathBuf {
let rand = gen_rand_path_component();
let extension = format!("{rand}.tmp");
file_path.with_extension(extension)
}
fn gen_rand_path_component() -> String {
(0..4).fold(String::new(), |mut output, _| {
output.push_str(&format!("{:02x}", rand::random::<u8>()));
output
})
}
/// TypeScript figures out the type of file based on the extension, but we take
/// other factors into account like the file headers. The hack here is to map the
/// specifier passed to TypeScript to a new specifier with the file extension.
pub fn mapped_specifier_for_tsc(
specifier: &ModuleSpecifier,
media_type: MediaType,
) -> Option<String> {
let ext_media_type = MediaType::from_specifier(specifier);
if media_type != ext_media_type {
// we can't just add on the extension because typescript considers
// all .d.*.ts files as declaration files in TS 5.0+
if media_type != MediaType::Dts
&& media_type == MediaType::TypeScript
&& specifier
.path()
.split('/')
.last()
.map(|last| last.contains(".d."))
.unwrap_or(false)
{
let mut path_parts = specifier
.path()
.split('/')
.map(ToOwned::to_owned)
.collect::<Vec<_>>();
let last_part = path_parts.last_mut().unwrap();
*last_part = last_part.replace(".d.", "$d$");
let mut specifier = specifier.clone();
specifier.set_path(&path_parts.join("/"));
Some(format!("{}{}", specifier, media_type.as_ts_extension()))
} else {
Some(format!("{}{}", specifier, media_type.as_ts_extension()))
}
} else {
None
}
}
/// `from.make_relative(to)` but with fixes.
pub fn relative_specifier(
from: &ModuleSpecifier,
to: &ModuleSpecifier,
) -> Option<String> {
let is_dir = to.path().ends_with('/');
if is_dir && from == to {
return Some("./".to_string());
}
// workaround using parent directory until https://github.com/servo/rust-url/pull/754 is merged
let from = if !from.path().ends_with('/') {
if let Some(end_slash) = from.path().rfind('/') {
let mut new_from = from.clone();
new_from.set_path(&from.path()[..end_slash + 1]);
Cow::Owned(new_from)
} else {
Cow::Borrowed(from)
}
} else {
Cow::Borrowed(from)
};
// workaround for url crate not adding a trailing slash for a directory
// it seems to be fixed once a version greater than 2.2.2 is released
let mut text = from.make_relative(to)?;
if is_dir && !text.ends_with('/') && to.query().is_none() {
text.push('/');
}
let text = if text.starts_with("../") || text.starts_with("./") {
text
} else {
format!("./{text}")
};
Some(to_percent_decoded_str(&text))
}
#[cfg_attr(windows, allow(dead_code))]
pub fn relative_path(from: &Path, to: &Path) -> Option<PathBuf> {
pathdiff::diff_paths(to, from)
}
/// Slightly different behaviour than the default matching
/// where an exact path needs to be matched to be opted-in
/// rather than just a partial directory match.
///
/// This is used by the test and bench filtering.
pub fn matches_pattern_or_exact_path(
path_or_pattern_set: &PathOrPatternSet,
path: &Path,
) -> bool {
for p in path_or_pattern_set.inner().iter().rev() {
match p {
PathOrPattern::Path(p) => {
if p == path {
return true;
}
}
PathOrPattern::NegatedPath(p) => {
if path.starts_with(p) {
return false;
}
}
PathOrPattern::RemoteUrl(_) => {}
PathOrPattern::Pattern(p) => match p.matches_path(path) {
PathGlobMatch::Matched => return true,
PathGlobMatch::MatchedNegated => return false,
PathGlobMatch::NotMatched => {}
},
}
}
false
}
/// For decoding percent-encodeing string
/// could be used for module specifier string literal of local modules,
/// or local file path to display `non-ASCII` characters correctly
/// # Examples
/// ```
/// use crate::util::path::to_percent_decoded_str;
///
/// let str = to_percent_decoded_str("file:///Users/path/to/%F0%9F%A6%95.ts");
/// assert_eq!(str, "file:///Users/path/to/🦕.ts");
/// ```
pub fn to_percent_decoded_str(s: &str) -> String {
match percent_encoding::percent_decode_str(s).decode_utf8() {
Ok(s) => s.to_string(),
// when failed to decode, return the original string
Err(_) => s.to_string(),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_is_script_ext() {
assert!(!is_script_ext(Path::new("tests/subdir/redirects")));
assert!(!is_script_ext(Path::new("README.md")));
assert!(is_script_ext(Path::new("lib/typescript.d.ts")));
assert!(is_script_ext(Path::new("testdata/run/001_hello.js")));
assert!(is_script_ext(Path::new("testdata/run/002_hello.ts")));
assert!(is_script_ext(Path::new("foo.jsx")));
assert!(is_script_ext(Path::new("foo.tsx")));
assert!(is_script_ext(Path::new("foo.TS")));
assert!(is_script_ext(Path::new("foo.TSX")));
assert!(is_script_ext(Path::new("foo.JS")));
assert!(is_script_ext(Path::new("foo.JSX")));
assert!(is_script_ext(Path::new("foo.mjs")));
assert!(is_script_ext(Path::new("foo.mts")));
assert!(is_script_ext(Path::new("foo.cjs")));
assert!(is_script_ext(Path::new("foo.cts")));
assert!(!is_script_ext(Path::new("foo.json")));
assert!(!is_script_ext(Path::new("foo.mjsx")));
}
#[test]
fn test_is_importable_ext() {
assert!(!is_importable_ext(Path::new("tests/subdir/redirects")));
assert!(!is_importable_ext(Path::new("README.md")));
assert!(is_importable_ext(Path::new("lib/typescript.d.ts")));
assert!(is_importable_ext(Path::new("testdata/run/001_hello.js")));
assert!(is_importable_ext(Path::new("testdata/run/002_hello.ts")));
assert!(is_importable_ext(Path::new("foo.jsx")));
assert!(is_importable_ext(Path::new("foo.tsx")));
assert!(is_importable_ext(Path::new("foo.TS")));
assert!(is_importable_ext(Path::new("foo.TSX")));
assert!(is_importable_ext(Path::new("foo.JS")));
assert!(is_importable_ext(Path::new("foo.JSX")));
assert!(is_importable_ext(Path::new("foo.mjs")));
assert!(is_importable_ext(Path::new("foo.mts")));
assert!(is_importable_ext(Path::new("foo.cjs")));
assert!(is_importable_ext(Path::new("foo.cts")));
assert!(is_importable_ext(Path::new("foo.json")));
assert!(!is_importable_ext(Path::new("foo.mjsx")));
}
#[test]
fn test_relative_specifier() {
let fixtures: Vec<(&str, &str, Option<&str>)> = vec![
("file:///from", "file:///to", Some("./to")),
("file:///from", "file:///from/other", Some("./from/other")),
("file:///from", "file:///from/other/", Some("./from/other/")),
("file:///from", "file:///other/from", Some("./other/from")),
("file:///from/", "file:///other/from", Some("../other/from")),
("file:///from", "file:///other/from/", Some("./other/from/")),
(
"file:///from",
"file:///to/other.txt",
Some("./to/other.txt"),
),
(
"file:///from/test",
"file:///to/other.txt",
Some("../to/other.txt"),
),
(
"file:///from/other.txt",
"file:///to/other.txt",
Some("../to/other.txt"),
),
(
"https://deno.land/x/a/b/d.ts",
"https://deno.land/x/a/b/c.ts",
Some("./c.ts"),
),
(
"https://deno.land/x/a/b/d.ts",
"https://deno.land/x/a/c.ts",
Some("../c.ts"),
),
(
"https://deno.land/x/a/b/d.ts",
"https://deno.land/x/a/b/c/d.ts",
Some("./c/d.ts"),
),
(
"https://deno.land/x/a/b/c/",
"https://deno.land/x/a/b/c/d.ts",
Some("./d.ts"),
),
(
"https://deno.land/x/a/b/c/",
"https://deno.land/x/a/b/c/d/e.ts",
Some("./d/e.ts"),
),
(
"https://deno.land/x/a/b/c/f.ts",
"https://deno.land/x/a/b/c/d/e.ts",
Some("./d/e.ts"),
),
(
"https://deno.land/x/a/b/d.ts",
"https://deno.land/x/a/c.ts?foo=bar",
Some("../c.ts?foo=bar"),
),
(
"https://deno.land/x/a/b/d.ts?foo=bar",
"https://deno.land/x/a/b/c.ts",
Some("./c.ts"),
),
("file:///a/b/d.ts", "file:///a/b/c.ts", Some("./c.ts")),
("https://deno.land/x/a/b/c.ts", "file:///a/b/c.ts", None),
(
"https://deno.land/",
"https://deno.land/x/a/b/c.ts",
Some("./x/a/b/c.ts"),
),
(
"https://deno.land/x/d/e/f.ts",
"https://deno.land/x/a/b/c.ts",
Some("../../a/b/c.ts"),
),
];
for (from_str, to_str, expected) in fixtures {
let from = ModuleSpecifier::parse(from_str).unwrap();
let to = ModuleSpecifier::parse(to_str).unwrap();
let actual = relative_specifier(&from, &to);
assert_eq!(
actual.as_deref(),
expected,
"from: \"{from_str}\" to: \"{to_str}\""
);
}
}
#[test]
fn test_to_percent_decoded_str() {
let str = to_percent_decoded_str("%F0%9F%A6%95");
assert_eq!(str, "🦕");
}
}