fc-gpui-util 0.7.0

A collection of utility structs and functions for fc-gpui (originally from Zed - github.com/zed-industries/zed)
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
#[cfg(any(windows, test))]
use std::ffi::OsStr;
#[cfg(any(windows, test))]
use std::path::PathBuf;
#[cfg(windows)]
use std::sync::LazyLock;
use std::{borrow::Cow, fmt, path::Path};

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ShellKind {
    #[default]
    Posix,
    Csh,
    Tcsh,
    Rc,
    Fish,
    PowerShell,
    Nushell,
    Cmd,
    Xonsh,
}

pub fn get_system_shell() -> String {
    if cfg!(windows) {
        get_windows_system_shell()
    } else {
        std::env::var("SHELL").unwrap_or("/bin/sh".to_string())
    }
}

pub fn get_default_system_shell() -> String {
    if cfg!(windows) {
        get_windows_system_shell()
    } else {
        "/bin/sh".to_string()
    }
}

/// Get the default system shell, preferring git-bash on Windows.
pub fn get_default_system_shell_preferring_bash() -> String {
    #[cfg(windows)]
    {
        get_windows_git_bash().unwrap_or_else(|| get_windows_system_shell())
    }

    #[cfg(not(windows))]
    {
        "/bin/sh".to_string()
    }
}

/// True Git for Windows install root: `git-bash.exe` plus `bin\bash.exe`.
#[cfg(any(windows, test))]
fn find_bash_in_installation(install_root: &Path) -> Option<PathBuf> {
    if !install_root.join("git-bash.exe").is_file() {
        return None;
    }
    let bash = install_root.join("bin").join("bash.exe");
    bash.is_file().then_some(bash)
}

/// Resolve Git Bash from a `git` executable path.
///
/// Git for Windows ships `git` under `cmd\` or, when already inside Git Bash,
/// `mingw64\bin\` (prepended to `PATH`). Walk one extra parent so the latter
/// still finds the install root.
#[cfg(any(windows, test))]
fn find_bash_from_git_binary(git: &Path) -> Option<PathBuf> {
    let binary_directory = git.parent()?;
    let parent = binary_directory.parent()?;
    find_bash_in_installation(parent).or_else(|| find_bash_in_installation(parent.parent()?))
}

#[cfg(any(windows, test))]
fn find_bash_using_git_install(
    git_install_root: Option<PathBuf>,
    git_binary: Option<&Path>,
) -> Option<PathBuf> {
    if let Some(bash) = git_install_root.and_then(|path| find_bash_in_installation(&path)) {
        return Some(bash);
    }
    find_bash_from_git_binary(git_binary?)
}

#[cfg(windows)]
pub fn get_windows_git_bash() -> Option<String> {
    fn find_bash_in_git() -> Option<PathBuf> {
        let git = which::which("git").ok();
        find_bash_using_git_install(
            std::env::var_os("GIT_INSTALL_ROOT").map(PathBuf::from),
            git.as_deref(),
        )
    }

    static GIT_BASH: LazyLock<Option<String>> = LazyLock::new(|| {
        let bash = find_bash_in_git().map(|p| p.to_string_lossy().into_owned());
        if let Some(ref path) = bash {
            log::info!("Found bash at {}", path);
        }
        bash
    });

    (*GIT_BASH).clone()
}

/// Scoop root from a non-empty `SCOOP`, otherwise `%USERPROFILE%\scoop`.
///
/// An empty `SCOOP` is treated as unset. `PathBuf::from("")` would otherwise
/// join `shims\pwsh.exe` relative to the current directory.
#[cfg(any(windows, test))]
fn scoop_install_root(scoop: Option<&OsStr>, userprofile: Option<&OsStr>) -> Option<PathBuf> {
    scoop
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
        .or_else(|| userprofile.map(|home| PathBuf::from(home).join("scoop")))
}

#[cfg(windows)]
pub fn get_powershell() -> Option<String> {
    fn find_pwsh_in_programfiles(find_alternate: bool, find_preview: bool) -> Option<PathBuf> {
        #[cfg(target_pointer_width = "64")]
        let env_var = if find_alternate {
            "ProgramFiles(x86)"
        } else {
            "ProgramFiles"
        };

        #[cfg(target_pointer_width = "32")]
        let env_var = if find_alternate {
            "ProgramW6432"
        } else {
            "ProgramFiles"
        };

        let install_base_dir = PathBuf::from(std::env::var_os(env_var)?).join("PowerShell");
        install_base_dir
            .read_dir()
            .ok()?
            .filter_map(Result::ok)
            .filter(|entry| matches!(entry.file_type(), Ok(ft) if ft.is_dir()))
            .filter_map(|entry| {
                let dir_name = entry.file_name();
                let dir_name = dir_name.to_string_lossy();

                let version = if find_preview {
                    let dash_index = dir_name.find('-')?;
                    if &dir_name[dash_index + 1..] != "preview" {
                        return None;
                    };
                    dir_name[..dash_index].parse::<u32>().ok()?
                } else {
                    dir_name.parse::<u32>().ok()?
                };

                let exe_path = entry.path().join("pwsh.exe");
                if exe_path.is_file() {
                    Some((version, exe_path))
                } else {
                    None
                }
            })
            .max_by_key(|(version, _)| *version)
            .map(|(_, path)| path)
    }

    fn find_pwsh_in_msix(find_preview: bool) -> Option<PathBuf> {
        let msix_app_dir =
            PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("Microsoft\\WindowsApps");
        let package_family_name = if find_preview {
            "Microsoft.PowerShellPreview_8wekyb3d8bbwe"
        } else {
            "Microsoft.PowerShell_8wekyb3d8bbwe"
        };
        let pwsh_exe = msix_app_dir.join(package_family_name).join("pwsh.exe");
        pwsh_exe.exists().then_some(pwsh_exe)
    }

    fn find_pwsh_in_scoop() -> Option<PathBuf> {
        // Scoop can be installed to a custom location; $SCOOP points at the
        // scoop root in that case and defaults to %USERPROFILE%\scoop otherwise.
        let scoop = std::env::var_os("SCOOP");
        let userprofile = std::env::var_os("USERPROFILE");
        let scoop_dir = scoop_install_root(scoop.as_deref(), userprofile.as_deref())?;
        let pwsh_exe = scoop_dir.join("shims").join("pwsh.exe");
        pwsh_exe.is_file().then_some(pwsh_exe)
    }

    fn find_pwsh_in_dotnet_tools() -> Option<PathBuf> {
        let pwsh_exe =
            PathBuf::from(std::env::var_os("USERPROFILE")?).join(".dotnet\\tools\\pwsh.exe");
        pwsh_exe.is_file().then_some(pwsh_exe)
    }

    fn find_windows_powershell() -> Option<PathBuf> {
        let system_root = PathBuf::from(std::env::var_os("SystemRoot")?);
        let powershell = system_root.join("System32\\WindowsPowerShell\\v1.0\\powershell.exe");
        powershell.is_file().then_some(powershell)
    }

    static POWERSHELL: LazyLock<Option<String>> = LazyLock::new(|| {
        let locations = [
            || find_pwsh_in_programfiles(false, false),
            || find_pwsh_in_programfiles(true, false),
            || find_pwsh_in_msix(false),
            || find_pwsh_in_programfiles(false, true),
            || find_pwsh_in_msix(true),
            || find_pwsh_in_programfiles(true, true),
            || find_pwsh_in_scoop(),
            || find_pwsh_in_dotnet_tools(),
            || which::which_global("pwsh.exe").ok(),
            || which::which_global("powershell.exe").ok(),
            || find_windows_powershell(),
        ];

        locations
            .into_iter()
            .find_map(|f| f())
            .map(|p| p.to_string_lossy().trim().to_owned())
            .inspect(|shell| log::info!("Found powershell in: {}", shell))
    });

    (*POWERSHELL).clone()
}

#[cfg(windows)]
pub fn get_windows_system_shell() -> String {
    static CMD: LazyLock<String> = LazyLock::new(|| {
        log::warn!("Powershell not found, falling back to `cmd`");
        let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
        PathBuf::from(system_root)
            .join("System32\\cmd.exe")
            .to_string_lossy()
            .into_owned()
    });
    get_powershell().unwrap_or_else(|| (*CMD).clone())
}

#[cfg(not(windows))]
pub fn get_windows_system_shell() -> String {
    "cmd.exe".to_string()
}

impl fmt::Display for ShellKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ShellKind::Posix => write!(f, "sh"),
            ShellKind::Csh => write!(f, "csh"),
            ShellKind::Tcsh => write!(f, "tcsh"),
            ShellKind::Fish => write!(f, "fish"),
            ShellKind::PowerShell => write!(f, "powershell"),
            ShellKind::Nushell => write!(f, "nu"),
            ShellKind::Cmd => write!(f, "cmd"),
            ShellKind::Rc => write!(f, "rc"),
            ShellKind::Xonsh => write!(f, "xonsh"),
        }
    }
}

impl ShellKind {
    pub fn system() -> Self {
        Self::new(&get_system_shell(), cfg!(windows))
    }

    pub fn new(program: impl AsRef<Path>, is_windows: bool) -> Self {
        let program = program.as_ref();
        let program = program
            .file_stem()
            .unwrap_or_else(|| program.as_os_str())
            .to_string_lossy();

        if program == "powershell" || program == "pwsh" {
            ShellKind::PowerShell
        } else if program == "cmd" {
            ShellKind::Cmd
        } else if program == "nu" {
            ShellKind::Nushell
        } else if program == "fish" {
            ShellKind::Fish
        } else if program == "csh" {
            ShellKind::Csh
        } else if program == "tcsh" {
            ShellKind::Tcsh
        } else if program == "rc" {
            ShellKind::Rc
        } else if program == "xonsh" {
            ShellKind::Xonsh
        } else if program == "sh" || program == "bash" {
            ShellKind::Posix
        } else {
            if is_windows {
                ShellKind::PowerShell
            } else {
                // Some other shell detected, the user might install and use a
                // unix-like shell.
                ShellKind::Posix
            }
        }
    }

    pub fn to_shell_variable(self, input: &str) -> String {
        match self {
            Self::PowerShell => Self::to_powershell_variable(input),
            Self::Cmd => Self::to_cmd_variable(input),
            Self::Posix => input.to_owned(),
            Self::Fish => input.to_owned(),
            Self::Csh => input.to_owned(),
            Self::Tcsh => input.to_owned(),
            Self::Rc => input.to_owned(),
            Self::Nushell => Self::to_nushell_variable(input),
            Self::Xonsh => input.to_owned(),
        }
    }

    fn to_cmd_variable(input: &str) -> String {
        if let Some(var_str) = input.strip_prefix("${") {
            match var_str.strip_suffix('}') {
                Some(var_name) if !var_name.is_empty() && !var_name.contains(':') => {
                    format!("%{var_name}%")
                }
                // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
                // which will result in the task failing to run in such cases.
                _ => input.into(),
            }
        } else if let Some(var_str) = input.strip_prefix('$') {
            // If the input starts with "$", directly append to "$env:"
            format!("%{}%", var_str)
        } else {
            // If no prefix is found, return the input as is
            input.into()
        }
    }

    fn to_powershell_variable(input: &str) -> String {
        if let Some(var_str) = input.strip_prefix("${") {
            match var_str.strip_suffix('}') {
                Some(var_name) if !var_name.is_empty() && !var_name.contains(':') => {
                    format!("$env:{var_name}")
                }
                // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
                // which will result in the task failing to run in such cases.
                _ => input.into(),
            }
        } else if let Some(var_str) = input.strip_prefix('$') {
            // If the input starts with "$", directly append to "$env:"
            format!("$env:{}", var_str)
        } else {
            // If no prefix is found, return the input as is
            input.into()
        }
    }

    fn to_nushell_variable(input: &str) -> String {
        let mut result = String::new();
        let mut source = input;
        let mut is_start = true;

        loop {
            match source.chars().next() {
                None => return result,
                Some('$') => {
                    source = Self::parse_nushell_var(&source[1..], &mut result, is_start);
                    is_start = false;
                }
                Some(_) => {
                    is_start = false;
                    let chunk_end = source.find('$').unwrap_or(source.len());
                    let (chunk, rest) = source.split_at(chunk_end);
                    result.push_str(chunk);
                    source = rest;
                }
            }
        }
    }

    fn parse_nushell_var<'a>(source: &'a str, text: &mut String, is_start: bool) -> &'a str {
        if source.starts_with("env.") {
            text.push('$');
            return source;
        }

        match source.chars().next() {
            Some('{') => {
                let source = &source[1..];
                if let Some(end) = source.find('}') {
                    let var_name = &source[..end];
                    if !var_name.is_empty() {
                        if !is_start {
                            text.push_str("(");
                        }
                        text.push_str("$env.");
                        text.push_str(var_name);
                        if !is_start {
                            text.push_str(")");
                        }
                        &source[end + 1..]
                    } else {
                        text.push_str("${}");
                        &source[end + 1..]
                    }
                } else {
                    text.push_str("${");
                    source
                }
            }
            Some(c) if c.is_alphabetic() || c == '_' => {
                let end = source
                    .find(|c: char| !c.is_alphanumeric() && c != '_')
                    .unwrap_or(source.len());
                let var_name = &source[..end];
                if !is_start {
                    text.push_str("(");
                }
                text.push_str("$env.");
                text.push_str(var_name);
                if !is_start {
                    text.push_str(")");
                }
                &source[end..]
            }
            _ => {
                text.push('$');
                source
            }
        }
    }

    pub fn args_for_shell(&self, interactive: bool, combined_command: String) -> Vec<String> {
        match self {
            ShellKind::PowerShell => vec!["-C".to_owned(), combined_command],
            ShellKind::Cmd => vec!["/C".to_owned(), combined_command],
            ShellKind::Posix
            | ShellKind::Nushell
            | ShellKind::Fish
            | ShellKind::Csh
            | ShellKind::Tcsh
            | ShellKind::Rc
            | ShellKind::Xonsh => interactive
                .then(|| "-i".to_owned())
                .into_iter()
                .chain(["-c".to_owned(), combined_command])
                .collect(),
        }
    }

    pub const fn command_prefix(&self) -> Option<char> {
        match self {
            ShellKind::PowerShell => Some('&'),
            ShellKind::Nushell => Some('^'),
            _ => None,
        }
    }

    pub const fn sequential_commands_separator(&self) -> char {
        match self {
            ShellKind::Cmd => '&',
            _ => ';',
        }
    }

    pub fn try_quote<'a>(&self, arg: &'a str) -> Option<Cow<'a, str>> {
        shlex::try_quote(arg).ok().map(|arg| match self {
            // If we are running in PowerShell, we want to take extra care when escaping strings.
            // In particular, we want to escape strings with a backtick (`) rather than a backslash (\).
            // TODO double escaping backslashes is not necessary in PowerShell and probably CMD
            ShellKind::PowerShell => Cow::Owned(arg.replace("\\\"", "`\"")),
            _ => arg,
        })
    }

    pub const fn activate_keyword(&self) -> &'static str {
        match self {
            ShellKind::Cmd => "",
            ShellKind::Nushell => "overlay use",
            ShellKind::PowerShell => ".",
            ShellKind::Fish => "source",
            ShellKind::Csh => "source",
            ShellKind::Tcsh => "source",
            ShellKind::Posix | ShellKind::Rc => "source",
            ShellKind::Xonsh => "source",
        }
    }

    pub const fn clear_screen_command(&self) -> &'static str {
        match self {
            ShellKind::Cmd => "cls",
            _ => "clear",
        }
    }
}

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

    fn git_for_windows_layout() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        std::fs::write(dir.path().join("git-bash.exe"), []).unwrap();
        std::fs::write(bin.join("bash.exe"), []).unwrap();
        dir
    }

    #[test]
    fn test_to_shell_variable() {
        assert_eq!(
            ShellKind::PowerShell.to_shell_variable("${FOO}"),
            "$env:FOO"
        );
        assert_eq!(ShellKind::Cmd.to_shell_variable("${FOO}"), "%FOO%");
        assert_eq!(ShellKind::Nushell.to_shell_variable("${FOO}"), "$env.FOO");
        assert_eq!(ShellKind::Posix.to_shell_variable("${FOO}"), "${FOO}");

        assert_eq!(ShellKind::PowerShell.to_shell_variable("$FOO"), "$env:FOO");
        assert_eq!(
            ShellKind::PowerShell.to_shell_variable("${日本}"),
            "$env:日本"
        );
        assert_eq!(
            ShellKind::PowerShell.to_shell_variable("${FOO:-bar}"),
            "${FOO:-bar}"
        );
    }

    #[test]
    fn test_to_shell_variable_malformed_is_passed_through() {
        for input in ["${", "${FOO", "${café", "${}", "${日本"] {
            for shell_kind in [ShellKind::PowerShell, ShellKind::Cmd, ShellKind::Nushell] {
                assert_eq!(shell_kind.to_shell_variable(input), input);
            }
        }
    }

    #[test]
    fn git_bash_requires_git_bash_exe_and_bin_bash() {
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        std::fs::write(bin.join("bash.exe"), []).unwrap();
        assert!(find_bash_in_installation(dir.path()).is_none());

        std::fs::write(dir.path().join("git-bash.exe"), []).unwrap();
        assert_eq!(
            find_bash_in_installation(dir.path()).as_deref(),
            Some(bin.join("bash.exe").as_path())
        );
    }

    #[test]
    fn git_bash_from_cmd_git_uses_install_root() {
        let install = git_for_windows_layout();
        let cmd = install.path().join("cmd");
        std::fs::create_dir_all(&cmd).unwrap();
        let git = cmd.join("git.exe");
        std::fs::write(&git, []).unwrap();
        assert_eq!(
            find_bash_from_git_binary(&git).unwrap(),
            install.path().join("bin").join("bash.exe")
        );
    }

    #[test]
    fn git_bash_from_mingw64_bin_walks_up_to_install_root() {
        let install = git_for_windows_layout();
        let mingw_bin = install.path().join("mingw64").join("bin");
        std::fs::create_dir_all(&mingw_bin).unwrap();
        let git = mingw_bin.join("git.exe");
        std::fs::write(&git, []).unwrap();
        assert_eq!(
            find_bash_from_git_binary(&git).unwrap(),
            install.path().join("bin").join("bash.exe")
        );
    }

    #[test]
    fn git_install_root_takes_precedence_over_git_binary() {
        let preferred = git_for_windows_layout();
        let other = git_for_windows_layout();
        let git = other.path().join("cmd").join("git.exe");
        std::fs::create_dir_all(git.parent().unwrap()).unwrap();
        std::fs::write(&git, []).unwrap();
        assert_eq!(
            find_bash_using_git_install(Some(preferred.path().to_path_buf()), Some(&git)).unwrap(),
            preferred.path().join("bin").join("bash.exe")
        );
    }

    #[test]
    fn empty_scoop_falls_back_to_userprofile() {
        assert_eq!(
            scoop_install_root(Some(OsStr::new("")), Some(OsStr::new(r"C:\Users\someone")))
                .unwrap(),
            PathBuf::from(r"C:\Users\someone").join("scoop")
        );
    }

    #[test]
    fn scoop_env_overrides_userprofile_when_non_empty() {
        assert_eq!(
            scoop_install_root(
                Some(OsStr::new(r"D:\Apps\scoop")),
                Some(OsStr::new(r"C:\Users\someone"))
            )
            .unwrap(),
            PathBuf::from(r"D:\Apps\scoop")
        );
    }

    #[test]
    fn scoop_root_is_none_when_scoop_and_userprofile_are_missing() {
        assert!(scoop_install_root(None, None).is_none());
        assert!(scoop_install_root(Some(OsStr::new("")), None).is_none());
    }

    #[cfg(not(windows))]
    #[test]
    fn unix_stubs_for_windows_shell_discovery() {
        assert_eq!(get_windows_system_shell(), "cmd.exe");
        assert_eq!(get_default_system_shell_preferring_bash(), "/bin/sh");
        assert_eq!(get_default_system_shell(), "/bin/sh");
    }
}