1use std::ffi::OsString;
2use std::io::IsTerminal;
3use std::io::Write;
4use std::path::{Path, PathBuf};
5use std::process;
6use std::{env, fs, io};
7
8pub struct Editor {
10 path: PathBuf,
11 truncate: bool,
12 cleanup: bool,
13}
14
15impl Default for Editor {
16 fn default() -> Self {
17 Self::comment()
18 }
19}
20
21impl Drop for Editor {
22 fn drop(&mut self) {
23 if self.cleanup {
24 fs::remove_file(&self.path).ok();
25 }
26 }
27}
28
29impl Editor {
30 pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
32 let path = path.as_ref();
33 if path.try_exists()? {
34 let meta = fs::metadata(path)?;
35 if !meta.is_file() {
36 return Err(io::Error::new(
37 io::ErrorKind::InvalidInput,
38 "must be used to edit a file",
39 ));
40 }
41 }
42 Ok(Self {
43 path: path.to_path_buf(),
44 truncate: false,
45 cleanup: false,
46 })
47 }
48
49 pub fn comment() -> Self {
50 const COMMENT_FILE: &str = "RAD_COMMENT";
51
52 let path = env::temp_dir().join(COMMENT_FILE);
53
54 Self {
55 path,
56 truncate: true,
57 cleanup: true,
58 }
59 }
60
61 pub fn extension(mut self, ext: &str) -> Self {
63 let ext = ext.trim_start_matches('.');
64
65 self.path.set_extension(ext);
66 self
67 }
68
69 pub fn truncate(mut self, truncate: bool) -> Self {
71 self.truncate = truncate;
72 self
73 }
74
75 pub fn cleanup(mut self, cleanup: bool) -> Self {
77 self.cleanup = cleanup;
78 self
79 }
80
81 #[allow(clippy::byte_char_slices)]
84 pub fn initial(self, content: impl AsRef<[u8]>) -> io::Result<Self> {
85 let content = content.as_ref();
86 let mut file = fs::OpenOptions::new()
87 .write(true)
88 .create(true)
89 .truncate(self.truncate)
90 .open(&self.path)?;
91
92 if file.metadata()?.len() == 0 {
93 file.write_all(content)?;
94 if !content.ends_with(&[b'\n']) {
95 file.write_all(b"\n")?;
96 }
97 file.flush()?;
98 }
99 Ok(self)
100 }
101
102 pub fn edit(&mut self) -> io::Result<Option<String>> {
107 let Some(cmd) = self::default_editor() else {
108 return Err(io::Error::new(
109 io::ErrorKind::NotFound,
110 "editor not configured: the `EDITOR` environment variable is not set",
111 ));
112 };
113
114 let lossy = cmd.to_string_lossy();
115
116 #[cfg(unix)]
117 let Some(parts) = shlex::split(&lossy) else {
118 return Err(io::Error::new(
119 io::ErrorKind::InvalidInput,
120 format!("invalid editor command {cmd:?}"),
121 ));
122 };
123
124 #[cfg(windows)]
125 let parts = winsplit::split(&lossy);
126
127 let Some((program, args)) = parts.split_first() else {
128 return Err(io::Error::new(
129 io::ErrorKind::InvalidInput,
130 format!("invalid editor command {cmd:?}"),
131 ));
132 };
133
134 let stdout: process::Stdio = {
135 #[cfg(unix)]
136 {
137 use std::os::fd::{AsRawFd as _, FromRawFd as _};
138
139 let stderr = io::stderr().as_raw_fd();
144 unsafe { process::Stdio::from_raw_fd(libc::dup(stderr)) }
145 }
146 #[cfg(not(unix))]
147 {
148 io::stderr().into()
152 }
153 };
154
155 let stdin = if io::stdin().is_terminal() {
156 process::Stdio::inherit()
157 } else if cfg!(unix) {
158 let tty = fs::OpenOptions::new()
161 .read(true)
162 .write(true)
163 .open("/dev/tty")?;
164 process::Stdio::from(tty)
165 } else {
166 return Err(io::Error::new(
167 io::ErrorKind::Unsupported,
168 format!("standard input is not a terminal, refusing to execute editor {cmd:?}"),
169 ));
170 };
171
172 process::Command::new(program)
173 .stdout(stdout)
174 .stderr(process::Stdio::inherit())
175 .stdin(stdin)
176 .args(args)
177 .arg(&self.path)
178 .spawn()
179 .map_err(|e| {
180 io::Error::new(
181 e.kind(),
182 format!("failed to spawn editor command {cmd:?}: {e}"),
183 )
184 })?
185 .wait()
186 .map_err(|e| {
187 io::Error::new(
188 e.kind(),
189 format!("editor command {cmd:?} didn't spawn: {e}"),
190 )
191 })?;
192
193 let text = fs::read_to_string(&self.path)?;
194 if text.trim().is_empty() {
195 return Ok(None);
196 }
197 Ok(Some(text))
198 }
199}
200
201fn default_editor() -> Option<OsString> {
203 if let Ok(visual) = env::var("VISUAL") {
205 if !visual.is_empty() {
206 return Some(visual.into());
207 }
208 }
209 if let Ok(editor) = env::var("EDITOR") {
210 if !editor.is_empty() {
211 return Some(editor.into());
212 }
213 }
214
215 #[cfg(all(feature = "git2", not(windows)))]
220 if let Ok(path) = git2::Config::open_default().and_then(|cfg| cfg.get_path("core.editor")) {
221 return Some(path.into_os_string());
222 }
223
224 #[cfg(target_os = "macos")]
227 if exists("nano") {
228 return Some("nano".into());
229 }
230
231 #[cfg(windows)]
233 if exists("edit.exe") {
234 return Some("edit.exe".into());
235 }
236
237 #[cfg(windows)]
239 if exists("notepad.exe") {
240 return Some("notepad.exe".into());
241 }
242
243 if exists("vi") {
245 return Some("vi".into());
246 }
247
248 None
249}
250
251#[cfg(unix)]
255fn exists(cmd: &str) -> bool {
256 const PATHS: &[&str] = &["/usr/local/bin", "/usr/bin", "/bin"];
258
259 for dir in PATHS {
260 if Path::new(dir).join(cmd).exists() {
261 return true;
262 }
263 }
264 false
265}
266
267#[cfg(windows)]
272fn exists(cmd: &str) -> bool {
273 std::process::Command::new("where.exe")
274 .arg("/q")
275 .arg("$PATH:".to_owned() + cmd)
276 .output()
277 .map(|output| output.status.success())
278 .unwrap_or_default()
279}