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
use std::borrow::Cow;
use std::ffi::OsStr;
use std::fs::{self, File};
use std::io::Read;
#[cfg(target_family = "windows")]
use std::path::Prefix;
use std::path::{Component, Path, PathBuf};

use crate::errors::*;

pub trait ToUtf8 {
    fn to_utf8(&self) -> Result<&str>;
}

impl ToUtf8 for OsStr {
    fn to_utf8(&self) -> Result<&str> {
        self.to_str()
            .ok_or_else(|| eyre::eyre!("unable to convert `{self:?}` to UTF-8 string"))
    }
}

impl ToUtf8 for Path {
    fn to_utf8(&self) -> Result<&str> {
        self.as_os_str().to_utf8()
    }
}

pub trait PathExt {
    fn as_posix(&self) -> Result<String>;
    #[cfg(target_family = "windows")]
    fn as_wslpath(&self) -> Result<String>;
}

#[cfg(target_family = "windows")]
fn format_prefix(prefix: &str) -> Result<String> {
    match prefix {
        "" => eyre::bail!("Error: got empty windows prefix"),
        _ => Ok(format!("/mnt/{}", prefix.to_lowercase())),
    }
}

#[cfg(target_family = "windows")]
fn fmt_disk(disk: u8) -> String {
    (disk as char).to_string()
}

#[cfg(target_family = "windows")]
fn fmt_unc(server: &std::ffi::OsStr, volume: &std::ffi::OsStr) -> Result<String> {
    let server = server.to_utf8()?;
    let volume = volume.to_utf8()?;
    let bytes = volume.as_bytes();
    if server == "localhost"
        && bytes.len() == 2
        && bytes[1] == b'$'
        && matches!(bytes[0], b'A'..=b'Z' | b'a'..=b'z')
    {
        Ok(fmt_disk(bytes[0]))
    } else {
        Ok(format!("{}/{}", server, volume))
    }
}

impl PathExt for Path {
    fn as_posix(&self) -> Result<String> {
        if cfg!(target_os = "windows") {
            let push = |p: &mut String, c: &str| {
                if !p.is_empty() && p != "/" {
                    p.push('/');
                }
                p.push_str(c);
            };

            // iterate over components to join them
            let mut output = String::new();
            for component in self.components() {
                match component {
                    Component::Prefix(prefix) => {
                        eyre::bail!("unix paths cannot handle windows prefix {prefix:?}.")
                    }
                    Component::RootDir => output = "/".to_string(),
                    Component::CurDir => push(&mut output, "."),
                    Component::ParentDir => push(&mut output, ".."),
                    Component::Normal(path) => push(&mut output, path.to_utf8()?),
                }
            }
            Ok(output)
        } else {
            self.to_utf8().map(|x| x.to_string())
        }
    }

    // this is similar to as_posix, but it handles drive separators
    // and doesn't assume a relative path.
    #[cfg(target_family = "windows")]
    fn as_wslpath(&self) -> Result<String> {
        let path = canonicalize(self)?;

        let push = |p: &mut String, c: &str, r: bool| {
            if !r {
                p.push('/');
            }
            p.push_str(c);
        };
        // iterate over components to join them
        let mut output = String::new();
        let mut root_prefix = String::new();
        let mut was_root = false;
        for component in path.components() {
            match component {
                Component::Prefix(prefix) => {
                    root_prefix = match prefix.kind() {
                        Prefix::Verbatim(verbatim) => verbatim.to_utf8()?.to_string(),
                        Prefix::VerbatimUNC(server, volume) => fmt_unc(server, volume)?,
                        // we should never get this, but it's effectively just
                        // a root_prefix since we force absolute paths.
                        Prefix::VerbatimDisk(disk) => fmt_disk(disk),
                        Prefix::UNC(server, volume) => fmt_unc(server, volume)?,
                        Prefix::DeviceNS(ns) => ns.to_utf8()?.to_string(),
                        Prefix::Disk(disk) => fmt_disk(disk),
                    }
                }
                Component::RootDir => output = format!("{}/", format_prefix(&root_prefix)?),
                Component::CurDir => push(&mut output, ".", was_root),
                Component::ParentDir => push(&mut output, "..", was_root),
                Component::Normal(path) => push(&mut output, path.to_utf8()?, was_root),
            }
            was_root = component == Component::RootDir;
        }

        // remove trailing '/'
        if was_root {
            output.truncate(output.len() - 1);
        }

        Ok(output)
    }
}

pub fn read<P>(path: P) -> Result<String>
where
    P: AsRef<Path>,
{
    read_(path.as_ref())
}

fn read_(path: &Path) -> Result<String> {
    let mut s = String::new();
    File::open(path)
        .wrap_err_with(|| format!("couldn't open {path:?}"))?
        .read_to_string(&mut s)
        .wrap_err_with(|| format!("couldn't read {path:?}"))?;
    Ok(s)
}

pub fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf> {
    _canonicalize(path.as_ref())
        .wrap_err_with(|| format!("when canonicalizing path `{:?}`", path.as_ref()))
}

fn _canonicalize(path: &Path) -> Result<PathBuf> {
    #[cfg(target_os = "windows")]
    {
        // Docker does not support UNC paths, this will try to not use UNC paths
        dunce::canonicalize(&path).map_err(Into::into)
    }
    #[cfg(not(target_os = "windows"))]
    {
        Path::new(&path).canonicalize().map_err(Into::into)
    }
}

/// Pretty format a file path. Also removes the path prefix from a command if wanted
pub fn pretty_path(path: impl AsRef<Path>, strip: impl for<'a> Fn(&'a str) -> bool) -> String {
    let path = path.as_ref();
    // TODO: Use Path::file_prefix
    let file_stem = path.file_stem();
    let file_name = path.file_name();
    let path = if let (Some(file_stem), Some(file_name)) = (file_stem, file_name) {
        if let Some(file_name) = file_name.to_str() {
            if strip(file_name) {
                Cow::Borrowed(file_stem)
            } else {
                Cow::Borrowed(path.as_os_str())
            }
        } else {
            Cow::Borrowed(path.as_os_str())
        }
    } else {
        maybe_canonicalize(path)
    };

    if let Some(path) = path.to_str() {
        shell_escape(path).to_string()
    } else {
        format!("{path:?}")
    }
}

pub fn shell_escape(string: &str) -> Cow<'_, str> {
    let escape: &[char] = if cfg!(target_os = "windows") {
        &['%', '$', '`', '!', '"']
    } else {
        &['$', '\'', '\\', '!', '"']
    };

    if string.contains(escape) {
        Cow::Owned(format!("{string:?}"))
    } else if string.contains(' ') {
        Cow::Owned(format!("\"{string}\""))
    } else {
        Cow::Borrowed(string)
    }
}

pub fn maybe_canonicalize(path: &Path) -> Cow<'_, OsStr> {
    canonicalize(path)
        .map(|p| Cow::Owned(p.as_os_str().to_owned()))
        .unwrap_or_else(|_| path.as_os_str().into())
}

pub fn write_file(path: impl AsRef<Path>, overwrite: bool) -> Result<File> {
    let path = path.as_ref();
    fs::create_dir_all(
        &path
            .parent()
            .ok_or_else(|| eyre::eyre!("could not find parent directory for `{path:?}`"))?,
    )
    .wrap_err_with(|| format!("couldn't create directory `{path:?}`"))?;

    let mut open = fs::OpenOptions::new();
    open.write(true);

    if overwrite {
        open.truncate(true).create(true);
    } else {
        open.create_new(true);
    }

    open.open(&path)
        .wrap_err(format!("couldn't write to file `{path:?}`"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fmt::Debug;

    macro_rules! p {
        ($path:expr) => {
            Path::new($path)
        };
    }

    fn result_eq<T: PartialEq + Eq + Debug>(x: Result<T>, y: Result<T>) {
        match (x, y) {
            (Ok(x), Ok(y)) => assert_eq!(x, y),
            (x, y) => panic!("assertion failed: `(left == right)`\nleft: {x:?}\nright: {y:?}"),
        }
    }

    #[test]
    fn as_posix() {
        result_eq(p!(".").join("..").as_posix(), Ok("./..".to_string()));
        result_eq(p!(".").join("/").as_posix(), Ok("/".to_string()));
        result_eq(p!("foo").join("bar").as_posix(), Ok("foo/bar".to_string()));
        result_eq(
            p!("/foo").join("bar").as_posix(),
            Ok("/foo/bar".to_string()),
        );
    }

    #[test]
    #[cfg(target_family = "windows")]
    fn as_posix_prefix() {
        assert_eq!(p!("C:").join(".."), p!("C:.."));
        assert!(p!("C:").join("..").as_posix().is_err());
    }

    #[test]
    #[cfg(target_family = "windows")]
    fn as_wslpath() {
        result_eq(p!(r"C:\").as_wslpath(), Ok("/mnt/c".to_string()));
        result_eq(p!(r"C:\Users").as_wslpath(), Ok("/mnt/c/Users".to_string()));
        result_eq(
            p!(r"\\localhost\c$\Users").as_wslpath(),
            Ok("/mnt/c/Users".to_string()),
        );
        result_eq(p!(r"\\.\C:\").as_wslpath(), Ok("/mnt/c".to_string()));
        result_eq(
            p!(r"\\.\C:\Users").as_wslpath(),
            Ok("/mnt/c/Users".to_string()),
        );
    }

    #[test]
    #[cfg(target_family = "windows")]
    fn pretty_path_windows() {
        assert_eq!(
            pretty_path("C:\\path\\bin\\cargo.exe", |f| f.contains("cargo")),
            "cargo".to_string()
        );
        assert_eq!(
            pretty_path("C:\\Program Files\\Docker\\bin\\docker.exe", |_| false),
            "\"C:\\Program Files\\Docker\\bin\\docker.exe\"".to_string()
        );
        assert_eq!(
            pretty_path("C:\\Program Files\\single'quote\\cargo.exe", |c| c
                .contains("cargo")),
            "cargo".to_string()
        );
        assert_eq!(
            pretty_path("C:\\Program Files\\single'quote\\cargo.exe", |_| false),
            "\"C:\\Program Files\\single'quote\\cargo.exe\"".to_string()
        );
        assert_eq!(
            pretty_path("C:\\Program Files\\%not_var%\\cargo.exe", |_| false),
            "\"C:\\\\Program Files\\\\%not_var%\\\\cargo.exe\"".to_string()
        );
    }

    #[test]
    #[cfg(target_family = "unix")]
    fn pretty_path_linux() {
        assert_eq!(
            pretty_path("/usr/bin/cargo", |f| f.contains("cargo")),
            "cargo".to_string()
        );
        assert_eq!(
            pretty_path("/home/user/my rust/bin/cargo", |_| false),
            "\"/home/user/my rust/bin/cargo\"".to_string(),
        );
        assert_eq!(
            pretty_path("/home/user/single'quote/cargo", |c| c.contains("cargo")),
            "cargo".to_string()
        );
        assert_eq!(
            pretty_path("/home/user/single'quote/cargo", |_| false),
            "\"/home/user/single'quote/cargo\"".to_string()
        );
    }
}