rustik: Add `editor` module
5207d7b5104778d1fd8a61fbf195b807010b6747
1 parent
0366279c
Cargo.lock
+2 -0
| 110 | 110 | ||
| 111 | 111 | [[package]] |
|
| 112 | 112 | name = "rustik" |
|
| 113 | 113 | version = "0.2.0" |
|
| 114 | 114 | dependencies = [ |
|
| 115 | + | "libc", |
|
| 115 | 116 | "rustik-diff", |
|
| 116 | 117 | "rustik-highlight", |
|
| 117 | 118 | "rustik-tui", |
|
| 119 | + | "shlex", |
|
| 118 | 120 | ] |
|
| 119 | 121 | ||
| 120 | 122 | [[package]] |
|
| 121 | 123 | name = "rustik-diff" |
|
| 122 | 124 | version = "0.2.0" |
Cargo.toml
+4 -0
| 31 | 31 | [dependencies] |
|
| 32 | 32 | rustik-diff = { workspace = true, optional = true } |
|
| 33 | 33 | rustik-highlight = { workspace = true, optional = true } |
|
| 34 | 34 | rustik-tui = { workspace = true } |
|
| 35 | 35 | ||
| 36 | + | [target.'cfg(unix)'.dependencies] |
|
| 37 | + | libc = { workspace = true } |
|
| 38 | + | shlex = "1.3" |
|
| 39 | + | ||
| 36 | 40 | [lints] |
|
| 37 | 41 | workspace = true |
|
| 38 | 42 | ||
| 39 | 43 | [workspace.package] |
|
| 40 | 44 | version = "0.2.0" |
src/editor.rs
added
+250 -0
| 1 | + | use std::ffi::OsString; |
|
| 2 | + | use std::io::IsTerminal; |
|
| 3 | + | use std::io::Write; |
|
| 4 | + | use std::path::{Path, PathBuf}; |
|
| 5 | + | use std::process; |
|
| 6 | + | use std::{env, fs, io}; |
|
| 7 | + | ||
| 8 | + | /// Allows for text input in the configured editor. |
|
| 9 | + | pub struct Editor { |
|
| 10 | + | path: PathBuf, |
|
| 11 | + | truncate: bool, |
|
| 12 | + | cleanup: bool, |
|
| 13 | + | } |
|
| 14 | + | ||
| 15 | + | impl Default for Editor { |
|
| 16 | + | fn default() -> Self { |
|
| 17 | + | Self::comment() |
|
| 18 | + | } |
|
| 19 | + | } |
|
| 20 | + | ||
| 21 | + | impl Drop for Editor { |
|
| 22 | + | fn drop(&mut self) { |
|
| 23 | + | if self.cleanup { |
|
| 24 | + | fs::remove_file(&self.path).ok(); |
|
| 25 | + | } |
|
| 26 | + | } |
|
| 27 | + | } |
|
| 28 | + | ||
| 29 | + | impl Editor { |
|
| 30 | + | /// Create a new editor. |
|
| 31 | + | 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 | + | /// Create an editor backed by a temporary "comment" file that is |
|
| 50 | + | /// truncated on open and cleaned up when the [`Editor`] is dropped. |
|
| 51 | + | pub fn comment() -> Self { |
|
| 52 | + | const COMMENT_FILE: &str = "RUSTIK_COMMENT"; |
|
| 53 | + | ||
| 54 | + | let path = env::temp_dir().join(COMMENT_FILE); |
|
| 55 | + | ||
| 56 | + | Self { |
|
| 57 | + | path, |
|
| 58 | + | truncate: true, |
|
| 59 | + | cleanup: true, |
|
| 60 | + | } |
|
| 61 | + | } |
|
| 62 | + | ||
| 63 | + | /// Set the file extension. |
|
| 64 | + | pub fn extension(mut self, ext: &str) -> Self { |
|
| 65 | + | let ext = ext.trim_start_matches('.'); |
|
| 66 | + | ||
| 67 | + | self.path.set_extension(ext); |
|
| 68 | + | self |
|
| 69 | + | } |
|
| 70 | + | ||
| 71 | + | /// Truncate the file to length 0 when opening |
|
| 72 | + | pub fn truncate(mut self, truncate: bool) -> Self { |
|
| 73 | + | self.truncate = truncate; |
|
| 74 | + | self |
|
| 75 | + | } |
|
| 76 | + | ||
| 77 | + | /// Clean up the file after the [`Editor`] is dropped. |
|
| 78 | + | pub fn cleanup(mut self, cleanup: bool) -> Self { |
|
| 79 | + | self.cleanup = cleanup; |
|
| 80 | + | self |
|
| 81 | + | } |
|
| 82 | + | ||
| 83 | + | /// Initialize the file with the provided `content`, as long as the file |
|
| 84 | + | /// does not already contain anything. |
|
| 85 | + | #[allow(clippy::byte_char_slices)] |
|
| 86 | + | pub fn initial(self, content: impl AsRef<[u8]>) -> io::Result<Self> { |
|
| 87 | + | let content = content.as_ref(); |
|
| 88 | + | let mut file = fs::OpenOptions::new() |
|
| 89 | + | .write(true) |
|
| 90 | + | .create(true) |
|
| 91 | + | .truncate(self.truncate) |
|
| 92 | + | .open(&self.path)?; |
|
| 93 | + | ||
| 94 | + | if file.metadata()?.len() == 0 { |
|
| 95 | + | file.write_all(content)?; |
|
| 96 | + | if !content.ends_with(&[b'\n']) { |
|
| 97 | + | file.write_all(b"\n")?; |
|
| 98 | + | } |
|
| 99 | + | file.flush()?; |
|
| 100 | + | } |
|
| 101 | + | Ok(self) |
|
| 102 | + | } |
|
| 103 | + | ||
| 104 | + | /// Open the editor and return the edited text. |
|
| 105 | + | /// |
|
| 106 | + | /// If the text hasn't changed from the initial contents of the editor, |
|
| 107 | + | /// return `None`. |
|
| 108 | + | pub fn edit(&mut self) -> io::Result<Option<String>> { |
|
| 109 | + | let Some(cmd) = self::default_editor() else { |
|
| 110 | + | return Err(io::Error::new( |
|
| 111 | + | io::ErrorKind::NotFound, |
|
| 112 | + | "editor not configured: the `EDITOR` environment variable is not set", |
|
| 113 | + | )); |
|
| 114 | + | }; |
|
| 115 | + | let lossy = cmd.to_string_lossy(); |
|
| 116 | + | ||
| 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 | + | let Some((program, args)) = parts.split_first() else { |
|
| 125 | + | return Err(io::Error::new( |
|
| 126 | + | io::ErrorKind::InvalidInput, |
|
| 127 | + | format!("invalid editor command {cmd:?}"), |
|
| 128 | + | )); |
|
| 129 | + | }; |
|
| 130 | + | ||
| 131 | + | let stdout: process::Stdio = { |
|
| 132 | + | use std::os::fd::{AsRawFd as _, FromRawFd as _}; |
|
| 133 | + | ||
| 134 | + | // We duplicate the stderr file descriptor to pass it to the child process; otherwise, if |
|
| 135 | + | // we simply pass the `RawFd` of our stderr, `Command` will close our stderr when the |
|
| 136 | + | // child exits. |
|
| 137 | + | ||
| 138 | + | let stderr = io::stderr().as_raw_fd(); |
|
| 139 | + | unsafe { process::Stdio::from_raw_fd(libc::dup(stderr)) } |
|
| 140 | + | }; |
|
| 141 | + | ||
| 142 | + | let stdin = if io::stdin().is_terminal() { |
|
| 143 | + | process::Stdio::inherit() |
|
| 144 | + | } else { |
|
| 145 | + | // If standard input is not a terminal device, the editor won't work correctly. |
|
| 146 | + | // In that case, we use the terminal device, eg. `/dev/tty` as standard input. |
|
| 147 | + | let tty = fs::OpenOptions::new() |
|
| 148 | + | .read(true) |
|
| 149 | + | .write(true) |
|
| 150 | + | .open("/dev/tty")?; |
|
| 151 | + | process::Stdio::from(tty) |
|
| 152 | + | }; |
|
| 153 | + | ||
| 154 | + | process::Command::new(program) |
|
| 155 | + | .stdout(stdout) |
|
| 156 | + | .stderr(process::Stdio::inherit()) |
|
| 157 | + | .stdin(stdin) |
|
| 158 | + | .args(args) |
|
| 159 | + | .arg(&self.path) |
|
| 160 | + | .spawn() |
|
| 161 | + | .map_err(|e| { |
|
| 162 | + | io::Error::new( |
|
| 163 | + | e.kind(), |
|
| 164 | + | format!("failed to spawn editor command {cmd:?}: {e}"), |
|
| 165 | + | ) |
|
| 166 | + | })? |
|
| 167 | + | .wait() |
|
| 168 | + | .map_err(|e| { |
|
| 169 | + | io::Error::new( |
|
| 170 | + | e.kind(), |
|
| 171 | + | format!("editor command {cmd:?} didn't spawn: {e}"), |
|
| 172 | + | ) |
|
| 173 | + | })?; |
|
| 174 | + | ||
| 175 | + | let text = fs::read_to_string(&self.path)?; |
|
| 176 | + | if text.trim().is_empty() { |
|
| 177 | + | return Ok(None); |
|
| 178 | + | } |
|
| 179 | + | Ok(Some(text)) |
|
| 180 | + | } |
|
| 181 | + | } |
|
| 182 | + | ||
| 183 | + | /// Get the default editor command. |
|
| 184 | + | fn default_editor() -> Option<OsString> { |
|
| 185 | + | // First check the standard environment variables. |
|
| 186 | + | if let Ok(visual) = env::var("VISUAL") |
|
| 187 | + | && !visual.is_empty() |
|
| 188 | + | { |
|
| 189 | + | return Some(visual.into()); |
|
| 190 | + | } |
|
| 191 | + | if let Ok(editor) = env::var("EDITOR") |
|
| 192 | + | && !editor.is_empty() |
|
| 193 | + | { |
|
| 194 | + | return Some(editor.into()); |
|
| 195 | + | } |
|
| 196 | + | ||
| 197 | + | // Check Git. The user might have configured their editor there. |
|
| 198 | + | if let Some(editor) = git_editor() { |
|
| 199 | + | return Some(editor); |
|
| 200 | + | } |
|
| 201 | + | ||
| 202 | + | // On macOS, `nano` is installed by default and it's what most users are used to |
|
| 203 | + | // in the terminal. |
|
| 204 | + | #[cfg(target_os = "macos")] |
|
| 205 | + | if exists("nano") { |
|
| 206 | + | return Some("nano".into()); |
|
| 207 | + | } |
|
| 208 | + | ||
| 209 | + | // If all else fails, we try `vi`. It's usually installed on most unix-based systems. |
|
| 210 | + | if exists("vi") { |
|
| 211 | + | return Some("vi".into()); |
|
| 212 | + | } |
|
| 213 | + | ||
| 214 | + | None |
|
| 215 | + | } |
|
| 216 | + | ||
| 217 | + | /// Ask `git` for the editor configured in `core.editor`, if `git` is available. |
|
| 218 | + | fn git_editor() -> Option<OsString> { |
|
| 219 | + | let output = process::Command::new("git") |
|
| 220 | + | .args(["config", "--get", "core.editor"]) |
|
| 221 | + | .output() |
|
| 222 | + | .ok()?; |
|
| 223 | + | ||
| 224 | + | if !output.status.success() { |
|
| 225 | + | return None; |
|
| 226 | + | } |
|
| 227 | + | let editor = String::from_utf8(output.stdout).ok()?; |
|
| 228 | + | let editor = editor.trim(); |
|
| 229 | + | ||
| 230 | + | if editor.is_empty() { |
|
| 231 | + | None |
|
| 232 | + | } else { |
|
| 233 | + | Some(editor.into()) |
|
| 234 | + | } |
|
| 235 | + | } |
|
| 236 | + | ||
| 237 | + | /// Check whether a binary can be found in the most common paths on Unix-like systems. |
|
| 238 | + | /// We don't bother checking the `$PATH` variable, as we're only looking for very standard tools |
|
| 239 | + | /// and prefer not to make this too complex. |
|
| 240 | + | fn exists(cmd: &str) -> bool { |
|
| 241 | + | // Some common paths where system-installed binaries are found. |
|
| 242 | + | const PATHS: &[&str] = &["/usr/local/bin", "/usr/bin", "/bin"]; |
|
| 243 | + | ||
| 244 | + | for dir in PATHS { |
|
| 245 | + | if Path::new(dir).join(cmd).exists() { |
|
| 246 | + | return true; |
|
| 247 | + | } |
|
| 248 | + | } |
|
| 249 | + | false |
|
| 250 | + | } |
src/lib.rs
+5 -0
| 9 | 9 | #![warn(clippy::unwrap_used)] |
|
| 10 | 10 | ||
| 11 | 11 | /// Plain string formatting helpers. |
|
| 12 | 12 | pub mod fmt; |
|
| 13 | 13 | ||
| 14 | + | /// Launch the user's configured editor for text input. |
|
| 15 | + | // The Unix backend duplicates the stderr file descriptor, which requires `unsafe`. |
|
| 16 | + | #[allow(unsafe_code)] |
|
| 17 | + | pub mod editor; |
|
| 18 | + | ||
| 14 | 19 | /// Re-export of the facade crate. |
|
| 15 | 20 | pub use rustik_tui as tui; |
|
| 16 | 21 | ||
| 17 | 22 | /// Re-export of the unified diff parser and viewer crate. |
|
| 18 | 23 | #[cfg(feature = "diff")] |