| 1 | mod align; |
| 2 | mod ansi; |
| 3 | mod cli; |
| 4 | mod color; |
| 5 | mod colors; |
| 6 | mod config; |
| 7 | mod delta; |
| 8 | mod edits; |
| 9 | mod env; |
| 10 | mod features; |
| 11 | mod format; |
| 12 | mod git_config; |
| 13 | mod handlers; |
| 14 | mod minusplus; |
| 15 | mod options; |
| 16 | mod paint; |
| 17 | mod parse_style; |
| 18 | mod parse_styles; |
| 19 | mod style; |
| 20 | mod utils; |
| 21 | mod wrapping; |
| 22 | |
| 23 | mod subcommands; |
| 24 | |
| 25 | mod tests; |
| 26 | |
| 27 | use std::ffi::{OsStr, OsString}; |
| 28 | use std::io::{self, BufRead, Cursor, ErrorKind, IsTerminal, Write}; |
| 29 | use std::process::{self, Command, Stdio}; |
| 30 | |
| 31 | use bytelines::ByteLinesReader; |
| 32 | |
| 33 | use crate::cli::Call; |
| 34 | use crate::config::delta_unreachable; |
| 35 | use crate::delta::delta; |
| 36 | use crate::subcommands::{SubCmdKind, SubCommand}; |
| 37 | use crate::utils::bat::assets::list_languages; |
| 38 | use crate::utils::bat::output::{OutputType, PagingMode}; |
| 39 | |
| 40 | pub fn fatal<T>(errmsg: T) -> ! |
| 41 | where |
| 42 | T: AsRef<str> + std::fmt::Display, |
| 43 | { |
| 44 | #[cfg(not(test))] |
| 45 | { |
| 46 | eprintln!("{errmsg}"); |
| 47 | // As in Config::error_exit_code: use 2 for error |
| 48 | // because diff uses 0 and 1 for non-error. |
| 49 | process::exit(2); |
| 50 | } |
| 51 | #[cfg(test)] |
| 52 | panic!("{}\n", errmsg); |
| 53 | } |
| 54 | |
| 55 | pub mod errors { |
| 56 | pub use anyhow::{anyhow, Context, Error, Result}; |
| 57 | } |
| 58 | |
| 59 | #[cfg(not(tarpaulin_include))] |
| 60 | fn main() -> std::io::Result<()> { |
| 61 | // Do this first because both parsing all the input in `run_app()` and |
| 62 | // listing all processes takes about 50ms on Linux. |
| 63 | // It also improves the chance that the calling process is still around when |
| 64 | // input is piped into delta (e.g. `git show --word-diff=color | delta`). |
| 65 | utils::process::start_determining_calling_process_in_thread(); |
| 66 | |
| 67 | // Ignore ctrl-c (SIGINT) to avoid leaving an orphaned pager process. |
| 68 | // See https://github.com/dandavison/delta/issues/681 |
| 69 | ctrlc::set_handler(|| {}) |
| 70 | .unwrap_or_else(|err| eprintln!("Failed to set ctrl-c handler: {err}")); |
| 71 | let exit_code = run_app(std::env::args_os().collect::<Vec<_>>(), None)?; |
| 72 | // when you call process::exit, no drop impls are called, so we want to do it only once, here |
| 73 | process::exit(exit_code); |
| 74 | } |
| 75 | |
| 76 | #[cfg(not(tarpaulin_include))] |
| 77 | // An Ok result contains the desired process exit code. Note that 1 is used to |
| 78 | // report that two files differ when delta is called with two positional |
| 79 | // arguments and without standard input; 2 is used to report a real problem. |
| 80 | pub fn run_app( |
| 81 | args: Vec<OsString>, |
| 82 | capture_output: Option<&mut Cursor<Vec<u8>>>, |
| 83 | ) -> std::io::Result<i32> { |
| 84 | let env = env::DeltaEnv::init(); |
| 85 | let assets = utils::bat::assets::load_highlighting_assets(); |
| 86 | let (call, opt) = cli::Opt::from_args_and_git_config(args, &env, assets); |
| 87 | |
| 88 | if let Call::Version(msg) = call { |
| 89 | writeln!(std::io::stdout(), "{}", msg.trim_end())?; |
| 90 | return Ok(0); |
| 91 | } else if let Call::Help(msg) = call { |
| 92 | OutputType::oneshot_write(msg)?; |
| 93 | return Ok(0); |
| 94 | } else if let Call::SubCommand(_, cmd) = &call { |
| 95 | // Set before creating the Config, which already asks for the calling process |
| 96 | // (not required for Call::DeltaDiff) |
| 97 | utils::process::set_calling_process( |
| 98 | &cmd.args |
| 99 | .iter() |
| 100 | .map(|arg| OsStr::to_string_lossy(arg).to_string()) |
| 101 | .collect::<Vec<_>>(), |
| 102 | ); |
| 103 | } |
| 104 | let opt = opt.unwrap_or_else(|| delta_unreachable("Opt is set")); |
| 105 | |
| 106 | let subcommand_result = if let Some(shell) = opt.generate_completion { |
| 107 | Some(subcommands::generate_completion::generate_completion_file( |
| 108 | shell, |
| 109 | )) |
| 110 | } else if opt.list_languages { |
| 111 | Some(list_languages()) |
| 112 | } else if opt.list_syntax_themes { |
| 113 | Some(subcommands::list_syntax_themes::list_syntax_themes()) |
| 114 | } else if opt.show_syntax_themes { |
| 115 | Some(subcommands::show_syntax_themes::show_syntax_themes()) |
| 116 | } else if opt.show_themes { |
| 117 | Some(subcommands::show_themes::show_themes( |
| 118 | opt.dark, |
| 119 | opt.light, |
| 120 | opt.computed.color_mode, |
| 121 | )) |
| 122 | } else if opt.show_colors { |
| 123 | Some(subcommands::show_colors::show_colors()) |
| 124 | } else if opt.parse_ansi { |
| 125 | Some(subcommands::parse_ansi::parse_ansi()) |
| 126 | } else { |
| 127 | None |
| 128 | }; |
| 129 | if let Some(result) = subcommand_result { |
| 130 | if let Err(error) = result { |
| 131 | match error.kind() { |
| 132 | ErrorKind::BrokenPipe => {} |
| 133 | _ => fatal(format!("{error}")), |
| 134 | } |
| 135 | } |
| 136 | return Ok(0); |
| 137 | }; |
| 138 | |
| 139 | let _show_config = opt.show_config; |
| 140 | let config = config::Config::from(opt); |
| 141 | |
| 142 | if _show_config { |
| 143 | let stdout = io::stdout(); |
| 144 | let mut stdout = stdout.lock(); |
| 145 | subcommands::show_config::show_config(&config, &mut stdout)?; |
| 146 | return Ok(0); |
| 147 | } |
| 148 | |
| 149 | // The following block structure is because of `writer` and related lifetimes: |
| 150 | let pager_cfg = (&config).into(); |
| 151 | let paging_mode = if capture_output.is_some() { |
| 152 | PagingMode::Capture |
| 153 | } else { |
| 154 | config.paging_mode |
| 155 | }; |
| 156 | let mut output_type = |
| 157 | OutputType::from_mode(&env, paging_mode, config.pager.clone(), &pager_cfg).unwrap(); |
| 158 | let mut writer: &mut dyn Write = if paging_mode == PagingMode::Capture { |
| 159 | &mut capture_output.unwrap() |
| 160 | } else { |
| 161 | output_type.handle().unwrap() |
| 162 | }; |
| 163 | |
| 164 | let subcmd = match call { |
| 165 | Call::DeltaDiff(_, minus, plus) => { |
| 166 | match subcommands::diff::build_diff_cmd(&minus, &plus, &config) { |
| 167 | Err(code) => return Ok(code), |
| 168 | Ok(val) => val, |
| 169 | } |
| 170 | } |
| 171 | Call::SubCommand(_, subcmd) => subcmd, |
| 172 | Call::Delta(_) => SubCommand::none(), |
| 173 | Call::Help(_) | Call::Version(_) => delta_unreachable("help/version handled earlier"), |
| 174 | }; |
| 175 | |
| 176 | if subcmd.is_none() { |
| 177 | // Default delta run: read input from stdin, write to stdout or pager (pager started already^). |
| 178 | |
| 179 | if io::stdin().is_terminal() { |
| 180 | eprintln!( |
| 181 | "\ |
| 182 | The main way to use delta is to configure it as the pager for git: \ |
| 183 | see https://github.com/dandavison/delta#get-started. \ |
| 184 | You can also use delta to diff two files: `delta file_A file_B`." |
| 185 | ); |
| 186 | return Ok(config.error_exit_code); |
| 187 | } |
| 188 | |
| 189 | let res = delta(io::stdin().lock().byte_lines(), &mut writer, &config); |
| 190 | |
| 191 | if let Err(error) = res { |
| 192 | match error.kind() { |
| 193 | ErrorKind::BrokenPipe => return Ok(0), |
| 194 | _ => { |
| 195 | eprintln!("{error}"); |
| 196 | return Ok(config.error_exit_code); |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | Ok(0) |
| 202 | } else { |
| 203 | // First start a subcommand, and pipe input from it to delta(). Also handle |
| 204 | // subcommand exit code and stderr (maybe truncate it, e.g. for git and diff logic). |
| 205 | |
| 206 | let (subcmd_bin, subcmd_args) = subcmd.args.split_first().unwrap(); |
| 207 | let subcmd_kind = subcmd.kind; // for easier {} formatting |
| 208 | |
| 209 | let subcmd_bin_path = match grep_cli::resolve_binary(std::path::PathBuf::from(subcmd_bin)) { |
| 210 | Ok(path) => path, |
| 211 | Err(err) => { |
| 212 | eprintln!("Failed to resolve command {subcmd_bin:?}: {err}"); |
| 213 | return Ok(config.error_exit_code); |
| 214 | } |
| 215 | }; |
| 216 | |
| 217 | let cmd = Command::new(subcmd_bin) |
| 218 | .args(subcmd_args.iter()) |
| 219 | .stdout(Stdio::piped()) |
| 220 | .stderr(Stdio::piped()) |
| 221 | .spawn(); |
| 222 | |
| 223 | if let Err(err) = cmd { |
| 224 | eprintln!("Failed to execute the command {subcmd_bin:?}: {err}"); |
| 225 | return Ok(config.error_exit_code); |
| 226 | } |
| 227 | let mut cmd = cmd.unwrap(); |
| 228 | |
| 229 | let cmd_stdout = cmd |
| 230 | .stdout |
| 231 | .take() |
| 232 | .unwrap_or_else(|| panic!("Failed to open stdout")); |
| 233 | let cmd_stdout_buf = io::BufReader::new(cmd_stdout); |
| 234 | |
| 235 | let res = delta(cmd_stdout_buf.byte_lines(), &mut writer, &config); |
| 236 | |
| 237 | if let Err(error) = res { |
| 238 | let _ = cmd.wait(); // for clippy::zombie_processes |
| 239 | match error.kind() { |
| 240 | ErrorKind::BrokenPipe => return Ok(0), |
| 241 | _ => { |
| 242 | eprintln!("{error}"); |
| 243 | return Ok(config.error_exit_code); |
| 244 | } |
| 245 | } |
| 246 | }; |
| 247 | |
| 248 | let subcmd_status = cmd |
| 249 | .wait() |
| 250 | .unwrap_or_else(|_| { |
| 251 | delta_unreachable(&format!("{subcmd_kind:?} process not running.")); |
| 252 | }) |
| 253 | .code() |
| 254 | .unwrap_or_else(|| { |
| 255 | eprintln!("delta: {subcmd_kind:?} process terminated without exit status."); |
| 256 | config.error_exit_code |
| 257 | }); |
| 258 | |
| 259 | let mut stderr_lines = io::BufReader::new( |
| 260 | cmd.stderr |
| 261 | .unwrap_or_else(|| panic!("Failed to open stderr")), |
| 262 | ) |
| 263 | .lines(); |
| 264 | if let Some(line1) = stderr_lines.next() { |
| 265 | // prefix the first error line with the called subcommand |
| 266 | eprintln!( |
| 267 | "{}: {}", |
| 268 | subcmd_kind, |
| 269 | line1.unwrap_or("<delta: could not parse stderr line>".into()) |
| 270 | ); |
| 271 | } |
| 272 | |
| 273 | // On `git diff` unknown option error: stop after printing the first line above (which is |
| 274 | // an error message), because the entire --help text follows. |
| 275 | if !(subcmd_status == 129 |
| 276 | && matches!(subcmd_kind, SubCmdKind::GitDiff | SubCmdKind::Git(_))) |
| 277 | { |
| 278 | for line in stderr_lines { |
| 279 | eprintln!( |
| 280 | "{}", |
| 281 | line.unwrap_or("<delta: could not parse stderr line>".into()) |
| 282 | ); |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | if matches!(subcmd_kind, SubCmdKind::GitDiff | SubCmdKind::Diff) && subcmd_status >= 2 { |
| 287 | eprintln!( |
| 288 | "{subcmd_kind:?} process failed with exit status {subcmd_status}. Command was: {}", |
| 289 | format_args!( |
| 290 | "{} {}", |
| 291 | subcmd_bin_path.display(), |
| 292 | shell_words::join( |
| 293 | subcmd_args |
| 294 | .iter() |
| 295 | .map(|arg0: &OsString| std::ffi::OsStr::to_string_lossy(arg0)) |
| 296 | ), |
| 297 | ) |
| 298 | ); |
| 299 | } |
| 300 | |
| 301 | Ok(subcmd_status) |
| 302 | } |
| 303 | |
| 304 | // `output_type` drop impl runs here |
| 305 | } |