Debian Codegraph @

src/cli.rs

raw symbols SCIP
1 use std::collections::{HashMap, HashSet};
2 use std::ffi::OsString;
3 use std::path::{Path, PathBuf};
4
5 use bat::assets::HighlightingAssets;
6 use clap::error::Error;
7 use clap::{ArgMatches, ColorChoice, CommandFactory, FromArgMatches, Parser, ValueEnum, ValueHint};
8 use clap_complete::Shell;
9 use console::Term;
10 use lazy_static::lazy_static;
11 use syntect::highlighting::Theme as SyntaxTheme;
12 use syntect::parsing::SyntaxSet;
13
14 use crate::ansi::{ANSI_SGR_BOLD, ANSI_SGR_RESET, ANSI_SGR_UNDERLINE};
15 use crate::color::ColorMode;
16 use crate::config::delta_unreachable;
17 use crate::env::DeltaEnv;
18 use crate::git_config::GitConfig;
19 use crate::options;
20 use crate::subcommands;
21 use crate::utils;
22 use crate::utils::bat::output::PagingMode;
23
24 const TERM_FALLBACK_WIDTH: usize = 79;
25
26 #[derive(Parser)]
27 #[command(
28 name = "delta",
29 about = "A viewer for git and diff output",
30 version,
31 color = ColorChoice::Always,
32 // output is wrapped by delta later:
33 term_width = usize::MAX,
34 max_term_width = usize::MAX,
35 )]
36 pub struct Opt {
37 #[arg(long = "blame-code-style", value_name = "STYLE")]
38 /// Style string for the code section of a git blame line.
39 ///
40 /// By default the code will be syntax-highlighted with the same background color as the blame
41 /// format section of the line (the background color is determined by blame-palette). E.g.
42 /// setting this option to 'syntax' will syntax-highlight the code with no background color.
43 pub blame_code_style: Option<String>,
44
45 #[arg(
46 long = "blame-format",
47 default_value = "{timestamp:<15} {author:<15.14} {commit:<8}",
48 value_name = "FMT"
49 )]
50 /// Format string for git blame commit metadata.
51 ///
52 /// Available placeholders are "{timestamp}", "{author}", and "{commit}".
53 pub blame_format: String,
54
55 #[arg(long = "blame-palette", value_name = "COLORS")]
56 /// Background colors used for git blame lines (space-separated string).
57 ///
58 /// Lines added by the same commit are painted with the same color; colors are recycled as
59 /// needed.
60 pub blame_palette: Option<String>,
61
62 #[arg(
63 long = "blame-separator-format",
64 default_value = "│{n:^4}│",
65 value_name = "FMT"
66 )]
67 /// Separator between the blame format and the code section of a git blame line.
68 ///
69 /// Contains the line number by default. Possible values are "none" to disable line numbers or a format
70 /// string. This may contain one "{n:}" placeholder and will display the line number on every line.
71 /// A type may be added after all other format specifiers and can be separated by '_':
72 /// If type is set to 'block' (e.g. "{n:^4_block}") the line number will only be shown when a new blame
73 /// block starts; or if it is set to 'every-N' the line will be show with every block and every
74 /// N-th (modulo) line.
75 pub blame_separator_format: String,
76
77 #[arg(long = "blame-separator-style", value_name = "STYLE")]
78 /// Style string for the blame-separator-format.
79 pub blame_separator_style: Option<String>,
80
81 #[arg(
82 long = "blame-timestamp-format",
83 default_value = "%Y-%m-%d %H:%M:%S %z",
84 value_name = "FMT"
85 )]
86 /// Format of `git blame` timestamp in raw git output received by delta.
87 pub blame_timestamp_format: String,
88
89 #[arg(long = "blame-timestamp-output-format", value_name = "FMT")]
90 /// Format string for git blame timestamp output.
91 ///
92 /// This string is used for formatting the timestamps in git blame output. It must follow
93 /// the `strftime` format syntax specification. If it is not present, the timestamps will
94 /// be formatted in a human-friendly but possibly less accurate form.
95 ///
96 /// See: <https://docs.rs/chrono/latest/chrono/format/strftime/index.html>
97 pub blame_timestamp_output_format: Option<String>,
98
99 #[arg(long = "color-only")]
100 /// Do not alter the input structurally in any way.
101 ///
102 /// But color and highlight hunk lines according to your delta configuration. This is mainly
103 /// intended for other tools that use delta.
104 pub color_only: bool,
105
106 #[arg(long = "config", default_value = "", value_name = "PATH", value_hint = ValueHint::FilePath)]
107 /// Load the config file at PATH instead of ~/.gitconfig.
108 pub config: String,
109
110 #[arg(
111 long = "commit-decoration-style",
112 default_value = "",
113 value_name = "STYLE"
114 )]
115 /// Style string for the commit hash decoration.
116 ///
117 /// See STYLES section. The style string should contain one of the special attributes 'box',
118 /// 'ul' (underline), 'ol' (overline), or the combination 'ul ol'.
119 pub commit_decoration_style: String,
120
121 #[arg(
122 long = "commit-regex",
123 default_value = r"^commit ",
124 value_name = "REGEX"
125 )]
126 /// Regular expression used to identify the commit line when parsing git output.
127 pub commit_regex: String,
128
129 #[arg(long = "commit-style", default_value = "raw", value_name = "STYLE")]
130 /// Style string for the commit hash line.
131 ///
132 /// See STYLES section. The style 'omit' can be used to remove the commit hash line from the
133 /// output.
134 pub commit_style: String,
135
136 #[arg(long = "dark")]
137 /// Use default colors appropriate for a dark terminal background.
138 ///
139 /// For more control, see the style options and --syntax-theme.
140 pub dark: bool,
141
142 #[arg(long = "default-language", value_name = "LANG", default_value = "txt")]
143 /// Default language used for syntax highlighting.
144 ///
145 /// Used as a fallback when the language cannot be inferred from a filename. It will
146 /// typically make sense to set this in the per-repository config file '.git/config'.
147 pub default_language: String,
148
149 /// Detect whether or not the terminal is dark or light by querying for its colors.
150 ///
151 /// Ignored if either `--dark` or `--light` is specified.
152 ///
153 /// Querying the terminal for its colors requires "exclusive" access
154 /// since delta reads/writes from the terminal and enables/disables raw mode.
155 /// This causes race conditions with pagers such as less when they are attached to the
156 /// same terminal as delta.
157 ///
158 /// This is usually only an issue when the output is manually piped to a pager.
159 /// For example: `git diff | delta | less`.
160 /// Otherwise, if delta starts the pager itself, then there's no race condition
161 /// since the pager is started *after* the color is detected.
162 ///
163 /// `auto` tries to account for these situations by testing if the output is redirected.
164 ///
165 /// The `--color-only` option is treated as an indicator that delta is used
166 /// as `interactive.diffFilter`. In this case the color is queried from the terminal even
167 /// though the output is redirected.
168 ///
169 #[arg(long = "detect-dark-light", value_enum, default_value_t = DetectDarkLight::default())]
170 pub detect_dark_light: DetectDarkLight,
171
172 #[arg(
173 long = "diff-args",
174 short = '@',
175 default_value = "",
176 value_name = "STRING"
177 )]
178 /// Extra arguments to pass to `git diff` when using delta to diff two files.
179 ///
180 /// E.g. `delta --diff-args=-U999 file_1 file_2` is equivalent to
181 /// `git diff --no-index --color -U999 file_1 file_2 | delta`.
182 ///
183 /// If you use process substitution (`delta <(command_1) <(command_2)`) and your git version
184 /// doesn't support it, then delta will fall back to `diff` instead of `git diff`.
185 pub diff_args: String,
186
187 #[arg(long = "diff-highlight")]
188 /// Emulate diff-highlight.
189 ///
190 /// <https://github.com/git/git/tree/master/contrib/diff-highlight>
191 pub diff_highlight: bool,
192
193 #[arg(long = "diff-so-fancy")]
194 /// Emulate diff-so-fancy.
195 ///
196 /// <https://github.com/so-fancy/diff-so-fancy>
197 pub diff_so_fancy: bool,
198
199 #[arg(long = "diff-stat-align-width", default_value = "48", value_name = "N")]
200 /// Width allocated for file paths in a diff stat section.
201 ///
202 /// If a relativized file path exceeds this width then the diff stat will be misaligned.
203 pub diff_stat_align_width: usize,
204
205 #[arg(long = "features", value_name = "FEATURES")]
206 /// Names of delta features to activate (space-separated).
207 ///
208 /// A feature is a named collection of delta options in ~/.gitconfig. See FEATURES section. The
209 /// environment variable DELTA_FEATURES can be set to a space-separated list of feature names.
210 /// If this is preceded with a + character, the features from the environment variable will be added
211 /// to those specified in git config. E.g. DELTA_FEATURES=+side-by-side can be used to activate
212 /// side-by-side temporarily (use DELTA_FEATURES=+ to go back to just the features from git config).
213 pub features: Option<String>,
214
215 #[arg(
216 long = "file-added-label",
217 default_value = "added:",
218 value_name = "STRING"
219 )]
220 /// Text to display before an added file path.
221 ///
222 /// Used in the default value of navigate-regex.
223 pub file_added_label: String,
224
225 #[arg(
226 long = "file-copied-label",
227 default_value = "copied:",
228 value_name = "STRING"
229 )]
230 /// Text to display before a copied file path.
231 pub file_copied_label: String,
232
233 #[arg(
234 long = "file-decoration-style",
235 default_value = "blue ul",
236 value_name = "STYLE"
237 )]
238 /// Style string for the file decoration.
239 ///
240 /// See STYLES section. The style string should contain one of the special attributes 'box',
241 /// 'ul' (underline), 'ol' (overline), or the combination 'ul ol'.
242 pub file_decoration_style: String,
243
244 #[arg(
245 long = "file-modified-label",
246 default_value = "",
247 value_name = "STRING"
248 )]
249 /// Text to display before a modified file path.
250 ///
251 /// Used in the default value of navigate-regex.
252 pub file_modified_label: String,
253
254 #[arg(
255 long = "file-removed-label",
256 default_value = "removed:",
257 value_name = "STRING"
258 )]
259 /// Text to display before a removed file path.
260 ///
261 /// Used in the default value of navigate-regex.
262 pub file_removed_label: String,
263
264 #[arg(
265 long = "file-renamed-label",
266 default_value = "renamed:",
267 value_name = "STRING"
268 )]
269 /// Text to display before a renamed file path.
270 ///
271 /// Used in the default value of navigate-regex.
272 pub file_renamed_label: String,
273
274 #[arg(long = "file-style", default_value = "blue", value_name = "STYLE")]
275 /// Style string for the file section.
276 ///
277 /// See STYLES section. The style 'omit' can be used to remove the file section from the output.
278 pub file_style: String,
279
280 #[arg(long = "file-transformation", value_name = "SED_CMD")]
281 /// Sed-style command transforming file paths for display.
282 pub file_regex_replacement: Option<String>,
283
284 #[arg(long = "generate-completion")]
285 /// Print completion file for the given shell.
286 pub generate_completion: Option<Shell>,
287
288 #[arg(long = "grep-context-line-style", value_name = "STYLE")]
289 /// Style string for non-matching lines of grep output.
290 ///
291 /// See STYLES section. Defaults to zero-style.
292 pub grep_context_line_style: Option<String>,
293
294 #[arg(
295 long = "grep-file-style",
296 default_value = "magenta",
297 value_name = "STYLE"
298 )]
299 /// Style string for file paths in grep output.
300 ///
301 /// See STYLES section.
302 pub grep_file_style: String,
303
304 #[arg(long = "grep-header-decoration-style", value_name = "STYLE")]
305 /// Style string for the header decoration in grep output.
306 ///
307 /// Default is "none" when grep-output-type-is "ripgrep", otherwise defaults
308 /// to value of header-decoration-style. See hunk-header-decoration-style.
309 pub grep_header_decoration_style: Option<String>,
310
311 #[arg(long = "grep-header-file-style", value_name = "STYLE")]
312 /// Style string for the file path part of the header in grep output.
313 ///
314 /// See hunk_header_file_style.
315 pub grep_header_file_style: Option<String>,
316
317 #[arg(
318 long = "grep-line-number-style",
319 default_value = "green",
320 value_name = "STYLE"
321 )]
322 /// Style string for line numbers in grep output.
323 ///
324 /// See STYLES section.
325 pub grep_line_number_style: String,
326
327 #[arg(long = "grep-output-type", value_name = "OUTPUT_TYPE", value_parser = ["ripgrep", "classic"])]
328 /// Grep output format. Possible values:
329 /// "ripgrep" - file name printed once, followed by matching lines within that file, each preceded by a line number.
330 /// "classic" - file name:line number, followed by matching line.
331 /// Default is "ripgrep" if `rg --json` format is detected, otherwise "classic".
332 pub grep_output_type: Option<String>,
333
334 #[arg(long = "grep-match-line-style", value_name = "STYLE")]
335 /// Style string for matching lines of grep output.
336 ///
337 /// See STYLES section. Defaults to plus-style.
338 pub grep_match_line_style: Option<String>,
339
340 #[arg(long = "grep-match-word-style", value_name = "STYLE")]
341 /// Style string for the matching substrings within a matching line of grep output.
342 ///
343 /// See STYLES section. Defaults to plus-style.
344 pub grep_match_word_style: Option<String>,
345
346 #[arg(
347 long = "grep-separator-symbol",
348 default_value = ":",
349 value_name = "STRING"
350 )]
351 /// Separator symbol printed after the file path and line number in grep output.
352 ///
353 /// Defaults to ":" for both match and context lines, since many terminal emulators recognize
354 /// constructs like "/path/to/file:7:". However, standard grep output uses "-" for context
355 /// lines: set this option to "keep" to keep the original separator symbols.
356 pub grep_separator_symbol: String,
357
358 #[arg(
359 long = "hunk-header-decoration-style",
360 default_value = "blue box",
361 value_name = "STYLE"
362 )]
363 /// Style string for the hunk-header decoration.
364 ///
365 /// See STYLES section. The style string should contain one of the special attributes 'box',
366 /// 'ul' (underline), 'ol' (overline), or the combination 'ul ol'.
367 pub hunk_header_decoration_style: String,
368
369 #[arg(
370 long = "hunk-header-file-style",
371 default_value = "blue",
372 value_name = "STYLE"
373 )]
374 /// Style string for the file path part of the hunk-header.
375 ///
376 /// See STYLES section. The file path will only be displayed if hunk-header-style contains the
377 /// 'file' special attribute.
378 pub hunk_header_file_style: String,
379
380 #[arg(
381 long = "hunk-header-line-number-style",
382 default_value = "blue",
383 value_name = "STYLE"
384 )]
385 /// Style string for the line number part of the hunk-header.
386 ///
387 /// See STYLES section. The line number will only be displayed if hunk-header-style contains the
388 /// 'line-number' special attribute.
389 pub hunk_header_line_number_style: String,
390
391 #[arg(
392 long = "hunk-header-style",
393 default_value = "line-number syntax",
394 value_name = "STYLE"
395 )]
396 /// Style string for the hunk-header.
397 ///
398 /// See STYLES section. Special attributes 'file' and 'line-number' can be used to include the
399 /// file path, and number of first hunk line, in the hunk header. The style 'omit' can be used
400 /// to remove the hunk header section from the output.
401 pub hunk_header_style: String,
402
403 #[arg(long = "hunk-label", default_value = "", value_name = "STRING")]
404 /// Text to display before a hunk header.
405 ///
406 /// Used in the default value of navigate-regex.
407 pub hunk_label: String,
408
409 #[arg(long = "hyperlinks")]
410 /// Render commit hashes, file names, and line numbers as hyperlinks.
411 ///
412 /// Following the hyperlink spec for terminal emulators:
413 /// <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>. By default, file names
414 /// and line numbers link to the local file using a file URL, whereas commit hashes link to the
415 /// commit in GitHub, if the remote repository is hosted by GitHub. See
416 /// --hyperlinks-file-link-format for full control over the file URLs emitted. Hyperlinks are
417 /// supported by several common terminal emulators. To make them work, you must use less
418 /// version >= 581 with the -R flag (or use -r with older less versions, but this will break
419 /// e.g. --navigate). If you use tmux, then you will also need a patched fork of tmux (see
420 /// <https://github.com/dandavison/tmux>).
421 pub hyperlinks: bool,
422
423 #[arg(long = "hyperlinks-commit-link-format", value_name = "FMT")]
424 /// Format string for commit hyperlinks (requires --hyperlinks).
425 ///
426 /// The placeholder "{commit}" will be replaced by the commit hash. For example:
427 /// --hyperlinks-commit-link-format='https://mygitrepo/{commit}/'
428 pub hyperlinks_commit_link_format: Option<String>,
429
430 #[arg(
431 long = "hyperlinks-file-link-format",
432 default_value = "file://{path}",
433 value_name = "FMT"
434 )]
435 /// Format string for file hyperlinks (requires --hyperlinks).
436 ///
437 /// Placeholders "{path}" and "{line}" will be replaced by the absolute file path and the line
438 /// number; "{host}" with the hostname delta is currently running on. The default is to create
439 /// a hyperlink containing a standard file URI with only the filename, which your terminal or
440 /// OS should handle. You can specify any scheme, such as "file-line://{path}:{line}" and
441 /// register an application to handle it. See
442 /// <https://dandavison.github.io/delta/hyperlinks.html> for details.
443 pub hyperlinks_file_link_format: String,
444
445 #[arg(
446 long = "inline-hint-style",
447 default_value = "blue",
448 value_name = "STYLE"
449 )]
450 /// Style string for short inline hint text.
451 ///
452 /// This styles certain content added by delta to the original diff such as special characters
453 /// to highlight tabs, and the symbols used to indicate wrapped lines. See STYLES section.
454 pub inline_hint_style: String,
455
456 #[arg(
457 long = "inspect-raw-lines",
458 default_value = "true",
459 value_name = "true|false",
460 value_parser = ["true", "false"],
461 )]
462 /// Kill-switch for --color-moved support.
463 ///
464 /// Whether to examine ANSI color escape sequences in raw lines received from Git and handle
465 /// lines colored in certain ways specially. This is on by default: it is how Delta supports
466 /// Git's --color-moved feature. Set this to "false" to disable this behavior.
467 pub inspect_raw_lines: String,
468
469 #[arg(long = "keep-plus-minus-markers")]
470 /// Prefix added/removed lines with a +/- character, as git does.
471 ///
472 /// By default, delta does not emit any prefix, so code can be copied directly from delta's
473 /// output.
474 pub keep_plus_minus_markers: bool,
475
476 #[arg(long = "light")]
477 /// Use default colors appropriate for a light terminal background.
478 ///
479 /// For more control, see the style options and --syntax-theme.
480 pub light: bool,
481
482 #[arg(long = "line-buffer-size", default_value = "32", value_name = "N")]
483 /// Size of internal line buffer.
484 ///
485 /// Delta compares the added and removed versions of nearby lines in order to detect and
486 /// highlight changes at the level of individual words/tokens. Therefore, nearby lines must be
487 /// buffered internally before they are painted and emitted. Increasing this value might improve
488 /// highlighting of some large diff hunks. However, setting this to a high value will adversely
489 /// affect delta's performance when entire files are added/removed.
490 pub line_buffer_size: usize,
491
492 #[arg(long = "line-fill-method", value_name = "STRING", value_parser = ["ansi", "spaces"])]
493 /// Line-fill method in side-by-side mode.
494 ///
495 /// How to extend the background color to the end of the line in side-by-side mode. Can be ansi
496 /// (default) or spaces (default if output is not to a terminal). Has no effect if
497 /// --width=variable is given.
498 pub line_fill_method: Option<String>,
499
500 #[arg(short = 'n', long = "line-numbers")]
501 /// Display line numbers next to the diff.
502 ///
503 /// See LINE NUMBERS section.
504 pub line_numbers: bool,
505
506 #[arg(
507 long = "line-numbers-left-format",
508 default_value = "{nm:^4}â‹®",
509 value_name = "FMT"
510 )]
511 /// Format string for the left column of line numbers.
512 ///
513 /// A typical value would be "{nm:^4}â‹®" which means to display the line numbers of the minus
514 /// file (old version), center-aligned, padded to a width of 4 characters, followed by a
515 /// dividing character. See the LINE NUMBERS section.
516 pub line_numbers_left_format: String,
517
518 #[arg(
519 long = "line-numbers-left-style",
520 default_value = "auto",
521 value_name = "STYLE"
522 )]
523 /// Style string for the left column of line numbers.
524 ///
525 /// See STYLES and LINE NUMBERS sections.
526 pub line_numbers_left_style: String,
527
528 #[arg(
529 long = "line-numbers-minus-style",
530 default_value = "auto",
531 value_name = "STYLE"
532 )]
533 /// Style string for line numbers in the old (minus) version of the file.
534 ///
535 /// See STYLES and LINE NUMBERS sections.
536 pub line_numbers_minus_style: String,
537
538 #[arg(
539 long = "line-numbers-plus-style",
540 default_value = "auto",
541 value_name = "STYLE"
542 )]
543 /// Style string for line numbers in the new (plus) version of the file.
544 ///
545 /// See STYLES and LINE NUMBERS sections.
546 pub line_numbers_plus_style: String,
547
548 #[arg(
549 long = "line-numbers-right-format",
550 default_value = "{np:^4}│",
551 value_name = "FMT"
552 )]
553 /// Format string for the right column of line numbers.
554 ///
555 /// A typical value would be "{np:^4}│ " which means to display the line numbers of the plus
556 /// file (new version), center-aligned, padded to a width of 4 characters, followed by a
557 /// dividing character, and a space. See the LINE NUMBERS section.
558 pub line_numbers_right_format: String,
559
560 #[arg(
561 long = "line-numbers-right-style",
562 default_value = "auto",
563 value_name = "STYLE"
564 )]
565 /// Style string for the right column of line numbers.
566 ///
567 /// See STYLES and LINE NUMBERS sections.
568 pub line_numbers_right_style: String,
569
570 #[arg(
571 long = "line-numbers-zero-style",
572 default_value = "auto",
573 value_name = "STYLE"
574 )]
575 /// Style string for line numbers in unchanged (zero) lines.
576 ///
577 /// See STYLES and LINE NUMBERS sections.
578 pub line_numbers_zero_style: String,
579
580 #[arg(long = "list-languages")]
581 /// List supported languages and associated file extensions.
582 pub list_languages: bool,
583
584 #[arg(long = "list-syntax-themes")]
585 /// List available syntax-highlighting color themes.
586 pub list_syntax_themes: bool,
587
588 #[arg(long = "map-styles", value_name = "STYLES_MAP")]
589 /// Map styles encountered in raw input to desired output styles.
590 ///
591 /// An example is --map-styles='bold purple => red "#eeeeee", bold cyan => syntax "#eeeeee"'
592 pub map_styles: Option<String>,
593
594 #[arg(long = "max-line-distance", default_value = "0.6", value_name = "DIST")]
595 /// Maximum line pair distance parameter in within-line diff algorithm.
596 ///
597 /// This parameter is the maximum distance (0.0 - 1.0) between two lines for them to be inferred
598 /// to be homologous. Homologous line pairs are highlighted according to the deletion and
599 /// insertion operations transforming one into the other.
600 pub max_line_distance: f64,
601
602 #[arg(
603 long = "max-syntax-highlighting-length",
604 default_value = "400",
605 value_name = "N"
606 )]
607 /// Stop syntax highlighting lines after this many characters.
608 ///
609 /// To always highlight entire lines, set to zero - but note that delta will be slow on very
610 /// long lines (e.g. minified .js).
611 pub max_syntax_length: usize,
612
613 #[arg(long = "max-line-length", default_value = "3000", value_name = "N")]
614 /// Truncate lines longer than this.
615 ///
616 /// To prevent any truncation, set to zero. When wrapping lines this does nothing as it is
617 /// overwritten to fit at least all visible characters, see `--wrap-max-lines`.
618 pub max_line_length: usize,
619
620 #[arg(
621 long = "merge-conflict-begin-symbol",
622 default_value = "â–¼",
623 value_name = "STRING"
624 )]
625 /// String marking the beginning of a merge conflict region.
626 ///
627 /// The string will be repeated until it reaches the required length.
628 pub merge_conflict_begin_symbol: String,
629
630 #[arg(
631 long = "merge-conflict-end-symbol",
632 default_value = "â–²",
633 value_name = "STRING"
634 )]
635 /// String marking the end of a merge conflict region.
636 ///
637 /// The string will be repeated until it reaches the required length.
638 pub merge_conflict_end_symbol: String,
639
640 #[arg(
641 long = "merge-conflict-ours-diff-header-decoration-style",
642 default_value = "box",
643 value_name = "STYLE"
644 )]
645 /// Style string for the decoration of the header above the 'ours' merge conflict diff.
646 ///
647 /// This styles the decoration of the header above the diff between the ancestral commit and the
648 /// 'ours' branch. See STYLES section. The style string should contain one of the special
649 /// attributes 'box', 'ul' (underline), 'ol' (overline), or the combination 'ul ol'.
650 pub merge_conflict_ours_diff_header_decoration_style: String,
651
652 #[arg(
653 long = "merge-conflict-ours-diff-header-style",
654 default_value = "normal",
655 value_name = "STYLE"
656 )]
657 /// Style string for the header above the 'ours' branch merge conflict diff.
658 ///
659 /// See STYLES section.
660 pub merge_conflict_ours_diff_header_style: String,
661
662 #[arg(
663 long = "merge-conflict-theirs-diff-header-decoration-style",
664 default_value = "box",
665 value_name = "STYLE"
666 )]
667 /// Style string for the decoration of the header above the 'theirs' merge conflict diff.
668 ///
669 /// This styles the decoration of the header above the diff between the ancestral commit and
670 /// 'their' branch. See STYLES section. The style string should contain one of the special
671 /// attributes 'box', 'ul' (underline), 'ol' (overline), or the combination 'ul ol'.
672 pub merge_conflict_theirs_diff_header_decoration_style: String,
673
674 #[arg(
675 long = "merge-conflict-theirs-diff-header-style",
676 default_value = "normal",
677 value_name = "STYLE"
678 )]
679 /// Style string for the header above the 'theirs' branch merge conflict diff.
680 ///
681 /// This styles the header above the diff between the ancestral commit and 'their' branch. See
682 /// STYLES section.
683 pub merge_conflict_theirs_diff_header_style: String,
684
685 #[arg(
686 long = "minus-empty-line-marker-style",
687 default_value = "normal auto",
688 value_name = "STYLE"
689 )]
690 /// Style string for removed empty line marker.
691 ///
692 /// Used only if --minus-style has no background color.
693 pub minus_empty_line_marker_style: String,
694
695 #[arg(
696 long = "minus-emph-style",
697 default_value = "normal auto",
698 value_name = "STYLE"
699 )]
700 /// Style string for emphasized sections of removed lines.
701 ///
702 /// See STYLES section.
703 pub minus_emph_style: String,
704
705 #[arg(
706 long = "minus-non-emph-style",
707 default_value = "minus-style",
708 value_name = "STYLE"
709 )]
710 /// Style string for non-emphasized sections of removed lines that have an emphasized section.
711 ///
712 /// See STYLES section.
713 pub minus_non_emph_style: String,
714
715 #[arg(
716 long = "minus-style",
717 default_value = "normal auto",
718 value_name = "STYLE"
719 )]
720 /// Style string for removed lines.
721 ///
722 /// See STYLES section.
723 pub minus_style: String,
724
725 #[arg(long = "navigate")]
726 /// Activate diff navigation.
727 ///
728 /// Use n to jump forwards and N to jump backwards. To change the file labels used see
729 /// --file-added-label, --file-copied-label, --file-modified-label, --file-removed-label, --file-renamed-label.
730 pub navigate: bool,
731
732 #[arg(long = "navigate-regex", value_name = "REGEX")]
733 /// Regular expression defining navigation stop points.
734 pub navigate_regex: Option<String>,
735
736 #[arg(long = "no-gitconfig")]
737 /// Do not read any settings from git config.
738 ///
739 /// See GIT CONFIG section.
740 pub no_gitconfig: bool,
741
742 #[arg(long = "pager", value_name = "CMD")]
743 /// Which pager to use.
744 ///
745 /// The default pager is `less`. You can also change pager by setting the
746 /// environment variable DELTA_PAGER, or PAGER. This option overrides these
747 /// environment variables.
748 pub pager: Option<String>,
749
750 #[arg(
751 long = "paging",
752 default_value = "auto",
753 value_name = "auto|always|never",
754 value_parser = ["auto", "always", "never"],
755 )]
756 /// Whether to use a pager when displaying output.
757 ///
758 /// Options are: auto, always, and never.
759 pub paging_mode: String,
760
761 #[arg(long = "parse-ansi")]
762 /// Display ANSI color escape sequences in human-readable form.
763 ///
764 /// Example usage: git show --color=always | delta --parse-ansi
765 /// This can be used to help identify input style strings to use with map-styles.
766 pub parse_ansi: bool,
767
768 #[arg(
769 long = "plus-emph-style",
770 default_value = "syntax auto",
771 value_name = "STYLE"
772 )]
773 /// Style string for emphasized sections of added lines.
774 ///
775 /// See STYLES section.
776 pub plus_emph_style: String,
777
778 #[arg(
779 long = "plus-empty-line-marker-style",
780 default_value = "normal auto",
781 value_name = "STYLE"
782 )]
783 /// Style string for added empty line marker.
784 ///
785 /// Used only if --plus-style has no background color.
786 pub plus_empty_line_marker_style: String,
787
788 #[arg(
789 long = "plus-non-emph-style",
790 default_value = "plus-style",
791 value_name = "STYLE"
792 )]
793 /// Style string for non-emphasized sections of added lines that have an emphasized section.
794 ///
795 /// See STYLES section.
796 pub plus_non_emph_style: String,
797
798 #[arg(
799 long = "plus-style",
800 default_value = "syntax auto",
801 value_name = "STYLE"
802 )]
803 /// Style string for added lines.
804 ///
805 /// See STYLES section.
806 pub plus_style: String,
807
808 #[arg(long = "raw")]
809 /// Do not alter the input in any way.
810 ///
811 /// This is mainly intended for testing delta.
812 pub raw: bool,
813
814 #[arg(long = "relative-paths")]
815 /// Output all file paths relative to the current directory.
816 ///
817 /// This means that they will resolve correctly when clicked on or used in shell commands.
818 pub relative_paths: bool,
819
820 #[arg(long = "right-arrow", default_value = "⟶ ", value_name = "STRING")]
821 /// Text to display with a changed file path.
822 ///
823 /// For example, a unified diff heading, a rename, or a chmod.
824 pub right_arrow: String,
825
826 #[arg(long = "show-colors")]
827 /// Show available named colors.
828 ///
829 /// In addition to named colors, arbitrary colors can be specified using RGB hex codes. See
830 /// COLORS section.
831 pub show_colors: bool,
832
833 #[arg(long = "show-config")]
834 /// Display the active values for all Delta options.
835 ///
836 /// Style string options are displayed with foreground and background colors. This can be used to
837 /// experiment with colors by combining this option with other options such as --minus-style,
838 /// --zero-style, --plus-style, --light, --dark, etc.
839 pub show_config: bool,
840
841 #[arg(long = "show-syntax-themes")]
842 /// Show example diff for available syntax-highlighting themes.
843 ///
844 /// If diff output is supplied on standard input then this will be used for the demo. For
845 /// example: `git show | delta --show-syntax-themes`.
846 pub show_syntax_themes: bool,
847
848 #[arg(long = "show-themes")]
849 /// Show example diff for available delta themes.
850 ///
851 /// A delta theme is a delta named feature (see --features) that sets either `light` or `dark`.
852 /// See <https://github.com/dandavison/delta#custom-color-themes>. If diff output is supplied on
853 /// standard input then this will be used for the demo. For example: `git show | delta
854 /// --show-themes`. By default shows dark or light themes only, according to whether delta is in
855 /// dark or light mode (as set by the user or inferred from BAT_THEME). To control the themes
856 /// shown, use --dark or --light, or both, on the command line together with this option.
857 pub show_themes: bool,
858
859 #[arg(short = 's', long = "side-by-side")]
860 /// Display diffs in side-by-side layout.
861 pub side_by_side: bool,
862
863 #[arg(long = "syntax-theme", value_name = "SYNTAX_THEME")]
864 /// The syntax-highlighting theme to use.
865 ///
866 /// Use --show-syntax-themes to demo available themes. Defaults to the value of the BAT_THEME
867 /// environment variable, if that contains a valid theme name. --syntax-theme=none disables all
868 /// syntax highlighting.
869 pub syntax_theme: Option<String>,
870
871 #[arg(long = "tabs", default_value = "8", value_name = "N")]
872 /// The number of spaces to replace tab characters with.
873 ///
874 /// Use --tabs=0 to pass tab characters through directly, but note that in that case delta will
875 /// calculate line widths assuming tabs occupy one character's width on the screen: if your
876 /// terminal renders tabs as more than one character wide then delta's output will look
877 /// incorrect.
878 pub tab_width: usize,
879
880 #[arg(
881 long = "true-color",
882 default_value = "auto",
883 value_name = "auto|always|never",
884 value_parser = ["auto", "always", "never"],
885 )]
886 /// Whether to emit 24-bit ("true color") RGB color codes.
887 ///
888 /// Options are auto, always, and never. "auto" means that delta will emit 24-bit color codes if
889 /// the environment variable COLORTERM has the value "truecolor" or "24bit". If your terminal
890 /// application (the application you use to enter commands at a shell prompt) supports 24 bit
891 /// colors, then it probably already sets this environment variable, in which case you don't
892 /// need to do anything.
893 pub true_color: String,
894
895 #[arg(
896 long = "whitespace-error-style",
897 default_value = "auto auto",
898 value_name = "STYLE"
899 )]
900 /// Style string for whitespace errors.
901 ///
902 /// Defaults to color.diff.whitespace if that is set in git config, or else 'magenta reverse'.
903 pub whitespace_error_style: String,
904
905 #[arg(short = 'w', long = "width", value_name = "N")]
906 /// The width of underline/overline decorations.
907 ///
908 /// Examples: "72" (exactly 72 characters), "-2" (auto-detected terminal width minus 2). An
909 /// expression such as "74-2" is also valid (equivalent to 72 but may be useful if the caller
910 /// has a variable holding the value "74"). Use --width=variable to extend decorations and
911 /// background colors to the end of the text only. Otherwise background colors extend to the
912 /// full terminal width.
913 pub width: Option<String>,
914
915 #[arg(long = "word-diff-regex", default_value = r"\w+", value_name = "REGEX")]
916 /// Regular expression defining a 'word' in within-line diff algorithm.
917 ///
918 /// The regular expression used to decide what a word is for the within-line highlight
919 /// algorithm. For less fine-grained matching than the default try --word-diff-regex="\S+"
920 /// --max-line-distance=1.0 (this is more similar to `git --word-diff`).
921 pub tokenization_regex: String,
922
923 #[arg(long = "wrap-left-symbol", default_value = "↵", value_name = "STRING")]
924 /// End-of-line wrapped content symbol (left-aligned).
925 ///
926 /// Symbol added to the end of a line indicating that the content has been wrapped onto the next
927 /// line and continues left-aligned.
928 pub wrap_left_symbol: String,
929
930 #[arg(long = "wrap-max-lines", default_value = "2", value_name = "N")]
931 /// How often a line should be wrapped if it does not fit.
932 ///
933 /// Zero means to never wrap. Any content which does not fit after wrapping will be truncated. A
934 /// value of "unlimited" means a line will be wrapped as many times as required.
935 pub wrap_max_lines: String,
936
937 #[arg(
938 long = "wrap-right-percent",
939 default_value = "37.0",
940 value_name = "PERCENT"
941 )]
942 /// Threshold for right-aligning wrapped content.
943 ///
944 /// If the length of the remaining wrapped content, as a percentage of width, is less than this
945 /// quantity it will be right-aligned. Otherwise it will be left-aligned.
946 pub wrap_right_percent: String,
947
948 #[arg(
949 long = "wrap-right-prefix-symbol",
950 default_value = "…",
951 value_name = "STRING"
952 )]
953 /// Pre-wrapped content symbol (right-aligned).
954 ///
955 /// Symbol displayed before right-aligned wrapped content.
956 pub wrap_right_prefix_symbol: String,
957
958 #[arg(long = "wrap-right-symbol", default_value = "↴", value_name = "STRING")]
959 /// End-of-line wrapped content symbol (right-aligned).
960 ///
961 /// Symbol added to the end of a line indicating that the content has been wrapped onto the next
962 /// line and continues right-aligned.
963 pub wrap_right_symbol: String,
964
965 #[arg(
966 long = "zero-style",
967 default_value = "syntax normal",
968 value_name = "STYLE"
969 )]
970 /// Style string for unchanged lines.
971 ///
972 /// See STYLES section.
973 pub zero_style: String,
974
975 #[arg(long = "24-bit-color", value_name = "auto|always|never", value_parser = ["auto", "always", "never"])]
976 /// Deprecated: use --true-color.
977 pub _24_bit_color: Option<String>,
978
979 /// First file to be compared when delta is being used to diff two files.
980 ///
981 /// `delta file1 file2` is equivalent to `diff -u file1 file2 | delta`.
982 pub minus_file: Option<PathBuf>,
983
984 /// Second file to be compared when delta is being used to diff two files.
985 pub plus_file: Option<PathBuf>,
986
987 #[arg(skip)]
988 pub computed: ComputedValues,
989
990 #[arg(skip)]
991 pub git_config: Option<GitConfig>,
992
993 #[arg(skip)]
994 pub env: DeltaEnv,
995 }
996
997 fn get_after_long_help(is_term: bool, no_indent: &str, no_wrap: &str) -> String {
998 let i0 = no_indent;
999 let l = no_wrap;
1000
1001 #[allow(non_snake_case)]
1002 // <H>header</H> and <u>underline</u>
1003 let (H_, _H, u_, _u) = if is_term {
1004 (
1005 format!("{ANSI_SGR_BOLD}{ANSI_SGR_UNDERLINE}"),
1006 ANSI_SGR_RESET,
1007 ANSI_SGR_UNDERLINE,
1008 ANSI_SGR_RESET,
1009 )
1010 } else {
1011 ("".to_string(), "", "", "")
1012 };
1013
1014 format!(
1015 r##"
1016
1017 {i0}{H_}Git config{_H}
1018
1019 By default, delta takes settings from a section named "delta" in git config files, if one is present. The git config file to use for delta options will usually be ~/.gitconfig, but delta follows the rules given in <https://git-scm.com/docs/git-config#FILES>. Most delta options can be given in a git config file, using the usual option names but without the initial '--'. An example is
1020
1021 [delta]
1022 line-numbers = true
1023 zero-style = dim syntax
1024
1025
1026 {i0}{H_}Features{_H}
1027
1028 A feature is a named collection of delta options in git config. An example is:
1029
1030 [delta "my-delta-feature"]
1031 syntax-theme = Dracula
1032 plus-style = bold syntax "#002800"
1033
1034 To activate those options, you would use:
1035
1036 delta --features my-delta-feature
1037
1038 A feature name may not contain whitespace. You can activate multiple features:
1039
1040 {l}[delta]
1041 {l} features = my-highlight-styles-colors-feature my-line-number-styles-feature
1042
1043 If more than one feature sets the same option, the last one wins.
1044
1045 If an option is present in the [delta] section, then features are not considered at all.
1046
1047 If you want an option to be fully overridable by a feature and also have a non default value when no features are used, then you need to define a "default" feature and include it in the main delta configuration.
1048
1049 For instance:
1050
1051 [delta]
1052 feature = default-feature
1053
1054 [delta "default-feature"]
1055 width = 123
1056
1057 At this point, you can override features set in the command line or in the environment variables and the "last one wins" rules will apply as expected.
1058
1059
1060 {i0}{H_}Styles{_H}
1061
1062 All options that have a name like --*-style work the same way. It is very similar to how colors/styles are specified in a gitconfig file: <https://git-scm.com/docs/git-config#Documentation/git-config.txt-color>
1063
1064 Here is an example:
1065
1066 --minus-style 'red bold ul "#ffeeee"'
1067
1068 That means: For removed lines, set the foreground (text) color to 'red', make it bold and underlined, and set the background color to '#ffeeee'.
1069
1070 See the {u_}Colors{_u} section below for how to specify a color. In addition to real colors, there are 4 special color names: 'auto', 'normal', 'raw', and 'syntax'.
1071
1072 Here is an example of using special color names together with a single attribute:
1073
1074 --minus-style 'syntax bold auto'
1075
1076 That means: For removed lines, syntax-highlight the text, and make it bold, and do whatever delta normally does for the background.
1077
1078 The available attributes are: 'blink', 'bold', 'dim', 'hidden', 'italic', 'reverse', 'strike', and 'ul' (or 'underline').
1079
1080 The attribute 'omit' is supported by commit-style, file-style, and hunk-header-style, meaning to remove the element entirely from the output.
1081
1082 A complete description of the style string syntax follows:
1083
1084 - If the input that delta is receiving already has colors, and you want delta to output those colors unchanged, then use the special style string 'raw'. Otherwise, delta will strip any colors from its input.
1085
1086 - A style string consists of 0, 1, or 2 colors, together with an arbitrary number of style attributes, all separated by spaces.
1087
1088 - The first color is the foreground (text) color. The second color is the background color. Attributes can go in any position.
1089
1090 - This means that in order to specify a background color you must also specify a foreground (text) color.
1091
1092 - If you want delta to choose one of the colors automatically, then use the special color 'auto'. This can be used for both foreground and background.
1093
1094 - If you want the foreground/background color to be your terminal's foreground/background color, then use the special color 'normal'.
1095
1096 - If you want the foreground text to be syntax-highlighted according to its language, then use the special foreground color 'syntax'. This can only be used for the foreground (text).
1097
1098 - The minimal style specification is the empty string ''. This means: do not apply any colors or styling to the element in question.
1099
1100
1101 {i0}{H_}Colors{_H}
1102
1103 There are four ways to specify a color (this section applies to foreground and background colors within a style string):
1104
1105 1. CSS color name
1106
1107 Any of the 140 color names used in CSS: <https://www.w3schools.com/colors/colors_groups.asp>
1108
1109 2. RGB hex code
1110
1111 An example of using an RGB hex code is:
1112 --file-style="#0e7c0e"
1113
1114 3. ANSI color name
1115
1116 There are 8 ANSI color names:
1117 black, red, green, yellow, blue, magenta, cyan, white.
1118
1119 In addition, all of them have a bright form:
1120 brightblack, brightred, brightgreen, brightyellow, brightblue, brightmagenta, brightcyan, brightwhite.
1121
1122 An example of using an ANSI color name is:
1123 --file-style="green"
1124
1125 Unlike RGB hex codes, ANSI color names are just names: you can choose the exact color that each name corresponds to in the settings of your terminal application (the application you use to enter commands at a shell prompt). This means that if you use ANSI color names, and you change the color theme used by your terminal, then delta's colors will respond automatically, without needing to change the delta command line.
1126
1127 "purple" is accepted as a synonym for "magenta". Color names and codes are case-insensitive.
1128
1129 4. ANSI color number
1130
1131 An example of using an ANSI color number is:
1132 --file-style=28
1133
1134 There are 256 ANSI color numbers: 0-255. The first 16 are the same as the colors described in the "ANSI color name" section above. See <https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit>. Specifying colors like this is useful if your terminal only supports 256 colors (i.e. doesn't support 24-bit color).
1135
1136
1137 {i0}{H_}Line Numbers{_H}
1138
1139 To display line numbers, use --line-numbers.
1140
1141 Line numbers are displayed in two columns. Here's what it looks like by default:
1142
1143 1 ⋮ 1 │ unchanged line
1144 2 ⋮ │ removed line
1145 ⋮ 2 │ added line
1146
1147 In that output, the line numbers for the old (minus) version of the file appear in the left column, and the line numbers for the new (plus) version of the file appear in the right column. In an unchanged (zero) line, both columns contain a line number.
1148
1149 The following options allow the line number display to be customized:
1150
1151 --line-numbers-left-format: Change the contents of the left column
1152 --line-numbers-right-format: Change the contents of the right column
1153 --line-numbers-left-style: Change the style applied to the left column
1154 --line-numbers-right-style: Change the style applied to the right column
1155 --line-numbers-minus-style: Change the style applied to line numbers in minus lines
1156 --line-numbers-zero-style: Change the style applied to line numbers in unchanged lines
1157 --line-numbers-plus-style: Change the style applied to line numbers in plus lines
1158
1159 Options --line-numbers-left-format and --line-numbers-right-format allow you to change the contents of the line number columns. Their values are arbitrary format strings, which are allowed to contain the placeholders {{nm}} for the line number associated with the old version of the file and {{np}} for the line number associated with the new version of the file. The placeholders support a subset of the string formatting syntax documented here: <https://doc.rust-lang.org/std/fmt/#formatting-parameters>. Specifically, you can use the alignment and width syntax.
1160
1161 For example, the default value of --line-numbers-left-format is '{{nm:^4}}â‹®'. This means that the left column should display the minus line number (nm), center-aligned, padded with spaces to a width of 4 characters, followed by a unicode dividing-line character (â‹®).
1162
1163 Similarly, the default value of --line-numbers-right-format is '{{np:^4}}│'. This means that the right column should display the plus line number (np), center-aligned, padded with spaces to a width of 4 characters, followed by a unicode dividing-line character (│).
1164
1165 Use '<' for left-align, '^' for center-align, and '>' for right-align.
1166
1167
1168 {i0}{H_}Support{_H}
1169
1170 If something isn't working correctly, or you have a feature request, please open an issue at <https://github.com/dandavison/delta/issues>.
1171
1172 For a short help summary, please use delta -h.
1173 "##
1174 )
1175 }
1176
1177 #[derive(Default, Clone, Debug)]
1178 pub struct ComputedValues {
1179 pub available_terminal_width: usize,
1180 pub stdout_is_term: bool,
1181 pub background_color_extends_to_terminal_width: bool,
1182 pub decorations_width: Width,
1183 pub inspect_raw_lines: InspectRawLines,
1184 pub color_mode: ColorMode,
1185 pub paging_mode: PagingMode,
1186 pub syntax_set: SyntaxSet,
1187 pub syntax_theme: Option<SyntaxTheme>,
1188 pub true_color: bool,
1189 }
1190
1191 #[derive(Clone, Debug, Default, PartialEq, Eq)]
1192 pub enum Width {
1193 Fixed(usize),
1194 #[default]
1195 Variable,
1196 }
1197
1198 #[derive(Clone, Debug, Default, PartialEq, Eq)]
1199 pub enum InspectRawLines {
1200 True,
1201 #[default]
1202 False,
1203 }
1204
1205 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
1206 pub enum DetectDarkLight {
1207 /// Only query the terminal for its colors if the output is not redirected.
1208 #[default]
1209 Auto,
1210 /// Always query the terminal for its colors.
1211 Always,
1212 /// Never query the terminal for its colors.
1213 Never,
1214 }
1215
1216 // Which call path to take
1217 #[derive(Debug)]
1218 pub enum Call<T> {
1219 Delta(T),
1220 DeltaDiff(T, PathBuf, PathBuf),
1221 SubCommand(T, subcommands::SubCommand),
1222 Help(String),
1223 Version(String),
1224 }
1225
1226 impl Opt {
1227 fn handle_help_and_version(args: &[OsString]) -> Call<ArgMatches> {
1228 match Self::command().try_get_matches_from(args) {
1229 Err(e) if e.kind() == clap::error::ErrorKind::DisplayVersion => {
1230 let version = Self::command().render_version();
1231 Call::Version(version)
1232 }
1233 Err(e) if e.kind() == clap::error::ErrorKind::DisplayHelp => {
1234 let term = Term::stdout();
1235 // No wrapping if short -h instead of --help was used:
1236 if args.iter().any(|arg| arg == "-h") {
1237 let help_clap = Self::command().render_help();
1238 return Call::Help(if term.is_term() {
1239 help_clap.ansi().to_string()
1240 } else {
1241 help_clap.to_string()
1242 });
1243 }
1244
1245 let help_clap = Self::command().render_long_help();
1246 let (help_clap, wrap_width) = if term.is_term() {
1247 (
1248 help_clap.ansi().to_string(),
1249 utils::workarounds::windows_msys2_width_fix(term.size(), &term),
1250 )
1251 } else {
1252 (help_clap.to_string(), TERM_FALLBACK_WIDTH)
1253 };
1254
1255 // Stop wrapping for very narrow terminals, and leave a 2 wide margin on the right.
1256 let wrap_width =
1257 wrap_width.clamp(TERM_FALLBACK_WIDTH - 22, TERM_FALLBACK_WIDTH + 22) - 2;
1258
1259 let mut help = utils::helpwrap::wrap(&help_clap, wrap_width, "", "", "");
1260 let indent_with = " ";
1261 let no_indent = ":no_Indent:";
1262 let no_wrap = ":no_Wrap:";
1263 let after_help = utils::helpwrap::wrap(
1264 &get_after_long_help(term.is_term(), no_indent, no_wrap),
1265 wrap_width,
1266 indent_with,
1267 no_indent,
1268 no_wrap,
1269 );
1270 help.push_str(&after_help);
1271
1272 Call::Help(help)
1273 }
1274 Err(e) => {
1275 // Calls `e.exit()` if error persists.
1276 let (matches, subcmd) = subcommands::extract(args, e);
1277 Call::SubCommand(matches, subcmd)
1278 }
1279 Ok(matches) => {
1280 // subcommands take precedence over diffs
1281 let minus_file = matches.get_one::<PathBuf>("minus_file").map(PathBuf::from);
1282 if let Some(subcmd) = &minus_file {
1283 if let Some(arg) = subcmd.to_str() {
1284 if subcommands::SUBCOMMANDS.contains(&arg) {
1285 let unreachable_error =
1286 Error::new(clap::error::ErrorKind::InvalidSubcommand);
1287 let (matches, subcmd) = subcommands::extract(args, unreachable_error);
1288 return Call::SubCommand(matches, subcmd);
1289 }
1290 }
1291 }
1292
1293 match (
1294 minus_file,
1295 matches.get_one::<PathBuf>("plus_file").map(PathBuf::from),
1296 ) {
1297 (Some(minus_file), Some(plus_file)) => {
1298 Call::DeltaDiff(matches, minus_file, plus_file)
1299 }
1300 _ => Call::Delta(matches),
1301 }
1302 }
1303 }
1304 }
1305
1306 pub fn from_args_and_git_config(
1307 args: Vec<OsString>,
1308 env: &DeltaEnv,
1309 assets: HighlightingAssets,
1310 ) -> (Call<()>, Option<Opt>) {
1311 #[cfg(test)]
1312 // Set argv[0] when called in tests:
1313 let args = {
1314 let mut args = args;
1315 args.insert(0, OsString::from("delta"));
1316 args
1317 };
1318 let (matches, call) = match Self::handle_help_and_version(&args) {
1319 Call::Delta(t) => (t, Call::Delta(())),
1320 Call::DeltaDiff(t, a, b) => (t, Call::DeltaDiff((), a, b)),
1321 Call::SubCommand(t, cmd) => (t, Call::SubCommand((), cmd)),
1322 Call::Help(help) => return (Call::Help(help), None),
1323 Call::Version(ver) => return (Call::Version(ver), None),
1324 };
1325
1326 let mut final_config = if *matches.get_one::<bool>("no_gitconfig").unwrap_or(&false) {
1327 None
1328 } else {
1329 GitConfig::try_create(env)
1330 };
1331
1332 if let Some(path) = matches.get_one::<String>("config") {
1333 if !path.is_empty() {
1334 let path = Path::new(path);
1335 final_config = Some(GitConfig::from_path(env, path, true));
1336 }
1337 }
1338
1339 let opt = Self::from_clap_and_git_config(env, matches, final_config, assets);
1340 (call, Some(opt))
1341 }
1342
1343 pub fn from_iter_and_git_config<I>(
1344 env: &DeltaEnv,
1345 iter: I,
1346 git_config: Option<GitConfig>,
1347 ) -> Self
1348 where
1349 I: IntoIterator,
1350 I::Item: Into<OsString> + Clone,
1351 {
1352 let assets = utils::bat::assets::load_highlighting_assets();
1353 Self::from_clap_and_git_config(
1354 env,
1355 Self::command().get_matches_from(iter),
1356 git_config,
1357 assets,
1358 )
1359 }
1360
1361 fn from_clap_and_git_config(
1362 env: &DeltaEnv,
1363 arg_matches: clap::ArgMatches,
1364 mut git_config: Option<GitConfig>,
1365 assets: HighlightingAssets,
1366 ) -> Self {
1367 let mut opt = Opt::from_arg_matches(&arg_matches)
1368 .unwrap_or_else(|_| delta_unreachable("Opt::from_arg_matches failed"));
1369 opt.env = env.clone();
1370 options::set::set_options(&mut opt, &mut git_config, &arg_matches, assets);
1371 opt.git_config = git_config;
1372 opt
1373 }
1374
1375 pub fn get_argument_and_option_names() -> HashMap<String, String> {
1376 let command = Self::command();
1377 command
1378 .get_opts()
1379 .chain(command.get_arguments())
1380 .filter_map(|arg| match (arg.get_id(), arg.get_long()) {
1381 (id, Some(long)) => {
1382 if IGNORED_OPTION_NAMES.contains(long) {
1383 None
1384 } else {
1385 Some((id.to_string(), long.to_owned()))
1386 }
1387 }
1388 _ => None,
1389 })
1390 .collect()
1391 }
1392
1393 pub fn git_config(&self) -> Option<&GitConfig> {
1394 self.git_config.as_ref()
1395 }
1396 }
1397
1398 // Option names to exclude when listing options to process for various purposes. These are all
1399 // pseudo-flag commands such as --list-languages
1400 lazy_static! {
1401 static ref IGNORED_OPTION_NAMES: HashSet<&'static str> = vec![
1402 "generate-completion",
1403 "list-languages",
1404 "list-syntax-themes",
1405 "show-config",
1406 "show-syntax-themes",
1407 ]
1408 .into_iter()
1409 .collect();
1410 }