Skip to main content

yt/
browser.rs

1use crate::env::Env;
2
3/// Whether a browser can be launched here: never over SSH, and on Linux only with a display.
4pub fn can_launch(env: &Env) -> bool {
5    let ssh = env.get("SSH_CONNECTION").is_some() || env.get("SSH_TTY").is_some();
6    let display = cfg!(target_os = "macos")
7        || env.get("DISPLAY").is_some()
8        || env.get("WAYLAND_DISPLAY").is_some();
9    !ssh && display
10}
11
12/// Opens `url` in the default browser; false when nothing was launched. Callers always print the URL too.
13pub fn open(env: &Env, url: &str) -> bool {
14    can_launch(env) && webbrowser::open(url).is_ok()
15}
16
17#[cfg(test)]
18mod tests {
19    use super::*;
20
21    #[test]
22    fn never_over_ssh() {
23        assert!(!can_launch(&Env::from_vars([
24            ("SSH_CONNECTION", "1.2.3.4 22"),
25            ("DISPLAY", ":0")
26        ])));
27        assert!(!can_launch(&Env::from_vars([
28            ("SSH_TTY", "/dev/ttys001"),
29            ("DISPLAY", ":0")
30        ])));
31    }
32
33    #[cfg(target_os = "linux")]
34    #[test]
35    fn linux_needs_a_display() {
36        assert!(!can_launch(&Env::default()));
37        assert!(can_launch(&Env::from_vars([(
38            "WAYLAND_DISPLAY",
39            "wayland-0"
40        )])));
41    }
42}