Skip to main content

codewhale_runtime/
browser.rs

1use std::process::Command;
2
3use anyhow::Result;
4
5/// Open a URL in the system's default browser.
6///
7/// Dispatches to the platform-appropriate opener:
8/// - macOS: `open`
9/// - Linux / BSD: `xdg-open`
10/// - Windows: `rundll32 url.dll,FileProtocolHandler`
11/// - Other: returns an error.
12///
13/// This is the single entry point for URL opening — every call site in
14/// the codebase should use this instead of hardcoding `Command::new("open")`,
15/// `Command::new("xdg-open")`, or `Command::new("cmd")`.
16pub fn open_url(url: &str) -> Result<()> {
17    let mut command = browser_open_command(url)?;
18    command
19        .stdout(std::process::Stdio::null())
20        .stderr(std::process::Stdio::null())
21        .spawn()
22        .map(|_| ())
23        .map_err(|e| anyhow::anyhow!("failed to launch browser command: {e}"))
24}
25
26fn browser_open_command(url: &str) -> Result<Command> {
27    if url.trim().is_empty() {
28        return Err(anyhow::anyhow!("browser URL cannot be empty"));
29    }
30
31    #[cfg(target_os = "macos")]
32    {
33        let mut command = Command::new("open");
34        command.arg(url);
35        Ok(command)
36    }
37
38    #[cfg(any(
39        all(target_os = "linux", not(target_env = "ohos")),
40        target_os = "netbsd",
41        target_os = "freebsd",
42        target_os = "openbsd",
43        target_os = "dragonfly"
44    ))]
45    {
46        let mut command = Command::new("xdg-open");
47        command.arg(url);
48        Ok(command)
49    }
50
51    // Not `cmd /C start`: cmd.exe would parse `&`, `|`, `^` and `%` inside
52    // the URL. The protocol handler receives it as data.
53    #[cfg(target_os = "windows")]
54    {
55        let mut cmd = Command::new("rundll32");
56        cmd.args(["url.dll,FileProtocolHandler", url]);
57        Ok(cmd)
58    }
59
60    #[cfg(not(any(
61        target_os = "macos",
62        all(target_os = "linux", not(target_env = "ohos")),
63        target_os = "windows",
64        target_os = "netbsd",
65        target_os = "freebsd",
66        target_os = "openbsd",
67        target_os = "dragonfly"
68    )))]
69    Err(anyhow::anyhow!(
70        "browser opening is unsupported on this platform"
71    ))
72}
73
74#[cfg(test)]
75mod tests {
76    // ===================================================================
77    // open_url tests
78    // ===================================================================
79
80    #[test]
81    fn open_url_builds_platform_command_without_spawning() {
82        let command = super::browser_open_command("https://example.com").expect("command");
83
84        #[cfg(target_os = "macos")]
85        {
86            assert_eq!(command.get_program(), "open");
87            assert_eq!(
88                command
89                    .get_args()
90                    .map(|arg| arg.to_string_lossy().into_owned())
91                    .collect::<Vec<_>>(),
92                vec!["https://example.com"]
93            );
94        }
95
96        #[cfg(any(
97            target_os = "netbsd",
98            target_os = "freebsd",
99            target_os = "openbsd",
100            target_os = "dragonfly"
101        ))]
102        {
103            assert_eq!(command.get_program(), "xdg-open");
104        }
105
106        #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
107        {
108            assert_eq!(command.get_program(), "xdg-open");
109            assert_eq!(
110                command
111                    .get_args()
112                    .map(|arg| arg.to_string_lossy().into_owned())
113                    .collect::<Vec<_>>(),
114                vec!["https://example.com"]
115            );
116        }
117
118        #[cfg(target_os = "windows")]
119        {
120            assert_eq!(command.get_program(), "rundll32");
121            assert_eq!(
122                command
123                    .get_args()
124                    .map(|arg| arg.to_string_lossy().into_owned())
125                    .collect::<Vec<_>>(),
126                vec!["url.dll,FileProtocolHandler", "https://example.com"]
127            );
128            // Shell metacharacters stay inside the single URL argument.
129            let url = "https://example.com/?a=1&b=2|x^y%PATH%";
130            let command = super::browser_open_command(url).expect("command");
131            assert_eq!(command.get_program(), "rundll32");
132            assert_eq!(
133                command
134                    .get_args()
135                    .last()
136                    .map(|arg| arg.to_string_lossy().into_owned()),
137                Some(url.to_string())
138            );
139        }
140    }
141
142    #[test]
143    fn open_url_rejects_empty_url_gracefully() {
144        // An empty URL should fail with a clear error, not panic.
145        let result = super::browser_open_command("");
146        match result {
147            Ok(_) => panic!("empty URL should not build an opener command"),
148            Err(e) => {
149                let msg = e.to_string();
150                assert!(!msg.is_empty(), "error message must not be empty");
151                assert!(msg.contains("empty"), "unexpected error message: {msg}");
152            }
153        }
154    }
155}