Debian Codegraph @

src/config.rs

raw symbols SCIP
1 use std::collections::HashMap;
2 use std::path::PathBuf;
3
4 use clap::parser::ValueSource;
5 use regex::Regex;
6 use syntect::highlighting::Style as SyntectStyle;
7 use syntect::highlighting::Theme as SyntaxTheme;
8 use syntect::parsing::SyntaxSet;
9
10 use crate::ansi;
11 use crate::cli;
12 use crate::color::{self, ColorMode};
13 use crate::delta::State;
14 use crate::fatal;
15 use crate::features::navigate;
16 use crate::features::side_by_side::{self, ansifill, LeftRight};
17 use crate::git_config::GitConfig;
18 use crate::handlers;
19 use crate::handlers::blame::parse_blame_line_numbers;
20 use crate::handlers::blame::BlameLineNumbers;
21 use crate::minusplus::MinusPlus;
22 use crate::paint::BgFillMethod;
23 use crate::parse_styles;
24 use crate::style;
25 use crate::style::Style;
26 use crate::tests::TESTING;
27 use crate::utils;
28 use crate::utils::bat::output::PagingMode;
29 use crate::utils::regex_replacement::RegexReplacement;
30 use crate::wrapping::WrapConfig;
31
32 pub const INLINE_SYMBOL_WIDTH_1: usize = 1;
33
34 // Used if an invalid default-language was specified.
35 pub const SYNTAX_FALLBACK_LANG: &str = "txt";
36
37 #[cfg_attr(test, derive(Clone))]
38 pub struct Config {
39 pub available_terminal_width: usize,
40 pub background_color_extends_to_terminal_width: bool,
41 pub blame_code_style: Option<Style>,
42 pub blame_format: String,
43 pub blame_separator_format: BlameLineNumbers,
44 pub blame_palette: Vec<String>,
45 pub blame_separator_style: Option<Style>,
46 pub blame_timestamp_format: String,
47 pub blame_timestamp_output_format: Option<String>,
48 pub color_only: bool,
49 pub commit_regex: Regex,
50 pub commit_style: Style,
51 pub cwd_of_delta_process: Option<PathBuf>,
52 pub cwd_of_user_shell_process: Option<PathBuf>,
53 pub cwd_relative_to_repo_root: Option<String>,
54 pub decorations_width: cli::Width,
55 pub default_language: String,
56 pub diff_args: String,
57 pub diff_stat_align_width: usize,
58 pub error_exit_code: i32,
59 pub file_added_label: String,
60 pub file_copied_label: String,
61 pub file_modified_label: String,
62 pub file_removed_label: String,
63 pub file_renamed_label: String,
64 pub file_regex_replacement: Option<RegexReplacement>,
65 pub right_arrow: String,
66 pub file_style: Style,
67 pub git_config: Option<GitConfig>,
68 pub git_minus_style: Style,
69 pub git_plus_style: Style,
70 pub grep_context_line_style: Style,
71 pub grep_file_style: Style,
72 pub classic_grep_header_file_style: Style,
73 pub classic_grep_header_style: Style,
74 pub ripgrep_header_style: Style,
75 pub grep_line_number_style: Style,
76 pub grep_match_line_style: Style,
77 pub grep_match_word_style: Style,
78 pub grep_output_type: Option<GrepType>,
79 pub grep_separator_symbol: String,
80 pub handle_merge_conflicts: bool,
81 pub hostname: Option<String>,
82 pub hunk_header_file_style: Style,
83 pub hunk_header_line_number_style: Style,
84 pub hunk_header_style_include_file_path: HunkHeaderIncludeFilePath,
85 pub hunk_header_style_include_line_number: HunkHeaderIncludeLineNumber,
86 pub hunk_header_style_include_code_fragment: HunkHeaderIncludeCodeFragment,
87 pub hunk_header_style: Style,
88 pub hunk_label: String,
89 pub hyperlinks_commit_link_format: Option<String>,
90 pub hyperlinks_file_link_format: String,
91 pub hyperlinks: bool,
92 pub inline_hint_style: Style,
93 pub inspect_raw_lines: cli::InspectRawLines,
94 pub keep_plus_minus_markers: bool,
95 pub line_buffer_size: usize,
96 pub line_fill_method: BgFillMethod,
97 pub line_numbers_format: LeftRight<String>,
98 pub line_numbers_style_leftright: LeftRight<Style>,
99 pub line_numbers_style_minusplus: MinusPlus<Style>,
100 pub line_numbers_zero_style: Style,
101 pub line_numbers: bool,
102 pub styles_map: Option<HashMap<style::AnsiTermStyleEqualityKey, Style>>,
103 pub max_line_distance_for_naively_paired_lines: f64,
104 pub max_line_distance: f64,
105 pub max_line_length: usize,
106 pub max_syntax_length: usize,
107 pub merge_conflict_begin_symbol: String,
108 pub merge_conflict_ours_diff_header_style: Style,
109 pub merge_conflict_theirs_diff_header_style: Style,
110 pub merge_conflict_end_symbol: String,
111 pub minus_emph_style: Style,
112 pub minus_empty_line_marker_style: Style,
113 pub minus_file: Option<PathBuf>,
114 pub minus_non_emph_style: Style,
115 pub minus_style: Style,
116 pub navigate_regex: Option<String>,
117 pub navigate: bool,
118 pub null_style: Style,
119 pub null_syntect_style: SyntectStyle,
120 pub pager: Option<String>,
121 pub paging_mode: PagingMode,
122 pub plus_emph_style: Style,
123 pub plus_empty_line_marker_style: Style,
124 pub plus_file: Option<PathBuf>,
125 pub plus_non_emph_style: Style,
126 pub plus_style: Style,
127 pub relative_paths: bool,
128 pub show_themes: bool,
129 pub side_by_side_data: side_by_side::SideBySideData,
130 pub side_by_side: bool,
131 pub syntax_set: SyntaxSet,
132 pub syntax_theme: Option<SyntaxTheme>,
133 pub tab_cfg: utils::tabs::TabCfg,
134 pub tokenization_regex: Regex,
135 pub true_color: bool,
136 pub truncation_symbol: String,
137 pub whitespace_error_style: Style,
138 pub wrap_config: WrapConfig,
139 pub zero_style: Style,
140 }
141
142 #[derive(Debug, Eq, PartialEq, Clone)]
143 pub enum GrepType {
144 Ripgrep,
145 Classic,
146 }
147
148 #[cfg_attr(test, derive(Clone))]
149 pub enum HunkHeaderIncludeFilePath {
150 Yes,
151 No,
152 }
153
154 #[cfg_attr(test, derive(Clone))]
155 pub enum HunkHeaderIncludeLineNumber {
156 Yes,
157 No,
158 }
159
160 #[cfg_attr(test, derive(Clone))]
161 pub enum HunkHeaderIncludeCodeFragment {
162 Yes,
163 YesNoSpace,
164 No,
165 }
166
167 impl Config {
168 pub fn get_style(&self, state: &State) -> &Style {
169 match state {
170 State::HunkMinus(_, _) => &self.minus_style,
171 State::HunkZero(_, _) => &self.zero_style,
172 State::HunkPlus(_, _) => &self.plus_style,
173 State::CommitMeta => &self.commit_style,
174 State::DiffHeader(_) => &self.file_style,
175 State::Grep(GrepType::Ripgrep, _, _, _) => &self.classic_grep_header_style,
176 State::HunkHeader(_, _, _, _) => &self.hunk_header_style,
177 State::SubmoduleLog => &self.file_style,
178 _ => delta_unreachable("Unreachable code reached in get_style."),
179 }
180 }
181
182 pub fn git_config(&self) -> Option<&GitConfig> {
183 self.git_config.as_ref()
184 }
185 }
186
187 impl From<cli::Opt> for Config {
188 fn from(opt: cli::Opt) -> Self {
189 let mut styles = parse_styles::parse_styles(&opt);
190 let styles_map = parse_styles::parse_styles_map(&opt);
191
192 let wrap_config = WrapConfig::from_opt(&opt, styles["inline-hint-style"]);
193
194 let max_line_distance_for_naively_paired_lines = opt
195 .env
196 .experimental_max_line_distance_for_naively_paired_lines
197 .as_ref()
198 .map(|s| s.parse::<f64>().unwrap_or(0.0))
199 .unwrap_or(0.0);
200
201 let commit_regex = Regex::new(&opt.commit_regex).unwrap_or_else(|_| {
202 fatal(format!(
203 "Invalid commit-regex: {}. \
204 The value must be a valid Rust regular expression. \
205 See https://docs.rs/regex.",
206 opt.commit_regex
207 ));
208 });
209
210 let tokenization_regex = Regex::new(&opt.tokenization_regex).unwrap_or_else(|_| {
211 fatal(format!(
212 "Invalid word-diff-regex: {}. \
213 The value must be a valid Rust regular expression. \
214 See https://docs.rs/regex.",
215 opt.tokenization_regex
216 ));
217 });
218
219 let blame_palette = make_blame_palette(opt.blame_palette, opt.computed.color_mode);
220
221 if blame_palette.is_empty() {
222 fatal("Option 'blame-palette' must not be empty.")
223 }
224
225 let file_added_label = opt.file_added_label;
226 let file_copied_label = opt.file_copied_label;
227 let file_modified_label = opt.file_modified_label;
228 let file_removed_label = opt.file_removed_label;
229 let file_renamed_label = opt.file_renamed_label;
230 let right_arrow = opt.right_arrow;
231 let hunk_label = opt.hunk_label;
232
233 let line_fill_method = match opt.line_fill_method.as_deref() {
234 // Note that "default" is not documented
235 Some("ansi") | Some("default") | None => BgFillMethod::TryAnsiSequence,
236 Some("spaces") => BgFillMethod::Spaces,
237 _ => fatal("Invalid option for line-fill-method: Expected \"ansi\" or \"spaces\"."),
238 };
239
240 let side_by_side_data = side_by_side::SideBySideData::new_sbs(
241 &opt.computed.decorations_width,
242 &opt.computed.available_terminal_width,
243 );
244 let side_by_side_data = ansifill::UseFullPanelWidth::sbs_odd_fix(
245 &opt.computed.decorations_width,
246 &line_fill_method,
247 side_by_side_data,
248 );
249
250 let navigate_regex = if (opt.navigate || opt.show_themes)
251 && (opt.navigate_regex.is_none() || opt.navigate_regex == Some("".to_string()))
252 {
253 Some(navigate::make_navigate_regex(
254 opt.show_themes,
255 &file_modified_label,
256 &file_added_label,
257 &file_removed_label,
258 &file_renamed_label,
259 &hunk_label,
260 ))
261 } else {
262 opt.navigate_regex
263 };
264
265 let grep_output_type = match opt.grep_output_type.as_deref() {
266 Some("ripgrep") => Some(GrepType::Ripgrep),
267 Some("classic") => Some(GrepType::Classic),
268 None => None,
269 _ => fatal("Invalid option for grep-output-type: Expected \"ripgrep\" or \"classic\"."),
270 };
271
272 #[cfg(not(test))]
273 let cwd_of_delta_process = opt.env.current_dir;
274 #[cfg(test)]
275 let cwd_of_delta_process = Some(utils::path::fake_delta_cwd_for_tests());
276
277 let cwd_relative_to_repo_root = opt.env.git_prefix;
278
279 let cwd_of_user_shell_process = utils::path::cwd_of_user_shell_process(
280 cwd_of_delta_process.as_ref(),
281 cwd_relative_to_repo_root.as_deref(),
282 );
283
284 Self {
285 available_terminal_width: opt.computed.available_terminal_width,
286 background_color_extends_to_terminal_width: opt
287 .computed
288 .background_color_extends_to_terminal_width,
289 blame_format: opt.blame_format,
290 blame_code_style: styles.remove("blame-code-style"),
291 blame_palette,
292 blame_separator_format: parse_blame_line_numbers(&opt.blame_separator_format),
293 blame_separator_style: styles.remove("blame-separator-style"),
294 blame_timestamp_format: opt.blame_timestamp_format,
295 blame_timestamp_output_format: opt.blame_timestamp_output_format,
296 commit_style: styles["commit-style"],
297 color_only: opt.color_only,
298 commit_regex,
299 cwd_of_delta_process,
300 cwd_of_user_shell_process,
301 cwd_relative_to_repo_root,
302 decorations_width: opt.computed.decorations_width,
303 default_language: opt.default_language,
304 diff_args: opt.diff_args,
305 diff_stat_align_width: opt.diff_stat_align_width,
306 error_exit_code: 2, // Use 2 for error because diff uses 0 and 1 for non-error.
307 file_added_label,
308 file_copied_label,
309 file_modified_label,
310 file_removed_label,
311 file_renamed_label,
312 file_regex_replacement: opt
313 .file_regex_replacement
314 .as_deref()
315 .and_then(RegexReplacement::from_sed_command),
316 right_arrow,
317 hunk_label,
318 file_style: styles["file-style"],
319 git_config: opt.git_config,
320 grep_context_line_style: styles["grep-context-line-style"],
321 grep_file_style: styles["grep-file-style"],
322 classic_grep_header_file_style: styles["classic-grep-header-file-style"],
323 classic_grep_header_style: styles["classic-grep-header-style"],
324 ripgrep_header_style: styles["ripgrep-header-style"],
325 grep_line_number_style: styles["grep-line-number-style"],
326 grep_match_line_style: styles["grep-match-line-style"],
327 grep_match_word_style: styles["grep-match-word-style"],
328 grep_output_type,
329 grep_separator_symbol: opt.grep_separator_symbol,
330 handle_merge_conflicts: !opt.raw,
331 hostname: opt.env.hostname,
332 hunk_header_file_style: styles["hunk-header-file-style"],
333 hunk_header_line_number_style: styles["hunk-header-line-number-style"],
334 hunk_header_style: styles["hunk-header-style"],
335 hunk_header_style_include_file_path: if opt
336 .hunk_header_style
337 .split(' ')
338 .any(|s| s == "file")
339 {
340 HunkHeaderIncludeFilePath::Yes
341 } else {
342 HunkHeaderIncludeFilePath::No
343 },
344 hunk_header_style_include_line_number: if opt
345 .hunk_header_style
346 .split(' ')
347 .any(|s| s == "line-number")
348 {
349 HunkHeaderIncludeLineNumber::Yes
350 } else {
351 HunkHeaderIncludeLineNumber::No
352 },
353 hunk_header_style_include_code_fragment: if opt
354 .hunk_header_style
355 .split(' ')
356 .any(|s| s == "omit-code-fragment")
357 {
358 HunkHeaderIncludeCodeFragment::No
359 } else {
360 HunkHeaderIncludeCodeFragment::Yes
361 },
362 hyperlinks: opt.hyperlinks,
363 hyperlinks_commit_link_format: opt.hyperlinks_commit_link_format,
364 hyperlinks_file_link_format: opt.hyperlinks_file_link_format,
365 inspect_raw_lines: opt.computed.inspect_raw_lines,
366 inline_hint_style: styles["inline-hint-style"],
367 keep_plus_minus_markers: opt.keep_plus_minus_markers,
368 line_fill_method: if !opt.computed.stdout_is_term && !TESTING {
369 // Don't write ANSI sequences (which rely on the width of the
370 // current terminal) into a file. Also see UseFullPanelWidth.
371 // But when testing always use given value.
372 BgFillMethod::Spaces
373 } else {
374 line_fill_method
375 },
376 line_numbers: opt.line_numbers && !handlers::hunk::is_word_diff(),
377 line_numbers_format: LeftRight::new(
378 opt.line_numbers_left_format,
379 opt.line_numbers_right_format,
380 ),
381 line_numbers_style_leftright: LeftRight::new(
382 styles["line-numbers-left-style"],
383 styles["line-numbers-right-style"],
384 ),
385 line_numbers_style_minusplus: MinusPlus::new(
386 styles["line-numbers-minus-style"],
387 styles["line-numbers-plus-style"],
388 ),
389 line_numbers_zero_style: styles["line-numbers-zero-style"],
390 line_buffer_size: opt.line_buffer_size,
391 max_line_distance: opt.max_line_distance,
392 max_line_distance_for_naively_paired_lines,
393 max_line_length: if opt.side_by_side {
394 wrap_config.config_max_line_length(
395 opt.max_line_length,
396 opt.computed.available_terminal_width,
397 )
398 } else {
399 opt.max_line_length
400 },
401 max_syntax_length: opt.max_syntax_length,
402 merge_conflict_begin_symbol: opt.merge_conflict_begin_symbol,
403 merge_conflict_ours_diff_header_style: styles["merge-conflict-ours-diff-header-style"],
404 merge_conflict_theirs_diff_header_style: styles
405 ["merge-conflict-theirs-diff-header-style"],
406 merge_conflict_end_symbol: opt.merge_conflict_end_symbol,
407 minus_emph_style: styles["minus-emph-style"],
408 minus_empty_line_marker_style: styles["minus-empty-line-marker-style"],
409 minus_file: opt.minus_file,
410 minus_non_emph_style: styles["minus-non-emph-style"],
411 minus_style: styles["minus-style"],
412 navigate: opt.navigate,
413 navigate_regex,
414 null_style: Style::new(),
415 null_syntect_style: SyntectStyle::default(),
416 pager: opt.pager,
417 paging_mode: opt.computed.paging_mode,
418 plus_emph_style: styles["plus-emph-style"],
419 plus_empty_line_marker_style: styles["plus-empty-line-marker-style"],
420 plus_file: opt.plus_file,
421 plus_non_emph_style: styles["plus-non-emph-style"],
422 plus_style: styles["plus-style"],
423 git_minus_style: styles["git-minus-style"],
424 git_plus_style: styles["git-plus-style"],
425 relative_paths: opt.relative_paths,
426 show_themes: opt.show_themes,
427 side_by_side: opt.side_by_side && !handlers::hunk::is_word_diff(),
428 side_by_side_data,
429 styles_map,
430 syntax_set: opt.computed.syntax_set,
431 syntax_theme: opt.computed.syntax_theme,
432 tab_cfg: utils::tabs::TabCfg::new(opt.tab_width),
433 tokenization_regex,
434 true_color: opt.computed.true_color,
435 truncation_symbol: format!("{}→{}", ansi::ANSI_SGR_REVERSE, ansi::ANSI_SGR_RESET),
436 wrap_config,
437 whitespace_error_style: styles["whitespace-error-style"],
438 zero_style: styles["zero-style"],
439 }
440 }
441 }
442
443 fn make_blame_palette(blame_palette: Option<String>, mode: ColorMode) -> Vec<String> {
444 match (blame_palette, mode) {
445 (Some(string), _) => string
446 .split_whitespace()
447 .map(|s| s.to_owned())
448 .collect::<Vec<String>>(),
449 (None, ColorMode::Light) => color::LIGHT_THEME_BLAME_PALETTE
450 .iter()
451 .map(|s| s.to_string())
452 .collect::<Vec<String>>(),
453 (None, ColorMode::Dark) => color::DARK_THEME_BLAME_PALETTE
454 .iter()
455 .map(|s| s.to_string())
456 .collect::<Vec<String>>(),
457 }
458 }
459
460 /// Did the user supply `option` on the command line?
461 pub fn user_supplied_option(option: &str, arg_matches: &clap::ArgMatches) -> bool {
462 arg_matches.value_source(option) == Some(ValueSource::CommandLine)
463 }
464
465 pub fn delta_unreachable(message: &str) -> ! {
466 fatal(format!(
467 "{message} This should not be possible. \
468 Please report the bug at https://github.com/dandavison/delta/issues.",
469 ));
470 }
471
472 #[cfg(test)]
473 // Usual length of the header returned by `run_delta()`, often `skip()`-ed.
474 pub const HEADER_LEN: usize = 7;
475
476 #[cfg(test)]
477 pub mod tests {
478 use crate::cli;
479 use crate::tests::integration_test_utils;
480 use crate::utils::bat::output::PagingMode;
481 use std::fs::remove_file;
482
483 #[test]
484 fn test_get_computed_values_from_config() {
485 let git_config_contents = b"
486 [delta]
487 true-color = never
488 width = 100
489 inspect-raw-lines = true
490 paging = never
491 syntax-theme = None
492 ";
493 let git_config_path = "delta__test_get_true_color_from_config.gitconfig";
494 let config = integration_test_utils::make_config_from_args_and_git_config(
495 &[],
496 Some(git_config_contents),
497 Some(git_config_path),
498 );
499 assert!(!config.true_color);
500 assert_eq!(config.decorations_width, cli::Width::Fixed(100));
501 assert!(config.background_color_extends_to_terminal_width);
502 assert_eq!(config.inspect_raw_lines, cli::InspectRawLines::True);
503 assert_eq!(config.paging_mode, PagingMode::Never);
504 assert!(config.syntax_theme.is_none());
505 // syntax_set doesn't depend on gitconfig.
506 remove_file(git_config_path).unwrap();
507 }
508 }