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 let Some(parts) = shlex::split(cmd.to_string_lossy().as_ref()) else {
114 return Err(io::Error::new(
115 io::ErrorKind::InvalidInput,
116 format!("invalid editor command {cmd:?}"),
117 ));
118 };
119 let Some((program, args)) = parts.split_first() else {
120 return Err(io::Error::new(
121 io::ErrorKind::InvalidInput,
122 format!("invalid editor command {cmd:?}"),
123 ));
124 };
125
126 let stdout: process::Stdio = {
127 #[cfg(unix)]
128 {
129 use std::os::fd::{AsRawFd as _, FromRawFd as _};
130
131 let stderr = io::stderr().as_raw_fd();
136 unsafe { process::Stdio::from_raw_fd(libc::dup(stderr)) }
137 }
138 #[cfg(not(unix))]
139 {
140 io::stderr().into()
144 }
145 };
146
147 let stdin = if io::stdin().is_terminal() {
148 process::Stdio::inherit()
149 } else if cfg!(unix) {
150 let tty = fs::OpenOptions::new()
153 .read(true)
154 .write(true)
155 .open("/dev/tty")?;
156 process::Stdio::from(tty)
157 } else {
158 return Err(io::Error::new(
159 io::ErrorKind::Unsupported,
160 format!("standard input is not a terminal, refusing to execute editor {cmd:?}"),
161 ));
162 };
163
164 process::Command::new(program)
165 .stdout(stdout)
166 .stderr(process::Stdio::inherit())
167 .stdin(stdin)
168 .args(args)
169 .arg(&self.path)
170 .spawn()
171 .map_err(|e| {
172 io::Error::new(
173 e.kind(),
174 format!("failed to spawn editor command {cmd:?}: {e}"),
175 )
176 })?
177 .wait()
178 .map_err(|e| {
179 io::Error::new(
180 e.kind(),
181 format!("editor command {cmd:?} didn't spawn: {e}"),
182 )
183 })?;
184
185 let text = fs::read_to_string(&self.path)?;
186 if text.trim().is_empty() {
187 return Ok(None);
188 }
189 Ok(Some(text))
190 }
191}
192
193fn default_editor() -> Option<OsString> {
195 if let Ok(visual) = env::var("VISUAL") {
197 if !visual.is_empty() {
198 return Some(visual.into());
199 }
200 }
201 if let Ok(editor) = env::var("EDITOR") {
202 if !editor.is_empty() {
203 return Some(editor.into());
204 }
205 }
206 #[cfg(feature = "git2")]
208 if let Ok(path) = git2::Config::open_default().and_then(|cfg| cfg.get_path("core.editor")) {
209 return Some(path.into_os_string());
210 }
211 if cfg!(target_os = "macos") && exists("nano") {
214 return Some("nano".into());
215 }
216 if exists("vi") {
218 return Some("vi".into());
219 }
220 None
221}
222
223fn exists(cmd: &str) -> bool {
227 const PATHS: &[&str] = &["/usr/local/bin", "/usr/bin", "/bin"];
229
230 for dir in PATHS {
231 if Path::new(dir).join(cmd).exists() {
232 return true;
233 }
234 }
235 false
236}