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
extern crate failure;
#[macro_use]
extern crate failure_derive;
#[cfg(target_os = "windows")]
extern crate winapi;
#[cfg(target_os = "windows")]
use windows::open_sys;
use std::{
ffi::OsStr,
fmt::{self, Display, Formatter},
io,
process::ExitStatus,
};
#[derive(Debug, Fail)]
pub enum OpenError {
#[cause]
Io(io::Error),
ExitStatus {
cmd: &'static str,
status: ExitStatus,
stderr: String,
},
}
impl Display for OpenError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
OpenError::Io(_) => {
write!(f, "IO error")?;
}
OpenError::ExitStatus {
cmd,
status,
stderr,
} => {
write!(
f,
"command '{}' did not execute successfully; {}",
cmd, status
)?;
let stderr = stderr.trim();
if !stderr.is_empty() {
write!(f, "\ncommand stderr:\n{}", stderr)?;
}
}
}
Ok(())
}
}
impl From<io::Error> for OpenError {
fn from(err: io::Error) -> Self {
OpenError::Io(err)
}
}
pub fn open<P>(path: P) -> Result<(), OpenError>
where
P: AsRef<OsStr>,
{
open_sys(path.as_ref())
}
#[cfg(target_os = "windows")]
mod windows {
use super::OpenError;
use std::{ffi::OsStr, io, os::windows::ffi::OsStrExt, ptr};
use winapi::{ctypes::c_int, um::shellapi::ShellExecuteW};
pub fn open_sys(path: &OsStr) -> Result<(), OpenError> {
const SW_SHOW: c_int = 5;
let path = convert_path(path)?;
let operation: Vec<u16> = OsStr::new("open\0").encode_wide().collect();
let result = unsafe {
ShellExecuteW(
ptr::null_mut(),
operation.as_ptr(),
path.as_ptr(),
ptr::null(),
ptr::null(),
SW_SHOW,
)
};
if result as c_int > 32 {
Ok(())
} else {
Err(io::Error::last_os_error().into())
}
}
fn convert_path(path: &OsStr) -> io::Result<Vec<u16>> {
let mut maybe_result: Vec<u16> = path.encode_wide().collect();
if maybe_result.iter().any(|&u| u == 0) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path contains NUL byte(s)",
));
}
maybe_result.push(0);
Ok(maybe_result)
}
}
#[cfg(target_os = "macos")]
fn open_sys(path: &OsStr) -> Result<(), OpenError> {
open_not_windows("open", path, &[], None, "open")
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
fn open_sys(path: &OsStr) -> Result<(), OpenError> {
const XDG_OPEN_SCRIPT: &[u8] = include_bytes!("xdg-open");
open_not_windows(
"sh",
path,
&["-s"],
Some(XDG_OPEN_SCRIPT),
"xdg-open (internal)",
)
}
#[cfg(not(target_os = "windows"))]
fn open_not_windows(
cmd: &str,
path: &OsStr,
extra_args: &[&str],
piped_input: Option<&[u8]>,
cmd_friendly_name: &'static str,
) -> Result<(), OpenError> {
use std::{
io::{Read, Write},
process::{Command, Stdio},
};
let stdin_type = if piped_input.is_some() {
Stdio::piped()
} else {
Stdio::null()
};
let mut cmd = Command::new(cmd)
.args(extra_args)
.arg(path)
.stdin(stdin_type)
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()?;
if let Some(stdin) = cmd.stdin.as_mut() {
stdin.write_all(piped_input.unwrap())?;
}
let exit_status = cmd.wait()?;
if exit_status.success() {
Ok(())
} else {
let mut stderr = String::new();
cmd.stderr.as_mut().unwrap().read_to_string(&mut stderr)?;
Err(OpenError::ExitStatus {
cmd: cmd_friendly_name,
status: exit_status,
stderr,
})
}
}