File size: 7,114 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use std::{
    borrow::Cow,
    io::{self, ErrorKind},
    path::Path,
};

use anyhow::{Context, Result, anyhow};
use turbo_tasks::Vc;

use crate::{DiskFileSystem, FileSystemPath};

/// Joins two /-separated paths into a normalized path.
/// Paths are concatenated with /.
///
/// see also [normalize_path] for normalization.
pub fn join_path(fs_path: &str, join: &str) -> Option<String> {
    // Paths that we join are written as source code (eg, `join_path(fs_path,
    // "foo/bar.js")`) and it's expected that they will never contain a
    // backslash.
    debug_assert!(
        !join.contains('\\'),
        "joined path {join} must not contain a Windows directory '\\', it must be normalized to \
         Unix '/'"
    );

    // TODO: figure out why this freezes the benchmarks.
    // // an absolute path would leave the file system root
    // if Path::new(join).is_absolute() {
    //     return None;
    // }

    if fs_path.is_empty() {
        normalize_path(join)
    } else if join.is_empty() {
        normalize_path(fs_path)
    } else {
        normalize_path(&[fs_path, "/", join].concat())
    }
}

/// Converts System paths into Unix paths. This is a noop on Unix systems, and
/// replaces backslash directory separators with forward slashes on Windows.
#[inline]
pub fn sys_to_unix(path: &str) -> Cow<'_, str> {
    #[cfg(not(target_family = "windows"))]
    {
        Cow::from(path)
    }
    #[cfg(target_family = "windows")]
    {
        Cow::Owned(path.replace(std::path::MAIN_SEPARATOR_STR, "/"))
    }
}

/// Converts Unix paths into System paths. This is a noop on Unix systems, and
/// replaces forward slash directory separators with backslashes on Windows.
#[inline]
pub fn unix_to_sys(path: &str) -> Cow<'_, str> {
    #[cfg(not(target_family = "windows"))]
    {
        Cow::from(path)
    }
    #[cfg(target_family = "windows")]
    {
        Cow::Owned(path.replace('/', std::path::MAIN_SEPARATOR_STR))
    }
}

/// Normalizes a /-separated path into a form that contains no leading /, no
/// double /, no "." segment, no ".." segment.
///
/// Returns None if the path would need to start with ".." to be equal.
pub fn normalize_path(str: &str) -> Option<String> {
    let mut segments = Vec::new();
    for segment in str.split('/') {
        match segment {
            "." | "" => {}
            ".." => {
                segments.pop()?;
            }
            segment => {
                segments.push(segment);
            }
        }
    }
    Some(segments.join("/"))
}

/// Normalizes a /-separated request into a form that contains no leading /, no
/// double /, and no "." or ".." segments in the middle of the request.
///
/// A request might only start with a single "." segment and no ".." segments, or
/// any positive number of ".." segments but no "." segment.
pub fn normalize_request(str: &str) -> String {
    let mut segments = vec!["."];
    // Keeps track of our directory depth so that we can pop directories when
    // encountering a "..". If this is positive, then we're inside a directory
    // and we can pop that. If it's 0, then we can't pop the directory and we must
    // keep the ".." in our segments. This is not the same as the segments.len(),
    // because we cannot pop a kept ".." when encountering another "..".
    let mut depth = 0;
    let mut popped_dot = false;
    for segment in str.split('/') {
        match segment {
            "." => {}
            ".." => {
                if depth > 0 {
                    depth -= 1;
                    segments.pop();
                } else {
                    // The first time we push a "..", we need to remove the "." we include by
                    // default.
                    if !popped_dot {
                        popped_dot = true;
                        segments.pop();
                    }
                    segments.push(segment);
                }
            }
            segment => {
                segments.push(segment);
                depth += 1;
            }
        }
    }
    segments.join("/")
}

/// Converts a disk access Result<T> into a Result<Some<T>>, where a NotFound
/// error results in a None value. This is purely to reduce boilerplate code
/// comparing NotFound errors against all other errors.
pub fn extract_disk_access<T>(value: io::Result<T>, path: &Path) -> Result<Option<T>> {
    match value {
        Ok(v) => Ok(Some(v)),
        Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::InvalidFilename) => Ok(None),
        Err(e) => Err(anyhow!(e).context(format!("reading file {}", path.display()))),
    }
}

#[cfg(not(target_os = "windows"))]
pub async fn uri_from_file(root: FileSystemPath, path: Option<&str>) -> Result<String> {
    let root_fs = root.fs();
    let root_fs = &*Vc::try_resolve_downcast_type::<DiskFileSystem>(root_fs)
        .await?
        .context("Expected root to have a DiskFileSystem")?
        .await?;

    Ok(format!(
        "file://{}",
        &sys_to_unix(
            &root_fs
                .to_sys_path(match path {
                    Some(path) => root.join(path)?,
                    None => root,
                })
                .await?
                .to_string_lossy()
        )
        .split('/')
        .map(|s| urlencoding::encode(s))
        .collect::<Vec<_>>()
        .join("/")
    ))
}

#[cfg(target_os = "windows")]
pub async fn uri_from_file(root: FileSystemPath, path: Option<&str>) -> Result<String> {
    let root_fs = root.fs();
    let root_fs = &*Vc::try_resolve_downcast_type::<DiskFileSystem>(root_fs)
        .await?
        .context("Expected root to have a DiskFileSystem")?
        .await?;

    let sys_path = root_fs
        .to_sys_path(match path {
            Some(path) => root.join(path.into())?,
            None => root,
        })
        .await?;

    let raw_path = sys_path.to_string_lossy().to_string();
    let normalized_path = raw_path.replace('\\', "/");

    let mut segments = normalized_path.split('/');

    let first = segments.next().unwrap_or_default(); // e.g., "C:"
    let encoded_path = std::iter::once(first.to_string()) // keep "C:" intact
        .chain(segments.map(|s| urlencoding::encode(s).into_owned()))
        .collect::<Vec<_>>()
        .join("/");

    let uri = format!("file:///{}", encoded_path);

    Ok(uri)
}

#[cfg(test)]
mod tests {

    use rstest::*;

    use crate::util::normalize_path;

    #[rstest]
    #[case("file.js")]
    #[case("a/b/c/d/e/file.js")]
    fn test_normalize_path_no_op(#[case] path: &str) {
        assert_eq!(path, normalize_path(path).unwrap());
    }

    #[rstest]
    #[case("/file.js", "file.js")]
    #[case("./file.js", "file.js")]
    #[case("././file.js", "file.js")]
    #[case("a/../c/../file.js", "file.js")]
    fn test_normalize_path(#[case] path: &str, #[case] normalized: &str) {
        assert_eq!(normalized, normalize_path(path).unwrap());
    }

    #[rstest]
    #[case("../file.js")]
    #[case("a/../../file.js")]
    fn test_normalize_path_invalid(#[case] path: &str) {
        assert_eq!(None, normalize_path(path));
    }
}