repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/parallel.rs
tests/parallel.rs
use super::*; #[test] #[ignore] fn prior_dependencies_run_in_parallel() { let start = Instant::now(); Test::new() .justfile( " [parallel] foo: a b c d e a: sleep 1 b: sleep 1 c: sleep 1 d: sleep 1 e: sleep 1 ", ) .stderr( " sleep 1 sleep 1 sleep 1 sleep 1 sleep 1 ", ) .run(); assert!(start.elapsed() < Duration::from_secs(2)); } #[test] #[ignore] fn subsequent_dependencies_run_in_parallel() { let start = Instant::now(); Test::new() .justfile( " [parallel] foo: && a b c d e a: sleep 1 b: sleep 1 c: sleep 1 d: sleep 1 e: sleep 1 ", ) .stderr( " sleep 1 sleep 1 sleep 1 sleep 1 sleep 1 ", ) .run(); assert!(start.elapsed() < Duration::from_secs(2)); } #[test] fn parallel_dependencies_report_errors() { Test::new() .justfile( " [parallel] foo: bar bar: exit 1 ", ) .stderr( " exit 1 error: Recipe `bar` failed on line 5 with exit code 1 ", ) .status(EXIT_FAILURE) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/directories.rs
tests/directories.rs
use super::*; #[test] fn cache_directory() { Test::new() .justfile("x := cache_directory()") .args(["--evaluate", "x"]) .stdout(dirs::cache_dir().unwrap_or_default().to_string_lossy()) .run(); } #[test] fn config_directory() { Test::new() .justfile("x := config_directory()") .args(["--evaluate", "x"]) .stdout(dirs::config_dir().unwrap_or_default().to_string_lossy()) .run(); } #[test] fn config_local_directory() { Test::new() .justfile("x := config_local_directory()") .args(["--evaluate", "x"]) .stdout( dirs::config_local_dir() .unwrap_or_default() .to_string_lossy(), ) .run(); } #[test] fn data_directory() { Test::new() .justfile("x := data_directory()") .args(["--evaluate", "x"]) .stdout(dirs::data_dir().unwrap_or_default().to_string_lossy()) .run(); } #[test] fn data_local_directory() { Test::new() .justfile("x := data_local_directory()") .args(["--evaluate", "x"]) .stdout(dirs::data_local_dir().unwrap_or_default().to_string_lossy()) .run(); } #[test] fn executable_directory() { if let Some(executable_dir) = dirs::executable_dir() { Test::new() .justfile("x := executable_directory()") .args(["--evaluate", "x"]) .stdout(executable_dir.to_string_lossy()) .run(); } else { Test::new() .justfile("x := executable_directory()") .args(["--evaluate", "x"]) .stderr( " error: Call to function `executable_directory` failed: executable directory not found ——▶ justfile:1:6 │ 1 │ x := executable_directory() │ ^^^^^^^^^^^^^^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } } #[test] fn home_directory() { Test::new() .justfile("x := home_directory()") .args(["--evaluate", "x"]) .stdout(dirs::home_dir().unwrap_or_default().to_string_lossy()) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/newline_escape.rs
tests/newline_escape.rs
use super::*; #[test] fn newline_escape_deps() { Test::new() .justfile( " default: a \\ b \\ c a: echo a b: echo b c: echo c ", ) .stdout("a\nb\nc\n") .stderr("echo a\necho b\necho c\n") .run(); } #[test] fn newline_escape_deps_no_indent() { Test::new() .justfile( " default: a\\ b\\ c a: echo a b: echo b c: echo c ", ) .stdout("a\nb\nc\n") .stderr("echo a\necho b\necho c\n") .run(); } #[test] fn newline_escape_deps_linefeed() { Test::new() .justfile( " default: a\\\r b a: echo a b: echo b ", ) .stdout("a\nb\n") .stderr("echo a\necho b\n") .run(); } #[test] fn newline_escape_deps_invalid_esc() { Test::new() .justfile( " default: a\\ b ", ) .stderr( " error: `\\ ` is not a valid escape sequence ——▶ justfile:1:11 │ 1 │ default: a\\ b │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn newline_escape_unpaired_linefeed() { Test::new() .justfile( " default:\\\ra", ) .stderr( " error: Unpaired carriage return ——▶ justfile:1:9 │ 1 │ default:\\\ra │ ^ ", ) .status(EXIT_FAILURE) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/changelog.rs
tests/changelog.rs
use super::*; #[test] fn print_changelog() { Test::new() .args(["--changelog"]) .stdout(fs::read_to_string("CHANGELOG.md").unwrap()) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/scope.rs
tests/scope.rs
use super::*; #[test] fn dependencies_in_submodules_run_with_submodule_scope() { Test::new() .write("bar.just", "x := 'X'\nbar a=x:\n echo {{ a }} {{ x }}") .justfile( " mod bar foo: bar::bar ", ) .stdout("X X\n") .stderr("echo X X\n") .run(); } #[test] fn aliases_in_submodules_run_with_submodule_scope() { Test::new() .write("bar.just", "x := 'X'\nbar a=x:\n echo {{ a }} {{ x }}") .justfile( " mod bar alias foo := bar::bar ", ) .arg("foo") .stdout("X X\n") .stderr("echo X X\n") .run(); } #[test] fn dependencies_in_nested_submodules_run_with_submodule_scope() { Test::new() .write( "b.just", " x := 'y' foo: @echo {{ x }} ", ) .write("a.just", "mod b") .stdout("y\n") .justfile("mod a") .args(["a", "b", "foo"]) .run(); } #[test] fn imported_recipes_run_in_correct_scope() { Test::new() .justfile( " mod a mod b ", ) .write("a.just", "X := 'A'\nimport 'shared.just'") .write("b.just", "X := 'B'\nimport 'shared.just'") .write("shared.just", "foo:\n @echo {{ X }}") .args(["a::foo", "b::foo"]) .stdout("A\nB\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/undefined_variables.rs
tests/undefined_variables.rs
use super::*; #[test] fn parameter_default_unknown_variable_in_expression() { Test::new() .justfile("foo a=(b+''):") .stderr( " error: Variable `b` not defined ——▶ justfile:1:8 │ 1 │ foo a=(b+''): │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_variable_in_unary_call() { Test::new() .justfile( " foo x=env_var(a): ", ) .stderr( " error: Variable `a` not defined ——▶ justfile:1:15 │ 1 │ foo x=env_var(a): │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_first_variable_in_binary_call() { Test::new() .justfile( " foo x=env_var_or_default(a, b): ", ) .stderr( " error: Variable `a` not defined ——▶ justfile:1:26 │ 1 │ foo x=env_var_or_default(a, b): │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_second_variable_in_binary_call() { Test::new() .justfile( " foo x=env_var_or_default('', b): ", ) .stderr( " error: Variable `b` not defined ——▶ justfile:1:30 │ 1 │ foo x=env_var_or_default('', b): │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_variable_in_ternary_call() { Test::new() .justfile( " foo x=replace(a, b, c): ", ) .stderr( " error: Variable `a` not defined ——▶ justfile:1:15 │ 1 │ foo x=replace(a, b, c): │ ^ ", ) .status(EXIT_FAILURE) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/summary.rs
tests/summary.rs
use super::*; #[test] fn summary() { Test::new() .arg("--summary") .justfile( "b: a a: d: c c: b _z: _y _y: ", ) .stdout("a b c d\n") .run(); } #[test] fn summary_sorted() { Test::new() .arg("--summary") .justfile( " b: c: a: ", ) .stdout("a b c\n") .run(); } #[test] fn summary_unsorted() { Test::new() .arg("--summary") .arg("--unsorted") .justfile( " b: c: a: ", ) .stdout("b c a\n") .run(); } #[test] fn summary_none() { Test::new() .arg("--summary") .arg("--quiet") .justfile("") .stdout("\n\n\n") .run(); } #[test] fn no_recipes() { Test::new() .arg("--summary") .stderr("Justfile contains no recipes.\n") .stdout("\n\n\n") .run(); } #[test] fn submodule_recipes() { Test::new() .write("foo.just", "mod bar\nfoo:") .write("bar.just", "mod baz\nbar:") .write("baz.just", "mod biz\nbaz:") .write("biz.just", "biz:") .justfile( " mod foo bar: ", ) .arg("--summary") .stdout("bar foo::foo foo::bar::bar foo::bar::baz::baz foo::bar::baz::biz::biz\n") .run(); } #[test] fn summary_implies_unstable() { Test::new() .write("foo.just", "foo:") .justfile( " mod foo ", ) .arg("--summary") .stdout("foo::foo\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/shell_expansion.rs
tests/shell_expansion.rs
use super::*; #[test] fn strings_are_shell_expanded() { Test::new() .justfile( " x := x'$JUST_TEST_VARIABLE' ", ) .env("JUST_TEST_VARIABLE", "FOO") .args(["--evaluate", "x"]) .stdout("FOO") .run(); } #[test] fn shell_expanded_strings_must_not_have_whitespace() { Test::new() .justfile( " x := x '$JUST_TEST_VARIABLE' ", ) .status(1) .stderr( " error: Expected '&&', '||', comment, end of file, end of line, '(', '+', or '/', but found string ——▶ justfile:1:8 │ 1 │ x := x '$JUST_TEST_VARIABLE' │ ^^^^^^^^^^^^^^^^^^^^^ ", ) .run(); } #[test] fn shell_expanded_error_messages_highlight_string_token() { Test::new() .justfile( " x := x'$FOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' ", ) .env("JUST_TEST_VARIABLE", "FOO") .args(["--evaluate", "x"]) .status(1) .stderr( " error: Shell expansion failed: error looking key 'FOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' up: environment variable not found ——▶ justfile:1:7 │ 1 │ x := x'$FOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ") .run(); } #[test] fn shell_expanded_strings_are_dumped_correctly() { Test::new() .justfile( " x := x'$JUST_TEST_VARIABLE' ", ) .env("JUST_TEST_VARIABLE", "FOO") .args(["--dump"]) .stdout("x := x'$JUST_TEST_VARIABLE'\n") .run(); } #[test] fn shell_expanded_strings_can_be_used_in_settings() { Test::new() .justfile( " set dotenv-filename := x'$JUST_TEST_VARIABLE' @foo: echo $DOTENV_KEY ", ) .write(".env", "DOTENV_KEY=dotenv-value") .env("JUST_TEST_VARIABLE", ".env") .stdout("dotenv-value\n") .run(); } #[test] fn shell_expanded_strings_can_be_used_in_import_paths() { Test::new() .justfile( " import x'$JUST_TEST_VARIABLE' foo: bar ", ) .write("import.just", "@bar:\n echo BAR") .env("JUST_TEST_VARIABLE", "import.just") .stdout("BAR\n") .run(); } #[test] fn shell_expanded_strings_can_be_used_in_mod_paths() { Test::new() .justfile( " mod foo x'$JUST_TEST_VARIABLE' ", ) .write("mod.just", "@bar:\n echo BAR") .env("JUST_TEST_VARIABLE", "mod.just") .args(["foo", "bar"]) .stdout("BAR\n") .run(); } #[test] fn shell_expanded_strings_do_not_conflict_with_dependencies() { Test::new() .justfile( " foo a b: @echo {{a}}{{b}} bar a b: (foo a 'c') ", ) .args(["bar", "A", "B"]) .stdout("Ac\n") .run(); Test::new() .justfile( " foo a b: @echo {{a}}{{b}} bar a b: (foo a'c') ", ) .args(["bar", "A", "B"]) .stdout("Ac\n") .run(); Test::new() .justfile( " foo a b: @echo {{a}}{{b}} bar x b: (foo x 'c') ", ) .args(["bar", "A", "B"]) .stdout("Ac\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/windows.rs
tests/windows.rs
use super::*; #[test] fn bare_bash_in_shebang() { Test::new() .justfile( " default: #!bash echo FOO ", ) .stdout("FOO\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/options.rs
tests/options.rs
use super::*; #[test] fn long_options_may_not_be_empty() { Test::new() .justfile( " [arg('bar', long='')] @foo bar: echo bar={{bar}} ", ) .stderr( " error: Option name for parameter `bar` is empty ——▶ justfile:1:18 │ 1 │ [arg('bar', long='')] │ ^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn short_options_may_not_be_empty() { Test::new() .justfile( " [arg('bar', short='')] @foo bar: echo bar={{bar}} ", ) .stderr( " error: Option name for parameter `bar` is empty ——▶ justfile:1:19 │ 1 │ [arg('bar', short='')] │ ^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn short_options_may_not_have_multiple_characters() { Test::new() .justfile( " [arg('bar', short='abc')] @foo bar: echo bar={{bar}} ", ) .stderr( " error: Short option name for parameter `bar` contains multiple characters ——▶ justfile:1:19 │ 1 │ [arg('bar', short='abc')] │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn parameters_may_be_passed_with_long_options() { Test::new() .justfile( " [arg('bar', long='bar')] @foo bar: echo bar={{bar}} ", ) .args(["foo", "--bar", "baz"]) .stdout("bar=baz\n") .run(); } #[test] fn long_option_defaults_to_parameter_name() { Test::new() .justfile( " [arg('bar', long)] @foo bar: echo bar={{bar}} ", ) .args(["foo", "--bar", "baz"]) .stdout("bar=baz\n") .run(); } #[test] fn parameters_may_be_passed_with_short_options() { Test::new() .justfile( " [arg('bar', short='b')] @foo bar: echo bar={{bar}} ", ) .args(["foo", "-b", "baz"]) .stdout("bar=baz\n") .run(); } const LONG_SHORT: &str = " [arg('bar', long='bar', short='b')] @foo bar: echo bar={{bar}} "; #[test] fn parameters_with_both_long_and_short_option_may_be_passed_as_long() { Test::new() .justfile(LONG_SHORT) .args(["foo", "--bar", "baz"]) .stdout("bar=baz\n") .run(); } #[test] fn parameters_with_both_long_and_short_option_may_be_passed_as_short() { Test::new() .justfile(LONG_SHORT) .args(["foo", "-b", "baz"]) .stdout("bar=baz\n") .run(); } #[test] fn parameters_with_both_long_and_short_may_not_use_both() { Test::new() .justfile(LONG_SHORT) .args(["foo", "--bar", "baz", "-b", "baz"]) .stderr("error: Recipe `foo` option `-b` cannot be passed more than once\n") .status(EXIT_FAILURE) .run(); } #[test] fn multiple_short_options_in_one_argument_is_an_error() { Test::new() .justfile( " [arg('bar', short='a')] [arg('baz', short='b')] @foo bar baz: ", ) .args(["foo", "-ab"]) .stderr("error: Passing multiple short options (`-ab`) in one argument is not supported\n") .status(EXIT_FAILURE) .run(); } #[test] fn duplicate_long_option_attributes_are_forbidden() { Test::new() .justfile( " [arg('bar', long='bar')] [arg('baz', long='bar')] foo bar baz: ", ) .stderr( " error: Recipe `foo` defines option `--bar` multiple times ——▶ justfile:2:18 │ 2 │ [arg('baz', long='bar')] │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn defaulted_duplicate_long_option() { Test::new() .justfile( " [arg( 'aaa', long='bar' )] [arg( 'bar', long)] foo aaa bar: ", ) .stderr( " error: Recipe `foo` defines option `--bar` multiple times ——▶ justfile:5:19 │ 5 │ [arg( 'bar', long)] │ ^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn duplicate_short_option_attributes_are_forbidden() { Test::new() .justfile( " [arg('bar', short='b')] [arg('baz', short='b')] foo bar baz: ", ) .stderr( " error: Recipe `foo` defines option `-b` multiple times ——▶ justfile:2:19 │ 2 │ [arg('baz', short='b')] │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn variadics_with_long_options_are_forbidden() { Test::new() .justfile( " [arg('bar', long='bar')] foo +bar: ", ) .stderr( " error: Variadic parameters may not be options ——▶ justfile:2:6 │ 2 │ foo +bar: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn variadics_with_short_options_are_forbidden() { Test::new() .justfile( " [arg('bar', short='b')] foo +bar: ", ) .stderr( " error: Variadic parameters may not be options ——▶ justfile:2:6 │ 2 │ foo +bar: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn long_option_names_may_not_contain_equal_sign() { Test::new() .justfile( " [arg('bar', long='bar=baz')] foo bar: ", ) .stderr( " error: Option name for parameter `bar` contains equal sign ——▶ justfile:1:18 │ 1 │ [arg('bar', long='bar=baz')] │ ^^^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn short_option_names_may_not_contain_equal_sign() { Test::new() .justfile( " [arg('bar', short='=')] foo bar: ", ) .stderr( " error: Option name for parameter `bar` contains equal sign ——▶ justfile:1:19 │ 1 │ [arg('bar', short='=')] │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn long_options_may_follow_an_omitted_positional_argument() { Test::new() .justfile( " [arg('baz', long='baz')] @foo bar='BAR' baz: echo bar={{bar}} echo baz={{baz}} ", ) .args(["foo", "--baz", "BAZ"]) .stdout( " bar=BAR baz=BAZ ", ) .run(); } #[test] fn short_options_may_follow_an_omitted_positional_argument() { Test::new() .justfile( " [arg('baz', short='b')] @foo bar='BAR' baz: echo bar={{bar}} echo baz={{baz}} ", ) .args(["foo", "-b", "BAZ"]) .stdout( " bar=BAR baz=BAZ ", ) .run(); } #[test] fn options_with_a_default_may_be_omitted() { Test::new() .justfile( " [arg('bar', long='bar')] @foo bar='BAR': echo bar={{bar}} ", ) .args(["foo"]) .stdout( " bar=BAR ", ) .run(); } #[test] fn variadics_can_follow_options() { Test::new() .justfile( " [arg('bar', long='bar')] @foo bar *baz: echo bar={{bar}} echo baz={{baz}} ", ) .args(["foo", "--bar=BAR", "A", "B", "C"]) .stdout( " bar=BAR baz=A B C ", ) .run(); } #[test] fn argument_values_starting_with_dashes_are_accepted_if_recipe_does_not_take_options() { Test::new() .justfile( " @foo *baz: echo baz={{baz}} ", ) .args(["foo", "--bar=BAR", "--A", "--B", "--C"]) .stdout( " baz=--bar=BAR --A --B --C ", ) .run(); } #[test] fn argument_values_starting_with_dashes_are_an_error_if_recipe_takes_options() { Test::new() .justfile( " [arg('bar', long='bar')] @foo bar *baz: echo bar={{bar}} echo baz={{baz}} ", ) .args(["foo", "--bar=BAR", "--A", "--B", "--C"]) .stderr("error: Recipe `foo` does not have option `--A`\n") .status(EXIT_FAILURE) .run(); } #[test] fn argument_values_starting_with_dashes_are_accepted_after_double_dash() { Test::new() .justfile( " [arg('bar', long='bar')] @foo bar *baz: echo bar={{bar}} echo baz={{baz}} ", ) .args(["foo", "--bar=BAR", "--", "--A", "--B", "--C"]) .stdout( " bar=BAR baz=--A --B --C ", ) .run(); } #[test] fn positional_and_long_option_arguments_can_be_intermixed() { Test::new() .justfile( " [arg('b', long='b')] [arg('d', long='d')] @foo a b c d e: echo a={{a}} echo b={{b}} echo c={{c}} echo d={{d}} echo e={{e}} ", ) .args(["foo", "A", "--d", "D", "C", "--b", "B", "E"]) .stdout( " a=A b=B c=C d=D e=E ", ) .run(); } #[test] fn positional_and_short_option_arguments_can_be_intermixed() { Test::new() .justfile( " [arg('b', short='b')] [arg('d', short='d')] @foo a b c d e: echo a={{a}} echo b={{b}} echo c={{c}} echo d={{d}} echo e={{e}} ", ) .args(["foo", "A", "-d", "D", "C", "-b", "B", "E"]) .stdout( " a=A b=B c=C d=D e=E ", ) .run(); } #[test] fn unknown_options_are_an_error() { Test::new() .justfile( " [arg('bar', long='bar')] @foo bar: ", ) .args(["foo", "--baz", "BAZ"]) .stderr("error: Recipe `foo` does not have option `--baz`\n") .status(EXIT_FAILURE) .run(); } #[test] fn missing_required_options_are_an_error() { Test::new() .justfile( " [arg('bar', long='bar')] @foo bar: ", ) .arg("foo") .stderr("error: Recipe `foo` requires option `--bar`\n") .status(EXIT_FAILURE) .run(); } #[test] fn duplicate_long_options_are_an_error() { Test::new() .justfile( " [arg('bar', long='bar')] @foo bar: ", ) .args(["foo", "--bar=a", "--bar=b"]) .stderr("error: Recipe `foo` option `--bar` cannot be passed more than once\n") .status(EXIT_FAILURE) .run(); } #[test] fn duplicate_short_options_are_an_error() { Test::new() .justfile( " [arg('bar', short='b')] @foo bar: ", ) .args(["foo", "-b=a", "-b=b"]) .stderr("error: Recipe `foo` option `-b` cannot be passed more than once\n") .status(EXIT_FAILURE) .run(); } #[test] fn options_require_value() { Test::new() .justfile( " [arg('bar', long='bar')] @foo bar: ", ) .args(["foo", "--bar"]) .stderr("error: Recipe `foo` option `--bar` missing value\n") .status(EXIT_FAILURE) .run(); } #[test] fn recipes_with_long_options_have_correct_positional_argument_mismatch_message() { Test::new() .justfile( " [arg('bar', long='bar')] @foo bar baz: ", ) .args(["foo", "--bar=value"]) .stderr( " error: Recipe `foo` got 0 positional arguments but takes 1 usage: just foo [OPTIONS] baz ", ) .status(EXIT_FAILURE) .run(); } #[test] fn recipes_with_short_options_have_correct_positional_argument_mismatch_message() { Test::new() .justfile( " [arg('bar', short='b')] @foo bar baz: ", ) .args(["foo", "-b=value"]) .stderr( " error: Recipe `foo` got 0 positional arguments but takes 1 usage: just foo [OPTIONS] baz ", ) .status(EXIT_FAILURE) .run(); } #[test] fn long_options_with_values_are_flags() { Test::new() .justfile( " [arg('bar', long='bar', value='baz')] @foo bar: echo bar={{bar}} ", ) .args(["foo", "--bar"]) .stdout("bar=baz\n") .run(); } #[test] fn short_options_with_values_are_flags() { Test::new() .justfile( " [arg('bar', short='b', value='baz')] @foo bar: echo bar={{bar}} ", ) .args(["foo", "-b"]) .stdout("bar=baz\n") .run(); } #[test] fn flags_cannot_take_values() { Test::new() .justfile( " [arg('bar', short='b', value='baz')] @foo bar: ", ) .args(["foo", "-b=hello"]) .stderr("error: Recipe `foo` flag `-b` does not take value\n") .status(EXIT_FAILURE) .run(); } #[test] fn value_requires_long_or_short() { Test::new() .justfile( " [arg('bar', value='baz')] @foo bar: ", ) .args(["foo", "-b=hello"]) .stderr( " error: Argument attribute `value` only valid with `long` or `short` ——▶ justfile:1:13 │ 1 │ [arg('bar', value='baz')] │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn options_arg_passed_as_positional_arguments() { Test::new() .justfile( r#" set positional-arguments [arg('bar', short='b')] @foo bar: echo args="$@" "#, ) .args(["foo", "-b", "baz"]) .stdout("args=baz\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/format.rs
tests/format.rs
use super::*; #[test] fn unstable_not_passed() { Test::new() .arg("--fmt") .justfile("") .stderr_regex("error: The `--fmt` command is currently unstable..*") .status(EXIT_FAILURE) .run(); } #[test] fn check_without_fmt() { Test::new() .arg("--check") .justfile("") .stderr_regex( "error: the following required arguments were not provided: --fmt (.|\\n)+", ) .status(2) .run(); } #[test] fn check_ok() { Test::new() .arg("--unstable") .arg("--fmt") .arg("--check") .justfile( r#" # comment with spaces export x := `backtick with lines` recipe: deps echo "$x" deps: echo {{ x }} echo '$x' "#, ) .status(EXIT_SUCCESS) .run(); } #[test] fn check_found_diff() { Test::new() .arg("--unstable") .arg("--fmt") .arg("--check") .justfile("x:=``\n") .stdout( " -x:=`` +x := `` ", ) .stderr( " error: Formatted justfile differs from original. ", ) .status(EXIT_FAILURE) .run(); } #[test] fn check_found_diff_quiet() { Test::new() .arg("--unstable") .arg("--fmt") .arg("--check") .arg("--quiet") .justfile("x:=``\n") .status(EXIT_FAILURE) .run(); } #[test] fn check_diff_color() { Test::new() .justfile("x:=``\n") .arg("--unstable") .arg("--fmt") .arg("--check") .arg("--color") .arg("always") .stdout("\n \u{1b}[31m-x:=``\n \u{1b}[0m\u{1b}[32m+x := ``\n \u{1b}[0m") .stderr("\n \u{1b}[1;31merror\u{1b}[0m: \u{1b}[1mFormatted justfile differs from original.\u{1b}[0m\n ") .status(EXIT_FAILURE) .run(); } #[test] fn unstable_passed() { let tmp = tempdir(); let justfile = tmp.path().join("justfile"); fs::write(&justfile, "x := 'hello' ").unwrap(); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--fmt") .arg("--unstable") .output() .unwrap(); if !output.status.success() { eprintln!("{}", String::from_utf8_lossy(&output.stderr)); eprintln!("{}", String::from_utf8_lossy(&output.stdout)); panic!("justfile failed with status: {}", output.status); } assert_eq!(fs::read_to_string(&justfile).unwrap(), "x := 'hello'\n"); } #[test] fn write_error() { // skip this test if running as root, since root can write files even if // permissions would otherwise forbid it #[cfg(not(windows))] if nix::unistd::getuid() == nix::unistd::ROOT { return; } let tempdir = temptree! { justfile: "x := 'hello' ", }; let test = Test::with_tempdir(tempdir) .no_justfile() .args(["--fmt", "--unstable"]) .status(EXIT_FAILURE) .stderr_regex(if cfg!(windows) { r"error: Failed to write justfile to `.*`: Access is denied. \(os error 5\)\n" } else { r"error: Failed to write justfile to `.*`: Permission denied \(os error 13\)\n" }); let justfile_path = test.justfile_path(); let output = Command::new("chmod") .arg("400") .arg(&justfile_path) .output() .unwrap(); assert!(output.status.success()); let _tempdir = test.run(); assert_eq!( fs::read_to_string(&justfile_path).unwrap(), "x := 'hello' " ); } #[test] fn alias_good() { Test::new() .arg("--dump") .justfile( " alias f := foo foo: echo foo ", ) .stdout( " alias f := foo foo: echo foo ", ) .run(); } #[test] fn alias_fix_indent() { Test::new() .arg("--dump") .justfile( " alias f:= foo foo: echo foo ", ) .stdout( " alias f := foo foo: echo foo ", ) .run(); } #[test] fn assignment_singlequote() { Test::new() .arg("--dump") .justfile( " foo := 'foo' ", ) .stdout( " foo := 'foo' ", ) .run(); } #[test] fn assignment_doublequote() { Test::new() .arg("--dump") .justfile( r#" foo := "foo" "#, ) .stdout( r#" foo := "foo" "#, ) .run(); } #[test] fn assignment_indented_singlequote() { Test::new() .arg("--dump") .justfile( " foo := ''' foo ''' ", ) .stdout( r" foo := ''' foo ''' ", ) .run(); } #[test] fn assignment_indented_doublequote() { Test::new() .arg("--dump") .justfile( r#" foo := """ foo """ "#, ) .stdout( r#" foo := """ foo """ "#, ) .run(); } #[test] fn assignment_backtick() { Test::new() .arg("--dump") .justfile( " foo := `foo` ", ) .stdout( " foo := `foo` ", ) .run(); } #[test] fn assignment_indented_backtick() { Test::new() .arg("--dump") .justfile( " foo := ``` foo ``` ", ) .stdout( " foo := ``` foo ``` ", ) .run(); } #[test] fn assignment_name() { Test::new() .arg("--dump") .justfile( " bar := 'bar' foo := bar ", ) .stdout( " bar := 'bar' foo := bar ", ) .run(); } #[test] fn assignment_parenthesized_expression() { Test::new() .arg("--dump") .justfile( " foo := ('foo') ", ) .stdout( " foo := ('foo') ", ) .run(); } #[test] fn assignment_export() { Test::new() .arg("--dump") .justfile( " export foo := 'foo' ", ) .stdout( " export foo := 'foo' ", ) .run(); } #[test] fn assignment_concat_values() { Test::new() .arg("--dump") .justfile( " foo := 'foo' + 'bar' ", ) .stdout( " foo := 'foo' + 'bar' ", ) .run(); } #[test] fn assignment_if_oneline() { Test::new() .arg("--dump") .justfile( " foo := if 'foo' == 'foo' { 'foo' } else { 'bar' } ", ) .stdout( " foo := if 'foo' == 'foo' { 'foo' } else { 'bar' } ", ) .run(); } #[test] fn assignment_if_multiline() { Test::new() .arg("--dump") .justfile( " foo := if 'foo' != 'foo' { 'foo' } else { 'bar' } ", ) .stdout( " foo := if 'foo' != 'foo' { 'foo' } else { 'bar' } ", ) .run(); } #[test] fn assignment_nullary_function() { Test::new() .arg("--dump") .justfile( " foo := arch() ", ) .stdout( " foo := arch() ", ) .run(); } #[test] fn assignment_unary_function() { Test::new() .arg("--dump") .justfile( " foo := env_var('foo') ", ) .stdout( " foo := env_var('foo') ", ) .run(); } #[test] fn assignment_binary_function() { Test::new() .arg("--dump") .justfile( " foo := env_var_or_default('foo', 'bar') ", ) .stdout( " foo := env_var_or_default('foo', 'bar') ", ) .run(); } #[test] fn assignment_path_functions() { Test::new() .arg("--dump") .justfile( " foo := without_extension('foo/bar.baz') foo2 := file_stem('foo/bar.baz') foo3 := parent_directory('foo/bar.baz') foo4 := file_name('foo/bar.baz') foo5 := extension('foo/bar.baz') ", ) .stdout( " foo := without_extension('foo/bar.baz') foo2 := file_stem('foo/bar.baz') foo3 := parent_directory('foo/bar.baz') foo4 := file_name('foo/bar.baz') foo5 := extension('foo/bar.baz') ", ) .run(); } #[test] fn recipe_ordinary() { Test::new() .justfile( " foo: echo bar ", ) .arg("--dump") .stdout( " foo: echo bar ", ) .run(); } #[test] fn recipe_with_docstring() { Test::new() .arg("--dump") .justfile( " # bar foo: echo bar ", ) .stdout( " # bar foo: echo bar ", ) .run(); } #[test] fn recipe_with_comments_in_body() { Test::new() .arg("--dump") .justfile( " foo: # bar echo bar ", ) .stdout( " foo: # bar echo bar ", ) .run(); } #[test] fn recipe_body_is_comment() { Test::new() .arg("--dump") .justfile( " foo: # bar ", ) .stdout( " foo: # bar ", ) .run(); } #[test] fn recipe_several_commands() { Test::new() .arg("--dump") .justfile( " foo: echo bar echo baz ", ) .stdout( " foo: echo bar echo baz ", ) .run(); } #[test] fn recipe_quiet() { Test::new() .arg("--dump") .justfile( " @foo: echo bar ", ) .stdout( " @foo: echo bar ", ) .run(); } #[test] fn recipe_quiet_command() { Test::new() .arg("--dump") .justfile( " foo: @echo bar ", ) .stdout( " foo: @echo bar ", ) .run(); } #[test] fn recipe_quiet_comment() { Test::new() .arg("--dump") .justfile( " foo: @# bar ", ) .stdout( " foo: @# bar ", ) .run(); } #[test] fn recipe_ignore_errors() { Test::new() .arg("--dump") .justfile( " foo: -echo foo ", ) .stdout( " foo: -echo foo ", ) .run(); } #[test] fn recipe_parameter() { Test::new() .arg("--dump") .justfile( " foo BAR: echo foo ", ) .stdout( " foo BAR: echo foo ", ) .run(); } #[test] fn recipe_parameter_default() { Test::new() .arg("--dump") .justfile( " foo BAR='bar': echo foo ", ) .stdout( " foo BAR='bar': echo foo ", ) .run(); } #[test] fn recipe_parameter_envar() { Test::new() .arg("--dump") .justfile( " foo $BAR: echo foo ", ) .stdout( " foo $BAR: echo foo ", ) .run(); } #[test] fn recipe_parameter_default_envar() { Test::new() .arg("--dump") .justfile( " foo $BAR='foo': echo foo ", ) .stdout( " foo $BAR='foo': echo foo ", ) .run(); } #[test] fn recipe_parameter_concat() { Test::new() .arg("--dump") .justfile( " foo BAR=('bar' + 'baz'): echo foo ", ) .stdout( " foo BAR=('bar' + 'baz'): echo foo ", ) .run(); } #[test] fn recipe_parameters() { Test::new() .arg("--dump") .justfile( " foo BAR BAZ: echo foo ", ) .stdout( " foo BAR BAZ: echo foo ", ) .run(); } #[test] fn recipe_parameters_envar() { Test::new() .arg("--dump") .justfile( " foo $BAR $BAZ: echo foo ", ) .stdout( " foo $BAR $BAZ: echo foo ", ) .run(); } #[test] fn recipe_variadic_plus() { Test::new() .arg("--dump") .justfile( " foo +BAR: echo foo ", ) .stdout( " foo +BAR: echo foo ", ) .run(); } #[test] fn recipe_variadic_star() { Test::new() .arg("--dump") .justfile( " foo *BAR: echo foo ", ) .stdout( " foo *BAR: echo foo ", ) .run(); } #[test] fn recipe_positional_variadic() { Test::new() .arg("--dump") .justfile( " foo BAR *BAZ: echo foo ", ) .stdout( " foo BAR *BAZ: echo foo ", ) .run(); } #[test] fn recipe_variadic_default() { Test::new() .arg("--dump") .justfile( " foo +BAR='bar': echo foo ", ) .stdout( " foo +BAR='bar': echo foo ", ) .run(); } #[test] fn recipe_parameter_in_body() { Test::new() .arg("--dump") .justfile( " foo BAR: echo {{ BAR }} ", ) .stdout( " foo BAR: echo {{ BAR }} ", ) .run(); } #[test] fn recipe_parameter_conditional() { Test::new() .arg("--dump") .justfile( " foo BAR: echo {{ if 'foo' == 'foo' { 'foo' } else { 'bar' } }} ", ) .stdout( " foo BAR: echo {{ if 'foo' == 'foo' { 'foo' } else { 'bar' } }} ", ) .run(); } #[test] fn recipe_escaped_braces() { Test::new() .arg("--dump") .justfile( " foo BAR: echo '{{{{BAR}}}}' ", ) .stdout( " foo BAR: echo '{{{{BAR}}}}' ", ) .run(); } #[test] fn recipe_assignment_in_body() { Test::new() .arg("--dump") .justfile( " bar := 'bar' foo: echo $bar ", ) .stdout( " bar := 'bar' foo: echo $bar ", ) .run(); } #[test] fn recipe_dependency() { Test::new() .arg("--dump") .justfile( " bar: echo bar foo: bar echo foo ", ) .stdout( " bar: echo bar foo: bar echo foo ", ) .run(); } #[test] fn recipe_dependency_param() { Test::new() .arg("--dump") .justfile( " bar BAR: echo bar foo: (bar 'bar') echo foo ", ) .stdout( " bar BAR: echo bar foo: (bar 'bar') echo foo ", ) .run(); } #[test] fn recipe_dependency_params() { Test::new() .arg("--dump") .justfile( " bar BAR BAZ: echo bar foo: (bar 'bar' 'baz') echo foo ", ) .stdout( " bar BAR BAZ: echo bar foo: (bar 'bar' 'baz') echo foo ", ) .run(); } #[test] fn recipe_dependencies() { Test::new() .arg("--dump") .justfile( " bar: echo bar baz: echo baz foo: baz bar echo foo ", ) .stdout( " bar: echo bar baz: echo baz foo: baz bar echo foo ", ) .run(); } #[test] fn recipe_dependencies_params() { Test::new() .arg("--dump") .justfile( " bar BAR: echo bar baz BAZ: echo baz foo: (baz 'baz') (bar 'bar') echo foo ", ) .stdout( " bar BAR: echo bar baz BAZ: echo baz foo: (baz 'baz') (bar 'bar') echo foo ", ) .run(); } #[test] fn set_true_explicit() { Test::new() .arg("--dump") .justfile( " set export := true ", ) .stdout( " set export := true ", ) .run(); } #[test] fn set_true_implicit() { Test::new() .arg("--dump") .justfile( " set export ", ) .stdout( " set export := true ", ) .run(); } #[test] fn set_false() { Test::new() .arg("--dump") .justfile( " set export := false ", ) .stdout( " set export := false ", ) .run(); } #[test] fn set_shell() { Test::new() .arg("--dump") .justfile( r#" set shell := ['sh', "-c"] "#, ) .stdout( r#" set shell := ['sh', "-c"] "#, ) .run(); } #[test] fn comment() { Test::new() .arg("--dump") .justfile( " # foo ", ) .stdout( " # foo ", ) .run(); } #[test] fn comment_multiline() { Test::new() .arg("--dump") .justfile( " # foo # bar ", ) .stdout( " # foo # bar ", ) .run(); } #[test] fn comment_leading() { Test::new() .arg("--dump") .justfile( " # foo foo := 'bar' ", ) .stdout( " # foo foo := 'bar' ", ) .run(); } #[test] fn comment_trailing() { Test::new() .arg("--dump") .justfile( " foo := 'bar' # foo ", ) .stdout( " foo := 'bar' # foo ", ) .run(); } #[test] fn comment_before_recipe() { Test::new() .arg("--dump") .justfile( " # foo foo: echo foo ", ) .stdout( " # foo foo: echo foo ", ) .run(); } #[test] fn comment_before_docstring_recipe() { Test::new() .arg("--dump") .justfile( " # bar # foo foo: echo foo ", ) .stdout( " # bar # foo foo: echo foo ", ) .run(); } #[test] fn group_recipes() { Test::new() .arg("--dump") .justfile( " foo: echo foo bar: echo bar ", ) .stdout( " foo: echo foo bar: echo bar ", ) .run(); } #[test] fn group_aliases() { Test::new() .arg("--dump") .justfile( " alias f := foo alias b := bar foo: echo foo bar: echo bar ", ) .stdout( " alias f := foo alias b := bar foo: echo foo bar: echo bar ", ) .run(); } #[test] fn group_assignments() { Test::new() .arg("--dump") .justfile( " foo := 'foo' bar := 'bar' ", ) .stdout( " foo := 'foo' bar := 'bar' ", ) .run(); } #[test] fn group_sets() { Test::new() .arg("--dump") .justfile( " set export := true set positional-arguments := true ", ) .stdout( " set export := true set positional-arguments := true ", ) .run(); } #[test] fn group_comments() { Test::new() .arg("--dump") .justfile( " # foo # bar ", ) .stdout( " # foo # bar ", ) .run(); } #[test] fn separate_recipes_aliases() { Test::new() .arg("--dump") .justfile( " alias f := foo foo: echo foo ", ) .stdout( " alias f := foo foo: echo foo ", ) .run(); } #[test] fn no_trailing_newline() { Test::new() .arg("--dump") .justfile( " foo: echo foo", ) .stdout( " foo: echo foo ", ) .run(); } #[test] fn subsequent() { Test::new() .arg("--dump") .justfile( " bar: foo: && bar echo foo", ) .stdout( " bar: foo: && bar echo foo ", ) .run(); } #[test] fn exported_parameter() { Test::new() .justfile("foo +$f:") .args(["--dump"]) .stdout("foo +$f:\n") .run(); } #[test] fn multi_argument_attribute() { Test::new() .justfile( " set unstable [script('a', 'b', 'c')] foo: ", ) .arg("--dump") .stdout( " set unstable := true [script('a', 'b', 'c')] foo: ", ) .run(); } #[test] fn doc_attribute_suppresses_comment() { Test::new() .justfile( " set unstable # COMMENT [doc('ATTRIBUTE')] foo: ", ) .arg("--dump") .stdout( " set unstable := true [doc('ATTRIBUTE')] foo: ", ) .run(); } #[test] fn unchanged_justfiles_are_not_written_to_disk() { let tmp = tempdir(); let justfile = tmp.path().join("justfile"); fs::write(&justfile, "").unwrap(); let mut permissions = fs::metadata(&justfile).unwrap().permissions(); permissions.set_readonly(true); fs::set_permissions(&justfile, permissions).unwrap(); Test::with_tempdir(tmp) .no_justfile() .args(["--fmt", "--unstable"]) .run(); } #[test] fn if_else() { Test::new() .justfile( " x := if '' == '' { '' } else if '' == '' { '' } else { '' } ", ) .arg("--dump") .stdout( " x := if '' == '' { '' } else if '' == '' { '' } else { '' } ", ) .run(); } #[test] fn private_variable() { Test::new() .justfile( " [private] foo := 'bar' ", ) .arg("--dump") .stdout( " [private] foo := 'bar' ", ) .run(); } #[test] fn module_groups_are_preserved() { Test::new() .justfile( r#" [group('bar')] [group("baz")] mod foo "#, ) .write("foo.just", "") .arg("--dump") .stdout( r#" [group: 'bar'] [group: "baz"] mod foo "#, ) .run(); } #[test] fn module_docs_are_preserved() { Test::new() .justfile( r" # bar mod foo ", ) .write("foo.just", "") .arg("--dump") .stdout( r" # bar mod foo ", ) .run(); } #[test] fn arg_attribute_long() { Test::new() .justfile( " [arg('bar', long='bar')] @foo bar: ", ) .arg("--dump") .stdout( " [arg('bar', long='bar')] @foo bar: ", ) .run(); } #[test] fn arg_attribute_pattern() { Test::new() .justfile( " [arg('bar', pattern='bar')] @foo bar: ", ) .arg("--dump") .stdout( " [arg('bar', pattern='bar')] @foo bar: ", ) .run(); } #[test] fn arg_attribute_long_and_pattern() { Test::new() .justfile( " [arg('bar', long='foo', pattern='baz')] @foo bar: ", ) .arg("--dump") .stdout( " [arg('bar', long='foo', pattern='baz')] @foo bar: ", ) .run(); } #[test] fn arg_attribute_help() { Test::new() .justfile( " [arg('bar', help='foo')] @foo bar: ", ) .arg("--dump") .stdout( " [arg('bar', help='foo')] @foo bar: ", ) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/run.rs
tests/run.rs
use super::*; #[test] fn dont_run_duplicate_recipes() { Test::new() .justfile( " @foo: echo foo ", ) .args(["foo", "foo"]) .stdout("foo\n") .run(); } #[test] fn one_flag_only_allows_one_invocation() { Test::new() .justfile( " @foo: echo foo ", ) .args(["--one", "foo"]) .stdout("foo\n") .run(); Test::new() .justfile( " @foo: echo foo @bar: echo bar ", ) .args(["--one", "foo", "bar"]) .stderr("error: Expected 1 command-line recipe invocation but found 2.\n") .status(1) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/alias.rs
tests/alias.rs
use super::*; #[test] fn alias_nested_module() { Test::new() .write("foo.just", "mod bar\nbaz: \n @echo FOO") .write("bar.just", "baz:\n @echo BAZ") .justfile( " mod foo alias b := foo::bar::baz baz: @echo 'HERE' ", ) .arg("b") .stdout("BAZ\n") .run(); } #[test] fn unknown_nested_alias() { Test::new() .write("foo.just", "baz: \n @echo FOO") .justfile( " mod foo alias b := foo::bar::baz ", ) .arg("b") .stderr( "\ error: Alias `b` has an unknown target `foo::bar::baz` ——▶ justfile:3:7 │ 3 │ alias b := foo::bar::baz │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn alias_in_submodule() { Test::new() .write( "foo.just", " alias b := bar bar: @echo BAR ", ) .justfile( " mod foo ", ) .arg("foo::b") .stdout("BAR\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/init.rs
tests/init.rs
use {super::*, just::INIT_JUSTFILE}; #[test] fn current_dir() { let tmp = tempdir(); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--init") .output() .unwrap(); assert!(output.status.success()); assert_eq!( fs::read_to_string(tmp.path().join("justfile")).unwrap(), INIT_JUSTFILE ); } #[test] fn exists() { let output = Test::new() .no_justfile() .arg("--init") .stderr_regex("Wrote justfile to `.*`\n") .run(); Test::with_tempdir(output.tempdir) .no_justfile() .arg("--init") .status(EXIT_FAILURE) .stderr_regex("error: Justfile `.*` already exists\n") .run(); } #[test] fn write_error() { let test = Test::new(); let justfile_path = test.justfile_path(); fs::create_dir(justfile_path).unwrap(); test .no_justfile() .args(["--init"]) .status(EXIT_FAILURE) .stderr_regex(if cfg!(windows) { r"error: Failed to write justfile to `.*`: Access is denied. \(os error 5\)\n" } else { r"error: Failed to write justfile to `.*`: Is a directory \(os error 21\)\n" }) .run(); } #[test] fn invocation_directory() { let tmp = temptree! { ".git": {}, }; let test = Test::with_tempdir(tmp); let justfile_path = test.justfile_path(); let _tmp = test .no_justfile() .stderr_regex("Wrote justfile to `.*`\n") .arg("--init") .run(); assert_eq!(fs::read_to_string(justfile_path).unwrap(), INIT_JUSTFILE); } #[test] fn parent_dir() { let tmp = temptree! { ".git": {}, sub: {}, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path().join("sub")) .arg("--init") .output() .unwrap(); assert!(output.status.success()); assert_eq!( fs::read_to_string(tmp.path().join("justfile")).unwrap(), INIT_JUSTFILE ); } #[test] fn alternate_marker() { let tmp = temptree! { "_darcs": {}, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--init") .output() .unwrap(); assert!(output.status.success()); assert_eq!( fs::read_to_string(tmp.path().join("justfile")).unwrap(), INIT_JUSTFILE ); } #[test] fn search_directory() { let tmp = temptree! { sub: { ".git": {}, }, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--init") .arg("sub/") .output() .unwrap(); assert!(output.status.success()); assert_eq!( fs::read_to_string(tmp.path().join("sub/justfile")).unwrap(), INIT_JUSTFILE ); } #[test] fn justfile() { let tmp = temptree! { sub: { ".git": {}, }, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path().join("sub")) .arg("--init") .arg("--justfile") .arg(tmp.path().join("justfile")) .output() .unwrap(); assert!(output.status.success()); assert_eq!( fs::read_to_string(tmp.path().join("justfile")).unwrap(), INIT_JUSTFILE ); } #[test] fn justfile_and_working_directory() { let tmp = temptree! { sub: { ".git": {}, }, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path().join("sub")) .arg("--init") .arg("--justfile") .arg(tmp.path().join("justfile")) .arg("--working-directory") .arg("/") .output() .unwrap(); assert!(output.status.success()); assert_eq!( fs::read_to_string(tmp.path().join("justfile")).unwrap(), INIT_JUSTFILE ); } #[test] fn fmt_compatibility() { let output = Test::new() .no_justfile() .arg("--init") .stderr_regex("Wrote justfile to `.*`\n") .run(); Test::with_tempdir(output.tempdir) .no_justfile() .arg("--unstable") .arg("--check") .arg("--fmt") .status(EXIT_SUCCESS) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/completions.rs
tests/completions.rs
use super::*; #[test] #[cfg(target_os = "linux")] fn bash() { let output = Command::new(executable_path("just")) .args(["--completions", "bash"]) .output() .unwrap(); assert!(output.status.success()); let script = str::from_utf8(&output.stdout).unwrap(); let tempdir = tempdir(); let path = tempdir.path().join("just.bash"); fs::write(&path, script).unwrap(); let status = Command::new("./tests/completions/just.bash") .arg(path) .status() .unwrap(); assert!(status.success()); } #[test] fn replacements() { for shell in ["bash", "elvish", "fish", "nushell", "powershell", "zsh"] { let output = Command::new(executable_path("just")) .args(["--completions", shell]) .output() .unwrap(); assert!( output.status.success(), "shell completion generation for {shell} failed: {}\n{}", output.status, String::from_utf8_lossy(&output.stderr), ); } }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/shebang.rs
tests/shebang.rs
use super::*; #[cfg(windows)] #[test] fn powershell() { Test::new() .justfile( r#" default: #!powershell Write-Host Hello-World "#, ) .stdout("Hello-World\n") .run(); } #[cfg(windows)] #[test] fn powershell_exe() { Test::new() .justfile( r#" default: #!powershell.exe Write-Host Hello-World "#, ) .stdout("Hello-World\n") .run(); } #[cfg(windows)] #[test] fn cmd() { Test::new() .justfile( r#" default: #!cmd /c @echo Hello-World "#, ) .stdout("Hello-World\r\n") .run(); } #[cfg(windows)] #[test] fn cmd_exe() { Test::new() .justfile( r#" default: #!cmd.exe /c @echo Hello-World "#, ) .stdout("Hello-World\r\n") .run(); } #[cfg(windows)] #[test] fn multi_line_cmd_shebangs_are_removed() { Test::new() .justfile( r#" default: #!cmd.exe /c #!foo @echo Hello-World "#, ) .stdout("Hello-World\r\n") .run(); } #[test] fn simple() { Test::new() .justfile( " foo: #!/bin/sh echo bar ", ) .stdout("bar\n") .run(); } #[test] fn echo() { Test::new() .justfile( " @baz: #!/bin/sh echo fizz ", ) .stdout("fizz\n") .stderr("#!/bin/sh\necho fizz\n") .run(); } #[test] fn echo_with_command_color() { Test::new() .justfile( " @baz: #!/bin/sh echo fizz ", ) .args(["--color", "always", "--command-color", "purple"]) .stdout("fizz\n") .stderr("\u{1b}[1;35m#!/bin/sh\u{1b}[0m\n\u{1b}[1;35mecho fizz\u{1b}[0m\n") .run(); } // This test exists to make sure that shebang recipes run correctly. Although // this script is still executed by a shell its behavior depends on the value of // a variable and continuing even though a command fails, whereas in plain // recipes variables are not available in subsequent lines and execution stops // when a line fails. #[test] fn run_shebang() { Test::new() .justfile( " a: #!/usr/bin/env sh code=200 x() { return $code; } x x ", ) .status(200) .stderr("error: Recipe `a` failed with exit code 200\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/attributes.rs
tests/attributes.rs
use super::*; #[test] fn all() { Test::new() .justfile( " [macos] [linux] [openbsd] [unix] [windows] [no-exit-message] foo: exit 1 ", ) .stderr("exit 1\n") .status(1) .run(); } #[test] fn duplicate_attributes_are_disallowed() { Test::new() .justfile( " [no-exit-message] [no-exit-message] foo: echo bar ", ) .stderr( " error: Recipe attribute `no-exit-message` first used on line 1 is duplicated on line 2 ——▶ justfile:2:2 │ 2 │ [no-exit-message] │ ^^^^^^^^^^^^^^^ ", ) .status(1) .run(); } #[test] fn multiple_attributes_one_line() { Test::new() .justfile( " [macos,windows,linux,openbsd] [no-exit-message] foo: exit 1 ", ) .stderr("exit 1\n") .status(1) .run(); } #[test] fn multiple_attributes_one_line_error_message() { Test::new() .justfile( " [macos,windows linux,openbsd] [no-exit-message] foo: exit 1 ", ) .stderr( " error: Expected ']', ':', ',', or '(', but found identifier ——▶ justfile:1:16 │ 1 │ [macos,windows linux,openbsd] │ ^^^^^ ", ) .status(1) .run(); } #[test] fn multiple_attributes_one_line_duplicate_check() { Test::new() .justfile( " [macos, windows, linux, openbsd] [linux] foo: exit 1 ", ) .stderr( " error: Recipe attribute `linux` first used on line 1 is duplicated on line 2 ——▶ justfile:2:2 │ 2 │ [linux] │ ^^^^^ ", ) .status(1) .run(); } #[test] fn unexpected_attribute_argument() { Test::new() .justfile( " [private('foo')] foo: exit 1 ", ) .stderr( " error: Attribute `private` got 1 argument but takes 0 arguments ——▶ justfile:1:2 │ 1 │ [private('foo')] │ ^^^^^^^ ", ) .status(1) .run(); } #[test] fn multiple_metadata_attributes() { Test::new() .justfile( " [metadata('example')] [metadata('sample')] [no-exit-message] foo: exit 1 ", ) .stderr("exit 1\n") .status(1) .run(); } #[test] fn multiple_metadata_attributes_with_multiple_args() { Test::new() .justfile( " [metadata('example', 'arg1')] [metadata('sample', 'argument')] [no-exit-message] foo: exit 1 ", ) .stderr("exit 1\n") .status(1) .run(); } #[test] fn expected_metadata_attribute_argument() { Test::new() .justfile( " [metadata] foo: exit 1 ", ) .stderr( " error: Attribute `metadata` got 0 arguments but takes at least 1 argument ——▶ justfile:1:2 │ 1 │ [metadata] │ ^^^^^^^^ ", ) .status(1) .run(); } #[test] fn doc_attribute() { Test::new() .justfile( " # Non-document comment [doc('The real docstring')] foo: echo foo ", ) .args(["--list"]) .stdout( " Available recipes: foo # The real docstring ", ) .run(); } #[test] fn doc_attribute_suppress() { Test::new() .justfile( " # Non-document comment [doc] foo: echo foo ", ) .args(["--list"]) .stdout( " Available recipes: foo ", ) .run(); } #[test] fn doc_multiline() { Test::new() .justfile( " [doc('multiline comment')] foo: ", ) .args(["--list"]) .stdout( " Available recipes: # multiline # comment foo ", ) .run(); } #[test] fn extension() { Test::new() .justfile( " [extension: '.txt'] baz: #!/bin/sh echo $0 ", ) .stdout_regex(r"*baz\.txt\n") .run(); } #[test] fn extension_on_linewise_error() { Test::new() .justfile( " [extension: '.txt'] baz: ", ) .stderr( " error: Recipe `baz` has invalid attribute `extension` ——▶ justfile:2:1 │ 2 │ baz: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn duplicate_non_repeatable_attributes_are_forbidden() { Test::new() .justfile( " [confirm: 'yes'] [confirm: 'no'] baz: ", ) .stderr( " error: Recipe attribute `confirm` first used on line 1 is duplicated on line 2 ——▶ justfile:2:2 │ 2 │ [confirm: 'no'] │ ^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn shell_expanded_strings_can_be_used_in_attributes() { Test::new() .justfile( " [doc(x'foo')] bar: ", ) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/arg_attribute.rs
tests/arg_attribute.rs
use super::*; #[test] fn pattern_match() { Test::new() .justfile( " [arg('bar', pattern='BAR')] foo bar: ", ) .args(["foo", "BAR"]) .run(); } #[test] fn pattern_mismatch() { Test::new() .justfile( " [arg('bar', pattern='BAR')] foo bar: ", ) .args(["foo", "bar"]) .stderr( " error: Argument `bar` passed to recipe `foo` parameter `bar` does not match pattern 'BAR' ", ) .status(EXIT_FAILURE) .run(); } #[test] fn patterns_are_regulare_expressions() { Test::new() .justfile( r" [arg('bar', pattern='\d+')] foo bar: ", ) .args(["foo", r"\d+"]) .stderr( r" error: Argument `\d+` passed to recipe `foo` parameter `bar` does not match pattern '\d+' ", ) .status(EXIT_FAILURE) .run(); } #[test] fn pattern_must_match_entire_string() { Test::new() .justfile( " [arg('bar', pattern='bar')] foo bar: ", ) .args(["foo", "xbarx"]) .stderr( " error: Argument `xbarx` passed to recipe `foo` parameter `bar` does not match pattern 'bar' ", ) .status(EXIT_FAILURE) .run(); } #[test] fn pattern_invalid_regex_error() { Test::new() .justfile( " [arg('bar', pattern='{')] foo bar: ", ) .stderr( " error: Failed to parse argument pattern ——▶ justfile:1:21 │ 1 │ [arg('bar', pattern='{')] │ ^^^ caused by: regex parse error: { ^ error: repetition operator missing expression ", ) .status(EXIT_FAILURE) .run(); } #[test] fn dump() { Test::new() .justfile( " [arg('bar', pattern='BAR')] foo bar: ", ) .arg("--dump") .stdout( " [arg('bar', pattern='BAR')] foo bar: ", ) .run(); } #[test] fn duplicate_attribute_error() { Test::new() .justfile( " [arg('bar', pattern='BAR')] [arg('bar', pattern='BAR')] foo bar: ", ) .args(["foo", "BAR"]) .stderr( " error: Recipe attribute for argument `bar` first used on line 1 is duplicated on line 2 ——▶ justfile:2:2 │ 2 │ [arg('bar', pattern='BAR')] │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn extra_keyword_error() { Test::new() .justfile( " [arg('bar', pattern='BAR', foo='foo')] foo bar: ", ) .args(["foo", "BAR"]) .stderr( " error: Unknown keyword `foo` for `arg` attribute ——▶ justfile:1:28 │ 1 │ [arg('bar', pattern='BAR', foo='foo')] │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unknown_argument_error() { Test::new() .justfile( " [arg('bar', pattern='BAR')] foo: ", ) .arg("foo") .stderr( " error: Argument attribute for undefined argument `bar` ——▶ justfile:1:6 │ 1 │ [arg('bar', pattern='BAR')] │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn split_across_multiple_lines() { Test::new() .justfile( " [arg( 'bar', pattern='BAR' )] foo bar: ", ) .args(["foo", "BAR"]) .run(); } #[test] fn optional_trailing_comma() { Test::new() .justfile( " [arg( 'bar', pattern='BAR', )] foo bar: ", ) .args(["foo", "BAR"]) .run(); } #[test] fn positional_arguments_cannot_follow_keyword_arguments() { Test::new() .justfile( " [arg(pattern='BAR', 'bar')] foo bar: ", ) .args(["foo", "BAR"]) .stderr( " error: Positional attribute arguments cannot follow keyword attribute arguments ——▶ justfile:1:21 │ 1 │ [arg(pattern='BAR', 'bar')] │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn pattern_mismatches_are_caught_before_running_dependencies() { Test::new() .justfile( " baz: exit 1 [arg('bar', pattern='BAR')] foo bar: baz ", ) .args(["foo", "bar"]) .stderr( " error: Argument `bar` passed to recipe `foo` parameter `bar` does not match pattern 'BAR' ", ) .status(EXIT_FAILURE) .run(); } #[test] fn pattern_mismatches_are_caught_before_running_invocation() { Test::new() .justfile( " baz: exit 1 [arg('bar', pattern='BAR')] foo bar: baz ", ) .args(["baz", "foo", "bar"]) .stderr( " error: Argument `bar` passed to recipe `foo` parameter `bar` does not match pattern 'BAR' ", ) .status(EXIT_FAILURE) .run(); } #[test] fn pattern_mismatches_are_caught_in_evaluated_arguments() { Test::new() .justfile( " bar: (foo 'ba' + 'r') [arg('bar', pattern='BAR')] foo bar: ", ) .stderr( " error: Argument `bar` passed to recipe `foo` parameter `bar` does not match pattern 'BAR' ", ) .status(EXIT_FAILURE) .run(); } #[test] fn alternates_do_not_bind_to_anchors() { Test::new() .justfile( " [arg('bar', pattern='a|b')] foo bar: ", ) .args(["foo", "aa"]) .stderr( " error: Argument `aa` passed to recipe `foo` parameter `bar` does not match pattern 'a|b' ", ) .status(EXIT_FAILURE) .run(); } #[test] fn pattern_match_variadic() { Test::new() .justfile( " [arg('bar', pattern='BAR')] foo *bar: ", ) .args(["foo", "BAR", "BAR"]) .run(); } #[test] fn pattern_mismatch_variadic() { Test::new() .justfile( " [arg('bar', pattern='BAR BAR')] foo *bar: ", ) .args(["foo", "BAR", "BAR"]) .stderr( " error: Argument `BAR` passed to recipe `foo` parameter `bar` does not match pattern 'BAR BAR' ", ) .status(EXIT_FAILURE) .run(); } #[test] fn pattern_requires_value() { Test::new() .justfile( " [arg('bar', pattern)] foo bar: ", ) .stderr( " error: Attribute key `pattern` requires value ——▶ justfile:1:13 │ 1 │ [arg('bar', pattern)] │ ^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn short_requires_value() { Test::new() .justfile( " [arg('bar', short)] foo bar: ", ) .stderr( " error: Attribute key `short` requires value ——▶ justfile:1:13 │ 1 │ [arg('bar', short)] │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn value_requires_value() { Test::new() .justfile( " [arg('bar', long, value)] foo bar: ", ) .stderr( " error: Attribute key `value` requires value ——▶ justfile:1:19 │ 1 │ [arg('bar', long, value)] │ ^^^^^ ", ) .status(EXIT_FAILURE) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/groups.rs
tests/groups.rs
use super::*; #[test] fn list_with_groups() { Test::new() .justfile( " [group('alpha')] a: # Doc comment [group('alpha')] [group('beta')] b: c: [group('multi word group')] d: [group('alpha')] e: [group('beta')] [group('alpha')] f: ", ) .arg("--list") .stdout( " Available recipes: c [alpha] a b # Doc comment e f [beta] b # Doc comment f [multi word group] d ", ) .run(); } #[test] fn list_with_groups_unsorted() { Test::new() .justfile( " [group('beta')] [group('alpha')] f: [group('alpha')] e: [group('multi word group')] d: c: # Doc comment [group('alpha')] [group('beta')] b: [group('alpha')] a: ", ) .args(["--list", "--unsorted"]) .stdout( " Available recipes: c [alpha] f e b # Doc comment a [beta] f b # Doc comment [multi word group] d ", ) .run(); } #[test] fn list_with_groups_unsorted_group_order() { Test::new() .justfile( " [group('y')] [group('x')] f: [group('b')] b: [group('a')] e: c: ", ) .args(["--list", "--unsorted"]) .stdout( " Available recipes: c [x] f [y] f [b] b [a] e ", ) .run(); } #[test] fn list_groups() { Test::new() .justfile( " [group('B')] bar: [group('A')] [group('B')] foo: ", ) .args(["--groups"]) .stdout( " Recipe groups: A B ", ) .run(); } #[test] fn list_groups_with_custom_prefix() { Test::new() .justfile( " [group('B')] foo: [group('A')] [group('B')] bar: ", ) .args(["--groups", "--list-prefix", "..."]) .stdout( " Recipe groups: ...A ...B ", ) .run(); } #[test] fn list_groups_with_shorthand_syntax() { Test::new() .justfile( " [group: 'B'] foo: [group: 'A', group: 'B'] bar: ", ) .arg("--groups") .stdout( " Recipe groups: A B ", ) .run(); } #[test] fn list_groups_unsorted() { Test::new() .justfile( " [group: 'Z'] baz: [group: 'B'] foo: [group: 'A', group: 'B'] bar: ", ) .args(["--groups", "--unsorted"]) .stdout( " Recipe groups: Z B A ", ) .run(); } #[test] fn list_groups_private_unsorted() { Test::new() .justfile( " [private] [group: 'A'] foo: [group: 'B'] bar: [group: 'A'] baz: ", ) .args(["--groups", "--unsorted"]) .stdout( " Recipe groups: B A ", ) .run(); } #[test] fn list_groups_private() { Test::new() .justfile( " [private] [group: 'A'] foo: [group: 'B'] bar: ", ) .args(["--groups", "--unsorted"]) .stdout( " Recipe groups: B ", ) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/show.rs
tests/show.rs
use super::*; #[test] fn show() { Test::new() .arg("--show") .arg("recipe") .justfile( r#"hello := "foo" bar := hello + hello recipe: echo {{hello + "bar" + bar}}"#, ) .stdout( r#" recipe: echo {{ hello + "bar" + bar }} "#, ) .run(); } #[test] fn alias_show() { Test::new() .arg("--show") .arg("f") .justfile("foo:\n bar\nalias f := foo") .stdout( " alias f := foo foo: bar ", ) .run(); } #[test] fn alias_show_missing_target() { Test::new() .arg("--show") .arg("f") .justfile("alias f := foo") .status(EXIT_FAILURE) .stderr( " error: Alias `f` has an unknown target `foo` ——▶ justfile:1:7 │ 1 │ alias f := foo │ ^ ", ) .run(); } #[test] fn show_suggestion() { Test::new() .arg("--show") .arg("hell") .justfile( r#" hello a b='B ' c='C': echo {{a}} {{b}} {{c}} a Z="\t z": "#, ) .stderr("error: Justfile does not contain recipe `hell`\nDid you mean `hello`?\n") .status(EXIT_FAILURE) .run(); } #[test] fn show_alias_suggestion() { Test::new() .arg("--show") .arg("fo") .justfile( r#" hello a b='B ' c='C': echo {{a}} {{b}} {{c}} alias foo := hello a Z="\t z": "#, ) .stderr( " error: Justfile does not contain recipe `fo` Did you mean `foo`, an alias for `hello`? ", ) .status(EXIT_FAILURE) .run(); } #[test] fn show_no_suggestion() { Test::new() .arg("--show") .arg("hell") .justfile( r#" helloooooo a b='B ' c='C': echo {{a}} {{b}} {{c}} a Z="\t z": "#, ) .stderr("error: Justfile does not contain recipe `hell`\n") .status(EXIT_FAILURE) .run(); } #[test] fn show_no_alias_suggestion() { Test::new() .arg("--show") .arg("fooooooo") .justfile( r#" hello a b='B ' c='C': echo {{a}} {{b}} {{c}} alias foo := hello a Z="\t z": "#, ) .stderr("error: Justfile does not contain recipe `fooooooo`\n") .status(EXIT_FAILURE) .run(); } #[test] fn show_recipe_at_path() { Test::new() .write("foo.just", "bar:\n @echo MODULE") .justfile( " mod foo ", ) .args(["--show", "foo::bar"]) .stdout("bar:\n @echo MODULE\n") .run(); } #[test] fn show_invalid_path() { Test::new() .args(["--show", "$hello"]) .stderr("error: Invalid module path `$hello`\n") .status(1) .run(); } #[test] fn show_space_separated_path() { Test::new() .write("foo.just", "bar:\n @echo MODULE") .justfile( " mod foo ", ) .args(["--show", "foo bar"]) .stdout("bar:\n @echo MODULE\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/edit.rs
tests/edit.rs
use super::*; const JUSTFILE: &str = "Yooooooo, hopefully this never becomes valid syntax."; /// Test that --edit doesn't require a valid justfile #[test] fn invalid_justfile() { let tmp = temptree! { justfile: JUSTFILE, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .output() .unwrap(); assert!(!output.status.success()); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--edit") .env("VISUAL", "cat") .output() .unwrap(); assert_stdout(&output, JUSTFILE); } #[test] fn invoke_error() { let tmp = temptree! { justfile: JUSTFILE, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .output() .unwrap(); assert!(!output.status.success()); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--edit") .env("VISUAL", "/") .output() .unwrap(); assert_eq!( String::from_utf8_lossy(&output.stderr), if cfg!(windows) { "error: Editor `/` invocation failed: program path has no file name\n" } else { "error: Editor `/` invocation failed: Permission denied (os error 13)\n" } ); } #[test] #[cfg(not(windows))] fn status_error() { let tmp = temptree! { justfile: JUSTFILE, "exit-2": "#!/usr/bin/env bash\nexit 2\n", }; let output = Command::new("chmod") .arg("+x") .arg(tmp.path().join("exit-2")) .output() .unwrap(); assert!(output.status.success()); let path = env::join_paths( iter::once(tmp.path().to_owned()).chain(env::split_paths(&env::var_os("PATH").unwrap())), ) .unwrap(); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--edit") .env("PATH", path) .env("VISUAL", "exit-2") .output() .unwrap(); assert!( Regex::new("^error: Editor `exit-2` failed: exit (code|status): 2\n$") .unwrap() .is_match(str::from_utf8(&output.stderr).unwrap()) ); assert_eq!(output.status.code().unwrap(), 2); } /// Test that editor is $VISUAL, $EDITOR, or "vim" in that order #[test] fn editor_precedence() { let tmp = temptree! { justfile: JUSTFILE, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--edit") .env("VISUAL", "cat") .env("EDITOR", "this-command-doesnt-exist") .output() .unwrap(); assert_stdout(&output, JUSTFILE); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--edit") .env_remove("VISUAL") .env("EDITOR", "cat") .output() .unwrap(); assert_stdout(&output, JUSTFILE); let cat = which("cat").unwrap(); let vim = tmp.path().join(format!("vim{EXE_SUFFIX}")); #[cfg(unix)] std::os::unix::fs::symlink(cat, vim).unwrap(); #[cfg(windows)] std::os::windows::fs::symlink_file(cat, vim).unwrap(); let path = env::join_paths( iter::once(tmp.path().to_owned()).chain(env::split_paths(&env::var_os("PATH").unwrap())), ) .unwrap(); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--edit") .env("PATH", path) .env_remove("VISUAL") .env_remove("EDITOR") .output() .unwrap(); assert_stdout(&output, JUSTFILE); } /// Test that editor working directory is the same as edited justfile #[cfg(unix)] #[test] fn editor_working_directory() { let tmp = temptree! { justfile: JUSTFILE, child: {}, editor: "#!/usr/bin/env sh\ncat $1\npwd", }; let editor = tmp.path().join("editor"); let permissions = std::os::unix::fs::PermissionsExt::from_mode(0o700); fs::set_permissions(&editor, permissions).unwrap(); let output = Command::new(executable_path("just")) .current_dir(tmp.path().join("child")) .arg("--edit") .env("VISUAL", &editor) .output() .unwrap(); let want = format!( "{JUSTFILE}{}\n", tmp.path().canonicalize().unwrap().display() ); assert_stdout(&output, &want); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/tempdir.rs
tests/tempdir.rs
use super::*; pub(crate) fn tempdir() -> TempDir { let mut builder = tempfile::Builder::new(); builder.prefix("just-test-tempdir"); if let Some(runtime_dir) = dirs::runtime_dir() { let path = runtime_dir.join("just"); fs::create_dir_all(&path).unwrap(); builder.tempdir_in(path) } else { builder.tempdir() } .expect("failed to create temporary directory") } #[test] fn setting() { Test::new() .justfile( " set tempdir := '.' foo: #!/usr/bin/env bash cat just*/foo ", ) .shell(false) .tree(tree! { bar: { } }) .current_dir("bar") .stdout(if cfg!(windows) { " cat just*/foo " } else { " #!/usr/bin/env bash cat just*/foo " }) .run(); } #[test] fn argument_overrides_setting() { Test::new() .args(["--tempdir", "."]) .justfile( " set tempdir := 'hello' foo: #!/usr/bin/env bash cat just*/foo ", ) .shell(false) .tree(tree! { bar: { } }) .current_dir("bar") .stdout(if cfg!(windows) { " cat just*/foo " } else { " #!/usr/bin/env bash cat just*/foo " }) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/script.rs
tests/script.rs
use super::*; #[test] fn runs_with_command() { Test::new() .justfile( " [script('cat')] foo: FOO ", ) .stdout( " FOO ", ) .run(); } #[test] fn no_arguments() { Test::new() .justfile( " [script('sh')] foo: echo foo ", ) .stdout("foo\n") .run(); } #[test] fn with_arguments() { Test::new() .justfile( " [script('sh', '-x')] foo: echo foo ", ) .stdout("foo\n") .stderr("+ echo foo\n") .run(); } #[test] fn allowed_with_shebang() { Test::new() .justfile( " [script('cat')] foo: #!/bin/sh ", ) .stdout( " #!/bin/sh ", ) .run(); } #[test] fn script_line_numbers() { Test::new() .justfile( " [script('cat')] foo: FOO BAR ", ) .stdout( " FOO BAR ", ) .run(); } #[test] fn script_line_numbers_with_multi_line_recipe_signature() { Test::new() .justfile( r" [script('cat')] foo bar='baz' \ : FOO BAR {{ \ bar \ }} BAZ ", ) .stdout( " FOO BAR baz BAZ ", ) .run(); } #[cfg(not(windows))] #[test] fn shebang_line_numbers() { Test::new() .justfile( "foo: #!/usr/bin/env cat a b c ", ) .stdout( "#!/usr/bin/env cat a b c ", ) .run(); } #[cfg(not(windows))] #[test] fn shebang_line_numbers_with_multiline_constructs() { Test::new() .justfile( r"foo b='b'\ : #!/usr/bin/env cat a {{ \ b \ }} c ", ) .stdout( "#!/usr/bin/env cat a b c ", ) .run(); } #[cfg(not(windows))] #[test] fn multiline_shebang_line_numbers() { Test::new() .justfile( "foo: #!/usr/bin/env cat #!shebang #!shebang a b c ", ) .stdout( "#!/usr/bin/env cat #!shebang #!shebang a b c ", ) .run(); } #[cfg(windows)] #[test] fn shebang_line_numbers() { Test::new() .justfile( "foo: #!/usr/bin/env cat a b c ", ) .stdout( " a b c ", ) .run(); } #[test] fn no_arguments_with_default_script_interpreter() { Test::new() .justfile( " [script] foo: case $- in *e*) echo '-e is set';; esac case $- in *u*) echo '-u is set';; esac ", ) .stdout( " -e is set -u is set ", ) .run(); } #[test] fn no_arguments_with_non_default_script_interpreter() { Test::new() .justfile( " set script-interpreter := ['sh'] [script] foo: case $- in *e*) echo '-e is set';; esac case $- in *u*) echo '-u is set';; esac ", ) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/constants.rs
tests/constants.rs
use super::*; #[test] fn constants_are_defined() { assert_eval_eq("HEX", "0123456789abcdef"); } #[test] fn constants_can_have_different_values_on_windows() { assert_eval_eq("PATH_SEP", if cfg!(windows) { "\\" } else { "/" }); assert_eval_eq("PATH_VAR_SEP", if cfg!(windows) { ";" } else { ":" }); } #[test] fn constants_are_defined_in_recipe_bodies() { Test::new() .justfile( " @foo: echo {{HEX}} ", ) .stdout("0123456789abcdef\n") .run(); } #[test] fn constants_are_defined_in_recipe_parameters() { Test::new() .justfile( " @foo hex=HEX: echo {{hex}} ", ) .stdout("0123456789abcdef\n") .run(); } #[test] fn constants_can_be_redefined() { Test::new() .justfile( " HEX := 'foo' ", ) .args(["--evaluate", "HEX"]) .stdout("foo") .run(); } #[test] fn constants_are_not_exported() { Test::new() .justfile( r#" set export foo: @'{{just_executable()}}' --request '{"environment-variable": "HEXUPPER"}' "#, ) .response(Response::EnvironmentVariable(None)) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/line_prefixes.rs
tests/line_prefixes.rs
use super::*; #[test] fn infallible_after_quiet() { Test::new() .justfile( " foo: @-exit 1 ", ) .run(); } #[test] fn quiet_after_infallible() { Test::new() .justfile( " foo: -@exit 1 ", ) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/export.rs
tests/export.rs
use super::*; #[test] fn success() { Test::new() .justfile( r#" export FOO := "a" baz := "c" export BAR := "b" export ABC := FOO + BAR + baz wut: echo $FOO $BAR $ABC "#, ) .stdout("a b abc\n") .stderr("echo $FOO $BAR $ABC\n") .run(); } #[test] fn parameter() { Test::new() .justfile( r#" wut $FOO='a' BAR='b': echo $FOO echo {{BAR}} if [ -n "${BAR+1}" ]; then echo defined; else echo undefined; fi "#, ) .stdout("a\nb\nundefined\n") .stderr( "echo $FOO\necho b\nif [ -n \"${BAR+1}\" ]; then echo defined; else echo undefined; fi\n", ) .run(); } #[test] fn parameter_not_visible_to_backtick() { Test::new() .arg("wut") .arg("bar") .justfile( r#" wut $FOO BAR=`if [ -n "${FOO+1}" ]; then echo defined; else echo undefined; fi`: echo $FOO echo {{BAR}} "#, ) .stdout("bar\nundefined\n") .stderr("echo $FOO\necho undefined\n") .run(); } #[test] fn override_variable() { Test::new() .arg("--set") .arg("BAR") .arg("bye") .arg("FOO=hello") .justfile( r#" export FOO := "a" baz := "c" export BAR := "b" export ABC := FOO + "-" + BAR + "-" + baz wut: echo $FOO $BAR $ABC "#, ) .stdout("hello bye hello-bye-c\n") .stderr("echo $FOO $BAR $ABC\n") .run(); } #[test] fn shebang() { Test::new() .justfile( r#" export FOO := "a" baz := "c" export BAR := "b" export ABC := FOO + BAR + baz wut: #!/bin/sh echo $FOO $BAR $ABC "#, ) .stdout("a b abc\n") .run(); } #[test] fn recipe_backtick() { Test::new() .justfile( r#" export EXPORTED_VARIABLE := "A-IS-A" recipe: echo {{`echo recipe $EXPORTED_VARIABLE`}} "#, ) .stdout("recipe A-IS-A\n") .stderr("echo recipe A-IS-A\n") .run(); } #[test] fn setting_implicit() { Test::new() .arg("foo") .arg("goodbye") .justfile( " set export A := 'hello' foo B C=`echo $A`: echo $A echo $B echo $C ", ) .stdout("hello\ngoodbye\nhello\n") .stderr("echo $A\necho $B\necho $C\n") .run(); } #[test] fn setting_true() { Test::new() .justfile( " set export := true A := 'hello' foo B C=`echo $A`: echo $A echo $B echo $C ", ) .arg("foo") .arg("goodbye") .stdout("hello\ngoodbye\nhello\n") .stderr("echo $A\necho $B\necho $C\n") .run(); } #[test] fn setting_false() { Test::new() .justfile( r#" set export := false A := 'hello' foo: if [ -n "${A+1}" ]; then echo defined; else echo undefined; fi "#, ) .stdout("undefined\n") .stderr("if [ -n \"${A+1}\" ]; then echo defined; else echo undefined; fi\n") .run(); } #[test] fn setting_shebang() { Test::new() .arg("foo") .arg("goodbye") .justfile( " set export A := 'hello' foo B: #!/bin/sh echo $A echo $B ", ) .stdout("hello\ngoodbye\n") .run(); } #[test] fn setting_override_undefined() { Test::new() .arg("A=zzz") .arg("foo") .justfile( r#" set export A := 'hello' B := `if [ -n "${A+1}" ]; then echo defined; else echo undefined; fi` foo C='goodbye' D=`if [ -n "${C+1}" ]; then echo defined; else echo undefined; fi`: echo $B echo $D "#, ) .stdout("undefined\nundefined\n") .stderr("echo $B\necho $D\n") .run(); } #[test] fn setting_variable_not_visible() { Test::new() .arg("A=zzz") .justfile( r#" export A := 'hello' export B := `if [ -n "${A+1}" ]; then echo defined; else echo undefined; fi` foo: echo $B "#, ) .stdout("undefined\n") .stderr("echo $B\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/request.rs
tests/request.rs
use super::*; #[test] fn environment_variable_set() { Test::new() .justfile( r#" export BAR := 'baz' @foo: '{{just_executable()}}' --request '{"environment-variable": "BAR"}' "#, ) .response(Response::EnvironmentVariable(Some("baz".into()))) .run(); } #[test] fn environment_variable_missing() { Test::new() .justfile( r#" @foo: '{{just_executable()}}' --request '{"environment-variable": "FOO_BAR_BAZ"}' "#, ) .response(Response::EnvironmentVariable(None)) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/conditional.rs
tests/conditional.rs
use super::*; #[test] fn then_branch_unevaluated() { Test::new() .justfile( " foo: echo {{ if 'a' == 'b' { `exit 1` } else { 'otherwise' } }} ", ) .stdout("otherwise\n") .stderr("echo otherwise\n") .run(); } #[test] fn otherwise_branch_unevaluated() { Test::new() .justfile( " foo: echo {{ if 'a' == 'a' { 'then' } else { `exit 1` } }} ", ) .stdout("then\n") .stderr("echo then\n") .run(); } #[test] fn otherwise_branch_unevaluated_inverted() { Test::new() .justfile( " foo: echo {{ if 'a' != 'b' { 'then' } else { `exit 1` } }} ", ) .stdout("then\n") .stderr("echo then\n") .run(); } #[test] fn then_branch_unevaluated_inverted() { Test::new() .justfile( " foo: echo {{ if 'a' != 'a' { `exit 1` } else { 'otherwise' } }} ", ) .stdout("otherwise\n") .stderr("echo otherwise\n") .run(); } #[test] fn complex_expressions() { Test::new() .justfile( " foo: echo {{ if 'a' + 'b' == `echo ab` { 'c' + 'd' } else { 'e' + 'f' } }} ", ) .stdout("cd\n") .stderr("echo cd\n") .run(); } #[test] fn undefined_lhs() { Test::new() .justfile( " a := if b == '' { '' } else { '' } foo: echo {{ a }} ", ) .stderr( " error: Variable `b` not defined ——▶ justfile:1:9 │ 1 │ a := if b == '' { '' } else { '' } │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn undefined_rhs() { Test::new() .justfile( " a := if '' == b { '' } else { '' } foo: echo {{ a }} ", ) .stderr( " error: Variable `b` not defined ——▶ justfile:1:15 │ 1 │ a := if '' == b { '' } else { '' } │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn undefined_then() { Test::new() .justfile( " a := if '' == '' { b } else { '' } foo: echo {{ a }} ", ) .stderr( " error: Variable `b` not defined ——▶ justfile:1:20 │ 1 │ a := if '' == '' { b } else { '' } │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn undefined_otherwise() { Test::new() .justfile( " a := if '' == '' { '' } else { b } foo: echo {{ a }} ", ) .stderr( " error: Variable `b` not defined ——▶ justfile:1:32 │ 1 │ a := if '' == '' { '' } else { b } │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn unexpected_op() { Test::new() .justfile( " a := if '' a '' { '' } else { b } foo: echo {{ a }} ", ) .stderr( " error: Expected '&&', '!=', '!~', '||', '==', '=~', '+', or '/', but found identifier ——▶ justfile:1:12 │ 1 │ a := if '' a '' { '' } else { b } │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn dump() { Test::new() .arg("--dump") .justfile( " a := if '' == '' { '' } else { '' } foo: echo {{ a }} ", ) .stdout( " a := if '' == '' { '' } else { '' } foo: echo {{ a }} ", ) .run(); } #[test] fn if_else() { Test::new() .justfile( " x := if '0' == '1' { 'a' } else if '0' == '0' { 'b' } else { 'c' } foo: echo {{ x }} ", ) .stdout("b\n") .stderr("echo b\n") .run(); } #[test] fn missing_else() { Test::new() .justfile( " TEST := if path_exists('/bin/bash') == 'true' {'yes'} ", ) .stderr( " error: Expected keyword `else` but found `end of line` ——▶ justfile:1:54 │ 1 │ TEST := if path_exists('/bin/bash') == 'true' {'yes'} │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn incorrect_else_identifier() { Test::new() .justfile( " TEST := if path_exists('/bin/bash') == 'true' {'yes'} els {'no'} ", ) .stderr( " error: Expected keyword `else` but found identifier `els` ——▶ justfile:1:55 │ 1 │ TEST := if path_exists('/bin/bash') == 'true' {'yes'} els {'no'} │ ^^^ ", ) .status(EXIT_FAILURE) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/interpolation.rs
tests/interpolation.rs
use super::*; #[test] fn closing_curly_brace_can_abut_interpolation_close() { Test::new() .justfile( " foo: echo {{if 'a' == 'b' { 'c' } else { 'd' }}} ", ) .stderr("echo d\n") .stdout("d\n") .run(); } #[test] fn eol_with_continuation_in_interpolation() { Test::new() .justfile( " foo: echo {{( 'a' )}} ", ) .stderr("echo a\n") .stdout("a\n") .run(); } #[test] fn eol_without_continuation_in_interpolation() { Test::new() .justfile( " foo: echo {{ 'a' }} ", ) .stderr("echo a\n") .stdout("a\n") .run(); } #[test] fn comment_in_interopolation() { Test::new() .justfile( " foo: echo {{ # hello 'a' }} ", ) .stderr( " error: Expected backtick, identifier, '(', '/', or string, but found comment ——▶ justfile:2:11 │ 2 │ echo {{ # hello │ ^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn indent_and_dedent_are_ignored_in_interpolation() { Test::new() .justfile( " foo: echo {{ 'a' + 'b' + 'c' }} echo foo ", ) .stderr("echo abc\necho foo\n") .stdout("abc\nfoo\n") .run(); } #[test] fn shebang_line_numbers_are_correct_with_multi_line_interpolations() { Test::new() .justfile( " foo: #!/usr/bin/env cat echo {{ 'a' + 'b' + 'c' }} echo foo ", ) .stdout(if cfg!(windows) { " echo abc echo foo " } else { " #!/usr/bin/env cat echo abc echo foo " }) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/quote.rs
tests/quote.rs
use super::*; #[test] fn single_quotes_are_prepended_and_appended() { Test::new() .justfile( " x := quote('abc') ", ) .args(["--evaluate", "x"]) .stdout("'abc'") .run(); } #[test] fn quotes_are_escaped() { Test::new() .justfile( r#" x := quote("'") "#, ) .args(["--evaluate", "x"]) .stdout(r"''\'''") .run(); } #[test] fn quoted_strings_can_be_used_as_arguments() { Test::new() .justfile( r#" file := quote("foo ' bar") @foo: touch {{ file }} ls -1 "#, ) .stdout("foo ' bar\njustfile\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/fallback.rs
tests/fallback.rs
use super::*; #[test] fn fallback_from_subdir_bugfix() { Test::new() .write( "sub/justfile", unindent( " set fallback @default: echo foo ", ), ) .args(["sub/default"]) .stdout("foo\n") .run(); } #[test] fn fallback_from_subdir_message() { Test::new() .justfile("bar:\n echo bar") .write( "sub/justfile", unindent( " set fallback @foo: echo foo ", ), ) .args(["sub/bar"]) .stderr(path("echo bar\n")) .stdout("bar\n") .run(); } #[test] fn fallback_from_subdir_verbose_message() { Test::new() .justfile("bar:\n echo bar") .write( "sub/justfile", unindent( " set fallback @foo: echo foo ", ), ) .args(["--verbose", "sub/bar"]) .stderr(path( " Trying ../justfile ===> Running recipe `bar`... echo bar ", )) .stdout("bar\n") .run(); } #[test] fn runs_recipe_in_parent_if_not_found_in_current() { Test::new() .tree(tree! { bar: { justfile: " set fallback := true baz: echo subdir " } }) .justfile( " foo: echo root ", ) .args(["foo"]) .current_dir("bar") .stderr( " echo root ", ) .stdout("root\n") .run(); } #[test] fn setting_accepts_value() { Test::new() .tree(tree! { bar: { justfile: " set fallback := true baz: echo subdir " } }) .justfile( " foo: echo root ", ) .args(["foo"]) .current_dir("bar") .stderr( " echo root ", ) .stdout("root\n") .run(); } #[test] fn print_error_from_parent_if_recipe_not_found_in_current() { Test::new() .tree(tree! { bar: { justfile: " set fallback := true baz: echo subdir " } }) .justfile("foo:\n echo {{bar}}") .args(["foo"]) .current_dir("bar") .stderr( " error: Variable `bar` not defined ——▶ justfile:2:9 │ 2 │ echo {{bar}} │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn requires_setting() { Test::new() .tree(tree! { bar: { justfile: " baz: echo subdir " } }) .justfile( " foo: echo root ", ) .args(["foo"]) .current_dir("bar") .status(EXIT_FAILURE) .stderr("error: Justfile does not contain recipe `foo`\n") .run(); } #[test] fn works_with_provided_search_directory() { Test::new() .tree(tree! { bar: { justfile: " set fallback := true baz: echo subdir " } }) .justfile( " foo: echo root ", ) .args(["./foo"]) .stdout("root\n") .stderr( " echo root ", ) .current_dir("bar") .run(); } #[test] fn doesnt_work_with_justfile() { Test::new() .tree(tree! { bar: { justfile: " baz: echo subdir " } }) .justfile( " foo: echo root ", ) .args(["--justfile", "justfile", "foo"]) .current_dir("bar") .status(EXIT_FAILURE) .stderr("error: Justfile does not contain recipe `foo`\n") .run(); } #[test] fn doesnt_work_with_justfile_and_working_directory() { Test::new() .tree(tree! { bar: { justfile: " baz: echo subdir " } }) .justfile( " foo: echo root ", ) .args(["--justfile", "justfile", "--working-directory", ".", "foo"]) .current_dir("bar") .status(EXIT_FAILURE) .stderr("error: Justfile does not contain recipe `foo`\n") .run(); } #[test] fn prints_correct_error_message_when_recipe_not_found() { Test::new() .tree(tree! { bar: { justfile: " set fallback := true bar: echo subdir " } }) .justfile( " bar: echo root ", ) .args(["foo"]) .current_dir("bar") .status(EXIT_FAILURE) .stderr( " error: Justfile does not contain recipe `foo` ", ) .run(); } #[test] fn multiple_levels_of_fallback_work() { Test::new() .tree(tree! { a: { b: { justfile: " set fallback := true foo: echo subdir " }, justfile: " set fallback := true bar: echo subdir " } }) .justfile( " baz: echo root ", ) .args(["baz"]) .current_dir("a/b") .stdout("root\n") .stderr( " echo root ", ) .run(); } #[test] fn stop_fallback_when_fallback_is_false() { Test::new() .tree(tree! { a: { b: { justfile: " set fallback := true foo: echo subdir " }, justfile: " bar: echo subdir " } }) .justfile( " baz: echo root ", ) .args(["baz"]) .current_dir("a/b") .stderr( " error: Justfile does not contain recipe `baz` Did you mean `bar`? ", ) .status(EXIT_FAILURE) .run(); } #[test] fn works_with_modules() { Test::new() .write("bar/justfile", "set fallback := true") .write("foo.just", "baz:\n @echo BAZ") .justfile("mod foo") .args(["foo::baz"]) .current_dir("bar") .stdout("BAZ\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/dependencies.rs
tests/dependencies.rs
use super::*; #[test] fn recipe_doubly_nested_module_dependencies() { Test::new() .write("foo.just", "mod bar\nbaz: \n @echo FOO") .write("bar.just", "baz:\n @echo BAZ") .justfile( " mod foo baz: foo::bar::baz ", ) .arg("baz") .stdout("BAZ\n") .run(); } #[test] fn recipe_singly_nested_module_dependencies() { Test::new() .write("foo.just", "mod bar\nbaz: \n @echo BAR") .write("bar.just", "baz:\n @echo BAZ") .justfile( " mod foo baz: foo::baz ", ) .arg("baz") .stdout("BAR\n") .run(); } #[test] fn dependency_not_in_submodule() { Test::new() .write("foo.just", "qux: \n @echo QUX") .justfile( " mod foo baz: foo::baz ", ) .arg("baz") .status(1) .stderr( "error: Recipe `baz` has unknown dependency `foo::baz` ——▶ justfile:2:11 │ 2 │ baz: foo::baz │ ^^^ ", ) .run(); } #[test] fn dependency_submodule_missing() { Test::new() .justfile( " foo: @echo FOO bar: @echo BAR baz: foo::bar ", ) .arg("baz") .status(1) .stderr( "error: Recipe `baz` has unknown dependency `foo::bar` ——▶ justfile:5:11 │ 5 │ baz: foo::bar │ ^^^ ", ) .run(); } #[test] fn recipe_dependency_on_module_fails() { Test::new() .write("foo.just", "mod bar\nbaz: \n @echo BAR") .write("bar.just", "baz:\n @echo BAZ") .justfile( " mod foo baz: foo::bar ", ) .arg("baz") .status(1) .stderr( "error: Recipe `baz` has unknown dependency `foo::bar` ——▶ justfile:2:11 │ 2 │ baz: foo::bar │ ^^^ ", ) .run(); } #[test] fn recipe_module_dependency_subsequent_mix() { Test::new() .write("foo.just", "bar: \n @echo BAR") .justfile( " mod foo baz: @echo BAZ quux: foo::bar && baz @echo QUUX ", ) .arg("quux") .stdout("BAR\nQUUX\nBAZ\n") .run(); } #[test] fn recipe_module_dependency_only_runs_once() { Test::new() .write("foo.just", "bar: baz \n \nbaz: \n @echo BAZ") .justfile( " mod foo qux: foo::bar foo::baz ", ) .arg("qux") .stdout("BAZ\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/working_directory.rs
tests/working_directory.rs
use super::*; const JUSTFILE: &str = r#" foo := `cat data` linewise bar=`cat data`: shebang echo expression: {{foo}} echo default: {{bar}} echo linewise: `cat data` shebang: #!/usr/bin/env sh echo "shebang:" `cat data` "#; const DATA: &str = "OK"; const WANT: &str = "shebang: OK\nexpression: OK\ndefault: OK\nlinewise: OK\n"; /// Test that just runs with the correct working directory when invoked with /// `--justfile` but not `--working-directory` #[test] fn justfile_without_working_directory() -> Result<(), Box<dyn Error>> { let tmp = temptree! { justfile: JUSTFILE, data: DATA, }; let output = Command::new(executable_path("just")) .arg("--justfile") .arg(tmp.path().join("justfile")) .output()?; if !output.status.success() { eprintln!("{:?}", String::from_utf8_lossy(&output.stderr)); panic!(); } let stdout = String::from_utf8(output.stdout).unwrap(); assert_eq!(stdout, WANT); Ok(()) } /// Test that just runs with the correct working directory when invoked with /// `--justfile` but not `--working-directory`, and justfile path has no parent #[test] fn justfile_without_working_directory_relative() -> Result<(), Box<dyn Error>> { let tmp = temptree! { justfile: JUSTFILE, data: DATA, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--justfile") .arg("justfile") .output()?; if !output.status.success() { eprintln!("{:?}", String::from_utf8_lossy(&output.stderr)); panic!(); } let stdout = String::from_utf8(output.stdout).unwrap(); assert_eq!(stdout, WANT); Ok(()) } /// Test that just invokes commands from the directory in which the justfile is /// found #[test] fn change_working_directory_to_search_justfile_parent() -> Result<(), Box<dyn Error>> { let tmp = temptree! { justfile: JUSTFILE, data: DATA, subdir: {}, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path().join("subdir")) .output()?; if !output.status.success() { eprintln!("{:?}", String::from_utf8_lossy(&output.stderr)); panic!(); } let stdout = String::from_utf8_lossy(&output.stdout); assert_eq!(stdout, WANT); Ok(()) } /// Test that just runs with the correct working directory when invoked with /// `--justfile` but not `--working-directory` #[test] fn justfile_and_working_directory() -> Result<(), Box<dyn Error>> { let tmp = temptree! { justfile: JUSTFILE, sub: { data: DATA, }, }; let output = Command::new(executable_path("just")) .arg("--justfile") .arg(tmp.path().join("justfile")) .arg("--working-directory") .arg(tmp.path().join("sub")) .output()?; if !output.status.success() { eprintln!("{:?}", String::from_utf8_lossy(&output.stderr)); panic!(); } let stdout = String::from_utf8(output.stdout).unwrap(); assert_eq!(stdout, WANT); Ok(()) } /// Test that just runs with the correct working directory when invoked with /// `--justfile` but not `--working-directory` #[test] fn search_dir_child() -> Result<(), Box<dyn Error>> { let tmp = temptree! { child: { justfile: JUSTFILE, data: DATA, }, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("child/") .output()?; if !output.status.success() { eprintln!("{:?}", String::from_utf8_lossy(&output.stderr)); panic!(); } let stdout = String::from_utf8(output.stdout).unwrap(); assert_eq!(stdout, WANT); Ok(()) } /// Test that just runs with the correct working directory when invoked with /// `--justfile` but not `--working-directory` #[test] fn search_dir_parent() -> Result<(), Box<dyn Error>> { let tmp = temptree! { child: { }, justfile: JUSTFILE, data: DATA, }; let output = Command::new(executable_path("just")) .current_dir(tmp.path().join("child")) .arg("../") .output()?; if !output.status.success() { eprintln!("{:?}", String::from_utf8_lossy(&output.stderr)); panic!(); } let stdout = String::from_utf8(output.stdout).unwrap(); assert_eq!(stdout, WANT); Ok(()) } #[test] fn setting() { Test::new() .justfile( r#" set working-directory := 'bar' print1: echo "$(basename "$PWD")" [no-cd] print2: echo "$(basename "$PWD")" "#, ) .current_dir("foo") .tree(tree! { foo: {}, bar: {} }) .args(["print1", "print2"]) .stderr( r#"echo "$(basename "$PWD")" echo "$(basename "$PWD")" "#, ) .stdout("bar\nfoo\n") .run(); } #[test] fn no_cd_overrides_setting() { Test::new() .justfile( " set working-directory := 'bar' [no-cd] foo: cat bar ", ) .current_dir("foo") .tree(tree! { foo: { bar: "hello", } }) .stderr("cat bar\n") .stdout("hello") .run(); } #[test] fn working_dir_in_submodule_is_relative_to_module_path() { Test::new() .write( "foo/mod.just", " set working-directory := 'bar' @foo: cat file.txt ", ) .justfile("mod foo") .write("foo/bar/file.txt", "FILE") .arg("foo") .stdout("FILE") .run(); } #[test] fn working_dir_applies_to_backticks() { Test::new() .justfile( " set working-directory := 'foo' file := `cat file.txt` @foo: echo {{ file }} ", ) .write("foo/file.txt", "FILE") .stdout("FILE\n") .run(); } #[test] fn working_dir_applies_to_shell_function() { Test::new() .justfile( " set working-directory := 'foo' file := shell('cat file.txt') @foo: echo {{ file }} ", ) .write("foo/file.txt", "FILE") .stdout("FILE\n") .run(); } #[test] fn working_dir_applies_to_backticks_in_submodules() { Test::new() .justfile("mod foo") .write( "foo/mod.just", " set working-directory := 'bar' file := `cat file.txt` @foo: echo {{ file }} ", ) .arg("foo") .write("foo/bar/file.txt", "FILE") .stdout("FILE\n") .run(); } #[test] fn working_dir_applies_to_shell_function_in_submodules() { Test::new() .justfile("mod foo") .write( "foo/mod.just", " set working-directory := 'bar' file := shell('cat file.txt') @foo: echo {{ file }} ", ) .arg("foo") .write("foo/bar/file.txt", "FILE") .stdout("FILE\n") .run(); } #[test] fn attribute_duplicate() { Test::new() .justfile( " [working-directory('bar')] [working-directory('baz')] foo: ", ) .stderr( "error: Recipe attribute `working-directory` first used on line 1 is duplicated on line 2 ——▶ justfile:2:2 │ 2 │ [working-directory('baz')] │ ^^^^^^^^^^^^^^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn attribute() { Test::new() .justfile( " [working-directory('foo')] @qux: echo baz > bar ", ) .create_dir("foo") .expect_file("foo/bar", "baz\n") .run(); } #[test] fn attribute_with_nocd_is_forbidden() { Test::new() .justfile( " [working-directory('foo')] [no-cd] bar: ", ) .stderr( " error: Recipe `bar` has both `[no-cd]` and `[working-directory]` attributes ——▶ justfile:3:1 │ 3 │ bar: │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn setting_and_attribute() { Test::new() .justfile( " set working-directory := 'foo' [working-directory('bar')] @baz: echo bob > fred ", ) .create_dir("foo/bar") .expect_file("foo/bar/fred", "bob\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/allow_missing.rs
tests/allow_missing.rs
use super::*; #[test] fn allow_missing_recipes_in_run_invocation() { Test::new() .arg("foo") .stderr("error: Justfile does not contain recipe `foo`\n") .status(EXIT_FAILURE) .run(); Test::new().args(["--allow-missing", "foo"]).run(); } #[test] fn allow_missing_modules_in_run_invocation() { Test::new() .arg("foo::bar") .stderr("error: Justfile does not contain submodule `foo`\n") .status(EXIT_FAILURE) .run(); Test::new().args(["--allow-missing", "foo::bar"]).run(); } #[test] fn allow_missing_does_not_apply_to_compilation_errors() { Test::new() .justfile("bar: foo") .args(["--allow-missing", "foo"]) .stderr( " error: Recipe `bar` has unknown dependency `foo` ——▶ justfile:1:6 │ 1 │ bar: foo │ ^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn allow_missing_does_not_apply_to_other_subcommands() { Test::new() .args(["--allow-missing", "--show", "foo"]) .stderr("error: Justfile does not contain recipe `foo`\n") .status(EXIT_FAILURE) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/private.rs
tests/private.rs
use super::*; #[test] fn private_attribute_for_recipe() { Test::new() .justfile( " [private] foo: ", ) .args(["--list"]) .stdout( " Available recipes: ", ) .run(); } #[test] fn private_attribute_for_alias() { Test::new() .justfile( " [private] alias f := foo foo: ", ) .args(["--list"]) .stdout( " Available recipes: foo ", ) .run(); } #[test] fn private_attribute_for_module() { Test::new() .write("foo.just", "bar:") .justfile( r" [private] mod foo baz: ", ) .test_round_trip(false) .arg("--list") .stdout( " Available recipes: baz ", ) .run(); } #[test] fn private_variables_are_not_listed() { Test::new() .justfile( " [private] foo := 'one' bar := 'two' _baz := 'three' ", ) .args(["--variables"]) .stdout("bar\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/confirm.rs
tests/confirm.rs
use super::*; #[test] fn confirm_recipe_arg() { Test::new() .arg("--yes") .justfile( " [confirm] requires_confirmation: echo confirmed ", ) .stderr("echo confirmed\n") .stdout("confirmed\n") .run(); } #[test] fn recipe_with_confirm_recipe_dependency_arg() { Test::new() .arg("--yes") .justfile( " dep_confirmation: requires_confirmation echo confirmed2 [confirm] requires_confirmation: echo confirmed ", ) .stderr("echo confirmed\necho confirmed2\n") .stdout("confirmed\nconfirmed2\n") .run(); } #[test] fn confirm_recipe() { Test::new() .justfile( " [confirm] requires_confirmation: echo confirmed ", ) .stderr("Run recipe `requires_confirmation`? echo confirmed\n") .stdout("confirmed\n") .stdin("y") .run(); } #[test] fn recipe_with_confirm_recipe_dependency() { Test::new() .justfile( " dep_confirmation: requires_confirmation echo confirmed2 [confirm] requires_confirmation: echo confirmed ", ) .stderr("Run recipe `requires_confirmation`? echo confirmed\necho confirmed2\n") .stdout("confirmed\nconfirmed2\n") .stdin("y") .run(); } #[test] fn do_not_confirm_recipe() { Test::new() .justfile( " [confirm] requires_confirmation: echo confirmed ", ) .stderr("Run recipe `requires_confirmation`? error: Recipe `requires_confirmation` was not confirmed\n") .status(1) .run(); } #[test] fn do_not_confirm_recipe_with_confirm_recipe_dependency() { Test::new() .justfile( " dep_confirmation: requires_confirmation echo mistake [confirm] requires_confirmation: echo confirmed ", ) .stderr("Run recipe `requires_confirmation`? error: Recipe `requires_confirmation` was not confirmed\n") .status(1) .run(); } #[test] fn confirm_recipe_with_prompt() { Test::new() .justfile( " [confirm(\"This is dangerous - are you sure you want to run it?\")] requires_confirmation: echo confirmed ", ) .stderr("This is dangerous - are you sure you want to run it? echo confirmed\n") .stdout("confirmed\n") .stdin("y") .run(); } #[test] fn confirm_recipe_with_prompt_too_many_args() { Test::new() .justfile( r#" [confirm("PROMPT","EXTRA")] requires_confirmation: echo confirmed "#, ) .stderr( r#" error: Attribute `confirm` got 2 arguments but takes at most 1 argument ——▶ justfile:1:2 │ 1 │ [confirm("PROMPT","EXTRA")] │ ^^^^^^^ "#, ) .status(1) .run(); } #[test] fn confirm_attribute_is_formatted_correctly() { Test::new() .justfile( " [confirm('prompt')] foo: ", ) .arg("--dump") .stdout("[confirm('prompt')]\nfoo:\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/recursion_limit.rs
tests/recursion_limit.rs
use super::*; #[test] fn bugfix() { let mut justfile = String::from("foo: (x "); for _ in 0..500 { justfile.push('('); } Test::new() .justfile(&justfile) .stderr(RECURSION_LIMIT_REACHED) .status(EXIT_FAILURE) .run(); } #[cfg(not(windows))] const RECURSION_LIMIT_REACHED: &str = " error: Parsing recursion depth exceeded ——▶ justfile:1:265 │ 1 │ foo: (x (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( │ ^ "; #[cfg(windows)] const RECURSION_LIMIT_REACHED: &str = " error: Parsing recursion depth exceeded ——▶ justfile:1:57 │ 1 │ foo: (x (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( │ ^ ";
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/assert_stdout.rs
tests/assert_stdout.rs
use super::*; pub(crate) fn assert_stdout(output: &std::process::Output, stdout: &str) { assert_success(output); assert_eq!(String::from_utf8_lossy(&output.stdout), stdout); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/logical_operators.rs
tests/logical_operators.rs
use super::*; #[track_caller] fn evaluate(expression: &str, expected: &str) { Test::new() .justfile(format!("x := {expression}")) .env("JUST_UNSTABLE", "1") .args(["--evaluate", "x"]) .stdout(expected) .run(); } #[test] fn logical_operators_are_unstable() { Test::new() .justfile("x := 'foo' && 'bar'") .args(["--evaluate", "x"]) .stderr_regex(r"error: The logical operators `&&` and `\|\|` are currently unstable. .*") .status(EXIT_FAILURE) .run(); Test::new() .justfile("x := 'foo' || 'bar'") .args(["--evaluate", "x"]) .stderr_regex(r"error: The logical operators `&&` and `\|\|` are currently unstable. .*") .status(EXIT_FAILURE) .run(); } #[test] fn and_returns_empty_string_if_lhs_is_empty() { evaluate("'' && 'hello'", ""); } #[test] fn and_returns_rhs_if_lhs_is_non_empty() { evaluate("'hello' && 'goodbye'", "goodbye"); } #[test] fn and_has_lower_precedence_than_plus() { evaluate("'' && 'goodbye' + 'foo'", ""); evaluate("'foo' + 'hello' && 'goodbye'", "goodbye"); evaluate("'foo' + '' && 'goodbye'", "goodbye"); evaluate("'foo' + 'hello' && 'goodbye' + 'bar'", "goodbyebar"); } #[test] fn or_returns_rhs_if_lhs_is_empty() { evaluate("'' || 'hello'", "hello"); } #[test] fn or_returns_lhs_if_lhs_is_non_empty() { evaluate("'hello' || 'goodbye'", "hello"); } #[test] fn or_has_lower_precedence_than_plus() { evaluate("'' || 'goodbye' + 'foo'", "goodbyefoo"); evaluate("'foo' + 'hello' || 'goodbye'", "foohello"); evaluate("'foo' + '' || 'goodbye'", "foo"); evaluate("'foo' + 'hello' || 'goodbye' + 'bar'", "foohello"); } #[test] fn and_has_higher_precedence_than_or() { evaluate("('' && 'foo') || 'bar'", "bar"); evaluate("'' && 'foo' || 'bar'", "bar"); evaluate("'a' && 'b' || 'c'", "b"); } #[test] fn nesting() { evaluate("'' || '' || '' || '' || 'foo'", "foo"); evaluate("'foo' && 'foo' && 'foo' && 'foo' && 'bar'", "bar"); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/assignment.rs
tests/assignment.rs
use super::*; #[test] fn set_export_parse_error() { Test::new() .justfile( " set export := fals ", ) .stderr( " error: Expected keyword `true` or `false` but found identifier `fals` ——▶ justfile:1:15 │ 1 │ set export := fals │ ^^^^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn set_export_parse_error_eol() { Test::new() .justfile( " set export := ", ) .stderr( " error: Expected identifier, but found end of line ——▶ justfile:1:14 │ 1 │ set export := │ ^ ", ) .status(EXIT_FAILURE) .run(); } #[test] fn invalid_attributes_are_an_error() { Test::new() .justfile( " [group: 'bar'] x := 'foo' ", ) .args(["--evaluate", "x"]) .stderr( " error: Assignment `x` has invalid attribute `group` ——▶ justfile:2:1 │ 2 │ x := 'foo' │ ^ ", ) .status(EXIT_FAILURE) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/assertions.rs
tests/assertions.rs
use super::*; #[test] fn assert_pass() { Test::new() .justfile( " foo: {{ assert('a' == 'a', 'error message') }} ", ) .run(); } #[test] fn assert_fail() { Test::new() .justfile( " foo: {{ assert('a' != 'a', 'error message') }} ", ) .stderr( " error: Assert failed: error message ——▶ justfile:2:6 │ 2 │ {{ assert('a' != 'a', 'error message') }} │ ^^^^^^ ", ) .status(EXIT_FAILURE) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/choose.rs
tests/choose.rs
use super::*; #[test] fn env() { Test::new() .arg("--choose") .env("JUST_CHOOSER", "head -n1") .justfile( " foo: echo foo bar: echo bar ", ) .stderr("echo bar\n") .stdout("bar\n") .run(); } #[test] fn chooser() { Test::new() .arg("--choose") .arg("--chooser") .arg("head -n1") .justfile( " foo: echo foo bar: echo bar ", ) .stderr("echo bar\n") .stdout("bar\n") .run(); } #[test] fn override_variable() { Test::new() .arg("--choose") .arg("baz=B") .env("JUST_CHOOSER", "head -n1") .justfile( " baz := 'A' foo: echo foo bar: echo {{baz}} ", ) .stderr("echo B\n") .stdout("B\n") .run(); } #[test] fn skip_private_recipes() { Test::new() .arg("--choose") .env("JUST_CHOOSER", "head -n1") .justfile( " foo: echo foo _bar: echo bar ", ) .stderr("echo foo\n") .stdout("foo\n") .run(); } #[test] fn recipes_in_submodules_can_be_chosen() { Test::new() .args(["--unstable", "--choose"]) .env("JUST_CHOOSER", "head -n10") .write("bar.just", "baz:\n echo BAZ") .justfile( " mod bar ", ) .stderr("echo BAZ\n") .stdout("BAZ\n") .run(); } #[test] fn skip_recipes_that_require_arguments() { Test::new() .arg("--choose") .env("JUST_CHOOSER", "head -n1") .justfile( " foo: echo foo bar BAR: echo {{BAR}} ", ) .stderr("echo foo\n") .stdout("foo\n") .run(); } #[test] fn no_choosable_recipes() { Test::new() .arg("--choose") .justfile( " _foo: echo foo bar BAR: echo {{BAR}} ", ) .status(EXIT_FAILURE) .stderr("error: Justfile contains no choosable recipes.\n") .run(); } #[test] fn multiple_recipes() { Test::new() .arg("--choose") .arg("--chooser") .arg("echo foo bar") .justfile( " foo: echo foo bar: echo bar ", ) .stderr("echo foo\necho bar\n") .stdout("foo\nbar\n") .run(); } #[test] fn invoke_error_function() { Test::new() .justfile( " foo: echo foo bar: echo bar ", ) .stderr_regex( r#"error: Chooser `/ -cu fzf --multi --preview 'just --unstable --color always --justfile ".*justfile" --show \{\}'` invocation failed: .*\n"#, ) .status(EXIT_FAILURE) .shell(false) .args(["--shell", "/", "--choose"]) .run(); } #[test] #[cfg(not(windows))] fn status_error() { let tmp = temptree! { justfile: "foo:\n echo foo\nbar:\n echo bar\n", "exit-2": "#!/usr/bin/env bash\nexit 2\n", }; let output = Command::new("chmod") .arg("+x") .arg(tmp.path().join("exit-2")) .output() .unwrap(); assert!(output.status.success()); let path = env::join_paths( iter::once(tmp.path().to_owned()).chain(env::split_paths(&env::var_os("PATH").unwrap())), ) .unwrap(); let output = Command::new(executable_path("just")) .current_dir(tmp.path()) .arg("--choose") .arg("--chooser") .arg("exit-2") .env("PATH", path) .output() .unwrap(); assert!( Regex::new("^error: Chooser `exit-2` failed: exit (code|status): 2\n$") .unwrap() .is_match(str::from_utf8(&output.stderr).unwrap()) ); assert_eq!(output.status.code().unwrap(), 2); } #[test] fn default() { let tmp = temptree! { justfile: "foo:\n echo foo\n", }; let cat = which("cat").unwrap(); let fzf = tmp.path().join(format!("fzf{EXE_SUFFIX}")); #[cfg(unix)] std::os::unix::fs::symlink(cat, fzf).unwrap(); #[cfg(windows)] std::os::windows::fs::symlink_file(cat, fzf).unwrap(); let path = env::join_paths( iter::once(tmp.path().to_owned()).chain(env::split_paths(&env::var_os("PATH").unwrap())), ) .unwrap(); let output = Command::new(executable_path("just")) .arg("--choose") .arg("--chooser=fzf") .current_dir(tmp.path()) .env("PATH", path) .output() .unwrap(); assert_stdout(&output, "foo\n"); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/timestamps.rs
tests/timestamps.rs
use super::*; #[test] fn print_timestamps() { Test::new() .justfile( " recipe: echo 'one' ", ) .arg("--timestamp") .stderr_regex(concat!(r"\[\d\d:\d\d:\d\d\] echo 'one'", "\n")) .stdout("one\n") .run(); } #[test] fn print_timestamps_with_format_string() { Test::new() .justfile( " recipe: echo 'one' ", ) .args(["--timestamp", "--timestamp-format", "%H:%M:%S.%3f"]) .stderr_regex(concat!(r"\[\d\d:\d\d:\d\d\.\d\d\d] echo 'one'", "\n")) .stdout("one\n") .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/examples.rs
tests/examples.rs
use super::*; #[test] fn examples() { for result in fs::read_dir("examples").unwrap() { let entry = result.unwrap(); let path = entry.path(); println!("Parsing `{}`…", path.display()); let output = Command::new(executable_path("just")) .arg("--justfile") .arg(&path) .arg("--dump") .output() .unwrap(); assert_success(&output); } }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/signals.rs
tests/signals.rs
use {super::*, nix::sys::signal::Signal, nix::unistd::Pid, std::process::Child}; fn kill(child: &Child, signal: Signal) { nix::sys::signal::kill(Pid::from_raw(child.id().try_into().unwrap()), signal).unwrap(); } fn interrupt_test(arguments: &[&str], justfile: &str) { let tmp = tempdir(); let mut justfile_path = tmp.path().to_path_buf(); justfile_path.push("justfile"); fs::write(justfile_path, unindent(justfile)).unwrap(); let start = Instant::now(); let mut child = Command::new(executable_path("just")) .current_dir(&tmp) .args(arguments) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .expect("just invocation failed"); while start.elapsed() < Duration::from_millis(500) {} kill(&child, Signal::SIGINT); let status = child.wait().unwrap(); let elapsed = start.elapsed(); assert!( elapsed <= Duration::from_secs(2), "process returned too late: {elapsed:?}" ); assert!( elapsed >= Duration::from_millis(100), "process returned too early : {elapsed:?}" ); assert_eq!(status.code(), Some(130)); } #[test] #[ignore] fn interrupt_shebang() { interrupt_test( &[], " default: #!/usr/bin/env sh sleep 1 ", ); } #[test] #[ignore] fn interrupt_line() { interrupt_test( &[], " default: @sleep 1 ", ); } #[test] #[ignore] fn interrupt_backtick() { interrupt_test( &[], " foo := `sleep 1` default: @echo {{foo}} ", ); } #[test] #[ignore] fn interrupt_command() { interrupt_test(&["--command", "sleep", "1"], ""); } // This test is ignored because it is sensitive to the process signal mask. // Programs like `watchexec` and `cargo-watch` change the signal mask to ignore // `SIGHUP`, which causes this test to fail. #[test] #[ignore] fn forwarding() { let just = executable_path("just"); let tempdir = tempdir(); fs::write( tempdir.path().join("justfile"), "foo:\n @{{just_executable()}} --request '\"signal\"'", ) .unwrap(); for signal in [Signal::SIGINT, Signal::SIGQUIT, Signal::SIGHUP] { let mut child = Command::new(&just) .current_dir(&tempdir) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .unwrap(); // wait for child to start thread::sleep(Duration::from_millis(500)); // send non-forwarded signal kill(&child, signal); // wait for child to receive signal thread::sleep(Duration::from_millis(500)); // assert that child does not exit, because signal is not forwarded assert!(child.try_wait().unwrap().is_none()); // send forwarded signal kill(&child, Signal::SIGTERM); // child exits let output = child.wait_with_output().unwrap(); let status = output.status; let stderr = str::from_utf8(&output.stderr).unwrap(); let stdout = str::from_utf8(&output.stdout).unwrap(); let mut failures = 0; if status.code() != Some(128 + signal as i32) { failures += 1; eprintln!("unexpected status: {status}"); } // just reports that it was interrupted by first, non-forwarded signal if stderr != format!("error: Interrupted by {signal}\n") { failures += 1; eprintln!("unexpected stderr: {stderr}"); } // child reports that it was terminated by forwarded signal if stdout != r#"{"signal":"SIGTERM"}"# { failures += 1; eprintln!("unexpected stdout: {stdout}"); } assert!(failures == 0, "{failures} failures"); } } #[test] #[ignore] #[cfg(any( target_os = "dragonfly", target_os = "freebsd", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd", ))] fn siginfo_prints_current_process() { let just = executable_path("just"); let tempdir = tempdir(); fs::write(tempdir.path().join("justfile"), "foo:\n @sleep 1").unwrap(); let child = Command::new(&just) .current_dir(&tempdir) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .unwrap(); thread::sleep(Duration::from_millis(500)); kill(&child, Signal::SIGINFO); let output = child.wait_with_output().unwrap(); let status = output.status; let stderr = str::from_utf8(&output.stderr).unwrap(); let stdout = str::from_utf8(&output.stdout).unwrap(); let mut failures = 0; if !status.success() { failures += 1; eprintln!("unexpected status: {status}"); } let re = Regex::new(r#"just \d+: 1 child process:\n\d+: cd ".*" && "sh" "-cu" "sleep 1"\n"#).unwrap(); if !re.is_match(stderr) { failures += 1; eprintln!("unexpected stderr: {stderr}"); } if !stdout.is_empty() { failures += 1; eprintln!("unexpected stdout: {stdout}"); } assert!(failures == 0, "{failures} failures"); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/usage.rs
tests/usage.rs
use super::*; #[test] fn usage() { Test::new() .justfile("mod bar") .write( "bar.just", " [arg('a', short='a')] [arg('b', pattern='123|789', help='hello')] [arg('d', short='d', long='delightful')] [arg('e', short='e', pattern='abc|xyz')] [arg('f', long='f', pattern='lucky')] [arg('g', short='g', value='foo')] foo a b c='abc' d e f='xyz' g='bar' *h: ", ) .args(["--usage", "bar", "foo"]) .stdout( " Usage: just bar foo [OPTIONS] b [c] [h...] Arguments: b hello [pattern: '123|789'] [c] [default: 'abc'] [h...] Options: -a a -d, --delightful d -e e [pattern: 'abc|xyz'] --f f [default: 'xyz'] [pattern: 'lucky'] -g ", ) .run(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/fuzz/fuzz_targets/compile.rs
fuzz/fuzz_targets/compile.rs
#![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|src: &str| { let _ = just::fuzzing::compile(src); });
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/crates/update-contributors/src/main.rs
crates/update-contributors/src/main.rs
use { regex::{Captures, Regex}, std::{fs, process::Command, str}, }; fn author(pr: u64) -> String { eprintln!("#{pr}"); let output = Command::new("sh") .args([ "-c", &format!("gh pr view {pr} --json author | jq -r .author.login"), ]) .output() .unwrap(); assert!( output.status.success(), "{}", String::from_utf8_lossy(&output.stderr) ); str::from_utf8(&output.stdout).unwrap().trim().to_owned() } fn main() { fs::write( "CHANGELOG.md", &*Regex::new(r"\(#(\d+)( by @[a-z]+)?\)") .unwrap() .replace_all( &fs::read_to_string("CHANGELOG.md").unwrap(), |captures: &Captures| { let pr = captures[1].parse().unwrap(); let contributor = author(pr); format!("([#{pr}](https://github.com/casey/just/pull/{pr}) by [{contributor}](https://github.com/{contributor}))") }, ), ) .unwrap(); }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
casey/just
https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/crates/generate-book/src/main.rs
crates/generate-book/src/main.rs
use { pulldown_cmark::{CowStr, Event, HeadingLevel, Options, Parser, Tag}, pulldown_cmark_to_cmark::cmark, std::{ collections::{BTreeMap, BTreeSet}, error::Error, fmt::Write, fs, ops::Deref, }, }; type Result<T = ()> = std::result::Result<T, Box<dyn Error>>; #[derive(Copy, Clone, Debug)] enum Language { English, Chinese, } impl Language { fn code(&self) -> &'static str { match self { Self::English => "en", Self::Chinese => "zh", } } fn suffix(&self) -> &'static str { match self { Self::English => "", Self::Chinese => ".中文", } } fn introduction(&self) -> &'static str { match self { Self::Chinese => "说明", Self::English => "Introduction", } } } #[derive(Debug)] struct Chapter<'a> { level: HeadingLevel, events: Vec<Event<'a>>, index: usize, language: Language, } impl Chapter<'_> { fn title(&self) -> String { if self.index == 0 { return self.language.introduction().into(); } self .events .iter() .skip_while(|event| !matches!(event, Event::Start(Tag::Heading(..)))) .skip(1) .take_while(|event| !matches!(event, Event::End(Tag::Heading(..)))) .filter_map(|event| match event { Event::Code(content) | Event::Text(content) => Some(content.deref()), _ => None, }) .collect() } fn filename(&self) -> String { slug(&self.title()) } fn markdown(&self) -> Result<String> { let mut markdown = String::new(); cmark(self.events.iter(), &mut markdown)?; if self.index == 0 { markdown = markdown.split_inclusive('\n').skip(1).collect::<String>(); } Ok(markdown) } } fn slug(s: &str) -> String { let mut slug = String::new(); for c in s.chars() { match c { 'A'..='Z' => slug.extend(c.to_lowercase()), ' ' => slug.push('-'), '?' | '.' | '?' | '’' => {} _ => slug.push(c), } } slug } fn main() -> Result { for language in [Language::English, Language::Chinese] { let src = format!("book/{}/src", language.code()); fs::remove_dir_all(&src).ok(); fs::create_dir(&src)?; let txt = fs::read_to_string(format!("README{}.md", language.suffix()))?; let mut chapters = vec![Chapter { level: HeadingLevel::H1, events: Vec::new(), index: 0, language, }]; for event in Parser::new_ext(&txt, Options::all()) { if let Event::Start(Tag::Heading(level @ (HeadingLevel::H2 | HeadingLevel::H3), ..)) = event { let index = chapters.last().unwrap().index + 1; chapters.push(Chapter { level, events: Vec::new(), index, language, }); } chapters.last_mut().unwrap().events.push(event); } let mut links = BTreeMap::new(); for chapter in &chapters { let mut current = None; for event in &chapter.events { match event { Event::Start(Tag::Heading(..)) => current = Some(Vec::new()), Event::End(Tag::Heading(level, ..)) => { let events = current.unwrap(); let title = events .iter() .filter_map(|event| match event { Event::Code(content) | Event::Text(content) => Some(content.deref()), _ => None, }) .collect::<String>(); let slug = slug(&title); let link = if let HeadingLevel::H1 | HeadingLevel::H2 | HeadingLevel::H3 = level { format!("{}.html", chapter.filename()) } else { format!("{}.html#{}", chapter.filename(), slug) }; links.insert(slug, link); current = None; } _ => { if let Some(events) = &mut current { events.push(event.clone()); } } } } } for chapter in &mut chapters { for event in &mut chapter.events { if let Event::Start(Tag::Link(_, dest, _)) | Event::End(Tag::Link(_, dest, _)) = event { if let Some(anchor) = dest.clone().strip_prefix('#') { if anchor != "just" { *dest = CowStr::Borrowed(&links[anchor]); } } } } } let mut summary = String::new(); let mut filenames = BTreeSet::new(); for chapter in chapters { let filename = chapter.filename(); assert!(!filenames.contains(&filename)); let path = format!("{src}/{filename}.md"); fs::write(path, chapter.markdown()?)?; let indent = match chapter.level { HeadingLevel::H1 => 0, HeadingLevel::H2 => 1, HeadingLevel::H3 => 2, HeadingLevel::H4 => 3, HeadingLevel::H5 => 4, HeadingLevel::H6 => 5, }; write!( summary, "{}- [{}](", " ".repeat(indent * 4), chapter.title(), )?; if chapter.events.len() > 3 { write!(summary, "{filename}.md")?; } writeln!(summary, ")")?; filenames.insert(filename); } fs::write(format!("{src}/SUMMARY.md"), summary).unwrap(); } Ok(()) }
rust
CC0-1.0
5732ee083a58c534804d184acbdede11d1bbaac5
2026-01-04T15:34:07.853244Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/config.rs
src/config.rs
use std::collections::HashMap; use std::path::PathBuf; use clap::parser::ValueSource; use regex::Regex; use syntect::highlighting::Style as SyntectStyle; use syntect::highlighting::Theme as SyntaxTheme; use syntect::parsing::SyntaxSet; use crate::ansi; use crate::cli; use crate::color::{self, ColorMode}; use crate::delta::State; use crate::fatal; use crate::features::navigate; use crate::features::side_by_side::{self, ansifill, LeftRight}; use crate::git_config::GitConfig; use crate::handlers; use crate::handlers::blame::parse_blame_line_numbers; use crate::handlers::blame::BlameLineNumbers; use crate::minusplus::MinusPlus; use crate::paint::BgFillMethod; use crate::parse_styles; use crate::style; use crate::style::Style; use crate::tests::TESTING; use crate::utils; use crate::utils::bat::output::PagingMode; use crate::utils::regex_replacement::RegexReplacement; use crate::wrapping::WrapConfig; pub const INLINE_SYMBOL_WIDTH_1: usize = 1; // Used if an invalid default-language was specified. pub const SYNTAX_FALLBACK_LANG: &str = "txt"; #[cfg_attr(test, derive(Clone))] pub struct Config { pub available_terminal_width: usize, pub background_color_extends_to_terminal_width: bool, pub blame_code_style: Option<Style>, pub blame_format: String, pub blame_separator_format: BlameLineNumbers, pub blame_palette: Vec<String>, pub blame_separator_style: Option<Style>, pub blame_timestamp_format: String, pub blame_timestamp_output_format: Option<String>, pub color_only: bool, pub commit_regex: Regex, pub commit_style: Style, pub cwd_of_delta_process: Option<PathBuf>, pub cwd_of_user_shell_process: Option<PathBuf>, pub cwd_relative_to_repo_root: Option<String>, pub decorations_width: cli::Width, pub default_language: String, pub diff_args: String, pub diff_stat_align_width: usize, pub error_exit_code: i32, pub file_added_label: String, pub file_copied_label: String, pub file_modified_label: String, pub file_removed_label: String, pub file_renamed_label: String, pub file_regex_replacement: Option<RegexReplacement>, pub right_arrow: String, pub file_style: Style, pub git_config: Option<GitConfig>, pub git_minus_style: Style, pub git_plus_style: Style, pub grep_context_line_style: Style, pub grep_file_style: Style, pub classic_grep_header_file_style: Style, pub classic_grep_header_style: Style, pub ripgrep_header_style: Style, pub grep_line_number_style: Style, pub grep_match_line_style: Style, pub grep_match_word_style: Style, pub grep_output_type: Option<GrepType>, pub grep_separator_symbol: String, pub handle_merge_conflicts: bool, pub hostname: Option<String>, pub hunk_header_file_style: Style, pub hunk_header_line_number_style: Style, pub hunk_header_style_include_file_path: HunkHeaderIncludeFilePath, pub hunk_header_style_include_line_number: HunkHeaderIncludeLineNumber, pub hunk_header_style_include_code_fragment: HunkHeaderIncludeCodeFragment, pub hunk_header_style: Style, pub hunk_label: String, pub hyperlinks_commit_link_format: Option<String>, pub hyperlinks_file_link_format: String, pub hyperlinks: bool, pub inline_hint_style: Style, pub inspect_raw_lines: cli::InspectRawLines, pub keep_plus_minus_markers: bool, pub line_buffer_size: usize, pub line_fill_method: BgFillMethod, pub line_numbers_format: LeftRight<String>, pub line_numbers_style_leftright: LeftRight<Style>, pub line_numbers_style_minusplus: MinusPlus<Style>, pub line_numbers_zero_style: Style, pub line_numbers: bool, pub styles_map: Option<HashMap<style::AnsiTermStyleEqualityKey, Style>>, pub max_line_distance_for_naively_paired_lines: f64, pub max_line_distance: f64, pub max_line_length: usize, pub max_syntax_length: usize, pub merge_conflict_begin_symbol: String, pub merge_conflict_ours_diff_header_style: Style, pub merge_conflict_theirs_diff_header_style: Style, pub merge_conflict_end_symbol: String, pub minus_emph_style: Style, pub minus_empty_line_marker_style: Style, pub minus_file: Option<PathBuf>, pub minus_non_emph_style: Style, pub minus_style: Style, pub navigate_regex: Option<String>, pub navigate: bool, pub null_style: Style, pub null_syntect_style: SyntectStyle, pub pager: Option<String>, pub paging_mode: PagingMode, pub plus_emph_style: Style, pub plus_empty_line_marker_style: Style, pub plus_file: Option<PathBuf>, pub plus_non_emph_style: Style, pub plus_style: Style, pub relative_paths: bool, pub show_themes: bool, pub side_by_side_data: side_by_side::SideBySideData, pub side_by_side: bool, pub syntax_set: SyntaxSet, pub syntax_theme: Option<SyntaxTheme>, pub tab_cfg: utils::tabs::TabCfg, pub tokenization_regex: Regex, pub true_color: bool, pub truncation_symbol: String, pub whitespace_error_style: Style, pub wrap_config: WrapConfig, pub zero_style: Style, } #[derive(Debug, Eq, PartialEq, Clone)] pub enum GrepType { Ripgrep, Classic, } #[cfg_attr(test, derive(Clone))] pub enum HunkHeaderIncludeFilePath { Yes, No, } #[cfg_attr(test, derive(Clone))] pub enum HunkHeaderIncludeLineNumber { Yes, No, } #[cfg_attr(test, derive(Clone))] pub enum HunkHeaderIncludeCodeFragment { Yes, YesNoSpace, No, } impl Config { pub fn get_style(&self, state: &State) -> &Style { match state { State::HunkMinus(_, _) => &self.minus_style, State::HunkZero(_, _) => &self.zero_style, State::HunkPlus(_, _) => &self.plus_style, State::CommitMeta => &self.commit_style, State::DiffHeader(_) => &self.file_style, State::Grep(GrepType::Ripgrep, _, _, _) => &self.classic_grep_header_style, State::HunkHeader(_, _, _, _) => &self.hunk_header_style, State::SubmoduleLog => &self.file_style, _ => delta_unreachable("Unreachable code reached in get_style."), } } pub fn git_config(&self) -> Option<&GitConfig> { self.git_config.as_ref() } } impl From<cli::Opt> for Config { fn from(opt: cli::Opt) -> Self { let mut styles = parse_styles::parse_styles(&opt); let styles_map = parse_styles::parse_styles_map(&opt); let wrap_config = WrapConfig::from_opt(&opt, styles["inline-hint-style"]); let max_line_distance_for_naively_paired_lines = opt .env .experimental_max_line_distance_for_naively_paired_lines .as_ref() .map(|s| s.parse::<f64>().unwrap_or(0.0)) .unwrap_or(0.0); let commit_regex = Regex::new(&opt.commit_regex).unwrap_or_else(|_| { fatal(format!( "Invalid commit-regex: {}. \ The value must be a valid Rust regular expression. \ See https://docs.rs/regex.", opt.commit_regex )); }); let tokenization_regex = Regex::new(&opt.tokenization_regex).unwrap_or_else(|_| { fatal(format!( "Invalid word-diff-regex: {}. \ The value must be a valid Rust regular expression. \ See https://docs.rs/regex.", opt.tokenization_regex )); }); let blame_palette = make_blame_palette(opt.blame_palette, opt.computed.color_mode); if blame_palette.is_empty() { fatal("Option 'blame-palette' must not be empty.") } let file_added_label = opt.file_added_label; let file_copied_label = opt.file_copied_label; let file_modified_label = opt.file_modified_label; let file_removed_label = opt.file_removed_label; let file_renamed_label = opt.file_renamed_label; let right_arrow = opt.right_arrow; let hunk_label = opt.hunk_label; let line_fill_method = match opt.line_fill_method.as_deref() { // Note that "default" is not documented Some("ansi") | Some("default") | None => BgFillMethod::TryAnsiSequence, Some("spaces") => BgFillMethod::Spaces, _ => fatal("Invalid option for line-fill-method: Expected \"ansi\" or \"spaces\"."), }; let side_by_side_data = side_by_side::SideBySideData::new_sbs( &opt.computed.decorations_width, &opt.computed.available_terminal_width, ); let side_by_side_data = ansifill::UseFullPanelWidth::sbs_odd_fix( &opt.computed.decorations_width, &line_fill_method, side_by_side_data, ); let navigate_regex = if (opt.navigate || opt.show_themes) && (opt.navigate_regex.is_none() || opt.navigate_regex == Some("".to_string())) { Some(navigate::make_navigate_regex( opt.show_themes, &file_modified_label, &file_added_label, &file_removed_label, &file_renamed_label, &hunk_label, )) } else { opt.navigate_regex }; let grep_output_type = match opt.grep_output_type.as_deref() { Some("ripgrep") => Some(GrepType::Ripgrep), Some("classic") => Some(GrepType::Classic), None => None, _ => fatal("Invalid option for grep-output-type: Expected \"ripgrep\" or \"classic\"."), }; #[cfg(not(test))] let cwd_of_delta_process = opt.env.current_dir; #[cfg(test)] let cwd_of_delta_process = Some(utils::path::fake_delta_cwd_for_tests()); let cwd_relative_to_repo_root = opt.env.git_prefix; let cwd_of_user_shell_process = utils::path::cwd_of_user_shell_process( cwd_of_delta_process.as_ref(), cwd_relative_to_repo_root.as_deref(), ); Self { available_terminal_width: opt.computed.available_terminal_width, background_color_extends_to_terminal_width: opt .computed .background_color_extends_to_terminal_width, blame_format: opt.blame_format, blame_code_style: styles.remove("blame-code-style"), blame_palette, blame_separator_format: parse_blame_line_numbers(&opt.blame_separator_format), blame_separator_style: styles.remove("blame-separator-style"), blame_timestamp_format: opt.blame_timestamp_format, blame_timestamp_output_format: opt.blame_timestamp_output_format, commit_style: styles["commit-style"], color_only: opt.color_only, commit_regex, cwd_of_delta_process, cwd_of_user_shell_process, cwd_relative_to_repo_root, decorations_width: opt.computed.decorations_width, default_language: opt.default_language, diff_args: opt.diff_args, diff_stat_align_width: opt.diff_stat_align_width, error_exit_code: 2, // Use 2 for error because diff uses 0 and 1 for non-error. file_added_label, file_copied_label, file_modified_label, file_removed_label, file_renamed_label, file_regex_replacement: opt .file_regex_replacement .as_deref() .and_then(RegexReplacement::from_sed_command), right_arrow, hunk_label, file_style: styles["file-style"], git_config: opt.git_config, grep_context_line_style: styles["grep-context-line-style"], grep_file_style: styles["grep-file-style"], classic_grep_header_file_style: styles["classic-grep-header-file-style"], classic_grep_header_style: styles["classic-grep-header-style"], ripgrep_header_style: styles["ripgrep-header-style"], grep_line_number_style: styles["grep-line-number-style"], grep_match_line_style: styles["grep-match-line-style"], grep_match_word_style: styles["grep-match-word-style"], grep_output_type, grep_separator_symbol: opt.grep_separator_symbol, handle_merge_conflicts: !opt.raw, hostname: opt.env.hostname, hunk_header_file_style: styles["hunk-header-file-style"], hunk_header_line_number_style: styles["hunk-header-line-number-style"], hunk_header_style: styles["hunk-header-style"], hunk_header_style_include_file_path: if opt .hunk_header_style .split(' ') .any(|s| s == "file") { HunkHeaderIncludeFilePath::Yes } else { HunkHeaderIncludeFilePath::No }, hunk_header_style_include_line_number: if opt .hunk_header_style .split(' ') .any(|s| s == "line-number") { HunkHeaderIncludeLineNumber::Yes } else { HunkHeaderIncludeLineNumber::No }, hunk_header_style_include_code_fragment: if opt .hunk_header_style .split(' ') .any(|s| s == "omit-code-fragment") { HunkHeaderIncludeCodeFragment::No } else { HunkHeaderIncludeCodeFragment::Yes }, hyperlinks: opt.hyperlinks, hyperlinks_commit_link_format: opt.hyperlinks_commit_link_format, hyperlinks_file_link_format: opt.hyperlinks_file_link_format, inspect_raw_lines: opt.computed.inspect_raw_lines, inline_hint_style: styles["inline-hint-style"], keep_plus_minus_markers: opt.keep_plus_minus_markers, line_fill_method: if !opt.computed.stdout_is_term && !TESTING { // Don't write ANSI sequences (which rely on the width of the // current terminal) into a file. Also see UseFullPanelWidth. // But when testing always use given value. BgFillMethod::Spaces } else { line_fill_method }, line_numbers: opt.line_numbers && !handlers::hunk::is_word_diff(), line_numbers_format: LeftRight::new( opt.line_numbers_left_format, opt.line_numbers_right_format, ), line_numbers_style_leftright: LeftRight::new( styles["line-numbers-left-style"], styles["line-numbers-right-style"], ), line_numbers_style_minusplus: MinusPlus::new( styles["line-numbers-minus-style"], styles["line-numbers-plus-style"], ), line_numbers_zero_style: styles["line-numbers-zero-style"], line_buffer_size: opt.line_buffer_size, max_line_distance: opt.max_line_distance, max_line_distance_for_naively_paired_lines, max_line_length: if opt.side_by_side { wrap_config.config_max_line_length( opt.max_line_length, opt.computed.available_terminal_width, ) } else { opt.max_line_length }, max_syntax_length: opt.max_syntax_length, merge_conflict_begin_symbol: opt.merge_conflict_begin_symbol, merge_conflict_ours_diff_header_style: styles["merge-conflict-ours-diff-header-style"], merge_conflict_theirs_diff_header_style: styles ["merge-conflict-theirs-diff-header-style"], merge_conflict_end_symbol: opt.merge_conflict_end_symbol, minus_emph_style: styles["minus-emph-style"], minus_empty_line_marker_style: styles["minus-empty-line-marker-style"], minus_file: opt.minus_file, minus_non_emph_style: styles["minus-non-emph-style"], minus_style: styles["minus-style"], navigate: opt.navigate, navigate_regex, null_style: Style::new(), null_syntect_style: SyntectStyle::default(), pager: opt.pager, paging_mode: opt.computed.paging_mode, plus_emph_style: styles["plus-emph-style"], plus_empty_line_marker_style: styles["plus-empty-line-marker-style"], plus_file: opt.plus_file, plus_non_emph_style: styles["plus-non-emph-style"], plus_style: styles["plus-style"], git_minus_style: styles["git-minus-style"], git_plus_style: styles["git-plus-style"], relative_paths: opt.relative_paths, show_themes: opt.show_themes, side_by_side: opt.side_by_side && !handlers::hunk::is_word_diff(), side_by_side_data, styles_map, syntax_set: opt.computed.syntax_set, syntax_theme: opt.computed.syntax_theme, tab_cfg: utils::tabs::TabCfg::new(opt.tab_width), tokenization_regex, true_color: opt.computed.true_color, truncation_symbol: format!("{}→{}", ansi::ANSI_SGR_REVERSE, ansi::ANSI_SGR_RESET), wrap_config, whitespace_error_style: styles["whitespace-error-style"], zero_style: styles["zero-style"], } } } fn make_blame_palette(blame_palette: Option<String>, mode: ColorMode) -> Vec<String> { match (blame_palette, mode) { (Some(string), _) => string .split_whitespace() .map(|s| s.to_owned()) .collect::<Vec<String>>(), (None, ColorMode::Light) => color::LIGHT_THEME_BLAME_PALETTE .iter() .map(|s| s.to_string()) .collect::<Vec<String>>(), (None, ColorMode::Dark) => color::DARK_THEME_BLAME_PALETTE .iter() .map(|s| s.to_string()) .collect::<Vec<String>>(), } } /// Did the user supply `option` on the command line? pub fn user_supplied_option(option: &str, arg_matches: &clap::ArgMatches) -> bool { arg_matches.value_source(option) == Some(ValueSource::CommandLine) } pub fn delta_unreachable(message: &str) -> ! { fatal(format!( "{message} This should not be possible. \ Please report the bug at https://github.com/dandavison/delta/issues.", )); } #[cfg(test)] // Usual length of the header returned by `run_delta()`, often `skip()`-ed. pub const HEADER_LEN: usize = 7; #[cfg(test)] pub mod tests { use crate::cli; use crate::tests::integration_test_utils; use crate::utils::bat::output::PagingMode; use std::fs::remove_file; #[test] fn test_get_computed_values_from_config() { let git_config_contents = b" [delta] true-color = never width = 100 inspect-raw-lines = true paging = never syntax-theme = None "; let git_config_path = "delta__test_get_true_color_from_config.gitconfig"; let config = integration_test_utils::make_config_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path), ); assert!(!config.true_color); assert_eq!(config.decorations_width, cli::Width::Fixed(100)); assert!(config.background_color_extends_to_terminal_width); assert_eq!(config.inspect_raw_lines, cli::InspectRawLines::True); assert_eq!(config.paging_mode, PagingMode::Never); assert!(config.syntax_theme.is_none()); // syntax_set doesn't depend on gitconfig. remove_file(git_config_path).unwrap(); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/paint.rs
src/paint.rs
use std::borrow::Cow; use std::collections::HashMap; use std::io::Write; use ansi_term::ANSIString; use itertools::Itertools; use syntect::easy::HighlightLines; use syntect::highlighting::Style as SyntectStyle; use syntect::parsing::{SyntaxReference, SyntaxSet}; use crate::config::{self, delta_unreachable, Config}; use crate::delta::{DiffType, InMergeConflict, MergeParents, State}; use crate::features::hyperlinks; use crate::features::line_numbers::{self, LineNumbersData}; use crate::features::side_by_side::ansifill; use crate::features::side_by_side::{self, PanelSide}; use crate::handlers::merge_conflict; use crate::minusplus::*; use crate::paint::superimpose_style_sections::superimpose_style_sections; use crate::style::Style; use crate::{ansi, style}; use crate::{edits, utils, utils::tabs}; pub type LineSections<'a, S> = Vec<(S, &'a str)>; pub struct Painter<'p> { pub minus_lines: Vec<(String, State)>, pub plus_lines: Vec<(String, State)>, pub writer: &'p mut dyn Write, pub syntax: &'p SyntaxReference, pub highlighter: Option<HighlightLines<'p>>, pub config: &'p config::Config, pub output_buffer: String, // If config.line_numbers is true, then the following is always Some(). // In side-by-side mode it is always Some (but possibly an empty one), even // if config.line_numbers is false. See `UseFullPanelWidth` as well. pub line_numbers_data: Option<line_numbers::LineNumbersData<'p>>, pub merge_conflict_lines: merge_conflict::MergeConflictLines, pub merge_conflict_commit_names: merge_conflict::MergeConflictCommitNames, } // How the background of a line is filled up to the end #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum BgFillMethod { // Fill the background with ANSI spaces if possible, // but might fallback to Spaces (e.g. in the left side-by-side panel), // also see `UseFullPanelWidth` TryAnsiSequence, Spaces, } // If the background of a line extends to the end, and if configured to do so, how. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum BgShouldFill { With(BgFillMethod), No, } impl Default for BgShouldFill { fn default() -> Self { BgShouldFill::With(BgFillMethod::TryAnsiSequence) } } #[derive(PartialEq, Debug)] pub enum StyleSectionSpecifier<'l> { Style(Style), StyleSections(LineSections<'l, Style>), } impl<'p> Painter<'p> { pub fn new(writer: &'p mut dyn Write, config: &'p config::Config) -> Self { let default_syntax = Self::get_syntax(&config.syntax_set, None, &config.default_language); let panel_width_fix = ansifill::UseFullPanelWidth::new(config); let line_numbers_data = if config.line_numbers { Some(line_numbers::LineNumbersData::from_format_strings( &config.line_numbers_format, panel_width_fix, )) } else if config.side_by_side { // If line numbers are disabled in side-by-side then the data is still used // for width calculation and to pad odd width to even, see `UseFullPanelWidth` // for details. Some(line_numbers::LineNumbersData::empty_for_sbs( panel_width_fix, )) } else { None }; Self { minus_lines: Vec::new(), plus_lines: Vec::new(), output_buffer: String::new(), syntax: default_syntax, highlighter: None, writer, config, line_numbers_data, merge_conflict_lines: merge_conflict::MergeConflictLines::new(), merge_conflict_commit_names: merge_conflict::MergeConflictCommitNames::new(), } } pub fn set_syntax(&mut self, filename: Option<&str>) { self.syntax = Painter::get_syntax( &self.config.syntax_set, filename, &self.config.default_language, ); } fn get_syntax<'a>( syntax_set: &'a SyntaxSet, filename: Option<&str>, fallback: &str, ) -> &'a SyntaxReference { if let Some(filename) = filename { let path = std::path::Path::new(filename); let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); let extension = path.extension().and_then(|x| x.to_str()).unwrap_or(""); // Like syntect's `find_syntax_for_file`, without inspecting the file content, plus: // If the file has NO extension then look up the whole filename as a // syntax definition (if it is longer than 4 bytes). // This means file formats like Makefile/Dockerfile/Rakefile etc. will get highlighted, // but 1-4 short filenames will not -- even if they, as a whole, match an extension: // 'rs' will not get highlighted, while 'x.rs' will. if !extension.is_empty() || file_name.len() > 4 { if let Some(syntax) = syntax_set .find_syntax_by_extension(file_name) .or_else(|| syntax_set.find_syntax_by_extension(extension)) { return syntax; } } } // Nothing found, try the user provided fallback, or the internal fallback. if let Some(syntax) = syntax_set.find_syntax_for_file(fallback).unwrap_or(None) { syntax } else { syntax_set .find_syntax_by_extension(config::SYNTAX_FALLBACK_LANG) .unwrap_or_else(|| { delta_unreachable("Failed to find any language syntax definitions.") }) } } pub fn set_highlighter(&mut self) { if let Some(ref syntax_theme) = self.config.syntax_theme { self.highlighter = Some(HighlightLines::new(self.syntax, syntax_theme)) }; } pub fn paint_buffered_minus_and_plus_lines(&mut self) { if self.minus_lines.is_empty() && self.plus_lines.is_empty() { return; } paint_minus_and_plus_lines( MinusPlus::new(&self.minus_lines, &self.plus_lines), &mut self.line_numbers_data, &mut self.highlighter, &mut self.output_buffer, self.config, ); self.minus_lines.clear(); self.plus_lines.clear(); } pub fn paint_zero_line(&mut self, line: &str, state: State) { let lines = &[(line.to_string(), state.clone())]; let syntax_style_sections = get_syntax_style_sections_for_lines(lines, self.highlighter.as_mut(), self.config); let mut diff_style_sections = vec![vec![(self.config.zero_style, lines[0].0.as_str())]]; // TODO: compute style from state Painter::update_diff_style_sections( lines, &mut diff_style_sections, None, None, &[false], self.config, ); if self.config.side_by_side { // `lines[0].0` so the line has the '\n' already added (as in the +- case) side_by_side::paint_zero_lines_side_by_side( &lines[0].0, syntax_style_sections, diff_style_sections, &mut self.output_buffer, self.config, &mut self.line_numbers_data.as_mut(), painted_prefix(state, self.config), BgShouldFill::With(BgFillMethod::Spaces), ); } else { Painter::paint_lines( lines, &syntax_style_sections, diff_style_sections.as_slice(), &[false], &mut self.output_buffer, self.config, &mut self.line_numbers_data.as_mut(), None, BgShouldFill::default(), ); } } /// Superimpose background styles and foreground syntax /// highlighting styles, and write colored lines to output buffer. #[allow(clippy::too_many_arguments)] pub fn paint_lines<'a>( lines: &'a [(String, State)], syntax_style_sections: &[LineSections<'a, SyntectStyle>], diff_style_sections: &[LineSections<'a, Style>], lines_have_homolog: &[bool], output_buffer: &mut String, config: &config::Config, line_numbers_data: &mut Option<&mut line_numbers::LineNumbersData>, empty_line_style: Option<Style>, // a style with background color to highlight an empty line background_color_extends_to_terminal_width: BgShouldFill, ) { // There's some unfortunate hackery going on here for two reasons: // // 1. The prefix needs to be injected into the output stream. // // 2. We must ensure that we fill rightwards with the appropriate // non-emph background color. In that case we don't use the last // style of the line, because this might be emph. for ((((_, state), syntax_sections), diff_sections), &line_has_homolog) in lines .iter() .zip_eq(syntax_style_sections) .zip_eq(diff_style_sections) .zip_eq(lines_have_homolog) { let (mut line, line_is_empty) = Painter::paint_line( syntax_sections, diff_sections, state, line_numbers_data, None, painted_prefix(state.clone(), config), config, ); let (bg_fill_mode, fill_style) = Painter::get_should_right_fill_background_color_and_fill_style( diff_sections, Some(line_has_homolog), state, background_color_extends_to_terminal_width, config, ); if let Some(BgFillMethod::TryAnsiSequence) = bg_fill_mode { Painter::right_fill_background_color(&mut line, fill_style); } else if let Some(BgFillMethod::Spaces) = bg_fill_mode { let text_width = ansi::measure_text_width(&line); line.push_str( #[allow(clippy::unnecessary_to_owned)] &fill_style .paint(" ".repeat(config.available_terminal_width - text_width)) .to_string(), ); } else if line_is_empty { if let Some(empty_line_style) = empty_line_style { Painter::mark_empty_line( &empty_line_style, &mut line, if config.line_numbers { Some(" ") } else { None }, ); } }; output_buffer.push_str(&line); output_buffer.push('\n'); } } /// Write painted line to the output buffer, with syntax-highlighting and `style` superimposed. // Note that, if passing `style_sections` as // `StyleSectionSpecifier::StyleSections`, then tabs must already have been // expanded in the text. pub fn syntax_highlight_and_paint_line( &mut self, line: &str, style_sections: StyleSectionSpecifier, state: State, background_color_extends_to_terminal_width: BgShouldFill, ) { let lines = vec![(tabs::expand(line, &self.config.tab_cfg), state)]; let syntax_style_sections = get_syntax_style_sections_for_lines(&lines, self.highlighter.as_mut(), self.config); let diff_style_sections = match style_sections { StyleSectionSpecifier::Style(style) => vec![vec![(style, lines[0].0.as_str())]], StyleSectionSpecifier::StyleSections(style_sections) => vec![style_sections], }; Painter::paint_lines( &lines, &syntax_style_sections, &diff_style_sections, &[false], &mut self.output_buffer, self.config, &mut None, None, background_color_extends_to_terminal_width, ); } /// Determine whether the terminal should fill the line rightwards with a background color, and /// the style for doing so. pub fn get_should_right_fill_background_color_and_fill_style( diff_sections: &[(Style, &str)], line_has_homolog: Option<bool>, state: &State, background_color_extends_to_terminal_width: BgShouldFill, config: &config::Config, ) -> (Option<BgFillMethod>, Style) { let fill_style = match state { State::HunkMinus(_, None) | State::HunkMinusWrapped => { if let Some(true) = line_has_homolog { config.minus_non_emph_style } else { config.minus_style } } State::HunkZero(_, None) | State::HunkZeroWrapped => config.zero_style, State::HunkPlus(_, None) | State::HunkPlusWrapped => { if let Some(true) = line_has_homolog { config.plus_non_emph_style } else { config.plus_style } } State::HunkMinus(_, Some(_)) | State::HunkZero(_, Some(_)) | State::HunkPlus(_, Some(_)) => { // Consider the following raw line, from git colorMoved: // ␛[1;36m+␛[m␛[1;36mclass·X:·pass␛[m␊ The last style section returned by // parse_style_sections will be a default style associated with the terminal newline // character; we want the last "real" style. diff_sections .iter() .rev() .filter(|(_, s)| s != &"\n") .map(|(style, _)| *style) .next() .unwrap_or(config.null_style) } State::Blame(_) => diff_sections[0].0, _ => config.null_style, }; match ( fill_style.get_background_color().is_some(), background_color_extends_to_terminal_width, ) { (false, _) | (_, BgShouldFill::No) => (None, fill_style), (_, BgShouldFill::With(bgmode)) => { if config.background_color_extends_to_terminal_width { (Some(bgmode), fill_style) } else { (None, fill_style) } } } } /// Emit line with ANSI sequences that extend the background color to the terminal width. pub fn right_fill_background_color(line: &mut String, fill_style: Style) { // HACK: How to properly incorporate the ANSI_CSI_CLEAR_TO_EOL into ansi_strings? line.push_str(&ansi_term::ANSIStrings(&[fill_style.paint("")]).to_string()); if line .to_lowercase() .ends_with(&ansi::ANSI_SGR_RESET.to_lowercase()) { line.truncate(line.len() - ansi::ANSI_SGR_RESET.len()); } line.push_str(ansi::ANSI_CSI_CLEAR_TO_EOL); line.push_str(ansi::ANSI_SGR_RESET); } /// Use ANSI sequences to visually mark the current line as empty. If `marker` is None then the /// line is marked using terminal emulator colors only, i.e. without appending any marker text /// to the line. This is typically appropriate only when the `line` buffer is empty, since /// otherwise the ANSI_CSI_CLEAR_TO_BOL instruction would overwrite the text to the left of the /// current buffer position. pub fn mark_empty_line(empty_line_style: &Style, line: &mut String, marker: Option<&str>) { line.push_str( #[allow(clippy::unnecessary_to_owned)] &empty_line_style .paint(marker.unwrap_or(ansi::ANSI_CSI_CLEAR_TO_BOL)) .to_string(), ); } /// Return painted line (maybe prefixed with line numbers field) and an is_empty? boolean. pub fn paint_line( syntax_sections: &[(SyntectStyle, &str)], diff_sections: &[(Style, &str)], state: &State, line_numbers_data: &mut Option<&mut line_numbers::LineNumbersData>, side_by_side_panel: Option<PanelSide>, mut painted_prefix: Option<ansi_term::ANSIString>, config: &config::Config, ) -> (String, bool) { let mut ansi_strings = Vec::new(); let output_line_numbers = line_numbers_data.is_some(); if output_line_numbers { // Unified diff lines are printed in one go, but side-by-side lines // are printed in two parts, so do not increment line numbers when the // first (left) part is printed. let increment = !matches!(side_by_side_panel, Some(side_by_side::Left)); if let Some((line_numbers, styles)) = line_numbers::linenumbers_and_styles( line_numbers_data.as_mut().unwrap(), state, config, increment, ) { ansi_strings.extend(line_numbers::format_and_paint_line_numbers( line_numbers_data.as_ref().unwrap(), side_by_side_panel, styles, line_numbers, config, )) } } let superimposed = superimpose_style_sections( syntax_sections, diff_sections, config.true_color, config.null_syntect_style, ); let mut handled_prefix = false; for (section_style, text) in &superimposed { // If requested re-insert the +/- prefix with proper styling. if !handled_prefix { if let Some(painted_prefix) = painted_prefix.take() { ansi_strings.push(painted_prefix) } } if !text.is_empty() { ansi_strings.push(section_style.paint(text.as_str())); } handled_prefix = true; } // Only if syntax is empty (implies diff empty) can a line actually be empty. let is_empty = syntax_sections.is_empty(); (ansi_term::ANSIStrings(&ansi_strings).to_string(), is_empty) } /// Write output buffer to output stream, and clear the buffer. pub fn emit(&mut self) -> std::io::Result<()> { write!(self.writer, "{}", self.output_buffer)?; self.output_buffer.clear(); Ok(()) } pub fn should_compute_syntax_highlighting(state: &State, config: &config::Config) -> bool { if config.syntax_theme.is_none() { return false; } match state { State::HunkMinus(_, None) => { config.minus_style.is_syntax_highlighted || config.minus_emph_style.is_syntax_highlighted || config.minus_non_emph_style.is_syntax_highlighted } State::HunkZero(_, None) => config.zero_style.is_syntax_highlighted, State::HunkPlus(_, None) => { config.plus_style.is_syntax_highlighted || config.plus_emph_style.is_syntax_highlighted || config.plus_non_emph_style.is_syntax_highlighted } State::HunkHeader(_, _, _, _) => true, State::HunkMinus(_, Some(_raw_line)) | State::HunkZero(_, Some(_raw_line)) | State::HunkPlus(_, Some(_raw_line)) => { // It is possible that the captured raw line contains an ANSI // style that has been mapped (via map-styles) to a delta Style // with syntax-highlighting. true } State::Blame(_) => true, State::GitShowFile => true, State::Grep(_, _, _, _) => true, State::Unknown | State::CommitMeta | State::DiffHeader(_) | State::HunkMinusWrapped | State::HunkZeroWrapped | State::HunkPlusWrapped | State::MergeConflict(_, _) | State::SubmoduleLog | State::SubmoduleShort(_) => { panic!( "should_compute_syntax_highlighting is undefined for state {:?}", state ) } } } /// There are some rules according to which we update line section styles that were computed /// during the initial edit inference pass. This function applies those rules. The rules are /// 1. If there are multiple diff styles in the line, then the line must have some /// inferred edit operations and so, if there is a special non-emph style that is /// distinct from the default style, then it should be used for the non-emph style /// sections. /// 2. If the line constitutes a whitespace error, then the whitespace error style /// should be applied to the added material. /// 3. If delta recognized the raw line as one containing ANSI colors that /// are going to be preserved in the output, then replace delta's /// computed diff styles with these styles from the raw line. (This is /// how support for git's --color-moved is implemented.) fn update_diff_style_sections<'a>( lines: &'a [(String, State)], diff_style_sections: &mut Vec<LineSections<'a, Style>>, whitespace_error_style: Option<Style>, non_emph_style: Option<Style>, lines_have_homolog: &[bool], config: &config::Config, ) { for (((_, state), style_sections), line_has_homolog) in lines .iter() .zip_eq(diff_style_sections) .zip_eq(lines_have_homolog) { if let State::HunkMinus(_, Some(raw_line)) | State::HunkZero(_, Some(raw_line)) | State::HunkPlus(_, Some(raw_line)) = state { // raw_line is captured in handle_hunk_line under certain conditions. If we have // done so, then overwrite the style sections with styles parsed directly from the // raw line. Currently the only reason this is done is to handle a diff.colorMoved // line. *style_sections = parse_style_sections(raw_line, config); continue; } let line_has_emph_and_non_emph_sections = style_sections_contain_more_than_one_style(style_sections); let should_update_non_emph_styles = non_emph_style.is_some() && *line_has_homolog; // TODO: Git recognizes blank lines at end of file (blank-at-eof) // as a whitespace error but delta does not yet. // https://git-scm.com/docs/git-config#Documentation/git-config.txt-corewhitespace let mut is_whitespace_error = whitespace_error_style.is_some(); for (style, s) in style_sections.iter_mut().rev() { if is_whitespace_error && !s.trim().is_empty() { is_whitespace_error = false; } // If the line as a whole constitutes a whitespace error then highlight this // section if either (a) it is an emph section, or (b) the line lacks any // emph/non-emph distinction. // TODO: is this logic correct now, after introducing // line_has_homolog for non_emph style? if is_whitespace_error && (style.is_emph || !line_has_emph_and_non_emph_sections) { *style = whitespace_error_style.unwrap(); } // Otherwise, update the style if this is a non-emph section that needs updating. else if should_update_non_emph_styles && !style.is_emph { *style = non_emph_style.unwrap(); if is_whitespace_error { *style = whitespace_error_style.unwrap(); } } } } } } /// Remove initial -/+ character, expand tabs as spaces, and terminate with newline. // Terminating with newline character is necessary for many of the sublime syntax definitions to // highlight correctly. // See https://docs.rs/syntect/3.2.0/syntect/parsing/struct.SyntaxSetBuilder.html#method.add_from_folder pub fn prepare(line: &str, prefix_length: usize, config: &config::Config) -> String { if !line.is_empty() { // The prefix contains -/+/space characters, added by git. We removes them now so they // are not present during syntax highlighting or wrapping. If --keep-plus-minus-markers // is in effect the prefix is re-inserted in Painter::paint_line. let mut line = tabs::remove_prefix_and_expand(prefix_length, line, &config.tab_cfg); line.push('\n'); line } else { "\n".to_string() } } // Remove initial -/+ characters, expand tabs as spaces, retaining ANSI sequences. Terminate with // newline character. pub fn prepare_raw_line(raw_line: &str, prefix_length: usize, config: &config::Config) -> String { let mut line = tabs::expand(raw_line, &config.tab_cfg); line.push('\n'); ansi::ansi_preserving_slice(&line, prefix_length) } pub fn paint_minus_and_plus_lines( lines: MinusPlus<&Vec<(String, State)>>, line_numbers_data: &mut Option<LineNumbersData>, highlighter: &mut Option<HighlightLines>, output_buffer: &mut String, config: &config::Config, ) { let syntax_style_sections = MinusPlus::new( get_syntax_style_sections_for_lines(lines[Minus], highlighter.as_mut(), config), get_syntax_style_sections_for_lines(lines[Plus], highlighter.as_mut(), config), ); let (mut diff_style_sections, line_alignment) = get_diff_style_sections(&lines, config); let lines_have_homolog = edits::make_lines_have_homolog(&line_alignment); Painter::update_diff_style_sections( lines[Minus], &mut diff_style_sections[Minus], None, if config.minus_non_emph_style != config.minus_emph_style { Some(config.minus_non_emph_style) } else { None }, &lines_have_homolog[Minus], config, ); Painter::update_diff_style_sections( lines[Plus], &mut diff_style_sections[Plus], Some(config.whitespace_error_style), if config.plus_non_emph_style != config.plus_emph_style { Some(config.plus_non_emph_style) } else { None }, &lines_have_homolog[Plus], config, ); if config.side_by_side { side_by_side::paint_minus_and_plus_lines_side_by_side( lines, syntax_style_sections, diff_style_sections, lines_have_homolog, line_alignment, line_numbers_data, output_buffer, config, ) } else { // Unified diff mode: if !lines[Minus].is_empty() { Painter::paint_lines( lines[Minus], &syntax_style_sections[Minus], &diff_style_sections[Minus], &lines_have_homolog[Minus], output_buffer, config, &mut line_numbers_data.as_mut(), Some(config.minus_empty_line_marker_style), BgShouldFill::default(), ); } if !lines[Plus].is_empty() { Painter::paint_lines( lines[Plus], &syntax_style_sections[Plus], &diff_style_sections[Plus], &lines_have_homolog[Plus], output_buffer, config, &mut line_numbers_data.as_mut(), Some(config.plus_empty_line_marker_style), BgShouldFill::default(), ); } } } pub fn get_syntax_style_sections_for_lines<'a>( lines: &'a [(String, State)], highlighter: Option<&mut HighlightLines>, config: &config::Config, ) -> Vec<LineSections<'a, SyntectStyle>> { let mut line_sections = Vec::new(); match ( highlighter, lines .iter() .any(|(_, state)| Painter::should_compute_syntax_highlighting(state, config)), ) { (Some(highlighter), true) => { for (line, _) in lines.iter() { // Fast but simple length comparison. Overcounts non-printable ansi // characters or wider UTF-8, but `truncate_str_short` in the // else branch corrects that. if line.len() < config.max_syntax_length || config.max_syntax_length == 0 { line_sections.push( highlighter .highlight_line(line, &config.syntax_set) .unwrap(), ); } else { let line_syntax = ansi::truncate_str_short(line, config.max_syntax_length); // Re-split to get references into `line` with correct lifetimes. // SAFETY: slicing the string is safe because `truncate_str_short` always // returns a prefix of the input and only cuts at grapheme borders. let (with_syntax, plain) = line.split_at(line_syntax.len()); // Note: splitting a line and only feeding one half to the highlighter may // result in wrong highlighting until it is reset the next hunk. // // Also, as lines are no longer newline terminated they might not be // highlighted correctly, and because of lifetimes inserting '\n' here is not // possible, also see `prepare()`. line_sections.push( highlighter .highlight_line(with_syntax, &config.syntax_set) .unwrap(), ); if !plain.is_empty() { line_sections .last_mut() .unwrap() .push((config.null_syntect_style, plain)); } } } } _ => { for (line, _) in lines.iter() { line_sections.push(vec![(config.null_syntect_style, line.as_str())]) } } } line_sections } /// Get background styles to represent diff for minus and plus lines in buffer. #[allow(clippy::type_complexity)] fn get_diff_style_sections<'a>( lines: &MinusPlus<&'a Vec<(String, State)>>, config: &config::Config, ) -> ( MinusPlus<Vec<LineSections<'a, Style>>>, Vec<(Option<usize>, Option<usize>)>, ) { let (minus_lines, minus_styles): (Vec<&str>, Vec<Style>) = lines[Minus] .iter() .map(|(s, state)| (s.as_str(), *config.get_style(state))) .unzip(); let (plus_lines, plus_styles): (Vec<&str>, Vec<Style>) = lines[Plus] .iter() .map(|(s, state)| (s.as_str(), *config.get_style(state))) .unzip(); let (minus_line_diff_style_sections, plus_line_diff_style_sections, line_alignment) = edits::infer_edits( minus_lines, plus_lines, minus_styles, config.minus_emph_style, // FIXME plus_styles, config.plus_emph_style, // FIXME &config.tokenization_regex, config.max_line_distance, config.max_line_distance_for_naively_paired_lines, ); let diff_sections = MinusPlus::new( minus_line_diff_style_sections, plus_line_diff_style_sections, ); (diff_sections, line_alignment) } fn painted_prefix(state: State, config: &config::Config) -> Option<ANSIString<'_>> { use DiffType::*; use State::*; match (state, config.keep_plus_minus_markers) { // For a combined diff, unless we are in a merge conflict, we do not honor // keep_plus_minus_markers -- i.e. we always emit the prefix -- because there is currently // no way to distinguish, say, a '+ ' line from a ' +' line, by styles alone. In a merge // conflict we do honor the setting because the way merge conflicts are displayed indicates // from which commit the lines derive. (HunkMinus(Combined(MergeParents::Prefix(prefix), InMergeConflict::No), _), _) => { Some(config.minus_style.paint(prefix)) } (HunkZero(Combined(MergeParents::Prefix(prefix), InMergeConflict::No), _), _) => {
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
true
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/parse_styles.rs
src/parse_styles.rs
use std::collections::{HashMap, HashSet}; use crate::cli; use crate::color; use crate::fatal; use crate::git_config::GitConfig; use crate::style::{self, Style}; #[derive(Debug, Clone)] enum StyleReference { Style(Style), Reference(String), } fn is_style_reference(style_string: &str) -> bool { style_string.ends_with("-style") && !style_string.chars().any(|c| c == ' ') } pub fn parse_styles(opt: &cli::Opt) -> HashMap<String, Style> { let mut styles: HashMap<&str, StyleReference> = HashMap::new(); make_hunk_styles(opt, &mut styles); make_commit_file_hunk_header_styles(opt, &mut styles); make_line_number_styles(opt, &mut styles); make_blame_styles(opt, &mut styles); make_grep_styles(opt, &mut styles); make_merge_conflict_styles(opt, &mut styles); make_misc_styles(opt, &mut styles); let mut resolved_styles = resolve_style_references(styles, opt); resolved_styles .get_mut("minus-emph-style") .unwrap_or_else(|| panic!("minus-emph-style not found in resolved styles")) .is_emph = true; resolved_styles .get_mut("plus-emph-style") .unwrap_or_else(|| panic!("plus-emph-style not found in resolved styles")) .is_emph = true; resolved_styles } pub fn parse_styles_map(opt: &cli::Opt) -> Option<HashMap<style::AnsiTermStyleEqualityKey, Style>> { if let Some(styles_map_str) = &opt.map_styles { let mut styles_map = HashMap::new(); for pair_str in styles_map_str.split(',') { let mut style_strs = pair_str.split("=>").map(|s| s.trim()); if let (Some(from_str), Some(to_str)) = (style_strs.next(), style_strs.next()) { let from_style = parse_as_style_or_reference_to_git_config(from_str, opt); let to_style = parse_as_style_or_reference_to_git_config(to_str, opt); styles_map.insert( style::ansi_term_style_equality_key(from_style.ansi_term_style), to_style, ); } } Some(styles_map) } else { None } } fn resolve_style_references( edges: HashMap<&str, StyleReference>, opt: &cli::Opt, ) -> HashMap<String, Style> { let mut resolved_styles = HashMap::new(); for starting_node in edges.keys() { if resolved_styles.contains_key(*starting_node) { continue; } let mut visited = HashSet::new(); let mut node = *starting_node; loop { if !visited.insert(node) { #[cfg(not(test))] fatal(format!("Your delta styles form a cycle! {visited:?}")); #[cfg(test)] return [("__cycle__", Style::default())] .iter() .map(|(a, b)| (a.to_string(), *b)) .collect(); } match &edges.get(&node) { Some(StyleReference::Reference(child_node)) => node = child_node, Some(StyleReference::Style(style)) => { resolved_styles.extend(visited.iter().map(|node| (node.to_string(), *style))); break; } None => { let style = parse_as_reference_to_git_config(node, opt); resolved_styles.extend(visited.iter().map(|node| (node.to_string(), style))); } } } } resolved_styles } fn parse_as_style_or_reference_to_git_config(style_string: &str, opt: &cli::Opt) -> Style { match style_from_str(style_string, None, None, true, opt.git_config()) { StyleReference::Reference(style_ref) => parse_as_reference_to_git_config(&style_ref, opt), StyleReference::Style(style) => style, } } fn parse_as_reference_to_git_config(style_string: &str, opt: &cli::Opt) -> Style { if let Some(git_config) = opt.git_config() { let git_config_key = format!("delta.{style_string}"); match git_config.get::<String>(&git_config_key) { Some(s) => Style::from_git_str(&s), _ => fatal(format!( "Style key not found in git config: {git_config_key}", )), } } else { fatal(format!( "Style not found (git config unavailable): {style_string}", )); } } fn make_hunk_styles(opt: &cli::Opt, styles: &mut HashMap<&str, StyleReference>) { let color_mode = opt.computed.color_mode; let true_color = opt.computed.true_color; let minus_style = style_from_str( &opt.minus_style, Some(Style::from_colors( None, Some(color::get_minus_background_color_default( color_mode, true_color, )), )), None, true_color, opt.git_config(), ); let minus_emph_style = style_from_str( &opt.minus_emph_style, Some(Style::from_colors( None, Some(color::get_minus_emph_background_color_default( color_mode, true_color, )), )), None, true_color, opt.git_config(), ); let minus_non_emph_style = style_from_str( &opt.minus_non_emph_style, None, None, true_color, opt.git_config(), ); // The style used to highlight a removed empty line when otherwise it would be invisible due to // lack of background color in minus-style. let minus_empty_line_marker_style = style_from_str( &opt.minus_empty_line_marker_style, Some(Style::from_colors( None, Some(color::get_minus_background_color_default( color_mode, true_color, )), )), None, true_color, opt.git_config(), ); let zero_style = style_from_str(&opt.zero_style, None, None, true_color, opt.git_config()); let plus_style = style_from_str( &opt.plus_style, Some(Style::from_colors( None, Some(color::get_plus_background_color_default( color_mode, true_color, )), )), None, true_color, opt.git_config(), ); let plus_emph_style = style_from_str( &opt.plus_emph_style, Some(Style::from_colors( None, Some(color::get_plus_emph_background_color_default( color_mode, true_color, )), )), None, true_color, opt.git_config(), ); let plus_non_emph_style = style_from_str( &opt.plus_non_emph_style, None, None, true_color, opt.git_config(), ); // The style used to highlight an added empty line when otherwise it would be invisible due to // lack of background color in plus-style. let plus_empty_line_marker_style = style_from_str( &opt.plus_empty_line_marker_style, Some(Style::from_colors( None, Some(color::get_plus_background_color_default( color_mode, true_color, )), )), None, true_color, opt.git_config(), ); let whitespace_error_style = style_from_str( &opt.whitespace_error_style, None, None, true_color, opt.git_config(), ); styles.extend([ ("minus-style", minus_style), ("minus-emph-style", minus_emph_style), ("minus-non-emph-style", minus_non_emph_style), ( "minus-empty-line-marker-style", minus_empty_line_marker_style, ), ("zero-style", zero_style), ("plus-style", plus_style), ("plus-emph-style", plus_emph_style), ("plus-non-emph-style", plus_non_emph_style), ("plus-empty-line-marker-style", plus_empty_line_marker_style), ("whitespace-error-style", whitespace_error_style), ]) } fn make_line_number_styles(opt: &cli::Opt, styles: &mut HashMap<&str, StyleReference>) { let true_color = opt.computed.true_color; let line_numbers_left_style = style_from_str( &opt.line_numbers_left_style, None, None, true_color, opt.git_config(), ); let line_numbers_minus_style = style_from_str( &opt.line_numbers_minus_style, None, None, true_color, opt.git_config(), ); let line_numbers_zero_style = style_from_str( &opt.line_numbers_zero_style, None, None, true_color, opt.git_config(), ); let line_numbers_plus_style = style_from_str( &opt.line_numbers_plus_style, None, None, true_color, opt.git_config(), ); let line_numbers_right_style = style_from_str( &opt.line_numbers_right_style, None, None, true_color, opt.git_config(), ); styles.extend([ ("line-numbers-minus-style", line_numbers_minus_style), ("line-numbers-zero-style", line_numbers_zero_style), ("line-numbers-plus-style", line_numbers_plus_style), ("line-numbers-left-style", line_numbers_left_style), ("line-numbers-right-style", line_numbers_right_style), ]) } fn make_commit_file_hunk_header_styles(opt: &cli::Opt, styles: &mut HashMap<&str, StyleReference>) { let true_color = opt.computed.true_color; styles.extend([ ( "commit-style", style_from_str_with_handling_of_special_decoration_attributes( &opt.commit_style, None, Some(&opt.commit_decoration_style), true_color, opt.git_config(), ), ), ( "file-style", style_from_str_with_handling_of_special_decoration_attributes( &opt.file_style, None, Some(&opt.file_decoration_style), true_color, opt.git_config(), ), ), ( "classic-grep-header-style", style_from_str_with_handling_of_special_decoration_attributes( opt.hunk_header_style.as_str(), None, opt.grep_header_decoration_style .as_deref() .or(Some(opt.hunk_header_decoration_style.as_str())), true_color, opt.git_config(), ), ), ( "ripgrep-header-style", style_from_str_with_handling_of_special_decoration_attributes( "file", None, opt.grep_header_decoration_style.as_deref().or(Some("none")), true_color, opt.git_config(), ), ), ( "hunk-header-style", style_from_str_with_handling_of_special_decoration_attributes( &opt.hunk_header_style, None, Some(&opt.hunk_header_decoration_style), true_color, opt.git_config(), ), ), ( "hunk-header-file-style", style_from_str_with_handling_of_special_decoration_attributes( &opt.hunk_header_file_style, None, None, true_color, opt.git_config(), ), ), ( "classic-grep-header-file-style", style_from_str_with_handling_of_special_decoration_attributes( opt.grep_header_file_style .as_deref() .unwrap_or(opt.hunk_header_file_style.as_str()), None, None, true_color, opt.git_config(), ), ), ( "ripgrep-header-file-style", style_from_str_with_handling_of_special_decoration_attributes( opt.grep_header_file_style.as_deref().unwrap_or("magenta"), None, None, true_color, opt.git_config(), ), ), ( "hunk-header-line-number-style", style_from_str_with_handling_of_special_decoration_attributes( &opt.hunk_header_line_number_style, None, None, true_color, opt.git_config(), ), ), ]); } fn make_blame_styles(opt: &cli::Opt, styles: &mut HashMap<&str, StyleReference>) { if let Some(style_string) = &opt.blame_code_style { styles.insert( "blame-code-style", style_from_str( style_string, None, None, opt.computed.true_color, opt.git_config(), ), ); }; if let Some(style_string) = &opt.blame_separator_style { styles.insert( "blame-separator-style", style_from_str( style_string, None, None, opt.computed.true_color, opt.git_config(), ), ); }; } fn make_grep_styles(opt: &cli::Opt, styles: &mut HashMap<&str, StyleReference>) { styles.extend([ ( "grep-match-line-style", if let Some(s) = &opt.grep_match_line_style { style_from_str(s, None, None, opt.computed.true_color, opt.git_config()) } else { StyleReference::Reference("zero-style".to_owned()) }, ), ( "grep-match-word-style", if let Some(s) = &opt.grep_match_word_style { style_from_str(s, None, None, opt.computed.true_color, opt.git_config()) } else { StyleReference::Reference("plus-emph-style".to_owned()) }, ), ( "grep-context-line-style", if let Some(s) = &opt.grep_context_line_style { style_from_str(s, None, None, opt.computed.true_color, opt.git_config()) } else { StyleReference::Reference("zero-style".to_owned()) }, ), ( "grep-file-style", style_from_str( &opt.grep_file_style, None, None, opt.computed.true_color, opt.git_config(), ), ), ( "grep-line-number-style", style_from_str( &opt.grep_line_number_style, None, None, opt.computed.true_color, opt.git_config(), ), ), ]) } fn make_merge_conflict_styles(opt: &cli::Opt, styles: &mut HashMap<&str, StyleReference>) { styles.insert( "merge-conflict-ours-diff-header-style", style_from_str_with_handling_of_special_decoration_attributes( &opt.merge_conflict_ours_diff_header_style, None, Some(&opt.merge_conflict_ours_diff_header_decoration_style), opt.computed.true_color, opt.git_config(), ), ); styles.insert( "merge-conflict-theirs-diff-header-style", style_from_str_with_handling_of_special_decoration_attributes( &opt.merge_conflict_theirs_diff_header_style, None, Some(&opt.merge_conflict_theirs_diff_header_decoration_style), opt.computed.true_color, opt.git_config(), ), ); } fn make_misc_styles(opt: &cli::Opt, styles: &mut HashMap<&str, StyleReference>) { styles.insert( "inline-hint-style", style_from_str( &opt.inline_hint_style, None, None, opt.computed.true_color, opt.git_config(), ), ); styles.insert( "git-minus-style", StyleReference::Style( match opt .git_config() .and_then(|cfg| cfg.get::<String>("color.diff.old")) { Some(s) => Style::from_git_str(&s), None => *style::GIT_DEFAULT_MINUS_STYLE, }, ), ); styles.insert( "git-plus-style", StyleReference::Style( match opt .git_config() .and_then(|cfg| cfg.get::<String>("color.diff.new")) { Some(s) => Style::from_git_str(&s), None => *style::GIT_DEFAULT_PLUS_STYLE, }, ), ); } fn style_from_str( style_string: &str, default: Option<Style>, decoration_style_string: Option<&str>, true_color: bool, git_config: Option<&GitConfig>, ) -> StyleReference { if is_style_reference(style_string) { StyleReference::Reference(style_string.to_owned()) } else { StyleReference::Style(Style::from_str( style_string, default, decoration_style_string, true_color, git_config, )) } } fn style_from_str_with_handling_of_special_decoration_attributes( style_string: &str, default: Option<Style>, decoration_style_string: Option<&str>, true_color: bool, git_config: Option<&GitConfig>, ) -> StyleReference { if is_style_reference(style_string) { StyleReference::Reference(style_string.to_owned()) } else { StyleReference::Style( Style::from_str_with_handling_of_special_decoration_attributes( style_string, default, decoration_style_string, true_color, git_config, ), ) } } #[cfg(test)] mod tests { use super::*; use crate::tests::integration_test_utils; fn resolve_style_references(edges: HashMap<&str, StyleReference>) -> HashMap<String, Style> { let opt = integration_test_utils::make_options_from_args(&[]); super::resolve_style_references(edges, &opt) } #[test] fn test_resolve_style_references_1() { let style_1 = Style::default(); let style_2 = style::Style { is_syntax_highlighted: !style_1.is_syntax_highlighted, ..Default::default() }; let edges: HashMap<&str, StyleReference> = [ ("a", StyleReference::Style(style_1)), ("b", StyleReference::Reference("c".to_string())), ("c", StyleReference::Style(style_2)), ] .iter() .map(|(a, b)| (*a, b.clone())) .collect(); let expected = [("a", style_1), ("b", style_2), ("c", style_2)] .iter() .map(|(a, b)| (a.to_string(), *b)) .collect(); assert_eq!(resolve_style_references(edges), expected); } #[test] fn test_resolve_style_references_2() { let style_1 = Style::default(); let style_2 = style::Style { is_syntax_highlighted: !style_1.is_syntax_highlighted, ..Default::default() }; let edges: HashMap<&str, StyleReference> = [ ("a", StyleReference::Reference("b".to_string())), ("b", StyleReference::Reference("c".to_string())), ("c", StyleReference::Style(style_1)), ("d", StyleReference::Reference("b".to_string())), ("e", StyleReference::Reference("a".to_string())), ("f", StyleReference::Style(style_2)), ("g", StyleReference::Reference("f".to_string())), ("h", StyleReference::Reference("g".to_string())), ("i", StyleReference::Reference("g".to_string())), ] .iter() .map(|(a, b)| (*a, b.clone())) .collect(); let expected = [ ("a", style_1), ("b", style_1), ("c", style_1), ("d", style_1), ("e", style_1), ("f", style_2), ("g", style_2), ("h", style_2), ("i", style_2), ] .iter() .map(|(a, b)| (a.to_string(), *b)) .collect(); assert_eq!(resolve_style_references(edges), expected); } #[test] fn test_resolve_style_references_cycle() { let edges: HashMap<&str, StyleReference> = [ ("a", StyleReference::Reference("b".to_string())), ("b", StyleReference::Reference("c".to_string())), ("c", StyleReference::Reference("a".to_string())), ] .iter() .map(|(a, b)| (*a, b.clone())) .collect(); assert_eq!( resolve_style_references(edges).keys().next().unwrap(), "__cycle__" ); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/delta.rs
src/delta.rs
use std::borrow::Cow; use std::collections::HashMap; use std::io::{self, BufRead, IsTerminal, Write}; use bytelines::ByteLines; use crate::ansi; use crate::config::delta_unreachable; use crate::config::Config; use crate::config::GrepType; use crate::features; use crate::handlers::grep; use crate::handlers::hunk_header::{AmbiguousDiffMinusCounter, ParsedHunkHeader}; use crate::handlers::{self, merge_conflict}; use crate::paint::Painter; use crate::style::DecorationStyle; use crate::utils; #[derive(Clone, Debug, PartialEq, Eq)] pub enum State { CommitMeta, // In commit metadata section DiffHeader(DiffType), // In diff metadata section, between (possible) commit metadata and first hunk HunkHeader(DiffType, ParsedHunkHeader, String, String), // In hunk metadata line (diff_type, parsed, line, raw_line) HunkZero(DiffType, Option<String>), // In hunk; unchanged line (prefix, raw_line) HunkMinus(DiffType, Option<String>), // In hunk; removed line (diff_type, raw_line) HunkPlus(DiffType, Option<String>), // In hunk; added line (diff_type, raw_line) MergeConflict(MergeParents, merge_conflict::MergeConflictCommit), SubmoduleLog, // In a submodule section, with gitconfig diff.submodule = log SubmoduleShort(String), // In a submodule section, with gitconfig diff.submodule = short Blame(String), // In a line of `git blame` output (key). GitShowFile, // In a line of `git show $revision:./path/to/file.ext` output Grep(GrepType, grep::LineType, String, Option<usize>), // In a line of `git grep` output (grep_type, line_type, path, line_number) Unknown, // The following elements are created when a line is wrapped to display it: HunkZeroWrapped, // Wrapped unchanged line HunkMinusWrapped, // Wrapped removed line HunkPlusWrapped, // Wrapped added line } #[derive(Clone, Debug, PartialEq, Eq)] pub enum DiffType { Unified, // https://git-scm.com/docs/git-diff#_combined_diff_format Combined(MergeParents, InMergeConflict), } #[derive(Clone, Debug, PartialEq, Eq)] pub enum MergeParents { Number(usize), // Number of parent commits == (number of @s in hunk header) - 1 Prefix(String), // Hunk line prefix, length == number of parent commits Unknown, } #[derive(Clone, Debug, PartialEq, Eq)] pub enum InMergeConflict { Yes, No, } impl DiffType { pub fn n_parents(&self) -> usize { use DiffType::*; use MergeParents::*; match self { Combined(Prefix(prefix), _) => prefix.len(), Combined(Number(n_parents), _) => *n_parents, Unified => 1, Combined(Unknown, _) => delta_unreachable("Number of merge parents must be known."), } } } #[derive(Debug, PartialEq, Eq)] pub enum Source { GitDiff, // Coming from a `git diff` command DiffUnified, // Coming from a `diff -u` command Unknown, } // Possible transitions, with actions on entry: // // // | from \ to | CommitMeta | DiffHeader | HunkHeader | HunkZero | HunkMinus | HunkPlus | // |-------------+-------------+-------------+-------------+-------------+-------------+----------| // | CommitMeta | emit | emit | | | | | // | DiffHeader | | emit | emit | | | | // | HunkHeader | | | | emit | push | push | // | HunkZero | emit | emit | emit | emit | push | push | // | HunkMinus | flush, emit | flush, emit | flush, emit | flush, emit | push | push | // | HunkPlus | flush, emit | flush, emit | flush, emit | flush, emit | flush, push | push | pub struct StateMachine<'a> { pub line: String, pub raw_line: String, pub state: State, pub source: Source, pub minus_file: String, pub plus_file: String, pub minus_file_event: handlers::diff_header::FileEvent, pub plus_file_event: handlers::diff_header::FileEvent, pub diff_line: String, pub mode_info: String, pub painter: Painter<'a>, pub config: &'a Config, // When a file is modified, we use lines starting with '---' or '+++' to obtain the file name. // When a file is renamed without changes, we use lines starting with 'rename' to obtain the // file name (there is no diff hunk and hence no lines starting with '---' or '+++'). But when // a file is renamed with changes, both are present, and we rely on the following variables to // avoid emitting the file meta header line twice (#245). pub current_file_pair: Option<(String, String)>, pub handled_diff_header_header_line_file_pair: Option<(String, String)>, pub blame_key_colors: HashMap<String, String>, pub minus_line_counter: AmbiguousDiffMinusCounter, } pub fn delta<I>(lines: ByteLines<I>, writer: &mut dyn Write, config: &Config) -> std::io::Result<()> where I: BufRead, { StateMachine::new(writer, config).consume(lines) } impl<'a> StateMachine<'a> { pub fn new(writer: &'a mut dyn Write, config: &'a Config) -> Self { Self { line: "".to_string(), raw_line: "".to_string(), state: State::Unknown, source: Source::Unknown, minus_file: "".to_string(), plus_file: "".to_string(), minus_file_event: handlers::diff_header::FileEvent::NoEvent, plus_file_event: handlers::diff_header::FileEvent::NoEvent, diff_line: "".to_string(), mode_info: "".to_string(), current_file_pair: None, handled_diff_header_header_line_file_pair: None, painter: Painter::new(writer, config), config, blame_key_colors: HashMap::new(), minus_line_counter: AmbiguousDiffMinusCounter::not_needed(), } } fn consume<I>(&mut self, mut lines: ByteLines<I>) -> std::io::Result<()> where I: BufRead, { while let Some(Ok(raw_line_bytes)) = lines.next() { self.ingest_line(raw_line_bytes); if self.source == Source::Unknown { self.source = detect_source(&self.line); // Handle (rare) plain `diff -u file1 file2` header. Done here to avoid having // to introduce and handle a Source::DiffUnifiedAmbiguous variant everywhere. if self.line.starts_with("--- ") { self.minus_line_counter = AmbiguousDiffMinusCounter::prepare_to_count(); } } // Every method named handle_* must return std::io::Result<bool>. // The bool indicates whether the line has been handled by that // method (in which case no subsequent handlers are permitted to // handle it). let _ = self.handle_commit_meta_header_line()? || self.handle_diff_stat_line()? || self.handle_diff_header_diff_line()? || self.handle_diff_header_file_operation_line()? || self.handle_diff_header_minus_line()? || self.handle_diff_header_plus_line()? || self.handle_hunk_header_line()? || self.handle_diff_header_mode_line()? || self.handle_diff_header_misc_line()? || self.handle_submodule_log_line()? || self.handle_submodule_short_line()? || self.handle_merge_conflict_line()? || self.handle_hunk_line()? || self.handle_git_show_file_line()? || self.handle_blame_line()? || self.handle_grep_line()? || self.should_skip_line() || self.emit_line_unchanged()?; } self.handle_pending_line_with_diff_name()?; self.painter.paint_buffered_minus_and_plus_lines(); self.painter.emit()?; Ok(()) } fn ingest_line(&mut self, raw_line_bytes: &[u8]) { match String::from_utf8(raw_line_bytes.to_vec()) { Ok(utf8) => self.ingest_line_utf8(utf8), Err(_) => { let raw_line = String::from_utf8_lossy(raw_line_bytes); let truncated_len = utils::round_char_boundary::floor_char_boundary( &raw_line, self.config.max_line_length, ); self.raw_line = raw_line[..truncated_len].to_string(); self.line.clone_from(&self.raw_line); } } } fn ingest_line_utf8(&mut self, raw_line: String) { self.raw_line = raw_line; // When a file has \r\n line endings, git sometimes adds ANSI escape sequences between the // \r and \n, in which case byte_lines does not remove the \r. Remove it now. [EndCRLF] // TODO: Limit the number of characters we examine when looking for the \r? if let Some(cr_index) = self.raw_line.rfind('\r') { if ansi::measure_text_width(&self.raw_line[cr_index + 1..]) == 0 { self.raw_line = format!( "{}{}", &self.raw_line[..cr_index], &self.raw_line[cr_index + 1..] ); } } if self.config.max_line_length > 0 && self.raw_line.len() > self.config.max_line_length // Do not truncate long hunk headers && !self.raw_line.starts_with("@@") // Do not truncate ripgrep --json output && !self.raw_line.starts_with('{') { self.raw_line = ansi::truncate_str( &self.raw_line, self.config.max_line_length, &self.config.truncation_symbol, ) .to_string() }; self.line = ansi::strip_ansi_codes(&self.raw_line); } /// Skip file metadata lines unless a raw diff style has been requested. pub fn should_skip_line(&self) -> bool { matches!(self.state, State::DiffHeader(_)) && self.should_handle() && !self.config.color_only } /// Emit unchanged any line that delta does not handle. pub fn emit_line_unchanged(&mut self) -> std::io::Result<bool> { self.painter.emit()?; writeln!( self.painter.writer, "{}", format_raw_line(&self.raw_line, self.config) )?; let handled_line = true; Ok(handled_line) } /// Should a handle_* function be called on this element? // TODO: I'm not sure the above description is accurate; I think this // function needs a more accurate name. pub fn should_handle(&self) -> bool { let style = self.config.get_style(&self.state); !(style.is_raw && style.decoration_style == DecorationStyle::NoDecoration) } } /// If output is going to a tty, emit hyperlinks if requested. // Although raw output should basically be emitted unaltered, we do this. pub fn format_raw_line<'a>(line: &'a str, config: &Config) -> Cow<'a, str> { if config.hyperlinks && io::stdout().is_terminal() { features::hyperlinks::format_commit_line_with_osc8_commit_hyperlink(line, config) } else { Cow::from(line) } } /// Try to detect what is producing the input for delta. /// /// Currently can detect: /// * git diff /// * diff -u fn detect_source(line: &str) -> Source { if line.starts_with("commit ") || line.starts_with("diff --git ") || line.starts_with("diff --cc ") || line.starts_with("diff --combined ") { Source::GitDiff } else if line.starts_with("diff -u") || line.starts_with("diff -ru") || line.starts_with("diff -r -u") || line.starts_with("diff -U") || line.starts_with("--- ") || line.starts_with("Only in ") { Source::DiffUnified } else { Source::Unknown } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/cli.rs
src/cli.rs
use std::collections::{HashMap, HashSet}; use std::ffi::OsString; use std::path::{Path, PathBuf}; use bat::assets::HighlightingAssets; use clap::error::Error; use clap::{ArgMatches, ColorChoice, CommandFactory, FromArgMatches, Parser, ValueEnum, ValueHint}; use clap_complete::Shell; use console::Term; use lazy_static::lazy_static; use syntect::highlighting::Theme as SyntaxTheme; use syntect::parsing::SyntaxSet; use crate::ansi::{ANSI_SGR_BOLD, ANSI_SGR_RESET, ANSI_SGR_UNDERLINE}; use crate::color::ColorMode; use crate::config::delta_unreachable; use crate::env::DeltaEnv; use crate::git_config::GitConfig; use crate::options; use crate::subcommands; use crate::utils; use crate::utils::bat::output::PagingMode; const TERM_FALLBACK_WIDTH: usize = 79; #[derive(Parser)] #[command( name = "delta", about = "A viewer for git and diff output", version, color = ColorChoice::Always, // output is wrapped by delta later: term_width = usize::MAX, max_term_width = usize::MAX, )] pub struct Opt { #[arg(long = "blame-code-style", value_name = "STYLE")] /// Style string for the code section of a git blame line. /// /// By default the code will be syntax-highlighted with the same background color as the blame /// format section of the line (the background color is determined by blame-palette). E.g. /// setting this option to 'syntax' will syntax-highlight the code with no background color. pub blame_code_style: Option<String>, #[arg( long = "blame-format", default_value = "{timestamp:<15} {author:<15.14} {commit:<8}", value_name = "FMT" )] /// Format string for git blame commit metadata. /// /// Available placeholders are "{timestamp}", "{author}", and "{commit}". pub blame_format: String, #[arg(long = "blame-palette", value_name = "COLORS")] /// Background colors used for git blame lines (space-separated string). /// /// Lines added by the same commit are painted with the same color; colors are recycled as /// needed. pub blame_palette: Option<String>, #[arg( long = "blame-separator-format", default_value = "│{n:^4}│", value_name = "FMT" )] /// Separator between the blame format and the code section of a git blame line. /// /// Contains the line number by default. Possible values are "none" to disable line numbers or a format /// string. This may contain one "{n:}" placeholder and will display the line number on every line. /// A type may be added after all other format specifiers and can be separated by '_': /// If type is set to 'block' (e.g. "{n:^4_block}") the line number will only be shown when a new blame /// block starts; or if it is set to 'every-N' the line will be show with every block and every /// N-th (modulo) line. pub blame_separator_format: String, #[arg(long = "blame-separator-style", value_name = "STYLE")] /// Style string for the blame-separator-format. pub blame_separator_style: Option<String>, #[arg( long = "blame-timestamp-format", default_value = "%Y-%m-%d %H:%M:%S %z", value_name = "FMT" )] /// Format of `git blame` timestamp in raw git output received by delta. pub blame_timestamp_format: String, #[arg(long = "blame-timestamp-output-format", value_name = "FMT")] /// Format string for git blame timestamp output. /// /// This string is used for formatting the timestamps in git blame output. It must follow /// the `strftime` format syntax specification. If it is not present, the timestamps will /// be formatted in a human-friendly but possibly less accurate form. /// /// See: <https://docs.rs/chrono/latest/chrono/format/strftime/index.html> pub blame_timestamp_output_format: Option<String>, #[arg(long = "color-only")] /// Do not alter the input structurally in any way. /// /// But color and highlight hunk lines according to your delta configuration. This is mainly /// intended for other tools that use delta. pub color_only: bool, #[arg(long = "config", default_value = "", value_name = "PATH", value_hint = ValueHint::FilePath)] /// Load the config file at PATH instead of ~/.gitconfig. pub config: String, #[arg( long = "commit-decoration-style", default_value = "", value_name = "STYLE" )] /// Style string for the commit hash decoration. /// /// See STYLES section. The style string should contain one of the special attributes 'box', /// 'ul' (underline), 'ol' (overline), or the combination 'ul ol'. pub commit_decoration_style: String, #[arg( long = "commit-regex", default_value = r"^commit ", value_name = "REGEX" )] /// Regular expression used to identify the commit line when parsing git output. pub commit_regex: String, #[arg(long = "commit-style", default_value = "raw", value_name = "STYLE")] /// Style string for the commit hash line. /// /// See STYLES section. The style 'omit' can be used to remove the commit hash line from the /// output. pub commit_style: String, #[arg(long = "dark")] /// Use default colors appropriate for a dark terminal background. /// /// For more control, see the style options and --syntax-theme. pub dark: bool, #[arg(long = "default-language", value_name = "LANG", default_value = "txt")] /// Default language used for syntax highlighting. /// /// Used as a fallback when the language cannot be inferred from a filename. It will /// typically make sense to set this in the per-repository config file '.git/config'. pub default_language: String, /// Detect whether or not the terminal is dark or light by querying for its colors. /// /// Ignored if either `--dark` or `--light` is specified. /// /// Querying the terminal for its colors requires "exclusive" access /// since delta reads/writes from the terminal and enables/disables raw mode. /// This causes race conditions with pagers such as less when they are attached to the /// same terminal as delta. /// /// This is usually only an issue when the output is manually piped to a pager. /// For example: `git diff | delta | less`. /// Otherwise, if delta starts the pager itself, then there's no race condition /// since the pager is started *after* the color is detected. /// /// `auto` tries to account for these situations by testing if the output is redirected. /// /// The `--color-only` option is treated as an indicator that delta is used /// as `interactive.diffFilter`. In this case the color is queried from the terminal even /// though the output is redirected. /// #[arg(long = "detect-dark-light", value_enum, default_value_t = DetectDarkLight::default())] pub detect_dark_light: DetectDarkLight, #[arg( long = "diff-args", short = '@', default_value = "", value_name = "STRING" )] /// Extra arguments to pass to `git diff` when using delta to diff two files. /// /// E.g. `delta --diff-args=-U999 file_1 file_2` is equivalent to /// `git diff --no-index --color -U999 file_1 file_2 | delta`. /// /// If you use process substitution (`delta <(command_1) <(command_2)`) and your git version /// doesn't support it, then delta will fall back to `diff` instead of `git diff`. pub diff_args: String, #[arg(long = "diff-highlight")] /// Emulate diff-highlight. /// /// <https://github.com/git/git/tree/master/contrib/diff-highlight> pub diff_highlight: bool, #[arg(long = "diff-so-fancy")] /// Emulate diff-so-fancy. /// /// <https://github.com/so-fancy/diff-so-fancy> pub diff_so_fancy: bool, #[arg(long = "diff-stat-align-width", default_value = "48", value_name = "N")] /// Width allocated for file paths in a diff stat section. /// /// If a relativized file path exceeds this width then the diff stat will be misaligned. pub diff_stat_align_width: usize, #[arg(long = "features", value_name = "FEATURES")] /// Names of delta features to activate (space-separated). /// /// A feature is a named collection of delta options in ~/.gitconfig. See FEATURES section. The /// environment variable DELTA_FEATURES can be set to a space-separated list of feature names. /// If this is preceded with a + character, the features from the environment variable will be added /// to those specified in git config. E.g. DELTA_FEATURES=+side-by-side can be used to activate /// side-by-side temporarily (use DELTA_FEATURES=+ to go back to just the features from git config). pub features: Option<String>, #[arg( long = "file-added-label", default_value = "added:", value_name = "STRING" )] /// Text to display before an added file path. /// /// Used in the default value of navigate-regex. pub file_added_label: String, #[arg( long = "file-copied-label", default_value = "copied:", value_name = "STRING" )] /// Text to display before a copied file path. pub file_copied_label: String, #[arg( long = "file-decoration-style", default_value = "blue ul", value_name = "STYLE" )] /// Style string for the file decoration. /// /// See STYLES section. The style string should contain one of the special attributes 'box', /// 'ul' (underline), 'ol' (overline), or the combination 'ul ol'. pub file_decoration_style: String, #[arg( long = "file-modified-label", default_value = "", value_name = "STRING" )] /// Text to display before a modified file path. /// /// Used in the default value of navigate-regex. pub file_modified_label: String, #[arg( long = "file-removed-label", default_value = "removed:", value_name = "STRING" )] /// Text to display before a removed file path. /// /// Used in the default value of navigate-regex. pub file_removed_label: String, #[arg( long = "file-renamed-label", default_value = "renamed:", value_name = "STRING" )] /// Text to display before a renamed file path. /// /// Used in the default value of navigate-regex. pub file_renamed_label: String, #[arg(long = "file-style", default_value = "blue", value_name = "STYLE")] /// Style string for the file section. /// /// See STYLES section. The style 'omit' can be used to remove the file section from the output. pub file_style: String, #[arg(long = "file-transformation", value_name = "SED_CMD")] /// Sed-style command transforming file paths for display. pub file_regex_replacement: Option<String>, #[arg(long = "generate-completion")] /// Print completion file for the given shell. pub generate_completion: Option<Shell>, #[arg(long = "grep-context-line-style", value_name = "STYLE")] /// Style string for non-matching lines of grep output. /// /// See STYLES section. Defaults to zero-style. pub grep_context_line_style: Option<String>, #[arg( long = "grep-file-style", default_value = "magenta", value_name = "STYLE" )] /// Style string for file paths in grep output. /// /// See STYLES section. pub grep_file_style: String, #[arg(long = "grep-header-decoration-style", value_name = "STYLE")] /// Style string for the header decoration in grep output. /// /// Default is "none" when grep-output-type-is "ripgrep", otherwise defaults /// to value of header-decoration-style. See hunk-header-decoration-style. pub grep_header_decoration_style: Option<String>, #[arg(long = "grep-header-file-style", value_name = "STYLE")] /// Style string for the file path part of the header in grep output. /// /// See hunk_header_file_style. pub grep_header_file_style: Option<String>, #[arg( long = "grep-line-number-style", default_value = "green", value_name = "STYLE" )] /// Style string for line numbers in grep output. /// /// See STYLES section. pub grep_line_number_style: String, #[arg(long = "grep-output-type", value_name = "OUTPUT_TYPE", value_parser = ["ripgrep", "classic"])] /// Grep output format. Possible values: /// "ripgrep" - file name printed once, followed by matching lines within that file, each preceded by a line number. /// "classic" - file name:line number, followed by matching line. /// Default is "ripgrep" if `rg --json` format is detected, otherwise "classic". pub grep_output_type: Option<String>, #[arg(long = "grep-match-line-style", value_name = "STYLE")] /// Style string for matching lines of grep output. /// /// See STYLES section. Defaults to plus-style. pub grep_match_line_style: Option<String>, #[arg(long = "grep-match-word-style", value_name = "STYLE")] /// Style string for the matching substrings within a matching line of grep output. /// /// See STYLES section. Defaults to plus-style. pub grep_match_word_style: Option<String>, #[arg( long = "grep-separator-symbol", default_value = ":", value_name = "STRING" )] /// Separator symbol printed after the file path and line number in grep output. /// /// Defaults to ":" for both match and context lines, since many terminal emulators recognize /// constructs like "/path/to/file:7:". However, standard grep output uses "-" for context /// lines: set this option to "keep" to keep the original separator symbols. pub grep_separator_symbol: String, #[arg( long = "hunk-header-decoration-style", default_value = "blue box", value_name = "STYLE" )] /// Style string for the hunk-header decoration. /// /// See STYLES section. The style string should contain one of the special attributes 'box', /// 'ul' (underline), 'ol' (overline), or the combination 'ul ol'. pub hunk_header_decoration_style: String, #[arg( long = "hunk-header-file-style", default_value = "blue", value_name = "STYLE" )] /// Style string for the file path part of the hunk-header. /// /// See STYLES section. The file path will only be displayed if hunk-header-style contains the /// 'file' special attribute. pub hunk_header_file_style: String, #[arg( long = "hunk-header-line-number-style", default_value = "blue", value_name = "STYLE" )] /// Style string for the line number part of the hunk-header. /// /// See STYLES section. The line number will only be displayed if hunk-header-style contains the /// 'line-number' special attribute. pub hunk_header_line_number_style: String, #[arg( long = "hunk-header-style", default_value = "line-number syntax", value_name = "STYLE" )] /// Style string for the hunk-header. /// /// See STYLES section. Special attributes 'file' and 'line-number' can be used to include the /// file path, and number of first hunk line, in the hunk header. The style 'omit' can be used /// to remove the hunk header section from the output. pub hunk_header_style: String, #[arg(long = "hunk-label", default_value = "", value_name = "STRING")] /// Text to display before a hunk header. /// /// Used in the default value of navigate-regex. pub hunk_label: String, #[arg(long = "hyperlinks")] /// Render commit hashes, file names, and line numbers as hyperlinks. /// /// Following the hyperlink spec for terminal emulators: /// <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>. By default, file names /// and line numbers link to the local file using a file URL, whereas commit hashes link to the /// commit in GitHub, if the remote repository is hosted by GitHub. See /// --hyperlinks-file-link-format for full control over the file URLs emitted. Hyperlinks are /// supported by several common terminal emulators. To make them work, you must use less /// version >= 581 with the -R flag (or use -r with older less versions, but this will break /// e.g. --navigate). If you use tmux, then you will also need a patched fork of tmux (see /// <https://github.com/dandavison/tmux>). pub hyperlinks: bool, #[arg(long = "hyperlinks-commit-link-format", value_name = "FMT")] /// Format string for commit hyperlinks (requires --hyperlinks). /// /// The placeholder "{commit}" will be replaced by the commit hash. For example: /// --hyperlinks-commit-link-format='https://mygitrepo/{commit}/' pub hyperlinks_commit_link_format: Option<String>, #[arg( long = "hyperlinks-file-link-format", default_value = "file://{path}", value_name = "FMT" )] /// Format string for file hyperlinks (requires --hyperlinks). /// /// Placeholders "{path}" and "{line}" will be replaced by the absolute file path and the line /// number; "{host}" with the hostname delta is currently running on. The default is to create /// a hyperlink containing a standard file URI with only the filename, which your terminal or /// OS should handle. You can specify any scheme, such as "file-line://{path}:{line}" and /// register an application to handle it. See /// <https://dandavison.github.io/delta/hyperlinks.html> for details. pub hyperlinks_file_link_format: String, #[arg( long = "inline-hint-style", default_value = "blue", value_name = "STYLE" )] /// Style string for short inline hint text. /// /// This styles certain content added by delta to the original diff such as special characters /// to highlight tabs, and the symbols used to indicate wrapped lines. See STYLES section. pub inline_hint_style: String, #[arg( long = "inspect-raw-lines", default_value = "true", value_name = "true|false", value_parser = ["true", "false"], )] /// Kill-switch for --color-moved support. /// /// Whether to examine ANSI color escape sequences in raw lines received from Git and handle /// lines colored in certain ways specially. This is on by default: it is how Delta supports /// Git's --color-moved feature. Set this to "false" to disable this behavior. pub inspect_raw_lines: String, #[arg(long = "keep-plus-minus-markers")] /// Prefix added/removed lines with a +/- character, as git does. /// /// By default, delta does not emit any prefix, so code can be copied directly from delta's /// output. pub keep_plus_minus_markers: bool, #[arg(long = "light")] /// Use default colors appropriate for a light terminal background. /// /// For more control, see the style options and --syntax-theme. pub light: bool, #[arg(long = "line-buffer-size", default_value = "32", value_name = "N")] /// Size of internal line buffer. /// /// Delta compares the added and removed versions of nearby lines in order to detect and /// highlight changes at the level of individual words/tokens. Therefore, nearby lines must be /// buffered internally before they are painted and emitted. Increasing this value might improve /// highlighting of some large diff hunks. However, setting this to a high value will adversely /// affect delta's performance when entire files are added/removed. pub line_buffer_size: usize, #[arg(long = "line-fill-method", value_name = "STRING", value_parser = ["ansi", "spaces"])] /// Line-fill method in side-by-side mode. /// /// How to extend the background color to the end of the line in side-by-side mode. Can be ansi /// (default) or spaces (default if output is not to a terminal). Has no effect if /// --width=variable is given. pub line_fill_method: Option<String>, #[arg(short = 'n', long = "line-numbers")] /// Display line numbers next to the diff. /// /// See LINE NUMBERS section. pub line_numbers: bool, #[arg( long = "line-numbers-left-format", default_value = "{nm:^4}⋮", value_name = "FMT" )] /// Format string for the left column of line numbers. /// /// A typical value would be "{nm:^4}⋮" which means to display the line numbers of the minus /// file (old version), center-aligned, padded to a width of 4 characters, followed by a /// dividing character. See the LINE NUMBERS section. pub line_numbers_left_format: String, #[arg( long = "line-numbers-left-style", default_value = "auto", value_name = "STYLE" )] /// Style string for the left column of line numbers. /// /// See STYLES and LINE NUMBERS sections. pub line_numbers_left_style: String, #[arg( long = "line-numbers-minus-style", default_value = "auto", value_name = "STYLE" )] /// Style string for line numbers in the old (minus) version of the file. /// /// See STYLES and LINE NUMBERS sections. pub line_numbers_minus_style: String, #[arg( long = "line-numbers-plus-style", default_value = "auto", value_name = "STYLE" )] /// Style string for line numbers in the new (plus) version of the file. /// /// See STYLES and LINE NUMBERS sections. pub line_numbers_plus_style: String, #[arg( long = "line-numbers-right-format", default_value = "{np:^4}│", value_name = "FMT" )] /// Format string for the right column of line numbers. /// /// A typical value would be "{np:^4}│ " which means to display the line numbers of the plus /// file (new version), center-aligned, padded to a width of 4 characters, followed by a /// dividing character, and a space. See the LINE NUMBERS section. pub line_numbers_right_format: String, #[arg( long = "line-numbers-right-style", default_value = "auto", value_name = "STYLE" )] /// Style string for the right column of line numbers. /// /// See STYLES and LINE NUMBERS sections. pub line_numbers_right_style: String, #[arg( long = "line-numbers-zero-style", default_value = "auto", value_name = "STYLE" )] /// Style string for line numbers in unchanged (zero) lines. /// /// See STYLES and LINE NUMBERS sections. pub line_numbers_zero_style: String, #[arg(long = "list-languages")] /// List supported languages and associated file extensions. pub list_languages: bool, #[arg(long = "list-syntax-themes")] /// List available syntax-highlighting color themes. pub list_syntax_themes: bool, #[arg(long = "map-styles", value_name = "STYLES_MAP")] /// Map styles encountered in raw input to desired output styles. /// /// An example is --map-styles='bold purple => red "#eeeeee", bold cyan => syntax "#eeeeee"' pub map_styles: Option<String>, #[arg(long = "max-line-distance", default_value = "0.6", value_name = "DIST")] /// Maximum line pair distance parameter in within-line diff algorithm. /// /// This parameter is the maximum distance (0.0 - 1.0) between two lines for them to be inferred /// to be homologous. Homologous line pairs are highlighted according to the deletion and /// insertion operations transforming one into the other. pub max_line_distance: f64, #[arg( long = "max-syntax-highlighting-length", default_value = "400", value_name = "N" )] /// Stop syntax highlighting lines after this many characters. /// /// To always highlight entire lines, set to zero - but note that delta will be slow on very /// long lines (e.g. minified .js). pub max_syntax_length: usize, #[arg(long = "max-line-length", default_value = "3000", value_name = "N")] /// Truncate lines longer than this. /// /// To prevent any truncation, set to zero. When wrapping lines this does nothing as it is /// overwritten to fit at least all visible characters, see `--wrap-max-lines`. pub max_line_length: usize, #[arg( long = "merge-conflict-begin-symbol", default_value = "▼", value_name = "STRING" )] /// String marking the beginning of a merge conflict region. /// /// The string will be repeated until it reaches the required length. pub merge_conflict_begin_symbol: String, #[arg( long = "merge-conflict-end-symbol", default_value = "▲", value_name = "STRING" )] /// String marking the end of a merge conflict region. /// /// The string will be repeated until it reaches the required length. pub merge_conflict_end_symbol: String, #[arg( long = "merge-conflict-ours-diff-header-decoration-style", default_value = "box", value_name = "STYLE" )] /// Style string for the decoration of the header above the 'ours' merge conflict diff. /// /// This styles the decoration of the header above the diff between the ancestral commit and the /// 'ours' branch. See STYLES section. The style string should contain one of the special /// attributes 'box', 'ul' (underline), 'ol' (overline), or the combination 'ul ol'. pub merge_conflict_ours_diff_header_decoration_style: String, #[arg( long = "merge-conflict-ours-diff-header-style", default_value = "normal", value_name = "STYLE" )] /// Style string for the header above the 'ours' branch merge conflict diff. /// /// See STYLES section. pub merge_conflict_ours_diff_header_style: String, #[arg( long = "merge-conflict-theirs-diff-header-decoration-style", default_value = "box", value_name = "STYLE" )] /// Style string for the decoration of the header above the 'theirs' merge conflict diff. /// /// This styles the decoration of the header above the diff between the ancestral commit and /// 'their' branch. See STYLES section. The style string should contain one of the special /// attributes 'box', 'ul' (underline), 'ol' (overline), or the combination 'ul ol'. pub merge_conflict_theirs_diff_header_decoration_style: String, #[arg( long = "merge-conflict-theirs-diff-header-style", default_value = "normal", value_name = "STYLE" )] /// Style string for the header above the 'theirs' branch merge conflict diff. /// /// This styles the header above the diff between the ancestral commit and 'their' branch. See /// STYLES section. pub merge_conflict_theirs_diff_header_style: String, #[arg( long = "minus-empty-line-marker-style", default_value = "normal auto", value_name = "STYLE" )] /// Style string for removed empty line marker. /// /// Used only if --minus-style has no background color. pub minus_empty_line_marker_style: String, #[arg( long = "minus-emph-style", default_value = "normal auto", value_name = "STYLE" )] /// Style string for emphasized sections of removed lines. /// /// See STYLES section. pub minus_emph_style: String, #[arg( long = "minus-non-emph-style", default_value = "minus-style", value_name = "STYLE" )] /// Style string for non-emphasized sections of removed lines that have an emphasized section. /// /// See STYLES section. pub minus_non_emph_style: String, #[arg( long = "minus-style", default_value = "normal auto", value_name = "STYLE" )] /// Style string for removed lines. /// /// See STYLES section. pub minus_style: String, #[arg(long = "navigate")] /// Activate diff navigation. /// /// Use n to jump forwards and N to jump backwards. To change the file labels used see /// --file-added-label, --file-copied-label, --file-modified-label, --file-removed-label, --file-renamed-label. pub navigate: bool, #[arg(long = "navigate-regex", value_name = "REGEX")] /// Regular expression defining navigation stop points. pub navigate_regex: Option<String>, #[arg(long = "no-gitconfig")] /// Do not read any settings from git config. /// /// See GIT CONFIG section. pub no_gitconfig: bool, #[arg(long = "pager", value_name = "CMD")] /// Which pager to use. /// /// The default pager is `less`. You can also change pager by setting the /// environment variable DELTA_PAGER, or PAGER. This option overrides these /// environment variables. pub pager: Option<String>, #[arg( long = "paging", default_value = "auto", value_name = "auto|always|never", value_parser = ["auto", "always", "never"], )] /// Whether to use a pager when displaying output. /// /// Options are: auto, always, and never. pub paging_mode: String, #[arg(long = "parse-ansi")] /// Display ANSI color escape sequences in human-readable form. /// /// Example usage: git show --color=always | delta --parse-ansi /// This can be used to help identify input style strings to use with map-styles. pub parse_ansi: bool, #[arg( long = "plus-emph-style", default_value = "syntax auto", value_name = "STYLE" )] /// Style string for emphasized sections of added lines. /// /// See STYLES section. pub plus_emph_style: String, #[arg( long = "plus-empty-line-marker-style", default_value = "normal auto", value_name = "STYLE" )] /// Style string for added empty line marker. /// /// Used only if --plus-style has no background color. pub plus_empty_line_marker_style: String, #[arg( long = "plus-non-emph-style", default_value = "plus-style", value_name = "STYLE" )] /// Style string for non-emphasized sections of added lines that have an emphasized section. /// /// See STYLES section. pub plus_non_emph_style: String, #[arg( long = "plus-style", default_value = "syntax auto", value_name = "STYLE" )] /// Style string for added lines. /// /// See STYLES section. pub plus_style: String, #[arg(long = "raw")] /// Do not alter the input in any way. /// /// This is mainly intended for testing delta. pub raw: bool, #[arg(long = "relative-paths")] /// Output all file paths relative to the current directory. /// /// This means that they will resolve correctly when clicked on or used in shell commands. pub relative_paths: bool, #[arg(long = "right-arrow", default_value = "⟶ ", value_name = "STRING")] /// Text to display with a changed file path. /// /// For example, a unified diff heading, a rename, or a chmod. pub right_arrow: String, #[arg(long = "show-colors")] /// Show available named colors. /// /// In addition to named colors, arbitrary colors can be specified using RGB hex codes. See /// COLORS section. pub show_colors: bool, #[arg(long = "show-config")] /// Display the active values for all Delta options. /// /// Style string options are displayed with foreground and background colors. This can be used to /// experiment with colors by combining this option with other options such as --minus-style, /// --zero-style, --plus-style, --light, --dark, etc. pub show_config: bool, #[arg(long = "show-syntax-themes")] /// Show example diff for available syntax-highlighting themes. /// /// If diff output is supplied on standard input then this will be used for the demo. For /// example: `git show | delta --show-syntax-themes`. pub show_syntax_themes: bool, #[arg(long = "show-themes")] /// Show example diff for available delta themes. /// /// A delta theme is a delta named feature (see --features) that sets either `light` or `dark`. /// See <https://github.com/dandavison/delta#custom-color-themes>. If diff output is supplied on /// standard input then this will be used for the demo. For example: `git show | delta /// --show-themes`. By default shows dark or light themes only, according to whether delta is in
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
true
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/minusplus.rs
src/minusplus.rs
use std::ops::{Index, IndexMut}; /// Represent data related to removed/minus and added/plus lines which /// can be indexed with [`MinusPlusIndex::{Plus`](MinusPlusIndex::Plus)`,`[`Minus}`](MinusPlusIndex::Minus). #[derive(Debug, Clone, PartialEq, Eq)] pub struct MinusPlus<T> { pub minus: T, pub plus: T, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MinusPlusIndex { Minus, Plus, } pub use MinusPlusIndex::*; impl<T> Index<MinusPlusIndex> for MinusPlus<T> { type Output = T; fn index(&self, side: MinusPlusIndex) -> &Self::Output { match side { Minus => &self.minus, Plus => &self.plus, } } } impl<T> IndexMut<MinusPlusIndex> for MinusPlus<T> { fn index_mut(&mut self, side: MinusPlusIndex) -> &mut Self::Output { match side { Minus => &mut self.minus, Plus => &mut self.plus, } } } impl<T> MinusPlus<T> { pub fn new(minus: T, plus: T) -> Self { MinusPlus { minus, plus } } } impl<T: Default> Default for MinusPlus<T> { fn default() -> Self { Self { minus: T::default(), plus: T::default(), } } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/wrapping.rs
src/wrapping.rs
use syntect::highlighting::Style as SyntectStyle; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; use crate::cli; use crate::config::INLINE_SYMBOL_WIDTH_1; use crate::fatal; use crate::config::Config; use crate::delta::DiffType; use crate::delta::State; use crate::features::line_numbers::{self, SideBySideLineWidth}; use crate::features::side_by_side::{available_line_width, line_is_too_long, Left, Right}; use crate::minusplus::*; use crate::paint::LineSections; use crate::style::Style; use crate::utils::syntect::FromDeltaStyle; /// See [`wrap_line`] for documentation. #[derive(Clone, Debug)] pub struct WrapConfig { pub left_symbol: String, pub right_symbol: String, pub right_prefix_symbol: String, // In fractions of 1000 so that a >100 wide panel can // still be configured down to a single character. pub use_wrap_right_permille: usize, // This value is --wrap-max-lines + 1, and unlimited is 0, see // adapt_wrap_max_lines_argument() pub max_lines: usize, pub inline_hint_syntect_style: SyntectStyle, } impl WrapConfig { pub fn from_opt(opt: &cli::Opt, inline_hint_style: Style) -> Self { Self { left_symbol: ensure_display_width_1("wrap-left-symbol", opt.wrap_left_symbol.clone()), right_symbol: ensure_display_width_1( "wrap-right-symbol", opt.wrap_right_symbol.clone(), ), right_prefix_symbol: ensure_display_width_1( "wrap-right-prefix-symbol", opt.wrap_right_prefix_symbol.clone(), ), use_wrap_right_permille: { let arg = &opt.wrap_right_percent; let percent = remove_percent_suffix(arg) .parse::<f64>() .unwrap_or_else(|err| { fatal(format!( "Could not parse wrap-right-percent argument {}: {}.", &arg, err )) }); if percent.is_finite() && percent > 0.0 && percent < 100.0 { (percent * 10.0).round() as usize } else { fatal("Invalid value for wrap-right-percent, not between 0 and 100.") } }, max_lines: adapt_wrap_max_lines_argument(opt.wrap_max_lines.clone()), inline_hint_syntect_style: SyntectStyle::from_delta_style(inline_hint_style), } } // Compute value of `max_line_length` field in the main `Config` struct. pub fn config_max_line_length( &self, max_line_length: usize, available_terminal_width: usize, ) -> usize { match self.max_lines { 1 => max_line_length, // Ensure there is enough text to wrap, either don't truncate the input at all (0) // or ensure there is enough for the requested number of lines. // The input can contain ANSI sequences, so round up a bit. This is enough for // normal `git diff`, but might not be with ANSI heavy input. 0 => 0, wrap_max_lines => { let single_pane_width = available_terminal_width / 2; let add_25_percent_or_term_width = |x| x + std::cmp::max((x * 250) / 1000, single_pane_width); std::cmp::max( max_line_length, add_25_percent_or_term_width(single_pane_width * wrap_max_lines), ) } } } } fn remove_percent_suffix(arg: &str) -> &str { match &arg.strip_suffix('%') { Some(s) => s, None => arg, } } fn ensure_display_width_1(what: &str, arg: String) -> String { match arg.grapheme_indices(true).count() { INLINE_SYMBOL_WIDTH_1 => arg, width => fatal(format!( "Invalid value for {what}, display width of \"{arg}\" must be {INLINE_SYMBOL_WIDTH_1} but is {width}", )), } } fn adapt_wrap_max_lines_argument(arg: String) -> usize { if arg == "∞" || arg == "unlimited" || arg.starts_with("inf") { 0 } else { arg.parse::<usize>() .unwrap_or_else(|err| fatal(format!("Invalid wrap-max-lines argument: {err}"))) + 1 } } #[derive(PartialEq)] enum Stop { StackEmpty, LineLimit, } /// Wrap the given `line` if it is longer than `line_width`. Wrap to at most /// [Config::WrapConfig::max_lines](WrapConfig::max_lines) lines, /// then truncate again - but never truncate if it is `0`. Place /// [left_symbol](WrapConfig::left_symbol) at the end of wrapped lines. /// If wrapping results in only *one* extra line and if the width of the wrapped /// line is less than [use_wrap_right_permille](WrapConfig::use_wrap_right_permille) /// then right-align the second line and use the symbols /// [right_symbol](WrapConfig::right_symbol) and /// on the next line [right_prefix_symbol](WrapConfig::right_prefix_symbol). /// The inserted characters will follow the /// [inline_hint_syntect_style](WrapConfig::inline_hint_syntect_style). pub fn wrap_line<'a, I, S>( config: &'a Config, line: I, line_width: usize, fill_style: &S, inline_hint_style: &Option<S>, ) -> Vec<LineSections<'a, S>> where I: IntoIterator<Item = (S, &'a str)> + std::fmt::Debug, <I as IntoIterator>::IntoIter: DoubleEndedIterator, S: Copy + Default + std::fmt::Debug, { let mut result = Vec::new(); let wrap_config = &config.wrap_config; // The current line being assembled from the input to fit exactly into the given width. // A somewhat leaky abstraction as the fields are also accessed directly. struct CurrLine<'a, S: Default> { line_segments: LineSections<'a, S>, len: usize, } impl<'a, S: Default> CurrLine<'a, S> { fn reset() -> Self { CurrLine { line_segments: Vec::new(), len: 0, } } fn push_and_set_len(&mut self, text: (S, &'a str), len: usize) { self.line_segments.push(text); self.len = len; } fn has_text(&self) -> bool { self.len > 0 } fn text_len(&self) -> usize { self.len } } let mut curr_line = CurrLine::reset(); // Determine the background (diff) and color (syntax) of an inserted symbol. let symbol_style = match inline_hint_style { Some(style) => *style, None => *fill_style, }; let mut stack = line.into_iter().rev().collect::<Vec<_>>(); // If only the wrap symbol and no extra text fits, then wrapping is not possible. let max_lines = if line_width <= INLINE_SYMBOL_WIDTH_1 { 1 } else { wrap_config.max_lines }; let line_limit_reached = |result: &Vec<_>| max_lines > 0 && result.len() + 1 >= max_lines; let stop = loop { if stack.is_empty() { break Stop::StackEmpty; } else if line_limit_reached(&result) { break Stop::LineLimit; } let (style, text, graphemes) = stack .pop() .map(|(style, text)| { ( style, text, text.graphemes(true) .map(|item| (item.len(), item.width())) .collect::<Vec<_>>(), ) }) .unwrap(); let graphemes_width: usize = graphemes.iter().map(|(_, w)| w).sum(); let new_len = curr_line.len + graphemes_width; #[allow(clippy::comparison_chain)] let must_split = if new_len < line_width { curr_line.push_and_set_len((style, text), new_len); false } else if new_len == line_width { match stack.last() { // Perfect fit, no need to make space for a `wrap_symbol`. None => { curr_line.push_and_set_len((style, text), new_len); false } #[allow(clippy::identity_op)] // A single '\n' left on the stack can be pushed onto the current line. Some((next_style, nl)) if stack.len() == 1 && *nl == "\n" => { curr_line.push_and_set_len((style, text), new_len); // Do not count the '\n': + 0 curr_line.push_and_set_len((*next_style, *nl), new_len + 0); stack.pop(); false } _ => true, } } else { true }; // Text must be split, one part (or just `wrap_symbol`) is added to the // current line, the other is pushed onto the stack. if must_split { let mut width_left = graphemes_width .saturating_sub(new_len - line_width) .saturating_sub(wrap_config.left_symbol.width()); // The length does not matter anymore and `curr_line` will be reset // at the end, so move the line segments out. let mut line_segments = curr_line.line_segments; let next_line = if width_left == 0 { text } else { let mut byte_split_pos = 0; // After loop byte_split_pos may still equal to 0. If width_left // is less than the width of first character, We can't display it. for &(item_len, item_width) in graphemes.iter() { if width_left >= item_width { byte_split_pos += item_len; width_left -= item_width; } else { break; } } let this_line = &text[..byte_split_pos]; line_segments.push((style, this_line)); &text[byte_split_pos..] }; stack.push((style, next_line)); line_segments.push((symbol_style, &wrap_config.left_symbol)); result.push(line_segments); curr_line = CurrLine::reset(); } }; // Right-align wrapped line: // Done if wrapping adds exactly one line and this line is less than the given // permille wide. Also change the wrap symbol at the end of the previous (first) line. if result.len() == 1 && curr_line.has_text() { let current_permille = (curr_line.text_len() * 1000) / line_width; // pad line will add a wrap_config.right_prefix_symbol let pad_len = line_width .saturating_sub(curr_line.text_len() + wrap_config.right_prefix_symbol.width()); if wrap_config.use_wrap_right_permille > current_permille && pad_len > 0 { // The inserted spaces, which align a line to the right, point into this string. const SPACES: &str = " "; match result.last_mut() { Some(ref mut vec) if !vec.is_empty() => { vec.last_mut().unwrap().1 = &wrap_config.right_symbol } _ => unreachable!("wrap result must not be empty"), } let mut right_aligned_line = Vec::new(); for _ in 0..(pad_len / SPACES.len()) { right_aligned_line.push((*fill_style, SPACES)); } match pad_len % SPACES.len() { 0 => (), n => right_aligned_line.push((*fill_style, &SPACES[0..n])), } right_aligned_line.push((symbol_style, &wrap_config.right_prefix_symbol)); right_aligned_line.extend(curr_line.line_segments); curr_line.line_segments = right_aligned_line; // curr_line.len not updated, as only 0 / >0 for `has_text()` is required. } } if curr_line.has_text() { result.push(curr_line.line_segments); } if stop == Stop::LineLimit && result.len() != max_lines { result.push(Vec::new()); } // Anything that is left will be added to the (last) line. If this is too long it will // be truncated later. if !stack.is_empty() { if result.is_empty() { result.push(Vec::new()); } // unwrap: previous `if` ensures result can not be empty result.last_mut().unwrap().extend(stack.into_iter().rev()); } result } fn wrap_if_too_long<'a, S>( config: &'a Config, wrapped: &mut Vec<LineSections<'a, S>>, input_vec: LineSections<'a, S>, must_wrap: bool, line_width: usize, fill_style: &S, inline_hint_style: &Option<S>, ) -> (usize, usize) where S: Copy + Default + std::fmt::Debug, { let size_prev = wrapped.len(); if must_wrap { wrapped.append(&mut wrap_line( config, input_vec, line_width, fill_style, inline_hint_style, )); } else { wrapped.push(input_vec.to_vec()); } (size_prev, wrapped.len()) } /// Call [`wrap_line`] for the `syntax` and the `diff` lines if `wrapinfo` says /// a specific line was longer than `line_width`. Return an adjusted `alignment` /// with regard to the added wrapped lines. #[allow(clippy::comparison_chain, clippy::type_complexity)] pub fn wrap_minusplus_block<'c: 'a, 'a>( config: &'c Config, syntax: MinusPlus<Vec<LineSections<'a, SyntectStyle>>>, diff: MinusPlus<Vec<LineSections<'a, Style>>>, alignment: &[(Option<usize>, Option<usize>)], line_width: &SideBySideLineWidth, wrapinfo: &'a MinusPlus<Vec<bool>>, ) -> ( Vec<(Option<usize>, Option<usize>)>, MinusPlus<Vec<State>>, MinusPlus<Vec<LineSections<'a, SyntectStyle>>>, MinusPlus<Vec<LineSections<'a, Style>>>, ) { let mut new_alignment = Vec::new(); let mut new_states = MinusPlus::<Vec<State>>::default(); let mut new_wrapped_syntax = MinusPlus::default(); let mut new_wrapped_diff = MinusPlus::default(); // Turn all these into pairs of iterators so they can be advanced according // to the alignment and independently. let mut syntax = MinusPlus::new(syntax.minus.into_iter(), syntax.plus.into_iter()); let mut diff = MinusPlus::new(diff.minus.into_iter(), diff.plus.into_iter()); let mut wrapinfo = MinusPlus::new(wrapinfo[Left].iter(), wrapinfo[Right].iter()); let fill_style = MinusPlus::new(&config.minus_style, &config.plus_style); // Internal helper function to perform wrapping for both the syntax and the // diff highlighting (SyntectStyle and Style). #[allow(clippy::too_many_arguments)] pub fn wrap_syntax_and_diff<'a, ItSyn, ItDiff, ItWrap>( config: &'a Config, wrapped_syntax: &mut Vec<LineSections<'a, SyntectStyle>>, wrapped_diff: &mut Vec<LineSections<'a, Style>>, syntax_iter: &mut ItSyn, diff_iter: &mut ItDiff, wrapinfo_iter: &mut ItWrap, line_width: usize, fill_style: &Style, errhint: &'a str, ) -> (usize, usize) where ItSyn: Iterator<Item = LineSections<'a, SyntectStyle>>, ItDiff: Iterator<Item = LineSections<'a, Style>>, ItWrap: Iterator<Item = &'a bool>, { let must_wrap = *wrapinfo_iter .next() .unwrap_or_else(|| panic!("bad wrap info {}", errhint)); let (start, extended_to) = wrap_if_too_long( config, wrapped_syntax, syntax_iter .next() .unwrap_or_else(|| panic!("bad syntax alignment {}", errhint)), must_wrap, line_width, &config.null_syntect_style, &Some(config.wrap_config.inline_hint_syntect_style), ); // TODO: Why is the background color set to white when // ansi_term_style.background is None? let inline_hint_style = if config .inline_hint_style .ansi_term_style .background .is_some() { Some(config.inline_hint_style) } else { None }; let (start2, extended_to2) = wrap_if_too_long( config, wrapped_diff, diff_iter .next() .unwrap_or_else(|| panic!("bad diff alignment {}", errhint)), must_wrap, line_width, fill_style, &inline_hint_style, ); // The underlying text is the same for the style and diff, so // the length of the wrapping should be identical: assert_eq!( (start, extended_to), (start2, extended_to2), "syntax and diff wrapping differs {errhint}", ); (start, extended_to) } // This macro avoids having the same code block 4x in the alignment processing macro_rules! wrap_and_assert { ($side:tt, $errhint:tt, $have:tt, $expected:tt) => {{ assert_eq!(*$have, $expected, "bad alignment index {}", $errhint); $expected += 1; wrap_syntax_and_diff( &config, &mut new_wrapped_syntax[$side], &mut new_wrapped_diff[$side], &mut syntax[$side], &mut diff[$side], &mut wrapinfo[$side], line_width[$side], &fill_style[$side], $errhint, ) }}; } let mut m_expected = 0; let mut p_expected = 0; // Process blocks according to the alignment and build a new alignment. // If lines get added via wrapping these are assigned the state HunkMinusWrapped/HunkPlusWrapped. for (minus, plus) in alignment { let (minus_extended, plus_extended) = match (minus, plus) { (Some(m), None) => { let (minus_start, extended_to) = wrap_and_assert!(Left, "[*l*] (-)", m, m_expected); for i in minus_start..extended_to { new_alignment.push((Some(i), None)); } (extended_to - minus_start, 0) } (None, Some(p)) => { let (plus_start, extended_to) = wrap_and_assert!(Right, "(-) [*r*]", p, p_expected); for i in plus_start..extended_to { new_alignment.push((None, Some(i))); } (0, extended_to - plus_start) } (Some(m), Some(p)) => { let (minus_start, m_extended_to) = wrap_and_assert!(Left, "[*l*] (r)", m, m_expected); let (plus_start, p_extended_to) = wrap_and_assert!(Right, "(l) [*r*]", p, p_expected); for (new_m, new_p) in (minus_start..m_extended_to).zip(plus_start..p_extended_to) { new_alignment.push((Some(new_m), Some(new_p))); } // This Some(m):Some(p) alignment might have become uneven, so fill // up the shorter side with None. let minus_extended = m_extended_to - minus_start; let plus_extended = p_extended_to - plus_start; let plus_minus = (minus_extended as isize) - (plus_extended as isize); if plus_minus > 0 { for m in (m_extended_to as isize - plus_minus) as usize..m_extended_to { new_alignment.push((Some(m), None)); } } else if plus_minus < 0 { for p in (p_extended_to as isize + plus_minus) as usize..p_extended_to { new_alignment.push((None, Some(p))); } } (minus_extended, plus_extended) } _ => unreachable!("None-None alignment"), }; if minus_extended > 0 { new_states[Left].push(State::HunkMinus(DiffType::Unified, None)); for _ in 1..minus_extended { new_states[Left].push(State::HunkMinusWrapped); } } if plus_extended > 0 { new_states[Right].push(State::HunkPlus(DiffType::Unified, None)); for _ in 1..plus_extended { new_states[Right].push(State::HunkPlusWrapped); } } } ( new_alignment, new_states, new_wrapped_syntax, new_wrapped_diff, ) } #[allow(clippy::comparison_chain, clippy::type_complexity)] pub fn wrap_zero_block<'c: 'a, 'a>( config: &'c Config, line: &str, mut states: Vec<State>, syntax_style_sections: Vec<LineSections<'a, SyntectStyle>>, diff_style_sections: Vec<LineSections<'a, Style>>, line_numbers_data: &Option<&mut line_numbers::LineNumbersData>, ) -> ( Vec<State>, Vec<LineSections<'a, SyntectStyle>>, Vec<LineSections<'a, Style>>, ) { // The width is the minimum of the left/right side. The panels should be equally sized, // but in rare cases the remaining panel width might differ due to the space the line // numbers take up. let line_width = if let Some(line_numbers_data) = line_numbers_data { let width = available_line_width(config, line_numbers_data); std::cmp::min(width[Left], width[Right]) } else { std::cmp::min( config.side_by_side_data[Left].width, config.side_by_side_data[Right].width, ) }; // Called with a single line, so no need to use the 1-sized bool vector. // If that changes the wrapping logic should be updated as well. debug_assert_eq!(diff_style_sections.len(), 1); let should_wrap = line_is_too_long(line, line_width); if should_wrap { let syntax_style = wrap_line( config, syntax_style_sections.into_iter().flatten(), line_width, &SyntectStyle::default(), &Some(config.wrap_config.inline_hint_syntect_style), ); // TODO: Why is the background color set to white when // ansi_term_style.background is None? let inline_hint_style = if config .inline_hint_style .ansi_term_style .background .is_some() { Some(config.inline_hint_style) } else { None }; let diff_style = wrap_line( config, diff_style_sections.into_iter().flatten(), line_width, // To actually highlight inline hint characters: &Style { is_syntax_highlighted: true, ..config.null_style }, &inline_hint_style, ); states.resize_with(syntax_style.len(), || State::HunkZeroWrapped); (states, syntax_style, diff_style) } else { (states, syntax_style_sections, diff_style_sections) } } #[cfg(test)] mod tests { use lazy_static::lazy_static; use syntect::highlighting::Style as SyntectStyle; use super::wrap_line; use super::WrapConfig; use crate::config::Config; use crate::paint::LineSections; use crate::style::Style; use crate::tests::integration_test_utils::{make_config_from_args, DeltaTest}; lazy_static! { static ref S1: Style = Style { is_syntax_highlighted: true, ..Default::default() }; } lazy_static! { static ref S2: Style = Style { is_emph: true, ..Default::default() }; } lazy_static! { static ref SY: SyntectStyle = SyntectStyle::default(); } lazy_static! { static ref SD: Style = Style::default(); } const W: &str = "+"; // wrap const WR: &str = "<"; // wrap-right const RA: &str = ">"; // right-align lazy_static! { static ref WRAP_DEFAULT_ARGS: Vec<&'static str> = vec![ "--wrap-left-symbol", W, "--wrap-right-symbol", WR, "--wrap-right-prefix-symbol", RA, "--wrap-max-lines", "4", "--wrap-right-percent", "37.0%", ]; } lazy_static! { static ref TEST_WRAP_CFG: WrapConfig = make_config_from_args(&WRAP_DEFAULT_ARGS).wrap_config; } fn default_wrap_cfg_plus<'a>(args: &[&'a str]) -> Vec<&'a str> { let mut result = WRAP_DEFAULT_ARGS.clone(); result.extend_from_slice(args); result } fn mk_wrap_cfg(wrap_cfg: &WrapConfig) -> Config { let mut cfg: Config = make_config_from_args(&[]); cfg.wrap_config = wrap_cfg.clone(); cfg } fn wrap_test<'a, I, S>(cfg: &'a Config, line: I, line_width: usize) -> Vec<LineSections<'a, S>> where I: IntoIterator<Item = (S, &'a str)> + std::fmt::Debug, <I as IntoIterator>::IntoIter: DoubleEndedIterator, S: Copy + Default + std::fmt::Debug, { wrap_line(cfg, line, line_width, &S::default(), &None) } #[test] fn test_wrap_line_single() { let cfg = mk_wrap_cfg(&TEST_WRAP_CFG); { let line = vec![(*SY, "0")]; let lines = wrap_test(&cfg, line, 6); assert_eq!(lines, vec![vec![(*SY, "0")]]); } { let line = vec![(*S1, "012"), (*S2, "34")]; let lines = wrap_test(&cfg, line, 6); assert_eq!(lines, vec![vec![(*S1, "012"), (*S2, "34")]]); } { let line = vec![(*S1, "012"), (*S2, "345")]; let lines = wrap_test(&cfg, line, 6); assert_eq!(lines, vec![vec![(*S1, "012"), (*S2, "345")]]); } { // Empty input usually does not happen let line = vec![(*S1, "")]; let lines = wrap_test(&cfg, line, 6); assert!(lines.is_empty()); } { // Partially empty should not happen either let line = vec![(*S1, ""), (*S2, "0")]; let lines = wrap_test(&cfg, line, 6); assert_eq!(lines, vec![vec![(*S1, ""), (*S2, "0")]]); } { let line = vec![(*S1, "0"), (*S2, "")]; let lines = wrap_test(&cfg, line, 6); assert_eq!(lines, vec![vec![(*S1, "0"), (*S2, "")]]); } { let line = vec![ (*S1, "0"), (*S2, ""), (*S1, ""), (*S2, ""), (*S1, ""), (*S2, ""), (*S1, ""), (*S2, ""), (*S1, ""), (*S2, ""), ]; let lines = wrap_test(&cfg, line, 6); assert_eq!( lines, vec![vec![ (*S1, "0"), (*S2, ""), (*S1, ""), (*S2, ""), (*S1, ""), (*S2, ""), (*S1, ""), (*S2, ""), (*S1, ""), (*S2, "") ]] ); } } #[test] fn test_wrap_line_align_right_1() { let cfg = mk_wrap_cfg(&TEST_WRAP_CFG); let line = vec![(*S1, "0123456789ab")]; let lines = wrap_test(&cfg, line, 11); assert_eq!(lines.len(), 2); assert_eq!(lines[0].last().unwrap().1, WR); assert_eq!(lines[1], [(*SD, " "), (*SD, ">"), (*S1, "ab")]); } #[test] fn test_wrap_line_align_right_2() { let line = vec![(*S1, "012"), (*S2, "3456")]; { // Right align lines on the second line let cfg = mk_wrap_cfg(&TEST_WRAP_CFG); let lines = wrap_test(&cfg, line.clone(), 6); assert_eq!( lines, vec![ vec![(*S1, "012"), (*S2, "34"), (*SD, WR)], vec![(*SD, " "), (*SD, RA), (*S2, "56")] ] ); } { // Set right align percentage lower, normal wrapping let mut no_align_right = TEST_WRAP_CFG.clone(); no_align_right.use_wrap_right_permille = 1; // 0.1% let cfg_no_align_right = mk_wrap_cfg(&no_align_right); let lines = wrap_test(&cfg_no_align_right, line, 6); assert_eq!( lines, vec![vec![(*S1, "012"), (*S2, "34"), (*SD, W)], vec![(*S2, "56")]] ); } } #[test] fn test_wrap_line_newlines() { fn mk_input(len: usize) -> LineSections<'static, Style> { const IN: &str = "0123456789abcdefZ"; let v = &[*S1, *S2]; let s1s2 = v.iter().cycle(); let text: Vec<_> = IN.matches(|_| true).take(len + 1).collect(); s1s2.zip(text.iter()) .map(|(style, text)| (*style, *text)) .collect() } fn mk_input_nl(len: usize) -> LineSections<'static, Style> { const NL: &str = "\n"; let mut line = mk_input(len); line.push((*S2, NL)); line } fn mk_expected<'a>( vec: &LineSections<'a, Style>, from: usize, to: usize, append: Option<(Style, &'a str)>, ) -> LineSections<'a, Style> { let mut result: Vec<_> = vec[from..to].to_vec(); if let Some(val) = append { result.push(val); } result } let cfg = mk_wrap_cfg(&TEST_WRAP_CFG); { let line = vec![(*S1, "012"), (*S2, "345\n")]; let lines = wrap_test(&cfg, line, 6); assert_eq!(lines, vec![vec![(*S1, "012"), (*S2, "345\n")]]); } { for i in 0..=5 { let line = mk_input(i); let lines = wrap_test(&cfg, line, 6); assert_eq!(lines, vec![mk_input(i)]); let line = mk_input_nl(i); let lines = wrap_test(&cfg, line, 6); assert_eq!(lines, vec![mk_input_nl(i)]); } } { let line = mk_input_nl(9); let lines = wrap_test(&cfg, line, 3); let expected = mk_input_nl(9); let line1 = mk_expected(&expected, 0, 2, Some((*SD, W))); let line2 = mk_expected(&expected, 2, 4, Some((*SD, W))); let line3 = mk_expected(&expected, 4, 6, Some((*SD, W))); let line4 = mk_expected(&expected, 6, 8, Some((*SD, W))); let line5 = mk_expected(&expected, 8, 11, None); assert_eq!(lines, vec![line1, line2, line3, line4, line5]); } { let line = mk_input_nl(10); let lines = wrap_test(&cfg, line, 3); let expected = mk_input_nl(10); let line1 = mk_expected(&expected, 0, 2, Some((*SD, W))); let line2 = mk_expected(&expected, 2, 4, Some((*SD, W))); let line3 = mk_expected(&expected, 4, 6, Some((*SD, W))); let line4 = mk_expected(&expected, 6, 8, Some((*SD, W))); let line5 = mk_expected(&expected, 8, 11, Some((*S2, "\n"))); assert_eq!(lines, vec![line1, line2, line3, line4, line5]); } { let line = vec![(*S1, "abc"), (*S2, "01230123012301230123"), (*S1, "ZZZZZ")]; let wcfg1 = mk_wrap_cfg(&WrapConfig { max_lines: 1, ..TEST_WRAP_CFG.clone() }); let wcfg2 = mk_wrap_cfg(&WrapConfig { max_lines: 2, ..TEST_WRAP_CFG.clone() }); let wcfg3 = mk_wrap_cfg(&WrapConfig { max_lines: 3, ..TEST_WRAP_CFG.clone() }); let lines = wrap_line(&wcfg1, line.clone(), 4, &Style::default(), &None); assert_eq!(lines.len(), 1); assert_eq!(lines.last().unwrap().last().unwrap().1, "ZZZZZ"); let lines = wrap_line(&wcfg2, line.clone(), 4, &Style::default(), &None); assert_eq!(lines.len(), 2); assert_eq!(lines.last().unwrap().last().unwrap().1, "ZZZZZ"); let lines = wrap_line(&wcfg3, line.clone(), 4, &Style::default(), &None); assert_eq!(lines.len(), 3); assert_eq!(lines.last().unwrap().last().unwrap().1, "ZZZZZ"); } } #[test] fn test_wrap_line_unicode() { let cfg = mk_wrap_cfg(&TEST_WRAP_CFG); // from UnicodeSegmentation documentation and the linked // Unicode Standard Annex #29
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
true
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/parse_style.rs
src/parse_style.rs
use bitflags::bitflags; use crate::color; use crate::config::delta_unreachable; use crate::fatal; use crate::git_config::GitConfig; use crate::style::{DecorationStyle, Style}; impl Style { /// Construct Style from style and decoration-style strings supplied on command line, together /// with defaults. A style string is a space-separated string containing 0, 1, or 2 colors /// (foreground and then background) and an arbitrary number of style attributes. See `delta /// --help` for more precise spec. pub fn from_str( style_string: &str, default: Option<Self>, decoration_style_string: Option<&str>, true_color: bool, git_config: Option<&GitConfig>, ) -> Self { let (ansi_term_style, is_omitted, is_raw, is_syntax_highlighted) = parse_ansi_term_style(style_string, default, true_color, git_config); let decoration_style = DecorationStyle::from_str( decoration_style_string.unwrap_or(""), true_color, git_config, ); Self { ansi_term_style, is_emph: false, is_omitted, is_raw, is_syntax_highlighted, decoration_style, } } pub fn from_git_str(git_style_string: &str) -> Self { Self::from_str(git_style_string, None, None, true, None) } /// Construct Style but interpreting 'ul', 'box', etc as applying to the decoration style. pub fn from_str_with_handling_of_special_decoration_attributes( style_string: &str, default: Option<Self>, decoration_style_string: Option<&str>, true_color: bool, git_config: Option<&GitConfig>, ) -> Self { let (special_attributes_from_style_string, style_string) = extract_special_decoration_attributes_from_non_decoration_style_string(style_string); let mut style = Style::from_str( &style_string, default, decoration_style_string, true_color, git_config, ); // TODO: box in this context resulted in box-with-underline for commit and file style.decoration_style = DecorationStyle::apply_special_decoration_attributes( &mut style, special_attributes_from_style_string, ); style } } bitflags! { #[derive(Clone, Copy, Debug, PartialEq)] struct DecorationAttributes: u8 { const EMPTY = 0b00000000; const BOX = 0b00000001; const OVERLINE = 0b00000010; const UNDERLINE = 0b00000100; } } impl DecorationStyle { pub fn from_str(style_string: &str, true_color: bool, git_config: Option<&GitConfig>) -> Self { let (special_attributes, style_string) = extract_special_decoration_attributes(style_string); let (style, is_omitted, is_raw, is_syntax_highlighted) = parse_ansi_term_style(&style_string, None, true_color, git_config); if is_raw { fatal("'raw' may not be used in a decoration style."); }; if is_syntax_highlighted { fatal("'syntax' may not be used in a decoration style."); }; #[allow(non_snake_case)] let (BOX, UL, OL, EMPTY) = ( DecorationAttributes::BOX, DecorationAttributes::UNDERLINE, DecorationAttributes::OVERLINE, DecorationAttributes::EMPTY, ); match special_attributes { bits if bits == EMPTY => DecorationStyle::NoDecoration, bits if bits == BOX => DecorationStyle::Box(style), bits if bits == UL => DecorationStyle::Underline(style), bits if bits == OL => DecorationStyle::Overline(style), bits if bits == UL | OL => DecorationStyle::UnderOverline(style), bits if bits == BOX | UL => DecorationStyle::BoxWithUnderline(style), bits if bits == BOX | OL => DecorationStyle::BoxWithOverline(style), bits if bits == BOX | UL | OL => DecorationStyle::BoxWithUnderOverline(style), _ if is_omitted => DecorationStyle::NoDecoration, _ => delta_unreachable("Unreachable code path reached in parse_decoration_style."), } } fn apply_special_decoration_attributes( style: &mut Style, special_attributes: DecorationAttributes, ) -> DecorationStyle { let ansi_term_style = match style.decoration_style { DecorationStyle::Box(ansi_term_style) => ansi_term_style, DecorationStyle::Underline(ansi_term_style) => ansi_term_style, DecorationStyle::Overline(ansi_term_style) => ansi_term_style, DecorationStyle::UnderOverline(ansi_term_style) => ansi_term_style, DecorationStyle::BoxWithUnderline(ansi_term_style) => ansi_term_style, DecorationStyle::BoxWithOverline(ansi_term_style) => ansi_term_style, DecorationStyle::BoxWithUnderOverline(ansi_term_style) => ansi_term_style, DecorationStyle::NoDecoration => ansi_term::Style::new(), }; #[allow(non_snake_case)] let (BOX, UL, OL, EMPTY) = ( DecorationAttributes::BOX, DecorationAttributes::UNDERLINE, DecorationAttributes::OVERLINE, DecorationAttributes::EMPTY, ); match special_attributes { bits if bits == EMPTY => style.decoration_style, bits if bits == BOX => DecorationStyle::Box(ansi_term_style), bits if bits == UL => DecorationStyle::Underline(ansi_term_style), bits if bits == OL => DecorationStyle::Overline(ansi_term_style), bits if bits == UL | OL => DecorationStyle::UnderOverline(ansi_term_style), bits if bits == BOX | UL => DecorationStyle::BoxWithUnderline(ansi_term_style), bits if bits == BOX | OL => DecorationStyle::BoxWithOverline(ansi_term_style), bits if bits == BOX | UL | OL => DecorationStyle::BoxWithUnderOverline(ansi_term_style), _ => DecorationStyle::NoDecoration, } } } fn parse_ansi_term_style( s: &str, default: Option<Style>, true_color: bool, git_config: Option<&GitConfig>, ) -> (ansi_term::Style, bool, bool, bool) { let mut style = ansi_term::Style::new(); let mut seen_foreground = false; let mut seen_background = false; let mut foreground_is_auto = false; let mut background_is_auto = false; let mut is_omitted = false; let mut is_raw = false; let mut seen_omit = false; let mut seen_raw = false; let mut is_syntax_highlighted = false; for word in s .to_lowercase() .split_whitespace() .map(|word| word.trim_matches(|c| c == '"' || c == '\'')) { if word == "blink" { style.is_blink = true; } else if word == "bold" { style.is_bold = true; } else if word == "dim" { style.is_dimmed = true; } else if word == "hidden" { style.is_hidden = true; } else if word == "italic" { style.is_italic = true; } else if word == "omit" { seen_omit = true; is_omitted = true; } else if word == "reverse" { style.is_reverse = true; } else if word == "raw" { seen_raw = true; is_raw = true; } else if word == "strike" { style.is_strikethrough = true; } else if word == "ul" || word == "underline" { style.is_underline = true; } else if word == "line-number" || word == "file" || word == "omit-code-fragment" { // Allow: these are meaningful in hunk-header-style. } else if !seen_foreground { if word == "syntax" { is_syntax_highlighted = true; } else if word == "auto" { foreground_is_auto = true; style.foreground = default.and_then(|s| s.ansi_term_style.foreground); is_syntax_highlighted = default.map(|s| s.is_syntax_highlighted).unwrap_or(false); } else { style.foreground = color::parse_color(word, true_color, git_config); } seen_foreground = true; } else if !seen_background { if word == "syntax" { fatal( "You have used the special color 'syntax' as a background color \ (second color in a style string). It may only be used as a foreground \ color (first color in a style string).", ); } else if word == "auto" { background_is_auto = true; style.background = default.and_then(|s| s.ansi_term_style.background); } else { style.background = color::parse_color(word, true_color, git_config); } seen_background = true; } else { fatal(format!( "Invalid style string: {s}. See the STYLES section of delta --help.", )); } } if foreground_is_auto && background_is_auto { if !seen_omit { is_omitted = default.map(|s| s.is_omitted).unwrap_or(false); } if !seen_raw { is_raw = default.map(|s| s.is_raw).unwrap_or(false); } } (style, is_omitted, is_raw, is_syntax_highlighted) } /// Extract set of 'special decoration attributes' and return it along with modified style string. fn extract_special_decoration_attributes(style_string: &str) -> (DecorationAttributes, String) { _extract_special_decoration_attributes(style_string, true) } fn extract_special_decoration_attributes_from_non_decoration_style_string( style_string: &str, ) -> (DecorationAttributes, String) { _extract_special_decoration_attributes(style_string, false) } // If this is being called in the context of processing a decoration style string then we treat // ul/ol as a request for an underline/overline decoration respectively. Otherwise they are // conventional character style attributes. fn _extract_special_decoration_attributes( style_string: &str, is_decoration_style_string: bool, ) -> (DecorationAttributes, String) { let mut attributes = DecorationAttributes::EMPTY; let mut new_style_string = Vec::new(); let style_string = style_string.to_lowercase(); for token in style_string .split_whitespace() .map(|word| word.trim_matches(|c| c == '"' || c == '\'')) { match token { "box" => attributes |= DecorationAttributes::BOX, token if token == "overline" || is_decoration_style_string && token == "ol" => { attributes |= DecorationAttributes::OVERLINE } token if token == "underline" || is_decoration_style_string && token == "ul" => { attributes |= DecorationAttributes::UNDERLINE } token if token == "none" || token == "plain" => {} _ => new_style_string.push(token), } } (attributes, new_style_string.join(" ")) } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_ansi_term_style() { assert_eq!( parse_ansi_term_style("", None, false, None), (ansi_term::Style::new(), false, false, false) ); assert_eq!( parse_ansi_term_style("red", None, false, None), ( ansi_term::Style { foreground: Some(ansi_term::Color::Red), ..ansi_term::Style::new() }, false, false, false ) ); assert_eq!( parse_ansi_term_style("red green", None, false, None), ( ansi_term::Style { foreground: Some(ansi_term::Color::Red), background: Some(ansi_term::Color::Green), ..ansi_term::Style::new() }, false, false, false ) ); assert_eq!( parse_ansi_term_style("bold red underline green blink", None, false, None), ( ansi_term::Style { foreground: Some(ansi_term::Color::Red), background: Some(ansi_term::Color::Green), is_blink: true, is_bold: true, is_underline: true, ..ansi_term::Style::new() }, false, false, false ) ); } #[test] fn test_parse_ansi_term_style_with_special_syntax_color() { assert_eq!( parse_ansi_term_style("syntax", None, false, None), (ansi_term::Style::new(), false, false, true) ); assert_eq!( parse_ansi_term_style("syntax italic white hidden", None, false, None), ( ansi_term::Style { background: Some(ansi_term::Color::White), is_italic: true, is_hidden: true, ..ansi_term::Style::new() }, false, false, true ) ); assert_eq!( parse_ansi_term_style("bold syntax italic white hidden", None, false, None), ( ansi_term::Style { background: Some(ansi_term::Color::White), is_bold: true, is_italic: true, is_hidden: true, ..ansi_term::Style::new() }, false, false, true ) ); } #[test] fn test_parse_ansi_term_style_with_special_omit_attribute() { assert_eq!( parse_ansi_term_style("omit", None, false, None), (ansi_term::Style::new(), true, false, false) ); // It doesn't make sense for omit to be combined with anything else, but it is not an error. assert_eq!( parse_ansi_term_style("omit syntax italic white hidden", None, false, None), ( ansi_term::Style { background: Some(ansi_term::Color::White), is_italic: true, is_hidden: true, ..ansi_term::Style::new() }, true, false, true ) ); } #[test] fn test_parse_ansi_term_style_with_special_raw_attribute() { assert_eq!( parse_ansi_term_style("raw", None, false, None), (ansi_term::Style::new(), false, true, false) ); // It doesn't make sense for raw to be combined with anything else, but it is not an error. assert_eq!( parse_ansi_term_style("raw syntax italic white hidden", None, false, None), ( ansi_term::Style { background: Some(ansi_term::Color::White), is_italic: true, is_hidden: true, ..ansi_term::Style::new() }, false, true, true ) ); } #[test] fn test_extract_special_decoration_attribute() { #[allow(non_snake_case)] let (BOX, UL, OL, EMPTY) = ( DecorationAttributes::BOX, DecorationAttributes::UNDERLINE, DecorationAttributes::OVERLINE, DecorationAttributes::EMPTY, ); assert_eq!( extract_special_decoration_attributes(""), (EMPTY, "".to_string(),) ); assert_eq!( extract_special_decoration_attributes("box"), (BOX, "".to_string()) ); assert_eq!( extract_special_decoration_attributes("ul"), (UL, "".to_string()) ); assert_eq!( extract_special_decoration_attributes("ol"), (OL, "".to_string()) ); assert_eq!( extract_special_decoration_attributes("box ul"), (BOX | UL, "".to_string()) ); assert_eq!( extract_special_decoration_attributes("box ol"), (BOX | OL, "".to_string()) ); assert_eq!( extract_special_decoration_attributes("ul box ol"), (BOX | UL | OL, "".to_string()) ); assert_eq!( extract_special_decoration_attributes("ol ul"), (UL | OL, "".to_string()) ); } #[test] fn test_decoration_style_from_str_empty_string() { assert_eq!( DecorationStyle::from_str("", true, None), DecorationStyle::NoDecoration, ) } #[test] fn test_decoration_style_from_str() { assert_eq!( DecorationStyle::from_str("ol red box bold green ul", true, None), DecorationStyle::BoxWithUnderOverline(ansi_term::Style { foreground: Some(ansi_term::Color::Red), background: Some(ansi_term::Color::Green), is_bold: true, ..ansi_term::Style::new() }) ) } #[test] fn test_style_from_str() { let actual_style = Style::from_str( "red green bold", None, Some("ol red box bold green ul"), true, None, ); let red_green_bold = ansi_term::Style { foreground: Some(ansi_term::Color::Red), background: Some(ansi_term::Color::Green), is_bold: true, ..ansi_term::Style::new() }; assert_eq!( actual_style, Style { ansi_term_style: red_green_bold, decoration_style: DecorationStyle::BoxWithUnderOverline(red_green_bold), ..Style::new() } ) } #[test] fn test_style_from_str_raw_with_box() { let actual_style = Style::from_str("raw", None, Some("box"), true, None); let empty_ansi_term_style = ansi_term::Style::new(); assert_eq!( actual_style, Style { ansi_term_style: empty_ansi_term_style, decoration_style: DecorationStyle::Box(empty_ansi_term_style), is_raw: true, ..Style::new() } ) } #[test] fn test_style_from_str_decoration_style_only() { let actual_style = Style::from_str("", None, Some("ol red box bold green ul"), true, None); let red_green_bold = ansi_term::Style { foreground: Some(ansi_term::Color::Red), background: Some(ansi_term::Color::Green), is_bold: true, ..ansi_term::Style::new() }; assert_eq!( actual_style, Style { decoration_style: DecorationStyle::BoxWithUnderOverline(red_green_bold), ..Style::new() } ) } #[test] fn test_style_from_str_with_handling_of_special_decoration_attributes() { let actual_style = Style::from_str_with_handling_of_special_decoration_attributes( "", None, Some("ol red box bold green ul"), true, None, ); let expected_decoration_style = DecorationStyle::BoxWithUnderOverline(ansi_term::Style { foreground: Some(ansi_term::Color::Red), background: Some(ansi_term::Color::Green), is_bold: true, ..ansi_term::Style::new() }); assert_eq!( actual_style, Style { decoration_style: expected_decoration_style, ..Style::new() } ) } #[test] fn test_style_from_str_with_handling_of_special_decoration_attributes_raw_with_box() { let actual_style = Style::from_str_with_handling_of_special_decoration_attributes( "raw", None, Some("box"), true, None, ); let empty_ansi_term_style = ansi_term::Style::new(); assert_eq!( actual_style, Style { ansi_term_style: empty_ansi_term_style, decoration_style: DecorationStyle::Box(empty_ansi_term_style), is_raw: true, ..Style::new() } ) } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/env.rs
src/env.rs
use std::env; const COLORTERM: &str = "COLORTERM"; const BAT_THEME: &str = "BAT_THEME"; const GIT_CONFIG_PARAMETERS: &str = "GIT_CONFIG_PARAMETERS"; const GIT_PREFIX: &str = "GIT_PREFIX"; const DELTA_FEATURES: &str = "DELTA_FEATURES"; const DELTA_NAVIGATE: &str = "DELTA_NAVIGATE"; const DELTA_EXPERIMENTAL_MAX_LINE_DISTANCE_FOR_NAIVELY_PAIRED_LINES: &str = "DELTA_EXPERIMENTAL_MAX_LINE_DISTANCE_FOR_NAIVELY_PAIRED_LINES"; const DELTA_PAGER: &str = "DELTA_PAGER"; #[derive(Default, Clone)] pub struct DeltaEnv { pub bat_theme: Option<String>, pub colorterm: Option<String>, pub current_dir: Option<std::path::PathBuf>, pub experimental_max_line_distance_for_naively_paired_lines: Option<String>, pub features: Option<String>, pub git_config_parameters: Option<String>, pub git_prefix: Option<String>, pub hostname: Option<String>, pub navigate: Option<String>, pub pagers: (Option<String>, Option<String>), } impl DeltaEnv { /// Create a structure with current environment variable pub fn init() -> Self { let bat_theme = env::var(BAT_THEME).ok(); let colorterm = env::var(COLORTERM).ok(); let experimental_max_line_distance_for_naively_paired_lines = env::var(DELTA_EXPERIMENTAL_MAX_LINE_DISTANCE_FOR_NAIVELY_PAIRED_LINES).ok(); let features = env::var(DELTA_FEATURES).ok(); let git_config_parameters = env::var(GIT_CONFIG_PARAMETERS).ok(); let git_prefix = env::var(GIT_PREFIX).ok(); let hostname = hostname(); let navigate = env::var(DELTA_NAVIGATE).ok(); let current_dir = env::current_dir().ok(); let pagers = ( env::var(DELTA_PAGER).ok(), // We're using `bat::config::get_pager_executable` here instead of just returning // the pager from the environment variables, because we want to make sure // that the pager is a valid pager from env and handle the case of // the PAGER being set to something invalid like "most" and "more". bat::config::get_pager_executable(None), ); Self { bat_theme, colorterm, current_dir, experimental_max_line_distance_for_naively_paired_lines, features, git_config_parameters, git_prefix, hostname, navigate, pagers, } } } fn hostname() -> Option<String> { grep_cli::hostname().ok()?.to_str().map(|s| s.to_string()) } #[cfg(test)] pub mod tests { use super::DeltaEnv; use lazy_static::lazy_static; use std::env; use std::sync::{Arc, Mutex}; lazy_static! { static ref ENV_ACCESS: Arc<Mutex<()>> = Arc::new(Mutex::new(())); } #[test] fn test_env_parsing() { let _guard = ENV_ACCESS.lock().unwrap(); let feature = "Awesome Feature"; env::set_var("DELTA_FEATURES", feature); let env = DeltaEnv::init(); assert_eq!(env.features, Some(feature.into())); // otherwise `current_dir` is not used in the test cfg: assert_eq!(env.current_dir, env::current_dir().ok()); } #[test] fn test_env_parsing_with_pager_set_to_bat() { let _guard = ENV_ACCESS.lock().unwrap(); env::set_var("PAGER", "bat"); let env = DeltaEnv::init(); assert_eq!( env.pagers.1, Some("bat".into()), "Expected env.pagers.1 == Some(bat) but was {:?}", env.pagers.1 ); } #[test] fn test_env_parsing_with_pager_set_to_more() { let _guard = ENV_ACCESS.lock().unwrap(); env::set_var("PAGER", "more"); let env = DeltaEnv::init(); assert_eq!(env.pagers.1, Some("less".into())); } #[test] fn test_env_parsing_with_pager_set_to_most() { let _guard = ENV_ACCESS.lock().unwrap(); env::set_var("PAGER", "most"); let env = DeltaEnv::init(); assert_eq!(env.pagers.1, Some("less".into())); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/edits.rs
src/edits.rs
use regex::Regex; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; use crate::align; use crate::minusplus::MinusPlus; /// Infer the edit operations responsible for the differences between a collection of old and new /// lines. A "line" is a string. An annotated line is a Vec of (op, &str) pairs, where the &str /// slices are slices of the line, and their concatenation equals the line. Return the input minus /// and plus lines, in annotated form. /// /// Also return a specification of the inferred alignment of minus and plus lines: a paired minus /// and plus line is represented in this alignment specification as /// (Some(minus_line_index),Some(plus_line_index)), whereas an unpaired minus line is /// (Some(minus_line_index), None). /// /// `noop_deletions[i]` is the appropriate deletion operation tag to be used for `minus_lines[i]`; /// `noop_deletions` is guaranteed to be the same length as `minus_lines`. The equivalent statements /// hold for `plus_insertions` and `plus_lines`. #[allow(clippy::too_many_arguments)] #[allow(clippy::type_complexity)] pub fn infer_edits<'a, EditOperation>( minus_lines: Vec<&'a str>, plus_lines: Vec<&'a str>, noop_deletions: Vec<EditOperation>, deletion: EditOperation, noop_insertions: Vec<EditOperation>, insertion: EditOperation, tokenization_regex: &Regex, max_line_distance: f64, max_line_distance_for_naively_paired_lines: f64, ) -> ( Vec<Vec<(EditOperation, &'a str)>>, // annotated minus lines Vec<Vec<(EditOperation, &'a str)>>, // annotated plus lines Vec<(Option<usize>, Option<usize>)>, // line alignment ) where EditOperation: Copy + PartialEq + std::fmt::Debug, { let mut annotated_minus_lines = Vec::<Vec<(EditOperation, &str)>>::new(); let mut annotated_plus_lines = Vec::<Vec<(EditOperation, &str)>>::new(); let mut line_alignment = Vec::<(Option<usize>, Option<usize>)>::new(); let mut plus_index = 0; // plus lines emitted so far 'minus_lines_loop: for (minus_index, minus_line) in minus_lines.iter().enumerate() { let mut considered = 0; // plus lines considered so far as match for minus_line for plus_line in &plus_lines[plus_index..] { let alignment = align::Alignment::new( tokenize(minus_line, tokenization_regex), tokenize(plus_line, tokenization_regex), ); let (annotated_minus_line, annotated_plus_line, distance) = annotate( alignment, noop_deletions[minus_index], deletion, noop_insertions[plus_index], insertion, minus_line, plus_line, ); if minus_lines.len() == plus_lines.len() && distance <= max_line_distance_for_naively_paired_lines || distance <= max_line_distance { // minus_line and plus_line are inferred to be a homologous pair. // Emit as unpaired the plus lines already considered and rejected for plus_line in &plus_lines[plus_index..(plus_index + considered)] { annotated_plus_lines.push(vec![(noop_insertions[plus_index], plus_line)]); line_alignment.push((None, Some(plus_index))); plus_index += 1; } annotated_minus_lines.push(annotated_minus_line); annotated_plus_lines.push(annotated_plus_line); line_alignment.push((Some(minus_index), Some(plus_index))); plus_index += 1; // Greedy: move on to the next minus line. continue 'minus_lines_loop; } else { considered += 1; } } // No homolog was found for minus i; emit as unpaired. annotated_minus_lines.push(vec![(noop_deletions[minus_index], minus_line)]); line_alignment.push((Some(minus_index), None)); } // Emit any remaining plus lines for plus_line in &plus_lines[plus_index..] { if let Some(content) = get_contents_before_trailing_whitespace(plus_line) { annotated_plus_lines.push(vec![ (noop_insertions[plus_index], content), (noop_insertions[plus_index], &plus_line[content.len()..]), ]); } else { annotated_plus_lines.push(vec![(noop_insertions[plus_index], plus_line)]); } line_alignment.push((None, Some(plus_index))); plus_index += 1; } (annotated_minus_lines, annotated_plus_lines, line_alignment) } // Return `None` if there is no trailing whitespace. // Return `Some(content)` where content is trimmed if there was some trailing whitespace fn get_contents_before_trailing_whitespace(line: &str) -> Option<&str> { let content = line.trim_end(); // if line has a trailing newline, do not consider it as a 'trailing whitespace' if !content.is_empty() && content != line.trim_end_matches('\n') { Some(content) } else { None } } // Return boolean arrays indicating whether each line has a homolog (is "paired"). pub fn make_lines_have_homolog( line_alignment: &[(Option<usize>, Option<usize>)], ) -> MinusPlus<Vec<bool>> { MinusPlus::new( line_alignment .iter() .filter(|(m, _)| m.is_some()) .map(|(_, p)| p.is_some()) .collect(), line_alignment .iter() .filter(|(_, p)| p.is_some()) .map(|(m, _)| m.is_some()) .collect(), ) } /// Split line into tokens for alignment. The alignment algorithm aligns sequences of substrings; /// not individual characters. fn tokenize<'a>(line: &'a str, regex: &Regex) -> Vec<&'a str> { // Starting with "", see comment in Alignment::new(). Historical note: Replacing the '+/-' // prefix with a space implicitly generated this. let mut tokens = vec![""]; let mut offset = 0; for m in regex.find_iter(line) { if offset == 0 && m.start() > 0 { tokens.push(""); } // Align separating text as multiple single-character tokens. for t in line[offset..m.start()].graphemes(true) { tokens.push(t); } tokens.push(&line[m.start()..m.end()]); offset = m.end(); } if offset < line.len() { if offset == 0 { tokens.push(""); } for t in line[offset..line.len()].graphemes(true) { tokens.push(t); } } tokens } /// Use alignment to "annotate" minus and plus lines. An "annotated" line is a sequence of /// (a: Annotation, s: &str) pairs, where the &strs reference the memory /// of the original line and their concatenation equals the line. // This function doesn't return "coalesced" annotations: i.e. they're often are runs of consecutive // occurrences of the same operation. Since it is returning &strs pointing into the memory of the // original line, it's not possible to coalesce them in this function. #[allow(clippy::type_complexity)] fn annotate<'a, Annotation>( alignment: align::Alignment<'a>, noop_deletion: Annotation, deletion: Annotation, noop_insertion: Annotation, insertion: Annotation, minus_line: &'a str, plus_line: &'a str, ) -> (Vec<(Annotation, &'a str)>, Vec<(Annotation, &'a str)>, f64) where Annotation: Copy + PartialEq + std::fmt::Debug, { let mut annotated_minus_line = Vec::new(); let mut annotated_plus_line = Vec::new(); let (mut x_offset, mut y_offset) = (0, 0); let (mut minus_line_offset, mut plus_line_offset) = (0, 0); let (mut d_numer, mut d_denom) = (0, 0); // Note that the inputs to align::Alignment are not the original strings themselves, but // sequences of substrings derived from the tokenization process. We have just applied // run_length_encoding to "coalesce" runs of the same edit operation into a single // operation. We now need to form a &str, pointing into the memory of the original line, // identifying a "section" which is the concatenation of the substrings involved in this // coalesced operation. That's what the following closures do. Note that they must be called // once only since they advance offset pointers. let get_section = |n: usize, line_offset: &mut usize, substrings_offset: &mut usize, substrings: &[&str], line: &'a str| { let section_length = substrings[*substrings_offset..*substrings_offset + n] .iter() .fold(0, |n, s| n + s.len()); let old_offset = *line_offset; *line_offset += section_length; *substrings_offset += n; &line[old_offset..*line_offset] }; let mut minus_section = |n: usize, offset: &mut usize| { get_section(n, &mut minus_line_offset, offset, &alignment.x, minus_line) }; let mut plus_section = |n: usize, offset: &mut usize| { get_section(n, &mut plus_line_offset, offset, &alignment.y, plus_line) }; let distance_contribution = |section: &str| UnicodeWidthStr::width(section.trim()); let (mut minus_op_prev, mut plus_op_prev) = (noop_deletion, noop_insertion); for (op, n) in alignment.coalesced_operations() { match op { align::Operation::Deletion => { let minus_section = minus_section(n, &mut x_offset); let n_d = distance_contribution(minus_section); d_denom += n_d; d_numer += n_d; annotated_minus_line.push((deletion, minus_section)); minus_op_prev = deletion; } align::Operation::NoOp => { let minus_section = minus_section(n, &mut x_offset); let n_d = distance_contribution(minus_section); d_denom += 2 * n_d; let is_space = minus_section.trim().is_empty(); let coalesce_space_with_previous = is_space && ((minus_op_prev == deletion && plus_op_prev == insertion && (x_offset < alignment.x.len() - 1 || y_offset < alignment.y.len() - 1)) || (minus_op_prev == noop_deletion && plus_op_prev == noop_insertion)); annotated_minus_line.push(( if coalesce_space_with_previous { minus_op_prev } else { noop_deletion }, minus_section, )); let op = if coalesce_space_with_previous { plus_op_prev } else { noop_insertion }; let plus_section = plus_section(n, &mut y_offset); if let Some(non_whitespace) = get_contents_before_trailing_whitespace(plus_section) { annotated_plus_line.push((op, non_whitespace)); annotated_plus_line.push((op, &plus_section[non_whitespace.len()..])); } else { annotated_plus_line.push((op, plus_section)); } minus_op_prev = noop_deletion; plus_op_prev = noop_insertion; } align::Operation::Insertion => { let plus_section = plus_section(n, &mut y_offset); let n_d = distance_contribution(plus_section); d_denom += n_d; d_numer += n_d; annotated_plus_line.push((insertion, plus_section)); plus_op_prev = insertion; } } } ( annotated_minus_line, annotated_plus_line, compute_distance(d_numer as f64, d_denom as f64), ) } fn compute_distance(d_numer: f64, d_denom: f64) -> f64 { if d_denom > 0.0 { d_numer / d_denom } else { 0.0 } } #[cfg(test)] mod tests { use super::*; use itertools::Itertools; use lazy_static::lazy_static; use unicode_segmentation::UnicodeSegmentation; lazy_static! { static ref DEFAULT_TOKENIZATION_REGEXP: Regex = Regex::new(r#"\w+"#).unwrap(); } #[derive(Clone, Copy, Debug, PartialEq)] enum EditOperation { MinusNoop, PlusNoop, Deletion, Insertion, } type Annotation<'a> = (EditOperation, &'a str); type AnnotatedLine<'a> = Vec<Annotation<'a>>; type AnnotatedLines<'a> = Vec<AnnotatedLine<'a>>; type Edits<'a> = (AnnotatedLines<'a>, AnnotatedLines<'a>); use EditOperation::*; #[test] fn test_tokenize_0() { assert_tokenize("", &[]); assert_tokenize(";", &["", ";"]); assert_tokenize(";;", &["", ";", ";"]); assert_tokenize(";;a", &["", ";", ";", "a"]); assert_tokenize(";;ab", &["", ";", ";", "ab"]); assert_tokenize(";;ab;", &["", ";", ";", "ab", ";"]); assert_tokenize(";;ab;;", &["", ";", ";", "ab", ";", ";"]); } #[test] fn test_tokenize_1() { assert_tokenize("aaa bbb", &["aaa", " ", "bbb"]) } #[test] fn test_tokenize_2() { assert_tokenize( "fn coalesce_edits<'a, EditOperation>(", &[ "fn", " ", "coalesce_edits", "<", "'", "a", ",", " ", "EditOperation", ">", "(", ], ); } #[test] fn test_tokenize_3() { assert_tokenize( "fn coalesce_edits<'a, 'b, EditOperation>(", &[ "fn", " ", "coalesce_edits", "<", "'", "a", ",", " ", "'", "b", ",", " ", "EditOperation", ">", "(", ], ); } #[test] fn test_tokenize_4() { assert_tokenize( "annotated_plus_lines.push(vec![(noop_insertion, plus_line)]);", &[ "annotated_plus_lines", ".", "push", "(", "vec", "!", "[", "(", "noop_insertion", ",", " ", "plus_line", ")", "]", ")", ";", ], ); } #[test] fn test_tokenize_5() { assert_tokenize( " let col = Color::from_str(s).unwrap_or_else(|_| die());", &[ "", " ", " ", " ", " ", " ", " ", " ", " ", " ", "let", " ", "col", " ", "=", " ", "Color", ":", ":", "from_str", "(", "s", ")", ".", "unwrap_or_else", "(", "|", "_", "|", " ", "die", "(", ")", ")", ";", ], ) } #[test] fn test_tokenize_6() { assert_tokenize( " (minus_file, plus_file) => format!(\"renamed: {} ⟶ {}\", minus_file, plus_file),", &["", " ", " ", " ", " ", " ", " ", " ", " ", " ", "(", "minus_file", ",", " ", "plus_file", ")", " ", "=", ">", " ", "format", "!", "(", "\"", "renamed", ":", " ", "{", "}", " ", "⟶", " ", " ", "{", "}", "\"", ",", " ", "minus_file", ",", " ", "plus_file", ")", ","]) } fn assert_tokenize(text: &str, expected_tokens: &[&str]) { let actual_tokens = tokenize(text, &DEFAULT_TOKENIZATION_REGEXP); assert_eq!(text, expected_tokens.iter().join("")); // tokenize() guarantees that the first element of the token stream is "". // See comment in Alignment::new() assert_eq!(actual_tokens[0], ""); assert_eq!(&actual_tokens[1..], expected_tokens); } #[test] fn test_infer_edits_1() { assert_paired_edits( vec!["aaa"], vec!["aba"], ( vec![vec![(MinusNoop, ""), (Deletion, "aaa")]], vec![vec![(PlusNoop, ""), (Insertion, "aba")]], ), ) } #[test] fn test_infer_edits_1_2() { assert_paired_edits( vec!["aaa ccc"], vec!["aba ccc"], ( vec![vec![ (MinusNoop, ""), (Deletion, "aaa"), (MinusNoop, " ccc"), ]], vec![vec![(PlusNoop, ""), (Insertion, "aba"), (PlusNoop, " ccc")]], ), ) } #[test] fn test_infer_edits_2() { assert_paired_edits( vec!["áaa"], vec!["ááb"], ( vec![vec![(MinusNoop, ""), (Deletion, "áaa")]], vec![vec![(PlusNoop, ""), (Insertion, "ááb")]], ), ) } #[test] fn test_infer_edits_3() { assert_paired_edits( vec!["d.iteritems()"], vec!["d.items()"], ( vec![vec![ (MinusNoop, "d."), (Deletion, "iteritems"), (MinusNoop, "()"), ]], vec![vec![ (PlusNoop, "d."), (Insertion, "items"), (PlusNoop, "()"), ]], ), ) } #[test] fn test_infer_edits_4() { assert_edits( vec!["á a a á a a á a a", "á á b á á b á á b"], vec!["á á b á á c á á b"], ( vec![ vec![(MinusNoop, "á a a á a a á a a")], vec![ (MinusNoop, "á á b á á "), (Deletion, "b"), (MinusNoop, " á á b"), ], ], vec![vec![ (PlusNoop, "á á b á á"), (PlusNoop, " "), (Insertion, "c"), (PlusNoop, " á á b"), ]], ), 0.66, ) } #[test] fn test_infer_edits_5() { assert_edits( vec!["aaaa a aaa", "bbbb b bbb", "cccc c ccc"], vec!["bbbb ! bbb", "dddd d ddd", "cccc ! ccc"], ( vec![ vec![(MinusNoop, "aaaa a aaa")], vec![(MinusNoop, "bbbb "), (Deletion, "b"), (MinusNoop, " bbb")], vec![(MinusNoop, "cccc "), (Deletion, "c"), (MinusNoop, " ccc")], ], vec![ vec![ (PlusNoop, "bbbb"), (PlusNoop, " "), (Insertion, "!"), (PlusNoop, " bbb"), ], vec![(PlusNoop, "dddd d ddd")], vec![ (PlusNoop, "cccc"), (PlusNoop, " "), (Insertion, "!"), (PlusNoop, " ccc"), ], ], ), 0.66, ) } #[test] fn test_infer_edits_6() { assert_no_edits( vec![ " let mut i = 0;", " for ((_, c0), (_, c1)) in s0.zip(s1) {", " if c0 != c1 {", " break;", " } else {", " i += c0.len();", " }", " }", " i", ], vec![ " s0.zip(s1)", " .take_while(|((_, c0), (_, c1))| c0 == c1) // TODO: Don't consume one-past-the-end!", " .fold(0, |offset, ((_, c0), (_, _))| offset + c0.len())" ], 0.5) } #[test] fn test_infer_edits_7() { assert_edits( vec!["fn coalesce_edits<'a, EditOperation>("], vec!["fn coalesce_edits<'a, 'b, EditOperation>("], ( vec![vec![ (MinusNoop, "fn coalesce_edits<'a, "), (MinusNoop, "EditOperation>("), ]], vec![vec![ (PlusNoop, "fn coalesce_edits<'a,"), (PlusNoop, " "), (Insertion, "'b, "), (PlusNoop, "EditOperation>("), ]], ), 0.66, ) } #[test] fn test_infer_edits_8() { assert_edits( vec!["for _ in range(0, options[\"count\"]):"], vec!["for _ in range(0, int(options[\"count\"])):"], ( vec![vec![ (MinusNoop, "for _ in range(0, "), (MinusNoop, "options[\"count\"])"), (MinusNoop, ":"), ]], vec![vec![ (PlusNoop, "for _ in range(0,"), (PlusNoop, " "), (Insertion, "int("), (PlusNoop, "options[\"count\"])"), (Insertion, ")"), (PlusNoop, ":"), ]], ), 0.3, ) } #[test] fn test_infer_edits_9() { assert_edits( vec!["a a"], vec!["a b a"], ( vec![vec![(MinusNoop, "a "), (MinusNoop, "a")]], vec![vec![ (PlusNoop, "a"), (PlusNoop, " "), (Insertion, "b "), (PlusNoop, "a"), ]], ), 1.0, ); assert_edits( vec!["a a"], vec!["a b b a"], ( vec![vec![(MinusNoop, "a "), (MinusNoop, "a")]], vec![vec![ (PlusNoop, "a"), (PlusNoop, " "), (Insertion, "b b "), (PlusNoop, "a"), ]], ), 1.0, ); } #[test] fn test_infer_edits_10() { assert_edits( vec!["so it is safe to read the commit number from any one of them."], vec!["so it is safe to read build info from any one of them."], ( // TODO: Coalesce runs of the same operation. vec![vec![ (MinusNoop, "so it is safe to read "), (Deletion, "the commit"), (Deletion, " "), (Deletion, "number"), (MinusNoop, " from any one of them."), ]], vec![vec![ (PlusNoop, "so it is safe to read"), (PlusNoop, " "), (Insertion, "build"), (Insertion, " "), (Insertion, "info"), (PlusNoop, " from any one of them."), ]], ), 1.0, ); } #[test] fn test_infer_edits_11() { assert_edits( vec![" self.table[index] ="], vec![" self.table[index] = candidates"], ( vec![vec![(MinusNoop, " self.table[index] =")]], vec![vec![ (PlusNoop, " self.table[index] ="), (Insertion, " candidates"), ]], ), 1.0, ); } #[test] fn test_infer_edits_12() { assert_edits( vec![" (xxxxxxxxx, \"build info\"),"], vec![" (xxxxxxxxx, \"build\"),"], ( vec![vec![ (MinusNoop, " (xxxxxxxxx, \"build"), (Deletion, " info"), (MinusNoop, "\"),"), ]], vec![vec![ (PlusNoop, " (xxxxxxxxx, \"build"), (PlusNoop, "\"),"), ]], ), 1.0, ); } #[test] fn test_infer_edits_13() { assert_paired_edits( vec!["'b '", "[element,]"], vec!["' b'", "[element],"], ( vec![ vec![ (MinusNoop, "'"), (Deletion, "b"), (MinusNoop, " "), (MinusNoop, "'"), ], vec![(MinusNoop, "[element"), (Deletion, ","), (MinusNoop, "]")], ], vec![ vec![ (PlusNoop, "'"), (PlusNoop, " "), (Insertion, "b"), (PlusNoop, "'"), ], vec![(PlusNoop, "[element"), (PlusNoop, "]"), (Insertion, ",")], ], ), ); } #[test] fn test_infer_edits_14() { assert_edits( vec!["a b c d ", "p "], vec!["x y c z ", "q r"], ( vec![ vec![ (MinusNoop, ""), (Deletion, "a"), (Deletion, " "), (Deletion, "b"), (MinusNoop, " c "), (Deletion, "d"), (MinusNoop, " "), ], vec![(MinusNoop, ""), (Deletion, "p"), (Deletion, " ")], ], vec![ vec![ (PlusNoop, ""), (Insertion, "x"), (Insertion, " "), (Insertion, "y"), (PlusNoop, " c"), (PlusNoop, " "), (Insertion, "z"), (PlusNoop, " "), ], vec![ (PlusNoop, ""), (Insertion, "q"), (Insertion, " "), (Insertion, "r"), ], ], ), 1.0, ); } #[test] fn test_infer_edits_15() { assert_paired_edits( vec![r#"printf "%s\n" s y y | git add -p &&"#], vec!["test_write_lines s y y | git add -p &&"], ( vec![vec![ (MinusNoop, ""), (Deletion, r#"printf "%s\n""#), (MinusNoop, " s y y | git add -p &&"), ]], vec![vec![ (PlusNoop, ""), (Insertion, "test_write_lines"), (PlusNoop, " s y y | git add -p &&"), ]], ), ); } #[test] fn test_infer_edits_16() { assert_edits( vec!["a a a a a a b b b"], vec!["c a a a a a a c c"], ( vec![vec![ (MinusNoop, ""), (MinusNoop, "a a a a a a "), (Deletion, "b b"), (Deletion, " "), (Deletion, "b"), ]], vec![vec![ (PlusNoop, ""), (Insertion, "c "), (PlusNoop, "a a a a a a"), (PlusNoop, " "), (Insertion, "c"), (Insertion, " "), (Insertion, "c"), ]], ), 1.0, ); } fn assert_edits( minus_lines: Vec<&str>, plus_lines: Vec<&str>, expected_edits: Edits, max_line_distance: f64, ) { let (minus_lines, noop_deletions): (Vec<&str>, Vec<EditOperation>) = minus_lines.into_iter().map(|s| (s, MinusNoop)).unzip(); let (plus_lines, noop_insertions): (Vec<&str>, Vec<EditOperation>) = plus_lines.into_iter().map(|s| (s, PlusNoop)).unzip(); let actual_edits = infer_edits( minus_lines, plus_lines, noop_deletions, Deletion, noop_insertions, Insertion, &DEFAULT_TOKENIZATION_REGEXP, max_line_distance, 0.0, ); // compare_annotated_lines(actual_edits, expected_edits); // TODO: test line alignment assert_eq!((actual_edits.0, actual_edits.1), expected_edits); } // Assert that no edits are inferred for the supplied minus and plus lines. fn assert_no_edits(minus_lines: Vec<&str>, plus_lines: Vec<&str>, max_line_distance: f64) { let expected_edits = ( minus_lines.iter().map(|s| vec![(MinusNoop, *s)]).collect(), plus_lines.iter().map(|s| vec![(PlusNoop, *s)]).collect(), ); assert_edits(minus_lines, plus_lines, expected_edits, max_line_distance) } // Assertions for a single pair of lines, considered as a homologous pair. We set // max_line_distance = 1.0 in order that the pair will be inferred to be homologous. fn assert_paired_edits(minus_lines: Vec<&str>, plus_lines: Vec<&str>, expected_edits: Edits) { assert_consistent_pairs(&expected_edits); assert_edits(minus_lines, plus_lines, expected_edits, 1.0); } fn assert_consistent_pairs(edits: &Edits) { let (minus_annotated_lines, plus_annotated_lines) = edits; for (minus_annotated_line, plus_annotated_line) in minus_annotated_lines.iter().zip(plus_annotated_lines) { let (minus_total, minus_delta) = summarize_annotated_line(minus_annotated_line); let (plus_total, plus_delta) = summarize_annotated_line(plus_annotated_line); assert_eq!( minus_total - minus_delta, plus_total - plus_delta, "\nInconsistent edits:\n \ {:?}\n \ \tminus_total - minus_delta = {} - {} = {}\n \ {:?}\n \ \tplus_total - plus_delta = {} - {} = {}\n", minus_annotated_line, minus_total, minus_delta, minus_total - minus_delta, plus_annotated_line, plus_total, plus_delta, plus_total - plus_delta ); } } fn summarize_annotated_line(sections: &AnnotatedLine) -> (usize, usize) { let mut total = 0; let mut delta = 0; for (edit, s) in sections { let length = s.graphemes(true).count(); total += length; if is_edit(edit) { delta += length; } } (total, delta) } // For debugging test failures: #[allow(dead_code)] fn compare_annotated_lines(actual: Edits, expected: Edits) { let (minus, plus) = actual; println!("\n\nactual minus:"); print_annotated_lines(minus);
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
true
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/align.rs
src/align.rs
use std::cmp::max; use std::collections::VecDeque; const DELETION_COST: usize = 2; const INSERTION_COST: usize = 2; // extra cost for starting a new group of changed tokens const INITIAL_MISMATCH_PENALTY: usize = 1; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Operation { NoOp, Deletion, Insertion, } use Operation::*; /// Needleman-Wunsch / Wagner-Fischer table for computation of edit distance and associated /// alignment. #[derive(Clone, Debug)] struct Cell { parent: usize, operation: Operation, cost: usize, } #[derive(Debug)] pub struct Alignment<'a> { pub x: Vec<&'a str>, pub y: Vec<&'a str>, table: Vec<Cell>, dim: [usize; 2], } impl<'a> Alignment<'a> { /// Fill table for Levenshtein distance / alignment computation pub fn new(x: Vec<&'a str>, y: Vec<&'a str>) -> Self { // TODO: Something downstream of the alignment algorithm requires that the first token in // both x and y is "", so this is explicitly inserted in `tokenize()`. let dim = [y.len() + 1, x.len() + 1]; let table = vec![ Cell { parent: 0, operation: NoOp, cost: 0 }; dim[0] * dim[1] ]; let mut alignment = Self { x, y, table, dim }; alignment.fill(); alignment } /// Fill table for Levenshtein distance / alignment computation pub fn fill(&mut self) { // x is written along the top of the table; y is written down the left side of the // table. Also, we insert a 0 in cell (0, 0) of the table, so x and y are shifted by one // position. Therefore, the element corresponding to (x[i], y[j]) is in column (i + 1) and // row (j + 1); the index of this element is given by index(i, j). for i in 1..self.dim[1] { self.table[i] = Cell { parent: 0, operation: Deletion, cost: i * DELETION_COST + INITIAL_MISMATCH_PENALTY, }; } for j in 1..self.dim[0] { self.table[j * self.dim[1]] = Cell { parent: 0, operation: Insertion, cost: j * INSERTION_COST + INITIAL_MISMATCH_PENALTY, }; } for (i, x_i) in self.x.iter().enumerate() { for (j, y_j) in self.y.iter().enumerate() { let (left, diag, up) = (self.index(i, j + 1), self.index(i, j), self.index(i + 1, j)); // The order of the candidates matters if two of them have the // same cost as in that case we choose the first one. Consider // insertions and deletions before matches in order to group // changes together. Insertions are preferred to deletions in // order to highlight moved tokens as a deletion followed by an // insertion (as the edit sequence is read backwards we need to // choose the insertion first) let candidates = [ Cell { parent: up, operation: Insertion, cost: self.mismatch_cost(up, INSERTION_COST), }, Cell { parent: left, operation: Deletion, cost: self.mismatch_cost(left, DELETION_COST), }, Cell { parent: diag, operation: NoOp, cost: if x_i == y_j { self.table[diag].cost } else { usize::MAX }, }, ]; let index = self.index(i + 1, j + 1); self.table[index] = candidates .iter() .min_by_key(|cell| cell.cost) .unwrap() .clone(); } } } fn mismatch_cost(&self, parent: usize, basic_cost: usize) -> usize { self.table[parent].cost + basic_cost + if self.table[parent].operation == NoOp { INITIAL_MISMATCH_PENALTY } else { 0 } } /// Read edit operations from the table. pub fn operations(&self) -> Vec<Operation> { let mut ops = VecDeque::with_capacity(max(self.x.len(), self.y.len())); let mut cell = &self.table[self.index(self.x.len(), self.y.len())]; loop { ops.push_front(cell.operation); if cell.parent == 0 { break; } cell = &self.table[cell.parent]; } Vec::from(ops) } pub fn coalesced_operations(&self) -> Vec<(Operation, usize)> { run_length_encode(self.operations()) } // Row-major storage of 2D array. fn index(&self, i: usize, j: usize) -> usize { j * self.dim[1] + i } } fn run_length_encode<T>(sequence: Vec<T>) -> Vec<(T, usize)> where T: Copy, T: PartialEq, { let mut encoded = Vec::with_capacity(sequence.len()); if sequence.is_empty() { return encoded; } let end = sequence.len(); let (mut i, mut j) = (0, 1); let mut curr = &sequence[i]; loop { if j == end || sequence[j] != *curr { encoded.push((*curr, j - i)); if j == end { return encoded; } else { curr = &sequence[j]; i = j; } } j += 1; } } #[cfg(test)] mod tests { use super::*; use unicode_segmentation::UnicodeSegmentation; #[test] fn test_run_length_encode() { assert_eq!(run_length_encode::<usize>(vec![]), vec![]); assert_eq!(run_length_encode(vec![0]), vec![(0, 1)]); assert_eq!(run_length_encode(vec!["0", "0"]), vec![("0", 2)]); assert_eq!( run_length_encode(vec![0, 0, 1, 2, 2, 2, 3, 4, 4, 4]), vec![(0, 2), (1, 1), (2, 3), (3, 1), (4, 3)] ); } #[test] fn test_0() { TestCase { before: "aaa", after: "aba", distance: 5, parts: (2, 4), operations: vec![NoOp, Deletion, Insertion, NoOp], } .run(); } #[test] fn test_0_nonascii() { TestCase { before: "ááb", after: "áaa", distance: 9, parts: (4, 5), operations: vec![NoOp, Deletion, Deletion, Insertion, Insertion], } .run(); } #[test] fn test_1() { TestCase { before: "kitten", after: "sitting", distance: 13, parts: (5, 9), operations: vec![ Deletion, // K - Insertion, // - S NoOp, // I I NoOp, // T T NoOp, // T T Deletion, // E - Insertion, // - I NoOp, // N N Insertion, // - G ], } .run(); } #[test] fn test_2() { TestCase { before: "saturday", after: "sunday", distance: 10, parts: (4, 9), operations: vec![ NoOp, // S S Deletion, // A - Deletion, // T - NoOp, // U U Deletion, // R - Insertion, // - N NoOp, // D D NoOp, // A A NoOp, // Y Y ], } .run(); } #[test] fn test_3() { TestCase { // Prefer [Deletion NoOp Insertion] over [Insertion NoOp Deletion] before: "ab", after: "ba", distance: 6, parts: (2, 3), operations: vec![ Deletion, // a - NoOp, // b b Insertion, // - a ], } .run(); } #[test] fn test_4() { // Deletions are grouped together. TestCase { before: "AABB", after: "AB", distance: 5, parts: (2, 4), operations: vec![ NoOp, // A A Deletion, // A - Deletion, // B - NoOp, // B B ], } .run(); } #[test] fn test_5() { // Insertions are grouped together. TestCase { before: "AB", after: "AABB", distance: 5, parts: (2, 4), operations: vec![ NoOp, // A A Insertion, // - A Insertion, // - B NoOp, // B B ], } .run(); } #[test] fn test_6() { // Insertion and Deletion are grouped together. TestCase { before: "AAABBB", after: "ACB", distance: 11, parts: (5, 7), operations: vec![ NoOp, // A A Deletion, // A - Deletion, // A - Deletion, // B - Deletion, // B - Insertion, // - C NoOp, // B B ], } .run(); } struct TestCase<'a> { before: &'a str, after: &'a str, distance: usize, parts: (usize, usize), operations: Vec<Operation>, } impl<'a> TestCase<'a> { pub fn run(&self) { self.assert_string_distance_parts(); assert_eq!(operations(self.before, self.after), self.operations); } fn assert_string_distance_parts(&self) { self.assert_string_levenshtein_distance(); assert_eq!(string_distance_parts(self.before, self.after), self.parts); assert_eq!(string_distance_parts(self.after, self.before), self.parts); } fn assert_string_levenshtein_distance(&self) { assert_eq!( string_levenshtein_distance(self.before, self.after), self.distance ); assert_eq!( string_levenshtein_distance(self.after, self.before), self.distance ); } } fn string_distance_parts(x: &str, y: &str) -> (usize, usize) { let (x, y) = ( x.graphemes(true).collect::<Vec<&str>>(), y.graphemes(true).collect::<Vec<&str>>(), ); Alignment::new(x, y).distance_parts() } fn string_levenshtein_distance(x: &str, y: &str) -> usize { let (x, y) = ( x.graphemes(true).collect::<Vec<&str>>(), y.graphemes(true).collect::<Vec<&str>>(), ); Alignment::new(x, y).levenshtein_distance() } fn operations<'a>(x: &'a str, y: &'a str) -> Vec<Operation> { let (x, y) = ( x.graphemes(true).collect::<Vec<&str>>(), y.graphemes(true).collect::<Vec<&str>>(), ); Alignment::new(x, y).operations() } impl<'a> Alignment<'a> { pub fn distance_parts(&self) -> (usize, usize) { let (mut numer, mut denom) = (0, 0); for op in self.operations() { if op != NoOp { numer += 1; } denom += 1; } (numer, denom) } /// Compute levenshtein distance from the filled table. pub fn levenshtein_distance(&self) -> usize { self.table[self.index(self.x.len(), self.y.len())].cost } #[allow(dead_code)] fn format_cell(&self, cell: &Cell) -> String { let parent = &self.table[cell.parent]; let op = match cell.operation { Deletion => "-", Insertion => "+", NoOp => ".", }; format!("{}{}{}", parent.cost, op, cell.cost) } #[allow(dead_code)] fn print(&self) { println!("x: {:?}", self.x); println!("y: {:?}", self.y); println!(); print!(" "); for j in 0..self.dim[1] { print!("{} ", if j > 0 { self.x[j - 1] } else { " " }) } println!(); for i in 0..self.dim[0] { for j in 0..self.dim[1] { if j == 0 { print!("{} ", if i > 0 { self.y[i - 1] } else { " " }) } let cell = &self.table[self.index(j, i)]; print!("{} ", self.format_cell(cell)); } println!(); } println!(); } } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/format.rs
src/format.rs
use std::convert::{TryFrom, TryInto}; use regex::Regex; use smol_str::SmolStr; use unicode_segmentation::UnicodeSegmentation; use crate::features::side_by_side::ansifill::ODD_PAD_CHAR; #[derive(Debug, PartialEq, Eq)] pub enum Placeholder<'a> { NumberMinus, NumberPlus, Str(&'a str), } impl<'a> TryFrom<Option<&'a str>> for Placeholder<'a> { type Error = (); fn try_from(from: Option<&'a str>) -> Result<Self, Self::Error> { match from { Some("nm") => Ok(Placeholder::NumberMinus), Some("np") => Ok(Placeholder::NumberPlus), Some(placeholder) => Ok(Placeholder::Str(placeholder)), _ => Err(()), } } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Align { Left, Center, Right, } impl TryFrom<Option<&str>> for Align { type Error = (); fn try_from(from: Option<&str>) -> Result<Self, Self::Error> { // inlined format args are not supported for `debug_assert` with edition 2018. #[allow(clippy::uninlined_format_args)] match from { Some("<") => Ok(Align::Left), Some(">") => Ok(Align::Right), Some("^") => Ok(Align::Center), Some(alignment) => { debug_assert!(false, "Unknown Alignment: {}", alignment); Err(()) } None => Err(()), } } } #[derive(Debug, PartialEq, Eq, Clone)] pub struct FormatStringPlaceholderDataAnyPlaceholder<T> { pub prefix: SmolStr, pub prefix_len: usize, pub placeholder: Option<T>, pub alignment_spec: Option<Align>, pub width: Option<usize>, pub precision: Option<usize>, pub fmt_type: SmolStr, pub suffix: SmolStr, pub suffix_len: usize, } impl<T> Default for FormatStringPlaceholderDataAnyPlaceholder<T> { fn default() -> Self { Self { prefix: SmolStr::default(), prefix_len: 0, placeholder: None, alignment_spec: None, width: None, precision: None, fmt_type: SmolStr::default(), suffix: SmolStr::default(), suffix_len: 0, } } } impl<T> FormatStringPlaceholderDataAnyPlaceholder<T> { pub fn only_string(s: &str) -> Self { Self { suffix: s.into(), suffix_len: s.graphemes(true).count(), ..Self::default() } } } pub type FormatStringPlaceholderData<'a> = FormatStringPlaceholderDataAnyPlaceholder<Placeholder<'a>>; pub type FormatStringSimple = FormatStringPlaceholderDataAnyPlaceholder<()>; impl FormatStringPlaceholderData<'_> { pub fn width(&self, hunk_max_line_number_width: usize) -> (usize, usize) { // Only if Some(placeholder) is present will there be a number formatted // by this placeholder, if not width is also None. ( self.prefix_len + std::cmp::max( self.placeholder .as_ref() .map_or(0, |_| hunk_max_line_number_width), self.width.unwrap_or(0), ), self.suffix_len, ) } pub fn into_simple(self) -> FormatStringSimple { FormatStringSimple { prefix: self.prefix, prefix_len: self.prefix_len, placeholder: None, alignment_spec: self.alignment_spec, width: self.width, precision: self.precision, fmt_type: self.fmt_type, suffix: self.suffix, suffix_len: self.suffix_len, } } } pub type FormatStringData<'a> = Vec<FormatStringPlaceholderData<'a>>; pub fn make_placeholder_regex(labels: &[&str]) -> Regex { Regex::new(&format!( r"(?x) \{{ ({}) # 1: Placeholder labels (?: # Start optional format spec (non-capturing) : # Literal colon (?: # Start optional fill/alignment spec (non-capturing) ([^<^>])? # 2: Optional fill character (ignored) ([<^>]) # 3: Alignment spec )? # (\d+)? # 4: Width (optional) (?: # Start optional precision (non-capturing) \.(\d+) # 5: Precision )? # (?: # Start optional format type (non-capturing) _?([A-Za-z][0-9A-Za-z_-]*) # 6: Format type, optional leading _ )? # )? # \}} ", labels.join("|") )) .unwrap() } // The resulting vector is never empty pub fn parse_line_number_format<'a>( format_string: &'a str, placeholder_regex: &Regex, mut prefix_with_space: bool, ) -> FormatStringData<'a> { let mut format_data = Vec::new(); let mut offset = 0; let mut expand_first_prefix = |prefix: SmolStr| { // Only prefix the first placeholder with a space, also see `UseFullPanelWidth` if prefix_with_space { let prefix = SmolStr::new(format!("{ODD_PAD_CHAR}{prefix}")); prefix_with_space = false; prefix } else { prefix } }; for captures in placeholder_regex.captures_iter(format_string) { let match_ = captures.get(0).unwrap(); let prefix = SmolStr::new(&format_string[offset..match_.start()]); let prefix = expand_first_prefix(prefix); let prefix_len = prefix.graphemes(true).count(); let suffix = SmolStr::new(&format_string[match_.end()..]); let suffix_len = suffix.graphemes(true).count(); format_data.push(FormatStringPlaceholderData { prefix, prefix_len, placeholder: captures.get(1).map(|m| m.as_str()).try_into().ok(), alignment_spec: captures.get(3).map(|m| m.as_str()).try_into().ok(), width: captures.get(4).map(|m| { m.as_str() .parse() .unwrap_or_else(|_| panic!("Invalid width in format string: {}", format_string)) }), precision: captures.get(5).map(|m| { m.as_str().parse().unwrap_or_else(|_| { panic!("Invalid precision in format string: {}", format_string) }) }), fmt_type: captures .get(6) .map(|m| SmolStr::from(m.as_str())) .unwrap_or_default(), suffix, suffix_len, }); offset = match_.end(); } if offset == 0 { let prefix = SmolStr::new(""); let prefix = expand_first_prefix(prefix); let prefix_len = prefix.graphemes(true).count(); // No placeholders format_data.push(FormatStringPlaceholderData { prefix, prefix_len, suffix: SmolStr::new(format_string), suffix_len: format_string.graphemes(true).count(), ..Default::default() }) } format_data } pub trait CenterRightNumbers { // There is no such thing as "Center Align" with discrete terminal cells. In // some cases a decision has to be made whether to use the left or the right // cell, e.g. when centering one char in 4 cells: "_X__" or "__X_". // // The format!() center/^ default is center left, but when padding numbers // these are now aligned to the center right by having this trait return " " // instead of "". This is prepended to the format string. In the case of " " // the trailing " " must then be removed so everything is shifted to the right. // This assumes no special padding characters, i.e. the default of space. fn center_right_space(&self, alignment: Align, width: usize) -> &'static str; } impl CenterRightNumbers for &str { fn center_right_space(&self, _alignment: Align, _width: usize) -> &'static str { // Disables center-right formatting and aligns strings center-left "" } } impl CenterRightNumbers for String { fn center_right_space(&self, alignment: Align, width: usize) -> &'static str { self.as_str().center_right_space(alignment, width) } } impl CenterRightNumbers for &std::borrow::Cow<'_, str> { fn center_right_space(&self, alignment: Align, width: usize) -> &'static str { self.as_ref().center_right_space(alignment, width) } } // Returns the base-10 width of `n`, i.e. `floor(log10(n)) + 1` and 0 is treated as 1. pub fn log10_plus_1(mut n: usize) -> usize { let mut len = 0; // log10 for integers is only in nightly and this is faster than // casting to f64 and back. loop { if n <= 9 { break len + 1; } if n <= 99 { break len + 2; } if n <= 999 { break len + 3; } if n <= 9999 { break len + 4; } len += 4; n /= 10000; } } impl CenterRightNumbers for usize { fn center_right_space(&self, alignment: Align, width: usize) -> &'static str { if alignment != Align::Center { return ""; } let width_of_number = log10_plus_1(*self); if width > width_of_number && (width % 2 != width_of_number % 2) { " " } else { "" } } } // Note that in this case of a string `s`, `precision` means "max width". // See https://doc.rust-lang.org/std/fmt/index.html pub fn pad<T: std::fmt::Display + CenterRightNumbers>( s: T, width: usize, alignment: Align, precision: Option<usize>, ) -> String { let space = s.center_right_space(alignment, width); let mut result = match precision { None => match alignment { Align::Left => format!("{space}{s:<width$}"), Align::Center => format!("{space}{s:^width$}"), Align::Right => format!("{space}{s:>width$}"), }, Some(precision) => match alignment { Align::Left => format!("{space}{s:<width$.precision$}"), Align::Center => format!("{space}{s:^width$.precision$}"), Align::Right => format!("{space}{s:>width$.precision$}"), }, }; if space == " " { result.pop(); } result } #[cfg(test)] mod tests { use super::*; #[test] fn test_log10_plus_1() { let nrs = [ 1, 9, 10, 11, 99, 100, 101, 999, 1_000, 1_001, 9_999, 10_000, 10_001, 99_999, 100_000, 100_001, 0, ]; let widths = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 1]; for (n, w) in nrs.iter().zip(widths.iter()) { assert_eq!(log10_plus_1(*n), *w); } #[cfg(target_pointer_width = "64")] { assert_eq!(log10_plus_1(744_073_709_551_615), 5 * 3); assert_eq!(log10_plus_1(18_446_744_073_709_551_615), 2 + 6 * 3); } } #[test] fn test_center_right_space_trait() { assert_eq!("abc".center_right_space(Align::Center, 6), ""); assert_eq!("abc".center_right_space(Align::Center, 7), ""); assert_eq!(123.center_right_space(Align::Center, 6), " "); assert_eq!(123.center_right_space(Align::Center, 7), ""); } #[test] fn test_pad_center_align() { assert_eq!(pad("abc", 6, Align::Center, None), " abc "); assert_eq!(pad(1, 1, Align::Center, None), "1"); assert_eq!(pad(1, 2, Align::Center, None), " 1"); assert_eq!(pad(1, 3, Align::Center, None), " 1 "); assert_eq!(pad(1, 4, Align::Center, None), " 1 "); assert_eq!(pad(1001, 3, Align::Center, None), "1001"); assert_eq!(pad(1001, 4, Align::Center, None), "1001"); assert_eq!(pad(1001, 5, Align::Center, None), " 1001"); assert_eq!(pad(1, 4, Align::Left, None), "1 "); assert_eq!(pad(1, 4, Align::Right, None), " 1"); assert_eq!(pad("abc", 5, Align::Left, None), "abc "); assert_eq!(pad("abc", 5, Align::Right, None), " abc"); } #[test] fn test_placeholder_with_notype() { let regex = make_placeholder_regex(&["placeholder"]); assert_eq!( parse_line_number_format("{placeholder:^4}", &regex, false), vec![FormatStringPlaceholderData { placeholder: Some(Placeholder::Str("placeholder")), alignment_spec: Some(Align::Center), width: Some(4), ..Default::default() }] ); } #[test] fn test_placeholder_with_only_type_dash_number() { let regex = make_placeholder_regex(&["placeholder"]); assert_eq!( parse_line_number_format("{placeholder:a_type-b-12}", &regex, false), vec![FormatStringPlaceholderData { placeholder: Some(Placeholder::Str("placeholder")), fmt_type: "a_type-b-12".into(), ..Default::default() }] ); } #[test] fn test_placeholder_with_empty_formatting() { let regex = make_placeholder_regex(&["placeholder"]); assert_eq!( parse_line_number_format("{placeholder:}", &regex, false), vec![FormatStringPlaceholderData { placeholder: Some(Placeholder::Str("placeholder")), ..Default::default() }] ); } #[test] fn test_placeholder_with_type_and_more() { let regex = make_placeholder_regex(&["placeholder"]); assert_eq!( parse_line_number_format("prefix {placeholder:<15.14type} suffix", &regex, false), vec![FormatStringPlaceholderData { prefix: "prefix ".into(), placeholder: Some(Placeholder::Str("placeholder")), alignment_spec: Some(Align::Left), width: Some(15), precision: Some(14), fmt_type: "type".into(), suffix: " suffix".into(), prefix_len: 7, suffix_len: 7, }] ); assert_eq!( parse_line_number_format("prefix {placeholder:<15.14_type} suffix", &regex, false), vec![FormatStringPlaceholderData { prefix: "prefix ".into(), placeholder: Some(Placeholder::Str("placeholder")), alignment_spec: Some(Align::Left), width: Some(15), precision: Some(14), fmt_type: "type".into(), suffix: " suffix".into(), prefix_len: 7, suffix_len: 7, }] ); } #[test] fn test_placeholder_regex() { let regex = make_placeholder_regex(&["placeholder"]); assert_eq!( parse_line_number_format("prefix {placeholder:<15.14} suffix", &regex, false), vec![FormatStringPlaceholderData { prefix: "prefix ".into(), placeholder: Some(Placeholder::Str("placeholder")), alignment_spec: Some(Align::Left), width: Some(15), precision: Some(14), fmt_type: SmolStr::default(), suffix: " suffix".into(), prefix_len: 7, suffix_len: 7, }] ); } #[test] fn test_placeholder_regex_empty_placeholder() { let regex = make_placeholder_regex(&[""]); assert_eq!( parse_line_number_format("prefix {:<15.14} suffix", &regex, false), vec![FormatStringPlaceholderData { prefix: "prefix ".into(), placeholder: Some(Placeholder::Str("")), alignment_spec: Some(Align::Left), width: Some(15), precision: Some(14), fmt_type: SmolStr::default(), suffix: " suffix".into(), prefix_len: 7, suffix_len: 7, }] ); } #[test] fn test_format_string_simple() { let regex = make_placeholder_regex(&["foo"]); let f = parse_line_number_format("prefix {foo:<15.14} suffix", &regex, false); assert_eq!( f, vec![FormatStringPlaceholderData { prefix: "prefix ".into(), placeholder: Some(Placeholder::Str("foo")), alignment_spec: Some(Align::Left), width: Some(15), precision: Some(14), fmt_type: SmolStr::default(), suffix: " suffix".into(), prefix_len: 7, suffix_len: 7, }] ); let simple: Vec<_> = f .into_iter() .map(FormatStringPlaceholderData::into_simple) .collect(); assert_eq!( simple, vec![FormatStringSimple { prefix: "prefix ".into(), placeholder: None, alignment_spec: Some(Align::Left), width: Some(15), precision: Some(14), fmt_type: SmolStr::default(), suffix: " suffix".into(), prefix_len: 7, suffix_len: 7, }] ); } #[test] fn test_line_number_format_only_string() { let f = FormatStringSimple::only_string("abc"); assert_eq!(f.suffix_len, 3); } #[test] fn test_parse_line_number_format_not_empty() { let regex = make_placeholder_regex(&["abc"]); assert!(!parse_line_number_format(" abc ", &regex, false).is_empty()); assert!(!parse_line_number_format("", &regex, false).is_empty()); let regex = make_placeholder_regex(&[""]); assert!(!parse_line_number_format(" abc ", &regex, false).is_empty()); assert!(!parse_line_number_format("", &regex, false).is_empty()); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/style.rs
src/style.rs
use std::borrow::Cow; use std::fmt; use std::hash::{Hash, Hasher}; use lazy_static::lazy_static; use crate::ansi; use crate::color; use crate::git_config::GitConfig; // PERF: Avoid deriving Copy here? #[derive(Clone, Copy, PartialEq, Default)] pub struct Style { pub ansi_term_style: ansi_term::Style, pub is_emph: bool, pub is_omitted: bool, pub is_raw: bool, pub is_syntax_highlighted: bool, pub decoration_style: DecorationStyle, } // More compact debug output, replace false/empty with lowercase and true with uppercase. impl fmt::Debug for Style { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ansi = if self.ansi_term_style.is_plain() { "<a".into() } else { format!("ansi_term_style: {:?}, <", self.ansi_term_style) }; let deco = if self.decoration_style == DecorationStyle::NoDecoration { "d>".into() } else { format!(">, decoration_style: {:?}", self.decoration_style) }; let is_set = |c: char, set: bool| -> String { if set { c.to_uppercase().to_string() } else { c.to_lowercase().to_string() } }; write!( f, "Style {{ {}{}{}{}{}{} }}", ansi, is_set('e', self.is_emph), is_set('o', self.is_omitted), is_set('r', self.is_raw), is_set('s', self.is_syntax_highlighted), deco ) } } #[derive(Clone, Copy, Debug, PartialEq, Default)] pub enum DecorationStyle { Box(ansi_term::Style), Underline(ansi_term::Style), Overline(ansi_term::Style), UnderOverline(ansi_term::Style), BoxWithUnderline(ansi_term::Style), BoxWithOverline(ansi_term::Style), BoxWithUnderOverline(ansi_term::Style), #[default] NoDecoration, } impl Style { pub fn new() -> Self { Self { ansi_term_style: ansi_term::Style::new(), is_emph: false, is_omitted: false, is_raw: false, is_syntax_highlighted: false, decoration_style: DecorationStyle::NoDecoration, } } pub fn from_colors( foreground: Option<ansi_term::Color>, background: Option<ansi_term::Color>, ) -> Self { Self { ansi_term_style: ansi_term::Style { foreground, background, ..ansi_term::Style::new() }, ..Self::new() } } pub fn paint<'a, I, S: 'a + ToOwned + ?Sized>( self, input: I, ) -> ansi_term::ANSIGenericString<'a, S> where I: Into<Cow<'a, S>>, <S as ToOwned>::Owned: fmt::Debug, { self.ansi_term_style.paint(input) } pub fn get_background_color(&self) -> Option<ansi_term::Color> { if self.ansi_term_style.is_reverse { self.ansi_term_style.foreground } else { self.ansi_term_style.background } } pub fn is_applied_to(&self, s: &str) -> bool { match ansi::parse_first_style(s) { Some(parsed_style) => ansi_term_style_equality(parsed_style, self.ansi_term_style), None => false, } } #[cfg(test)] pub fn get_matching_substring<'a>(&self, s: &'a str) -> Option<&'a str> { for (parsed_style, parsed_str) in ansi::parse_style_sections(s) { if ansi_term_style_equality(parsed_style, self.ansi_term_style) { return Some(parsed_str); } } None } pub fn to_painted_string(self) -> ansi_term::ANSIGenericString<'static, str> { self.paint(self.to_string()) } } /// Interpret `color_string` as a color specifier and return it painted accordingly. pub fn paint_color_string<'a>( color_string: &'a str, true_color: bool, git_config: Option<&GitConfig>, ) -> ansi_term::ANSIGenericString<'a, str> { if let Some(color) = color::parse_color(color_string, true_color, git_config) { let style = ansi_term::Style { background: Some(color), ..ansi_term::Style::default() }; style.paint(color_string) } else { ansi_term::ANSIGenericString::from(color_string) } } impl fmt::Display for Style { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.is_raw { return write!(f, "raw"); } let mut words = Vec::<String>::new(); if self.is_omitted { words.push("omit".to_string()); } if self.ansi_term_style.is_blink { words.push("blink".to_string()); } if self.ansi_term_style.is_bold { words.push("bold".to_string()); } if self.ansi_term_style.is_dimmed { words.push("dim".to_string()); } if self.ansi_term_style.is_italic { words.push("italic".to_string()); } if self.ansi_term_style.is_reverse { words.push("reverse".to_string()); } if self.ansi_term_style.is_strikethrough { words.push("strike".to_string()); } if self.ansi_term_style.is_underline { words.push("ul".to_string()); } match (self.is_syntax_highlighted, self.ansi_term_style.foreground) { (true, _) => words.push("syntax".to_string()), (false, Some(color)) => { words.push(color::color_to_string(color)); } (false, None) => words.push("normal".to_string()), } if let Some(color) = self.ansi_term_style.background { words.push(color::color_to_string(color)) } let style_str = words.join(" "); write!(f, "{style_str}") } } pub fn ansi_term_style_equality(a: ansi_term::Style, b: ansi_term::Style) -> bool { let a_attrs = ansi_term::Style { foreground: None, background: None, ..a }; let b_attrs = ansi_term::Style { foreground: None, background: None, ..b }; if a_attrs != b_attrs { false } else { ansi_term_color_equality(a.foreground, b.foreground) & ansi_term_color_equality(a.background, b.background) } } // TODO: The equality methods were implemented first, and the equality_key // methods later. The former should be re-implemented in terms of the latter. // But why did the former not address equality of ansi_term::Color::RGB values? #[derive(Clone)] pub struct AnsiTermStyleEqualityKey { attrs_key: (bool, bool, bool, bool, bool, bool, bool, bool), foreground_key: Option<(u8, u8, u8, u8)>, background_key: Option<(u8, u8, u8, u8)>, } impl PartialEq for AnsiTermStyleEqualityKey { fn eq(&self, other: &Self) -> bool { let option_eq = |opt_a, opt_b| match (opt_a, opt_b) { (Some(a), Some(b)) => a == b, (None, None) => true, _ => false, }; if self.attrs_key != other.attrs_key { false } else { option_eq(self.foreground_key, other.foreground_key) && option_eq(self.background_key, other.background_key) } } } impl Eq for AnsiTermStyleEqualityKey {} impl Hash for AnsiTermStyleEqualityKey { fn hash<H: Hasher>(&self, state: &mut H) { self.attrs_key.hash(state); self.foreground_key.hash(state); self.background_key.hash(state); } } pub fn ansi_term_style_equality_key(style: ansi_term::Style) -> AnsiTermStyleEqualityKey { let attrs_key = ( style.is_bold, style.is_dimmed, style.is_italic, style.is_underline, style.is_blink, style.is_reverse, style.is_hidden, style.is_strikethrough, ); AnsiTermStyleEqualityKey { attrs_key, foreground_key: style.foreground.map(ansi_term_color_equality_key), background_key: style.background.map(ansi_term_color_equality_key), } } impl fmt::Debug for AnsiTermStyleEqualityKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let is_set = |c: char, set: bool| -> String { if set { c.to_uppercase().to_string() } else { c.to_lowercase().to_string() } }; let (bold, dimmed, italic, underline, blink, reverse, hidden, strikethrough) = self.attrs_key; write!( f, "ansi_term::Style {{ {:?} {:?} {}{}{}{}{}{}{}{} }}", self.foreground_key, self.background_key, is_set('b', bold), is_set('d', dimmed), is_set('i', italic), is_set('u', underline), is_set('l', blink), is_set('r', reverse), is_set('h', hidden), is_set('s', strikethrough), ) } } fn ansi_term_color_equality(a: Option<ansi_term::Color>, b: Option<ansi_term::Color>) -> bool { match a.zip(b) { Some((a, b)) => { a == b || ansi_term_16_color_equality(a, b) || ansi_term_16_color_equality(b, a) } None => a.is_none() && b.is_none(), } } fn ansi_term_16_color_equality(a: ansi_term::Color, b: ansi_term::Color) -> bool { matches!( (a, b), (ansi_term::Color::Fixed(0), ansi_term::Color::Black) | (ansi_term::Color::Fixed(1), ansi_term::Color::Red) | (ansi_term::Color::Fixed(2), ansi_term::Color::Green) | (ansi_term::Color::Fixed(3), ansi_term::Color::Yellow) | (ansi_term::Color::Fixed(4), ansi_term::Color::Blue) | (ansi_term::Color::Fixed(5), ansi_term::Color::Purple) | (ansi_term::Color::Fixed(6), ansi_term::Color::Cyan) | (ansi_term::Color::Fixed(7), ansi_term::Color::White) ) } fn ansi_term_color_equality_key(color: ansi_term::Color) -> (u8, u8, u8, u8) { // Same (r, g, b, a) encoding as in utils::bat::terminal::to_ansi_color. // When a = 0xFF, then a 256-color number is stored in the red channel, and // the green and blue channels are meaningless. But a=0 signifies an RGB // color. let default = 0xFF; match color { ansi_term::Color::Fixed(0) | ansi_term::Color::Black => (0, default, default, default), ansi_term::Color::Fixed(1) | ansi_term::Color::Red => (1, default, default, default), ansi_term::Color::Fixed(2) | ansi_term::Color::Green => (2, default, default, default), ansi_term::Color::Fixed(3) | ansi_term::Color::Yellow => (3, default, default, default), ansi_term::Color::Fixed(4) | ansi_term::Color::Blue => (4, default, default, default), ansi_term::Color::Fixed(5) | ansi_term::Color::Purple => (5, default, default, default), ansi_term::Color::Fixed(6) | ansi_term::Color::Cyan => (6, default, default, default), ansi_term::Color::Fixed(7) | ansi_term::Color::White => (7, default, default, default), ansi_term::Color::Fixed(n) => (n, default, default, default), ansi_term::Color::RGB(r, g, b) => (r, g, b, 0), } } lazy_static! { pub static ref GIT_DEFAULT_MINUS_STYLE: Style = Style { ansi_term_style: ansi_term::Color::Red.normal(), ..Style::new() }; pub static ref GIT_DEFAULT_PLUS_STYLE: Style = Style { ansi_term_style: ansi_term::Color::Green.normal(), ..Style::new() }; } pub fn line_has_style_other_than(line: &str, styles: &[Style]) -> bool { if !ansi::string_starts_with_ansi_style_sequence(line) { return false; } for style in styles { if style.is_applied_to(line) { return false; } } true } #[cfg(test)] pub mod tests { use super::*; // To add to these tests: // 1. Stage a file with a single line containing the string "text" // 2. git -c 'color.diff.new = $STYLE_STRING' diff --cached --color=always | cat -A lazy_static! { pub static ref GIT_STYLE_STRING_EXAMPLES: Vec<(&'static str, &'static str)> = vec![ // <git-default> "\x1b[32m+\x1b[m\x1b[32mtext\x1b[m\n" ("0", "\x1b[30m+\x1b[m\x1b[30mtext\x1b[m\n"), ("black", "\x1b[30m+\x1b[m\x1b[30mtext\x1b[m\n"), ("1", "\x1b[31m+\x1b[m\x1b[31mtext\x1b[m\n"), ("red", "\x1b[31m+\x1b[m\x1b[31mtext\x1b[m\n"), ("0 1", "\x1b[30;41m+\x1b[m\x1b[30;41mtext\x1b[m\n"), ("black red", "\x1b[30;41m+\x1b[m\x1b[30;41mtext\x1b[m\n"), ("19", "\x1b[38;5;19m+\x1b[m\x1b[38;5;19mtext\x1b[m\n"), ("black 19", "\x1b[30;48;5;19m+\x1b[m\x1b[30;48;5;19mtext\x1b[m\n"), ("19 black", "\x1b[38;5;19;40m+\x1b[m\x1b[38;5;19;40mtext\x1b[m\n"), ("19 20", "\x1b[38;5;19;48;5;20m+\x1b[m\x1b[38;5;19;48;5;20mtext\x1b[m\n"), ("#aabbcc", "\x1b[38;2;170;187;204m+\x1b[m\x1b[38;2;170;187;204mtext\x1b[m\n"), ("0 #aabbcc", "\x1b[30;48;2;170;187;204m+\x1b[m\x1b[30;48;2;170;187;204mtext\x1b[m\n"), ("#aabbcc 0", "\x1b[38;2;170;187;204;40m+\x1b[m\x1b[38;2;170;187;204;40mtext\x1b[m\n"), ("19 #aabbcc", "\x1b[38;5;19;48;2;170;187;204m+\x1b[m\x1b[38;5;19;48;2;170;187;204mtext\x1b[m\n"), ("#aabbcc 19", "\x1b[38;2;170;187;204;48;5;19m+\x1b[m\x1b[38;2;170;187;204;48;5;19mtext\x1b[m\n"), ("#aabbcc #ddeeff" , "\x1b[38;2;170;187;204;48;2;221;238;255m+\x1b[m\x1b[38;2;170;187;204;48;2;221;238;255mtext\x1b[m\n"), ("bold #aabbcc #ddeeff" , "\x1b[1;38;2;170;187;204;48;2;221;238;255m+\x1b[m\x1b[1;38;2;170;187;204;48;2;221;238;255mtext\x1b[m\n"), ("bold #aabbcc ul #ddeeff" , "\x1b[1;4;38;2;170;187;204;48;2;221;238;255m+\x1b[m\x1b[1;4;38;2;170;187;204;48;2;221;238;255mtext\x1b[m\n"), ("bold #aabbcc ul #ddeeff strike" , "\x1b[1;4;9;38;2;170;187;204;48;2;221;238;255m+\x1b[m\x1b[1;4;9;38;2;170;187;204;48;2;221;238;255mtext\x1b[m\n"), ("bold 0 ul 1 strike", "\x1b[1;4;9;30;41m+\x1b[m\x1b[1;4;9;30;41mtext\x1b[m\n"), ("bold 0 ul 19 strike", "\x1b[1;4;9;30;48;5;19m+\x1b[m\x1b[1;4;9;30;48;5;19mtext\x1b[m\n"), ("bold 19 ul 0 strike", "\x1b[1;4;9;38;5;19;40m+\x1b[m\x1b[1;4;9;38;5;19;40mtext\x1b[m\n"), ("bold #aabbcc ul 0 strike", "\x1b[1;4;9;38;2;170;187;204;40m+\x1b[m\x1b[1;4;9;38;2;170;187;204;40mtext\x1b[m\n"), ("bold #aabbcc ul 19 strike" , "\x1b[1;4;9;38;2;170;187;204;48;5;19m+\x1b[m\x1b[1;4;9;38;2;170;187;204;48;5;19mtext\x1b[m\n"), ("bold 19 ul #aabbcc strike" , "\x1b[1;4;9;38;5;19;48;2;170;187;204m+\x1b[m\x1b[1;4;9;38;5;19;48;2;170;187;204mtext\x1b[m\n"), ("bold 0 ul #aabbcc strike", "\x1b[1;4;9;30;48;2;170;187;204m+\x1b[m\x1b[1;4;9;30;48;2;170;187;204mtext\x1b[m\n"), (r##"black "#ddeeff""##, "\x1b[30;48;2;221;238;255m+\x1b[m\x1b[30;48;2;221;238;255mtext\x1b[m\n"), ("brightred", "\x1b[91m+\x1b[m\x1b[91mtext\x1b[m\n"), ("normal", "\x1b[mtext\x1b[m\n"), ("blink", "\x1b[5m+\x1b[m\x1b[5mtext\x1b[m\n"), ]; } #[test] fn test_parse_git_style_string_and_ansi_code_iterator() { for (git_style_string, git_output) in &*GIT_STYLE_STRING_EXAMPLES { assert!(Style::from_git_str(git_style_string).is_applied_to(git_output)); } } #[test] fn test_is_applied_to_negative_assertion() { let style_string_from_24 = "bold #aabbcc ul 19 strike"; let git_output_from_25 = "\x1b[1;4;9;38;5;19;48;2;170;187;204m+\x1b[m\x1b[1;4;9;38;5;19;48;2;170;187;204mtext\x1b[m\n"; assert!(!Style::from_git_str(style_string_from_24).is_applied_to(git_output_from_25)); } #[test] fn test_git_default_styles() { let minus_line_from_unconfigured_git = "\x1b[31m-____\x1b[m\n"; let plus_line_from_unconfigured_git = "\x1b[32m+\x1b[m\x1b[32m____\x1b[m\n"; assert!(GIT_DEFAULT_MINUS_STYLE.is_applied_to(minus_line_from_unconfigured_git)); assert!(!GIT_DEFAULT_MINUS_STYLE.is_applied_to(plus_line_from_unconfigured_git)); assert!(GIT_DEFAULT_PLUS_STYLE.is_applied_to(plus_line_from_unconfigured_git)); assert!(!GIT_DEFAULT_PLUS_STYLE.is_applied_to(minus_line_from_unconfigured_git)); } #[test] fn test_line_has_style_other_than() { let minus_line_from_unconfigured_git = "\x1b[31m-____\x1b[m\n"; let plus_line_from_unconfigured_git = "\x1b[32m+\x1b[m\x1b[32m____\x1b[m\n"; // Unstyled lines should test negative, regardless of supplied styles. assert!(!line_has_style_other_than("", &[])); assert!(!line_has_style_other_than("", &[*GIT_DEFAULT_MINUS_STYLE])); // Lines from git should test negative when corresponding default is supplied assert!(!line_has_style_other_than( minus_line_from_unconfigured_git, &[*GIT_DEFAULT_MINUS_STYLE] )); assert!(!line_has_style_other_than( plus_line_from_unconfigured_git, &[*GIT_DEFAULT_PLUS_STYLE] )); // Styled lines should test positive when unless their style is supplied. assert!(line_has_style_other_than( minus_line_from_unconfigured_git, &[*GIT_DEFAULT_PLUS_STYLE] )); assert!(line_has_style_other_than( minus_line_from_unconfigured_git, &[] )); assert!(line_has_style_other_than( plus_line_from_unconfigured_git, &[*GIT_DEFAULT_MINUS_STYLE] )); assert!(line_has_style_other_than( plus_line_from_unconfigured_git, &[] )); } #[test] fn test_style_compact_debug_fmt() { let mut s = Style::new(); assert_eq!(format!("{s:?}"), "Style { <aeorsd> }"); s.is_emph = true; assert_eq!(format!("{s:?}"), "Style { <aEorsd> }"); s.ansi_term_style = ansi_term::Style::new().bold(); assert_eq!( format!("{s:?}"), "Style { ansi_term_style: Style { bold }, <Eorsd> }" ); s.decoration_style = DecorationStyle::Underline(s.ansi_term_style); assert_eq!( format!("{s:?}"), "Style { ansi_term_style: Style { bold }, <Eors>, \ decoration_style: Underline(Style { bold }) }" ); s.ansi_term_style = ansi_term::Style::default(); assert_eq!( format!("{s:?}"), "Style { <aEors>, decoration_style: Underline(Style { bold }) }" ); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/main.rs
src/main.rs
mod align; mod ansi; mod cli; mod color; mod colors; mod config; mod delta; mod edits; mod env; mod features; mod format; mod git_config; mod handlers; mod minusplus; mod options; mod paint; mod parse_style; mod parse_styles; mod style; mod utils; mod wrapping; mod subcommands; mod tests; use std::ffi::{OsStr, OsString}; use std::io::{self, BufRead, Cursor, ErrorKind, IsTerminal, Write}; use std::process::{self, Command, Stdio}; use bytelines::ByteLinesReader; use crate::cli::Call; use crate::config::delta_unreachable; use crate::delta::delta; use crate::subcommands::{SubCmdKind, SubCommand}; use crate::utils::bat::assets::list_languages; use crate::utils::bat::output::{OutputType, PagingMode}; pub fn fatal<T>(errmsg: T) -> ! where T: AsRef<str> + std::fmt::Display, { #[cfg(not(test))] { eprintln!("{errmsg}"); // As in Config::error_exit_code: use 2 for error // because diff uses 0 and 1 for non-error. process::exit(2); } #[cfg(test)] panic!("{}\n", errmsg); } pub mod errors { pub use anyhow::{anyhow, Context, Error, Result}; } #[cfg(not(tarpaulin_include))] fn main() -> std::io::Result<()> { // Do this first because both parsing all the input in `run_app()` and // listing all processes takes about 50ms on Linux. // It also improves the chance that the calling process is still around when // input is piped into delta (e.g. `git show --word-diff=color | delta`). utils::process::start_determining_calling_process_in_thread(); // Ignore ctrl-c (SIGINT) to avoid leaving an orphaned pager process. // See https://github.com/dandavison/delta/issues/681 ctrlc::set_handler(|| {}) .unwrap_or_else(|err| eprintln!("Failed to set ctrl-c handler: {err}")); let exit_code = run_app(std::env::args_os().collect::<Vec<_>>(), None)?; // when you call process::exit, no drop impls are called, so we want to do it only once, here process::exit(exit_code); } #[cfg(not(tarpaulin_include))] // An Ok result contains the desired process exit code. Note that 1 is used to // report that two files differ when delta is called with two positional // arguments and without standard input; 2 is used to report a real problem. pub fn run_app( args: Vec<OsString>, capture_output: Option<&mut Cursor<Vec<u8>>>, ) -> std::io::Result<i32> { let env = env::DeltaEnv::init(); let assets = utils::bat::assets::load_highlighting_assets(); let (call, opt) = cli::Opt::from_args_and_git_config(args, &env, assets); if let Call::Version(msg) = call { writeln!(std::io::stdout(), "{}", msg.trim_end())?; return Ok(0); } else if let Call::Help(msg) = call { OutputType::oneshot_write(msg)?; return Ok(0); } else if let Call::SubCommand(_, cmd) = &call { // Set before creating the Config, which already asks for the calling process // (not required for Call::DeltaDiff) utils::process::set_calling_process( &cmd.args .iter() .map(|arg| OsStr::to_string_lossy(arg).to_string()) .collect::<Vec<_>>(), ); } let opt = opt.unwrap_or_else(|| delta_unreachable("Opt is set")); let subcommand_result = if let Some(shell) = opt.generate_completion { Some(subcommands::generate_completion::generate_completion_file( shell, )) } else if opt.list_languages { Some(list_languages()) } else if opt.list_syntax_themes { Some(subcommands::list_syntax_themes::list_syntax_themes()) } else if opt.show_syntax_themes { Some(subcommands::show_syntax_themes::show_syntax_themes()) } else if opt.show_themes { Some(subcommands::show_themes::show_themes( opt.dark, opt.light, opt.computed.color_mode, )) } else if opt.show_colors { Some(subcommands::show_colors::show_colors()) } else if opt.parse_ansi { Some(subcommands::parse_ansi::parse_ansi()) } else { None }; if let Some(result) = subcommand_result { if let Err(error) = result { match error.kind() { ErrorKind::BrokenPipe => {} _ => fatal(format!("{error}")), } } return Ok(0); }; let _show_config = opt.show_config; let config = config::Config::from(opt); if _show_config { let stdout = io::stdout(); let mut stdout = stdout.lock(); subcommands::show_config::show_config(&config, &mut stdout)?; return Ok(0); } // The following block structure is because of `writer` and related lifetimes: let pager_cfg = (&config).into(); let paging_mode = if capture_output.is_some() { PagingMode::Capture } else { config.paging_mode }; let mut output_type = OutputType::from_mode(&env, paging_mode, config.pager.clone(), &pager_cfg).unwrap(); let mut writer: &mut dyn Write = if paging_mode == PagingMode::Capture { &mut capture_output.unwrap() } else { output_type.handle().unwrap() }; let subcmd = match call { Call::DeltaDiff(_, minus, plus) => { match subcommands::diff::build_diff_cmd(&minus, &plus, &config) { Err(code) => return Ok(code), Ok(val) => val, } } Call::SubCommand(_, subcmd) => subcmd, Call::Delta(_) => SubCommand::none(), Call::Help(_) | Call::Version(_) => delta_unreachable("help/version handled earlier"), }; if subcmd.is_none() { // Default delta run: read input from stdin, write to stdout or pager (pager started already^). if io::stdin().is_terminal() { eprintln!( "\ The main way to use delta is to configure it as the pager for git: \ see https://github.com/dandavison/delta#get-started. \ You can also use delta to diff two files: `delta file_A file_B`." ); return Ok(config.error_exit_code); } let res = delta(io::stdin().lock().byte_lines(), &mut writer, &config); if let Err(error) = res { match error.kind() { ErrorKind::BrokenPipe => return Ok(0), _ => { eprintln!("{error}"); return Ok(config.error_exit_code); } } } Ok(0) } else { // First start a subcommand, and pipe input from it to delta(). Also handle // subcommand exit code and stderr (maybe truncate it, e.g. for git and diff logic). let (subcmd_bin, subcmd_args) = subcmd.args.split_first().unwrap(); let subcmd_kind = subcmd.kind; // for easier {} formatting let subcmd_bin_path = match grep_cli::resolve_binary(std::path::PathBuf::from(subcmd_bin)) { Ok(path) => path, Err(err) => { eprintln!("Failed to resolve command {subcmd_bin:?}: {err}"); return Ok(config.error_exit_code); } }; let cmd = Command::new(subcmd_bin) .args(subcmd_args.iter()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn(); if let Err(err) = cmd { eprintln!("Failed to execute the command {subcmd_bin:?}: {err}"); return Ok(config.error_exit_code); } let mut cmd = cmd.unwrap(); let cmd_stdout = cmd .stdout .take() .unwrap_or_else(|| panic!("Failed to open stdout")); let cmd_stdout_buf = io::BufReader::new(cmd_stdout); let res = delta(cmd_stdout_buf.byte_lines(), &mut writer, &config); if let Err(error) = res { let _ = cmd.wait(); // for clippy::zombie_processes match error.kind() { ErrorKind::BrokenPipe => return Ok(0), _ => { eprintln!("{error}"); return Ok(config.error_exit_code); } } }; let subcmd_status = cmd .wait() .unwrap_or_else(|_| { delta_unreachable(&format!("{subcmd_kind:?} process not running.")); }) .code() .unwrap_or_else(|| { eprintln!("delta: {subcmd_kind:?} process terminated without exit status."); config.error_exit_code }); let mut stderr_lines = io::BufReader::new( cmd.stderr .unwrap_or_else(|| panic!("Failed to open stderr")), ) .lines(); if let Some(line1) = stderr_lines.next() { // prefix the first error line with the called subcommand eprintln!( "{}: {}", subcmd_kind, line1.unwrap_or("<delta: could not parse stderr line>".into()) ); } // On `git diff` unknown option error: stop after printing the first line above (which is // an error message), because the entire --help text follows. if !(subcmd_status == 129 && matches!(subcmd_kind, SubCmdKind::GitDiff | SubCmdKind::Git(_))) { for line in stderr_lines { eprintln!( "{}", line.unwrap_or("<delta: could not parse stderr line>".into()) ); } } if matches!(subcmd_kind, SubCmdKind::GitDiff | SubCmdKind::Diff) && subcmd_status >= 2 { eprintln!( "{subcmd_kind:?} process failed with exit status {subcmd_status}. Command was: {}", format_args!( "{} {}", subcmd_bin_path.display(), shell_words::join( subcmd_args .iter() .map(|arg0: &OsString| std::ffi::OsStr::to_string_lossy(arg0)) ), ) ); } Ok(subcmd_status) } // `output_type` drop impl runs here }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/colors.rs
src/colors.rs
pub fn color_groups() -> Vec<(&'static str, Vec<(&'static str, &'static str)>)> { vec![ ( "Blue", vec![ ("cadetblue", "#5f9ea0"), ("steelblue", "#4682b4"), ("lightsteelblue", "#b0c4de"), ("lightblue", "#add8e6"), ("powderblue", "#b0e0e6"), ("lightskyblue", "#87cefa"), ("skyblue", "#87ceeb"), ("cornflowerblue", "#6495ed"), ("deepskyblue", "#00bfff"), ("dodgerblue", "#1e90ff"), ("royalblue", "#4169e1"), ("blue", "#0000ff"), ("mediumblue", "#0000cd"), ("darkblue", "#00008b"), ("navy", "#000080"), ("midnightblue", "#191970"), ], ), ( "Brown", vec![ ("cornsilk", "#fff8dc"), ("blanchedalmond", "#ffebcd"), ("bisque", "#ffe4c4"), ("navajowhite", "#ffdead"), ("wheat", "#f5deb3"), ("burlywood", "#deb887"), ("tan", "#d2b48c"), ("rosybrown", "#bc8f8f"), ("sandybrown", "#f4a460"), ("goldenrod", "#daa520"), ("darkgoldenrod", "#b8860b"), ("peru", "#cd853f"), ("chocolate", "#d2691e"), ("olive", "#808000"), ("saddlebrown", "#8b4513"), ("sienna", "#a0522d"), ("brown", "#a52a2a"), ("maroon", "#800000"), ], ), ( "Cyan", vec![ ("aqua", "#00ffff"), ("cyan", "#00ffff"), ("lightcyan", "#e0ffff"), ("paleturquoise", "#afeeee"), ("aquamarine", "#7fffd4"), ("turquoise", "#40e0d0"), ("mediumturquoise", "#48d1cc"), ("darkturquoise", "#00ced1"), ], ), ( "Green", vec![ ("greenyellow", "#adff2f"), ("chartreuse", "#7fff00"), ("lawngreen", "#7cfc00"), ("lime", "#00ff00"), ("limegreen", "#32cd32"), ("palegreen", "#98fb98"), ("lightgreen", "#90ee90"), ("mediumspringgreen", "#00fa9a"), ("springgreen", "#00ff7f"), ("mediumseagreen", "#3cb371"), ("seagreen", "#2e8b57"), ("forestgreen", "#228b22"), ("green", "#008000"), ("darkgreen", "#006400"), ("yellowgreen", "#9acd32"), ("olivedrab", "#6b8e23"), ("darkolivegreen", "#556b2f"), ("mediumaquamarine", "#66cdaa"), ("darkseagreen", "#8fbc8f"), ("lightseagreen", "#20b2aa"), ("darkcyan", "#008b8b"), ("teal", "#008080"), ], ), ( "Grey", vec![ ("gainsboro", "#dcdcdc"), ("lightgray", "#d3d3d3"), ("silver", "#c0c0c0"), ("darkgray", "#a9a9a9"), ("dimgray", "#696969"), ("gray", "#808080"), ("lightslategray", "#778899"), ("slategray", "#708090"), ("darkslategray", "#2f4f4f"), ("black", "#000000"), ], ), ( "Orange", vec![ ("orange", "#ffa500"), ("darkorange", "#ff8c00"), ("coral", "#ff7f50"), ("tomato", "#ff6347"), ("orangered", "#ff4500"), ], ), ( "Pink", vec![ ("pink", "#ffc0cb"), ("lightpink", "#ffb6c1"), ("hotpink", "#ff69b4"), ("deeppink", "#ff1493"), ("palevioletred", "#db7093"), ("mediumvioletred", "#c71585"), ], ), ( "Purple", vec![ ("lavender", "#e6e6fa"), ("thistle", "#d8bfd8"), ("plum", "#dda0dd"), ("orchid", "#da70d6"), ("violet", "#ee82ee"), ("fuchsia", "#ff00ff"), ("magenta", "#ff00ff"), ("mediumorchid", "#ba55d3"), ("darkorchid", "#9932cc"), ("darkviolet", "#9400d3"), ("blueviolet", "#8a2be2"), ("darkmagenta", "#8b008b"), ("purple", "#800080"), ("mediumpurple", "#9370db"), ("mediumslateblue", "#7b68ee"), ("slateblue", "#6a5acd"), ("darkslateblue", "#483d8b"), ("rebeccapurple", "#663399"), ("indigo", "#4b0082"), ], ), ( "Red", vec![ ("lightsalmon", "#ffa07a"), ("salmon", "#fa8072"), ("darksalmon", "#e9967a"), ("lightcoral", "#f08080"), ("indianred", "#cd5c5c"), ("crimson", "#dc143c"), ("red", "#ff0000"), ("firebrick", "#b22222"), ("darkred", "#8b0000"), ], ), ( "White", vec![ ("white", "#ffffff"), ("snow", "#fffafa"), ("honeydew", "#f0fff0"), ("mintcream", "#f5fffa"), ("azure", "#f0ffff"), ("aliceblue", "#f0f8ff"), ("ghostwhite", "#f8f8ff"), ("whitesmoke", "#f5f5f5"), ("seashell", "#fff5ee"), ("beige", "#f5f5dc"), ("oldlace", "#fdf5e6"), ("floralwhite", "#fffaf0"), ("ivory", "#fffff0"), ("antiquewhite", "#faebd7"), ("linen", "#faf0e6"), ("lavenderblush", "#fff0f5"), ("mistyrose", "#ffe4e1"), ], ), ( "Yellow", vec![ ("gold", "#ffd700"), ("yellow", "#ffff00"), ("lightyellow", "#ffffe0"), ("lemonchiffon", "#fffacd"), ("lightgoldenrodyellow", "#fafad2"), ("papayawhip", "#ffefd5"), ("moccasin", "#ffe4b5"), ("peachpuff", "#ffdab9"), ("palegoldenrod", "#eee8aa"), ("khaki", "#f0e68c"), ("darkkhaki", "#bdb76b"), ], ), ] }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/color.rs
src/color.rs
use std::collections::HashMap; use std::str::FromStr; use ansi_term::Color; use lazy_static::lazy_static; use syntect::highlighting::Color as SyntectColor; use crate::fatal; use crate::git_config::GitConfig; use crate::utils; use ColorMode::*; pub fn parse_color(s: &str, true_color: bool, git_config: Option<&GitConfig>) -> Option<Color> { if s == "normal" { return None; } let die = || { fatal(format!("Invalid color or style attribute: {s}")); }; let syntect_color = if s.starts_with('#') { SyntectColor::from_str(s).unwrap_or_else(|_| die()) } else { let syntect_color = s .parse::<u8>() .ok() .and_then(utils::syntect::syntect_color_from_ansi_number) .or_else(|| utils::syntect::syntect_color_from_ansi_name(s)) .or_else(|| utils::syntect::syntect_color_from_name(s)); if syntect_color.is_none() { if let Some(git_config) = git_config { if let Some(val) = git_config.get::<String>(&format!("delta.{s}")) { return parse_color(&val, true_color, None); } } die(); } syntect_color.unwrap() }; utils::bat::terminal::to_ansi_color(syntect_color, true_color) } pub fn color_to_string(color: Color) -> String { match color { Color::Fixed(n) if n < 16 => ansi_16_color_number_to_name(n).unwrap().to_string(), Color::Fixed(n) => format!("{n}"), Color::RGB(r, g, b) => format!("\"#{r:02x?}{g:02x?}{b:02x?}\""), Color::Black => "black".to_string(), Color::Red => "red".to_string(), Color::Green => "green".to_string(), Color::Yellow => "yellow".to_string(), Color::Blue => "blue".to_string(), Color::Purple => "purple".to_string(), Color::Cyan => "cyan".to_string(), Color::White => "white".to_string(), } } // See // https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit lazy_static! { static ref ANSI_16_COLORS: HashMap<&'static str, u8> = { vec![ ("black", 0), ("red", 1), ("green", 2), ("yellow", 3), ("blue", 4), ("magenta", 5), ("purple", 5), ("cyan", 6), ("white", 7), ("bright-black", 8), ("brightblack", 8), ("bright-red", 9), ("brightred", 9), ("bright-green", 10), ("brightgreen", 10), ("bright-yellow", 11), ("brightyellow", 11), ("bright-blue", 12), ("brightblue", 12), ("bright-magenta", 13), ("brightmagenta", 13), ("bright-purple", 13), ("brightpurple", 13), ("bright-cyan", 14), ("brightcyan", 14), ("bright-white", 15), ("brightwhite", 15), ] .into_iter() .collect() }; } pub fn ansi_16_color_name_to_number(name: &str) -> Option<u8> { ANSI_16_COLORS.get(name).copied() } fn ansi_16_color_number_to_name(n: u8) -> Option<&'static str> { for (k, _n) in &*ANSI_16_COLORS { if *_n == n { return Some(*k); } } None } /// The color mode determines some default color choices /// such as the diff background color or the palette used for blame. #[derive(Default, Clone, Copy, Debug, PartialEq, Eq)] pub enum ColorMode { #[default] /// Dark background with light text. Dark, /// Light background with dark text. Light, } pub fn get_minus_background_color_default(mode: ColorMode, is_true_color: bool) -> Color { match (mode, is_true_color) { (Light, true) => LIGHT_THEME_MINUS_COLOR, (Light, false) => LIGHT_THEME_MINUS_COLOR_256, (Dark, true) => DARK_THEME_MINUS_COLOR, (Dark, false) => DARK_THEME_MINUS_COLOR_256, } } pub fn get_minus_emph_background_color_default(mode: ColorMode, is_true_color: bool) -> Color { match (mode, is_true_color) { (Light, true) => LIGHT_THEME_MINUS_EMPH_COLOR, (Light, false) => LIGHT_THEME_MINUS_EMPH_COLOR_256, (Dark, true) => DARK_THEME_MINUS_EMPH_COLOR, (Dark, false) => DARK_THEME_MINUS_EMPH_COLOR_256, } } pub fn get_plus_background_color_default(mode: ColorMode, is_true_color: bool) -> Color { match (mode, is_true_color) { (Light, true) => LIGHT_THEME_PLUS_COLOR, (Light, false) => LIGHT_THEME_PLUS_COLOR_256, (Dark, true) => DARK_THEME_PLUS_COLOR, (Dark, false) => DARK_THEME_PLUS_COLOR_256, } } pub fn get_plus_emph_background_color_default(mode: ColorMode, is_true_color: bool) -> Color { match (mode, is_true_color) { (Light, true) => LIGHT_THEME_PLUS_EMPH_COLOR, (Light, false) => LIGHT_THEME_PLUS_EMPH_COLOR_256, (Dark, true) => DARK_THEME_PLUS_EMPH_COLOR, (Dark, false) => DARK_THEME_PLUS_EMPH_COLOR_256, } } const LIGHT_THEME_MINUS_COLOR: Color = Color::RGB(0xff, 0xe0, 0xe0); const LIGHT_THEME_MINUS_COLOR_256: Color = Color::Fixed(224); const LIGHT_THEME_MINUS_EMPH_COLOR: Color = Color::RGB(0xff, 0xc0, 0xc0); const LIGHT_THEME_MINUS_EMPH_COLOR_256: Color = Color::Fixed(217); const LIGHT_THEME_PLUS_COLOR: Color = Color::RGB(0xd0, 0xff, 0xd0); const LIGHT_THEME_PLUS_COLOR_256: Color = Color::Fixed(194); const LIGHT_THEME_PLUS_EMPH_COLOR: Color = Color::RGB(0xa0, 0xef, 0xa0); const LIGHT_THEME_PLUS_EMPH_COLOR_256: Color = Color::Fixed(157); const DARK_THEME_MINUS_COLOR: Color = Color::RGB(0x3f, 0x00, 0x01); const DARK_THEME_MINUS_COLOR_256: Color = Color::Fixed(52); const DARK_THEME_MINUS_EMPH_COLOR: Color = Color::RGB(0x90, 0x10, 0x11); const DARK_THEME_MINUS_EMPH_COLOR_256: Color = Color::Fixed(124); const DARK_THEME_PLUS_COLOR: Color = Color::RGB(0x00, 0x28, 0x00); const DARK_THEME_PLUS_COLOR_256: Color = Color::Fixed(22); const DARK_THEME_PLUS_EMPH_COLOR: Color = Color::RGB(0x00, 0x60, 0x00); const DARK_THEME_PLUS_EMPH_COLOR_256: Color = Color::Fixed(28); // blame pub const LIGHT_THEME_BLAME_PALETTE: &[&str] = &["#FFFFFF", "#DDDDDD", "#BBBBBB"]; pub const DARK_THEME_BLAME_PALETTE: &[&str] = &["#000000", "#222222", "#444444"];
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/options/theme.rs
src/options/theme.rs
//! Delta doesn't have a formal concept of a "theme". What it has is //! //! 1. The choice of "theme". This is the language syntax highlighting theme; you have to make this //! choice when using `bat` also. //! 2. The choice of "light vs dark mode". This determines whether the background colors should be //! chosen for a light or dark terminal background. (`bat` has no equivalent.) //! //! Basically: //! 1. The theme is specified by the `--syntax-theme` option. If this isn't supplied then it is specified //! by the `BAT_THEME` environment variable. //! 2. Light vs dark mode is specified by the `--light` or `--dark` options. If these aren't //! supplied then it detected from the terminal. If this fails it is inferred from the chosen theme. //! //! In the absence of other factors, the default assumes a dark terminal background. use std::io::{stdout, IsTerminal}; use bat; use bat::assets::HighlightingAssets; #[cfg(not(test))] use terminal_colorsaurus::{color_scheme, QueryOptions}; use crate::cli::{self, DetectDarkLight}; use crate::color::{ColorMode, ColorMode::*}; #[allow(non_snake_case)] pub fn set__color_mode__syntax_theme__syntax_set(opt: &mut cli::Opt, assets: HighlightingAssets) { let (color_mode, syntax_theme_name) = get_color_mode_and_syntax_theme_name(opt.syntax_theme.as_ref(), get_color_mode(opt)); opt.computed.color_mode = color_mode; opt.computed.syntax_theme = if is_no_syntax_highlighting_syntax_theme_name(&syntax_theme_name) { None } else { Some(assets.get_theme(&syntax_theme_name).clone()) }; opt.computed.syntax_set = assets.get_syntax_set().unwrap().clone(); } pub fn is_light_syntax_theme(theme: &str) -> bool { LIGHT_SYNTAX_THEMES.contains(&theme) || theme.to_lowercase().contains("light") } pub fn color_mode_from_syntax_theme(theme: &str) -> ColorMode { if is_light_syntax_theme(theme) { ColorMode::Light } else { ColorMode::Dark } } const LIGHT_SYNTAX_THEMES: [&str; 7] = [ "Catppuccin Latte", "GitHub", "gruvbox-light", "gruvbox-white", "Monokai Extended Light", "OneHalfLight", "Solarized (light)", ]; const DEFAULT_LIGHT_SYNTAX_THEME: &str = "GitHub"; const DEFAULT_DARK_SYNTAX_THEME: &str = "Monokai Extended"; fn is_no_syntax_highlighting_syntax_theme_name(theme_name: &str) -> bool { theme_name.to_lowercase() == "none" } /// Return a (theme_name, color_mode) tuple. /// theme_name == None in return value means syntax highlighting is disabled. fn get_color_mode_and_syntax_theme_name( syntax_theme: Option<&String>, mode: Option<ColorMode>, ) -> (ColorMode, String) { match (syntax_theme, mode) { (Some(theme), None) => (color_mode_from_syntax_theme(theme), theme.to_string()), (Some(theme), Some(mode)) => (mode, theme.to_string()), (None, None | Some(Dark)) => (Dark, DEFAULT_DARK_SYNTAX_THEME.to_string()), (None, Some(Light)) => (Light, DEFAULT_LIGHT_SYNTAX_THEME.to_string()), } } fn get_color_mode(opt: &cli::Opt) -> Option<ColorMode> { if opt.light { Some(Light) } else if opt.dark { Some(Dark) } else if should_detect_color_mode(opt) { detect_color_mode() } else { None } } /// See [`cli::Opt::detect_dark_light`] for a detailed explanation. fn should_detect_color_mode(opt: &cli::Opt) -> bool { match opt.detect_dark_light { DetectDarkLight::Auto => opt.color_only || stdout().is_terminal(), DetectDarkLight::Always => true, DetectDarkLight::Never => false, } } #[cfg(not(test))] fn detect_color_mode() -> Option<ColorMode> { color_scheme(QueryOptions::default()) .ok() .map(ColorMode::from) } impl From<terminal_colorsaurus::ColorScheme> for ColorMode { fn from(value: terminal_colorsaurus::ColorScheme) -> Self { match value { terminal_colorsaurus::ColorScheme::Dark => ColorMode::Dark, terminal_colorsaurus::ColorScheme::Light => ColorMode::Light, } } } #[cfg(test)] fn detect_color_mode() -> Option<ColorMode> { None } #[cfg(test)] mod tests { use super::*; use crate::color; use crate::tests::integration_test_utils; // TODO: Test influence of BAT_THEME env var. E.g. see utils::process::tests::FakeParentArgs. #[test] fn test_syntax_theme_selection() { for ( syntax_theme, mode, // (--light, --dark) expected_syntax_theme, expected_mode, ) in vec![ (None, None, DEFAULT_DARK_SYNTAX_THEME, Dark), (Some("GitHub"), None, "GitHub", Light), (Some("Nord"), None, "Nord", Dark), (None, Some(Dark), DEFAULT_DARK_SYNTAX_THEME, Dark), (None, Some(Light), DEFAULT_LIGHT_SYNTAX_THEME, Light), (Some("GitHub"), Some(Light), "GitHub", Light), (Some("GitHub"), Some(Dark), "GitHub", Dark), (Some("Nord"), Some(Light), "Nord", Light), (Some("Nord"), Some(Dark), "Nord", Dark), (Some("none"), None, "none", Dark), (Some("none"), Some(Dark), "none", Dark), (Some("None"), Some(Light), "none", Light), ] { let mut args = vec![]; if let Some(syntax_theme) = syntax_theme { args.push("--syntax-theme"); args.push(syntax_theme); } let is_true_color = true; if is_true_color { args.push("--true-color"); args.push("always"); } else { args.push("--true-color"); args.push("never"); } match mode { Some(Light) => { args.push("--light"); } Some(Dark) => { args.push("--dark"); } None => {} } let config = integration_test_utils::make_config_from_args(&args); assert_eq!( &config .syntax_theme .clone() .map(|t| t.name.unwrap()) .unwrap_or("none".to_string()), expected_syntax_theme ); if is_no_syntax_highlighting_syntax_theme_name(expected_syntax_theme) { assert!(config.syntax_theme.is_none()) } else { assert_eq!( config.syntax_theme.unwrap().name.as_ref().unwrap(), expected_syntax_theme ); } assert_eq!( config.minus_style.ansi_term_style.background.unwrap(), color::get_minus_background_color_default(expected_mode, is_true_color) ); assert_eq!( config.minus_emph_style.ansi_term_style.background.unwrap(), color::get_minus_emph_background_color_default(expected_mode, is_true_color) ); assert_eq!( config.plus_style.ansi_term_style.background.unwrap(), color::get_plus_background_color_default(expected_mode, is_true_color) ); assert_eq!( config.plus_emph_style.ansi_term_style.background.unwrap(), color::get_plus_emph_background_color_default(expected_mode, is_true_color) ); } } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/options/option_value.rs
src/options/option_value.rs
use crate::config::delta_unreachable; /// A value associated with a Delta command-line option name. pub enum OptionValue { Boolean(bool), Float(f64), OptionString(Option<String>), String(String), Int(usize), } /// An OptionValue, tagged according to its provenance/semantics. pub enum ProvenancedOptionValue { GitConfigValue(OptionValue), DefaultValue(OptionValue), } impl From<bool> for OptionValue { fn from(value: bool) -> Self { OptionValue::Boolean(value) } } impl From<OptionValue> for bool { fn from(value: OptionValue) -> Self { match value { OptionValue::Boolean(value) => value, _ => delta_unreachable("Error converting OptionValue to bool."), } } } impl From<f64> for OptionValue { fn from(value: f64) -> Self { OptionValue::Float(value) } } impl From<OptionValue> for f64 { fn from(value: OptionValue) -> Self { match value { OptionValue::Float(value) => value, _ => delta_unreachable("Error converting OptionValue to f64."), } } } impl From<Option<String>> for OptionValue { fn from(value: Option<String>) -> Self { OptionValue::OptionString(value) } } impl From<OptionValue> for Option<String> { fn from(value: OptionValue) -> Self { match value { OptionValue::OptionString(value) => value, _ => delta_unreachable("Error converting OptionValue to Option<String>."), } } } impl From<String> for OptionValue { fn from(value: String) -> Self { OptionValue::String(value) } } impl From<&str> for OptionValue { fn from(value: &str) -> Self { value.to_string().into() } } impl From<OptionValue> for String { fn from(value: OptionValue) -> Self { match value { OptionValue::String(value) => value, _ => delta_unreachable("Error converting OptionValue to String."), } } } impl From<usize> for OptionValue { fn from(value: usize) -> Self { OptionValue::Int(value) } } impl From<OptionValue> for usize { fn from(value: OptionValue) -> Self { match value { OptionValue::Int(value) => value, _ => delta_unreachable("Error converting OptionValue to usize."), } } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/options/mod.rs
src/options/mod.rs
pub mod get; pub mod option_value; pub mod set; pub mod theme;
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/options/set.rs
src/options/set.rs
use std::collections::{HashMap, HashSet, VecDeque}; use std::convert::TryInto; use std::result::Result; use std::str::FromStr; use bat::assets::HighlightingAssets; use console::Term; use crate::cli; use crate::config; use crate::env::DeltaEnv; use crate::errors::*; use crate::fatal; use crate::features; use crate::git_config::GitConfig; use crate::options::option_value::{OptionValue, ProvenancedOptionValue}; use crate::options::theme; use crate::utils::bat::output::PagingMode; macro_rules! set_options { ([$( $field_ident:ident ),* ], $opt:expr, $builtin_features:expr, $git_config:expr, $arg_matches:expr, $expected_option_name_map:expr, $check_names:expr) => { let mut option_names = HashSet::new(); $( let field_name = stringify!($field_ident); let option_name = &$expected_option_name_map[field_name]; if !$crate::config::user_supplied_option(&field_name, $arg_matches) { if let Some(value) = $crate::options::get::get_option_value( option_name, &$builtin_features, $opt, $git_config ) { $opt.$field_ident = value; } } if $check_names { option_names.insert(option_name.as_str()); } )* if $check_names { option_names.extend(&[ "24-bit-color", "diff-highlight", // Does not exist as a flag on config "diff-so-fancy", // Does not exist as a flag on config "detect-dark-light", // Does not exist as a flag on config "features", // Processed differently // Set prior to the rest "no-gitconfig", "dark", "light", "syntax-theme", ]); let expected_option_names: HashSet<_> = $expected_option_name_map .values() .map(String::as_str) .collect(); if option_names != expected_option_names { $crate::config::delta_unreachable( &format!("Error processing options.\nUnhandled names: {:?}\nInvalid names: {:?}.\n", &expected_option_names - &option_names, &option_names - &expected_option_names)); } } } } pub fn set_options( opt: &mut cli::Opt, git_config: &mut Option<GitConfig>, arg_matches: &clap::ArgMatches, assets: HighlightingAssets, ) { if let Some(git_config) = git_config { if opt.no_gitconfig { git_config.enabled = false; } } opt.navigate = opt.navigate || opt.env.navigate.is_some(); if opt.syntax_theme.is_none() { opt.syntax_theme.clone_from(&opt.env.bat_theme); } let option_names = cli::Opt::get_argument_and_option_names(); // Set features let mut builtin_features = features::make_builtin_features(); // --color-only is used for interactive.diffFilter (git add -p) and side-by-side cannot be used // there (does not emit lines in 1-1 correspondence with raw git output). See #274. if config::user_supplied_option("color_only", arg_matches) { builtin_features.remove("side-by-side"); } let features = gather_features(opt, &builtin_features, git_config); opt.features = Some(features.join(" ")); // Set light, dark, and syntax-theme. set__light__dark__syntax_theme__options(opt, git_config, arg_matches, &option_names); // HACK: make minus-line styles have syntax-highlighting iff side-by-side. if features.contains(&"side-by-side".to_string()) { let prefix = "normal "; if !config::user_supplied_option("minus_style", arg_matches) && opt.minus_style.starts_with(prefix) { opt.minus_style = format!("syntax {}", &opt.minus_style[prefix.len()..]); } if !config::user_supplied_option("minus_emph_style", arg_matches) && opt.minus_emph_style.starts_with(prefix) { opt.minus_emph_style = format!("syntax {}", &opt.minus_emph_style[prefix.len()..]); } } // Handle options which default to an arbitrary git config value. // TODO: incorporate this logic into the set_options macro. if !config::user_supplied_option("whitespace_error_style", arg_matches) { opt.whitespace_error_style = if let Some(git_config) = git_config { git_config.get::<String>("color.diff.whitespace") } else { None } .unwrap_or_else(|| "magenta reverse".to_string()) } set_options!( [ blame_code_style, blame_format, blame_separator_format, blame_palette, blame_separator_style, blame_timestamp_format, blame_timestamp_output_format, color_only, config, commit_decoration_style, commit_regex, commit_style, default_language, diff_args, diff_stat_align_width, file_added_label, file_copied_label, file_decoration_style, file_modified_label, file_removed_label, file_renamed_label, file_regex_replacement, right_arrow, hunk_label, file_style, grep_context_line_style, grep_file_style, grep_header_decoration_style, grep_header_file_style, grep_output_type, grep_line_number_style, grep_match_line_style, grep_match_word_style, grep_separator_symbol, hunk_header_decoration_style, hunk_header_file_style, hunk_header_line_number_style, hunk_header_style, hyperlinks, hyperlinks_commit_link_format, hyperlinks_file_link_format, inline_hint_style, inspect_raw_lines, keep_plus_minus_markers, line_buffer_size, map_styles, max_line_distance, max_line_length, max_syntax_length, // Hack: minus-style must come before minus-*emph-style because the latter default // dynamically to the value of the former. merge_conflict_begin_symbol, merge_conflict_end_symbol, merge_conflict_ours_diff_header_decoration_style, merge_conflict_ours_diff_header_style, merge_conflict_theirs_diff_header_decoration_style, merge_conflict_theirs_diff_header_style, minus_style, minus_emph_style, minus_empty_line_marker_style, minus_non_emph_style, minus_non_emph_style, navigate, navigate_regex, line_fill_method, line_numbers, line_numbers_left_format, line_numbers_left_style, line_numbers_minus_style, line_numbers_plus_style, line_numbers_right_format, line_numbers_right_style, line_numbers_zero_style, pager, paging_mode, parse_ansi, // Hack: plus-style must come before plus-*emph-style because the latter default // dynamically to the value of the former. plus_style, plus_emph_style, plus_empty_line_marker_style, plus_non_emph_style, raw, relative_paths, show_colors, show_themes, side_by_side, wrap_max_lines, wrap_right_prefix_symbol, wrap_right_percent, wrap_right_symbol, wrap_left_symbol, tab_width, tokenization_regex, true_color, whitespace_error_style, width, zero_style ], opt, builtin_features, git_config, arg_matches, &option_names, true ); // Setting ComputedValues set_widths_and_isatty(opt); set_true_color(opt); theme::set__color_mode__syntax_theme__syntax_set(opt, assets); opt.computed.inspect_raw_lines = cli::InspectRawLines::from_str(&opt.inspect_raw_lines).unwrap(); opt.computed.paging_mode = parse_paging_mode(&opt.paging_mode); // --color-only is used for interactive.diffFilter (git add -p). side-by-side, and // **-decoration-style cannot be used there (does not emit lines in 1-1 correspondence with raw git output). // See #274. if opt.color_only { opt.side_by_side = false; opt.file_decoration_style = "none".to_string(); opt.commit_decoration_style = "none".to_string(); opt.hunk_header_decoration_style = "none".to_string(); } } #[allow(non_snake_case)] fn set__light__dark__syntax_theme__options( opt: &mut cli::Opt, git_config: &mut Option<GitConfig>, arg_matches: &clap::ArgMatches, option_names: &HashMap<String, String>, ) { let validate_light_and_dark = |opt: &cli::Opt| { if opt.light && opt.dark { fatal("--light and --dark cannot be used together."); } }; let empty_builtin_features = HashMap::new(); validate_light_and_dark(opt); if !(opt.light || opt.dark) { set_options!( [dark, light], opt, &empty_builtin_features, git_config, arg_matches, option_names, false ); } validate_light_and_dark(opt); set_options!( [syntax_theme], opt, &empty_builtin_features, git_config, arg_matches, option_names, false ); } // Features are processed differently from all other options. The role of this function is to // collect all configuration related to features and summarize it as a single list // (space-separated string) of enabled features. The list is arranged in order of increasing // priority in the sense that, when searching for a option value, one starts at the right-hand end // and moves leftward, examining each feature in turn until a feature that associates a value with // the option name is encountered. This search is documented in // `get_option_value::get_option_value`. // // The feature list comprises features deriving from the following sources, listed in order of // decreasing priority: // // 1. Suppose the command-line has `--features "a b"`. Then // - `b`, followed by b's "ordered descendents" // - `a`, followed by a's "ordered descendents" // // 2. Suppose the command line enables two builtin features via `--navigate --diff-so-fancy`. Then // - `diff-so-fancy` // - `navigate` // // 3. Suppose the main [delta] section has `features = d e`. Then // - `e`, followed by e's "ordered descendents" // - `d`, followed by d's "ordered descendents" // // 4. Suppose the main [delta] section has `diff-highlight = true` followed by `raw = true`. // Then // - `diff-highlight` // - `raw` // // The "ordered descendents" of a feature `f` is a list of features obtained via a pre-order // traversal of the feature tree rooted at `f`. This tree arises because it is allowed for a // feature to contain a (key, value) pair that itself enables features. // // If a feature has already been included at higher priority, and is encountered again, it is // ignored. // // Thus, for example: // // delta --features "my-navigate-settings" --navigate => "navigate my-navigate-settings" // // In the following configuration, the feature names indicate their priority, with `a` having // highest priority: // // delta --g --features "d a" // // [delta "a"] // features = c b // // [delta "d"] // features = f e fn gather_features( opt: &mut cli::Opt, builtin_features: &HashMap<String, features::BuiltinFeature>, git_config: &Option<GitConfig>, ) -> Vec<String> { let from_env_var = &opt.env.features; let from_args = opt.features.as_deref().unwrap_or(""); let input_features: Vec<&str> = match from_env_var.as_deref() { Some(from_env_var) if from_env_var.starts_with('+') => from_env_var[1..] .split_whitespace() .chain(split_feature_string(from_args)) .collect(), Some(from_env_var) => { opt.features = Some(from_env_var.to_string()); split_feature_string(from_env_var).collect() } None => split_feature_string(from_args).collect(), }; let mut features = VecDeque::new(); // Gather features from command line. if let Some(git_config) = git_config { for feature in input_features { gather_features_recursively(feature, &mut features, builtin_features, opt, git_config); } } else { for feature in input_features { features.push_front(feature.to_string()); } } // Gather builtin feature flags supplied on command line. // TODO: Iterate over programmatically-obtained names of builtin features. if opt.raw { gather_builtin_features_recursively("raw", &mut features, builtin_features, opt); } if opt.color_only { gather_builtin_features_recursively("color-only", &mut features, builtin_features, opt); } if opt.diff_highlight { gather_builtin_features_recursively("diff-highlight", &mut features, builtin_features, opt); } if opt.diff_so_fancy { gather_builtin_features_recursively("diff-so-fancy", &mut features, builtin_features, opt); } if opt.hyperlinks { gather_builtin_features_recursively("hyperlinks", &mut features, builtin_features, opt); } if opt.line_numbers { gather_builtin_features_recursively("line-numbers", &mut features, builtin_features, opt); } if opt.navigate { gather_builtin_features_recursively("navigate", &mut features, builtin_features, opt); } if opt.side_by_side { gather_builtin_features_recursively("side-by-side", &mut features, builtin_features, opt); } if let Some(git_config) = git_config { // Gather features from [delta] section if --features was not passed. if opt.features.is_none() { if let Some(feature_string) = git_config.get::<String>("delta.features") { for feature in split_feature_string(&feature_string) { gather_features_recursively( feature, &mut features, builtin_features, opt, git_config, ) } } } // Always gather builtin feature flags from [delta] section. gather_builtin_features_from_flags_in_gitconfig( "delta", &mut features, builtin_features, opt, git_config, ); } Vec::<String>::from(features) } /// Add to feature list `features` all features in the tree rooted at `feature`. fn gather_features_recursively( feature: &str, features: &mut VecDeque<String>, builtin_features: &HashMap<String, features::BuiltinFeature>, opt: &cli::Opt, git_config: &GitConfig, ) { if builtin_features.contains_key(feature) { gather_builtin_features_recursively(feature, features, builtin_features, opt); } else { features.push_front(feature.to_string()); } if let Some(child_features) = git_config.get::<String>(&format!("delta.{feature}.features")) { for child_feature in split_feature_string(&child_features) { if !features.contains(&child_feature.to_string()) { gather_features_recursively( child_feature, features, builtin_features, opt, git_config, ) } } } gather_builtin_features_from_flags_in_gitconfig( &format!("delta.{feature}"), features, builtin_features, opt, git_config, ); } /// Look for builtin features requested via boolean feature flags (as opposed to via a "features" /// list) in a custom feature section in git config and add them to the features list. fn gather_builtin_features_from_flags_in_gitconfig( git_config_key: &str, features: &mut VecDeque<String>, builtin_features: &HashMap<String, features::BuiltinFeature>, opt: &cli::Opt, git_config: &GitConfig, ) { for child_feature in builtin_features.keys() { if let Some(true) = git_config.get::<bool>(&format!("{git_config_key}.{child_feature}")) { gather_builtin_features_recursively(child_feature, features, builtin_features, opt); } } } /// Add to feature list `features` all builtin features in the tree rooted at `builtin_feature`. A /// builtin feature is a named collection of (option-name, value) pairs. This tree arises because /// those option names might include (a) a "features" list, and (b) boolean feature flags. I.e. the /// children of a node in the tree are features in (a) and (b). (In both cases the features /// referenced will be other builtin features, since a builtin feature is determined at compile /// time and therefore cannot know of the existence of a non-builtin custom features in gitconfig). fn gather_builtin_features_recursively( feature: &str, features: &mut VecDeque<String>, builtin_features: &HashMap<String, features::BuiltinFeature>, opt: &cli::Opt, ) { let feature_string = feature.to_string(); if features.contains(&feature_string) { return; } features.push_front(feature_string); if let Some(feature_data) = builtin_features.get(feature) { if let Some(child_features_fn) = feature_data.get("features") { if let ProvenancedOptionValue::DefaultValue(OptionValue::String(features_string)) = child_features_fn(opt, &None) { for child_feature in split_feature_string(&features_string) { gather_builtin_features_recursively( child_feature, features, builtin_features, opt, ); } } } for child_feature in builtin_features.keys() { if let Some(child_features_fn) = feature_data.get(child_feature) { if let ProvenancedOptionValue::DefaultValue(OptionValue::Boolean(true)) = child_features_fn(opt, &None) { gather_builtin_features_recursively( child_feature, features, builtin_features, opt, ); } } } } } fn split_feature_string(features: &str) -> impl Iterator<Item = &str> { features.split_whitespace().rev() } impl FromStr for cli::InspectRawLines { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_lowercase().as_str() { "true" => Ok(Self::True), "false" => Ok(Self::False), _ => { fatal(format!( r#"Invalid value for inspect-raw-lines option: {s}. Valid values are "true", and "false"."#, )); } } } } fn parse_paging_mode(paging_mode_string: &str) -> PagingMode { match paging_mode_string.to_lowercase().as_str() { "always" => PagingMode::Always, "never" => PagingMode::Never, "auto" => PagingMode::QuitIfOneScreen, _ => { fatal(format!( "Invalid value for --paging option: {paging_mode_string} (valid values are \"always\", \"never\", and \"auto\")", )); } } } fn parse_width_specifier(width_arg: &str, terminal_width: usize) -> Result<usize, String> { let width_arg = width_arg.trim(); let parse = |width: &str, must_be_negative, subexpression| -> Result<isize, String> { let remove_spaces = |s: &str| s.chars().filter(|c| c != &' ').collect::<String>(); match remove_spaces(width).parse() { Ok(val) if must_be_negative && val > 0 => Err(()), Err(_) => Err(()), Ok(ok) => Ok(ok), } .map_err(|_| { let pos = if must_be_negative { " negative" } else { "n" }; let subexpr = if subexpression { format!(" (from {width_arg:?})") } else { "".into() }; format!("{width:?}{subexpr} is not a{pos} integer") }) }; let width = match width_arg.find('-') { None => parse(width_arg, false, false)?.try_into().unwrap(), Some(0) => (terminal_width as isize + parse(width_arg, true, false)?) .try_into() .map_err(|_| { format!( "the current terminal width of {} minus {} is negative", terminal_width, &width_arg[1..].trim(), ) })?, Some(index) => { let a = parse(&width_arg[0..index], false, true)?; let b = parse(&width_arg[index..], true, true)?; (a + b) .try_into() .map_err(|_| format!("expression {width_arg:?} is not positive"))? } }; Ok(width) } fn set_widths_and_isatty(opt: &mut cli::Opt) { let term_stdout = Term::stdout(); opt.computed.stdout_is_term = term_stdout.is_term(); // If one extra character for e.g. `less --status-column` is required use "-1" // as an argument, also see #41, #10, #115 and #727. opt.computed.available_terminal_width = crate::utils::workarounds::windows_msys2_width_fix(term_stdout.size(), &term_stdout); let (decorations_width, background_color_extends_to_terminal_width) = match opt.width.as_deref() { Some("variable") => (cli::Width::Variable, false), Some(width) => { let width = parse_width_specifier(width, opt.computed.available_terminal_width) .unwrap_or_else(|err| fatal(format!("Invalid value for width: {err}"))); (cli::Width::Fixed(width), true) } None => { #[cfg(test)] { // instead of passing `--width=..` to all tests, set it here: (cli::Width::Fixed(tests::TERMINAL_WIDTH_IN_TESTS), true) } #[cfg(not(test))] { ( cli::Width::Fixed(opt.computed.available_terminal_width), true, ) } } }; opt.computed.decorations_width = decorations_width; opt.computed.background_color_extends_to_terminal_width = background_color_extends_to_terminal_width; } fn set_true_color(opt: &mut cli::Opt) { if opt.true_color == "auto" { // It's equal to its default, so the user might be using the deprecated // --24-bit-color option. if let Some(_24_bit_color) = opt._24_bit_color.as_ref() { opt.true_color.clone_from(_24_bit_color); } } opt.computed.true_color = match opt.true_color.as_ref() { "always" => true, "never" => false, "auto" => is_truecolor_terminal(&opt.env), _ => { fatal(format!( "Invalid value for --true-color option: {} (valid values are \"always\", \"never\", and \"auto\")", opt.true_color )); } }; } fn is_truecolor_terminal(env: &DeltaEnv) -> bool { env.colorterm .as_ref() .map(|colorterm| colorterm == "truecolor" || colorterm == "24bit") .unwrap_or(false) } #[cfg(test)] pub mod tests { use std::fs::remove_file; use crate::cli; use crate::tests::integration_test_utils; use crate::utils::bat::output::PagingMode; pub const TERMINAL_WIDTH_IN_TESTS: usize = 43; #[test] fn test_options_can_be_set_in_git_config() { // In general the values here are not the default values. However there are some exceptions // since e.g. color-only = true (non-default) forces side-by-side = false (default). let git_config_contents = b" [delta] color-only = false commit-decoration-style = black black commit-style = black black dark = false default-language = rs diff-highlight = true diff-so-fancy = true features = xxxyyyzzz file-added-label = xxxyyyzzz file-decoration-style = black black file-modified-label = xxxyyyzzz file-removed-label = xxxyyyzzz file-renamed-label = xxxyyyzzz file-transformation = s/foo/bar/ right-arrow = xxxyyyzzz file-style = black black hunk-header-decoration-style = black black hunk-header-style = black black keep-plus-minus-markers = true light = true line-numbers = true line-numbers-left-format = xxxyyyzzz line-numbers-left-style = black black line-numbers-minus-style = black black line-numbers-plus-style = black black line-numbers-right-format = xxxyyyzzz line-numbers-right-style = black black line-numbers-zero-style = black black max-line-distance = 77 max-line-length = 77 minus-emph-style = black black minus-empty-line-marker-style = black black minus-non-emph-style = black black minus-style = black black navigate = true navigate-regex = xxxyyyzzz paging = never plus-emph-style = black black plus-empty-line-marker-style = black black plus-non-emph-style = black black plus-style = black black raw = true side-by-side = true syntax-theme = xxxyyyzzz tabs = 77 true-color = never whitespace-error-style = black black width = 77 word-diff-regex = xxxyyyzzz zero-style = black black # no-gitconfig "; let git_config_path = "delta__test_options_can_be_set_in_git_config.gitconfig"; let opt = integration_test_utils::make_options_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path), ); assert_eq!(opt.true_color, "never"); assert!(!opt.color_only); assert_eq!(opt.commit_decoration_style, "black black"); assert_eq!(opt.commit_style, "black black"); assert!(!opt.dark); assert_eq!(opt.default_language, "rs".to_owned()); // TODO: should set_options not be called on any feature flags? // assert_eq!(opt.diff_highlight, true); // assert_eq!(opt.diff_so_fancy, true); assert!(opt .features .unwrap() .split_whitespace() .any(|s| s == "xxxyyyzzz")); assert_eq!(opt.file_added_label, "xxxyyyzzz"); assert_eq!(opt.file_decoration_style, "black black"); assert_eq!(opt.file_modified_label, "xxxyyyzzz"); assert_eq!(opt.file_removed_label, "xxxyyyzzz"); assert_eq!(opt.file_renamed_label, "xxxyyyzzz"); assert_eq!(opt.right_arrow, "xxxyyyzzz"); assert_eq!(opt.file_style, "black black"); assert_eq!(opt.file_regex_replacement, Some("s/foo/bar/".to_string())); assert_eq!(opt.hunk_header_decoration_style, "black black"); assert_eq!(opt.hunk_header_style, "black black"); assert!(opt.keep_plus_minus_markers); assert!(opt.light); assert!(opt.line_numbers); assert_eq!(opt.line_numbers_left_format, "xxxyyyzzz"); assert_eq!(opt.line_numbers_left_style, "black black"); assert_eq!(opt.line_numbers_minus_style, "black black"); assert_eq!(opt.line_numbers_plus_style, "black black"); assert_eq!(opt.line_numbers_right_format, "xxxyyyzzz"); assert_eq!(opt.line_numbers_right_style, "black black"); assert_eq!(opt.line_numbers_zero_style, "black black"); assert_eq!(opt.max_line_distance, 77.0); assert_eq!(opt.max_line_length, 77); assert_eq!(opt.minus_emph_style, "black black"); assert_eq!(opt.minus_empty_line_marker_style, "black black"); assert_eq!(opt.minus_non_emph_style, "black black"); assert_eq!(opt.minus_style, "black black"); assert!(opt.navigate); assert_eq!(opt.navigate_regex, Some("xxxyyyzzz".to_string())); assert_eq!(opt.paging_mode, "never"); assert_eq!(opt.plus_emph_style, "black black"); assert_eq!(opt.plus_empty_line_marker_style, "black black"); assert_eq!(opt.plus_non_emph_style, "black black"); assert_eq!(opt.plus_style, "black black"); assert!(opt.raw); assert!(opt.side_by_side); assert_eq!(opt.syntax_theme, Some("xxxyyyzzz".to_string())); assert_eq!(opt.tab_width, 77); assert_eq!(opt.true_color, "never"); assert_eq!(opt.whitespace_error_style, "black black"); assert_eq!(opt.width, Some("77".to_string())); assert_eq!(opt.tokenization_regex, "xxxyyyzzz"); assert_eq!(opt.zero_style, "black black"); assert_eq!(opt.computed.paging_mode, PagingMode::Never); remove_file(git_config_path).unwrap(); } #[test] fn test_width_in_git_config_is_honored() { let git_config_contents = b" [delta] features = my-width-feature [delta \"my-width-feature\"] width = variable "; let git_config_path = "delta__test_width_in_git_config_is_honored.gitconfig"; let opt = integration_test_utils::make_options_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path), ); assert_eq!(opt.computed.decorations_width, cli::Width::Variable); remove_file(git_config_path).unwrap(); } #[test] fn test_parse_width_specifier() { use super::parse_width_specifier; let term_width = 12; let assert_failure_containing = |x, errmsg| { assert!(parse_width_specifier(x, term_width) .unwrap_err() .contains(errmsg)); }; assert_failure_containing("", "is not an integer"); assert_failure_containing("foo", "is not an integer"); assert_failure_containing("123foo", "is not an integer"); assert_failure_containing("+12bar", "is not an integer"); assert_failure_containing("-456bar", "is not a negative integer"); assert_failure_containing("-13", "minus 13 is negative"); assert_failure_containing(" - 13 ", "minus 13 is negative"); assert_failure_containing("12-13", "expression"); assert_failure_containing(" 12 - 13 ", "expression \"12 - 13\" is not"); assert_failure_containing("12+foo", "is not an integer"); assert_failure_containing( " 12 - bar ", "\"- bar\" (from \"12 - bar\") is not a negative integer", ); assert_eq!(parse_width_specifier("1", term_width).unwrap(), 1); assert_eq!(parse_width_specifier(" 1 ", term_width).unwrap(), 1); assert_eq!(parse_width_specifier("-2", term_width).unwrap(), 10); assert_eq!(parse_width_specifier(" - 2", term_width).unwrap(), 10); assert_eq!(parse_width_specifier("-12", term_width).unwrap(), 0); assert_eq!(parse_width_specifier(" - 12 ", term_width).unwrap(), 0); assert_eq!(parse_width_specifier(" 2 - 2 ", term_width).unwrap(), 0); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/options/get.rs
src/options/get.rs
use std::collections::HashMap; use crate::cli; use crate::features; use crate::git_config::{self, GitConfigGet}; use crate::options::option_value::{OptionValue, ProvenancedOptionValue}; use ProvenancedOptionValue::*; // Look up a value of type `T` associated with `option name`. The search rules are: // // 1. If there is a value associated with `option_name` in the main [delta] git config // section, then stop searching and return that value (steps 2 and 3 are not executed at all). // // 2. For each feature in the ordered list of enabled features: // // 2.1 Look-up the value, treating `feature` as a custom feature. // I.e., if there is a value associated with `option_name` in a git config section // named [delta "`feature`"] then stop searching and return that value. // // 2.2 Look-up the value, treating `feature` as a builtin feature. // I.e., if there is a value (not a default value) associated with `option_name` in a // builtin feature named `feature`, then stop searching and return that value. // Otherwise, record the default value and continue searching. // // 3. Return the last default value that was encountered. pub fn get_option_value<T>( option_name: &str, builtin_features: &HashMap<String, features::BuiltinFeature>, opt: &cli::Opt, git_config: &mut Option<git_config::GitConfig>, ) -> Option<T> where T: GitConfigGet, T: GetOptionValue, T: From<OptionValue>, T: Into<OptionValue>, { T::get_option_value(option_name, builtin_features, opt, git_config) } static GIT_CONFIG_THEME_REGEX: &str = r"^delta\.(.+)\.(light|dark)$"; pub fn get_themes(git_config: Option<git_config::GitConfig>) -> Vec<String> { let mut themes: Vec<String> = Vec::new(); let git_config = git_config.unwrap(); git_config.for_each(GIT_CONFIG_THEME_REGEX, |name, _| { if let Some(name) = name.strip_prefix("delta.") { if let Some((name, _)) = name.rsplit_once('.') { let name = name.to_owned(); if !themes.contains(&name) { themes.push(name); } } } }); themes.sort_by_key(|a| a.to_lowercase()); themes } pub trait GetOptionValue { fn get_option_value( option_name: &str, builtin_features: &HashMap<String, features::BuiltinFeature>, opt: &cli::Opt, git_config: &mut Option<git_config::GitConfig>, ) -> Option<Self> where Self: Sized, Self: GitConfigGet, Self: From<OptionValue>, Self: Into<OptionValue>, { if let Some(git_config) = git_config { if let Some(value) = git_config.get::<Self>(&format!("delta.{option_name}")) { return Some(value); } } if let Some(features) = &opt.features { for feature in features.split_whitespace().rev() { match Self::get_provenanced_value_for_feature( option_name, feature, builtin_features, opt, git_config, ) { Some(GitConfigValue(value)) | Some(DefaultValue(value)) => { return Some(value.into()); } None => {} } } } None } /// Return the value, or default value, associated with `option_name` under feature name /// `feature`. This may refer to a custom feature, or a builtin feature, or both. Only builtin /// features have defaults. See `GetOptionValue::get_option_value`. fn get_provenanced_value_for_feature( option_name: &str, feature: &str, builtin_features: &HashMap<String, features::BuiltinFeature>, opt: &cli::Opt, git_config: &mut Option<git_config::GitConfig>, ) -> Option<ProvenancedOptionValue> where Self: Sized, Self: GitConfigGet, Self: Into<OptionValue>, { if let Some(git_config) = git_config { if let Some(value) = git_config.get::<Self>(&format!("delta.{feature}.{option_name}")) { return Some(GitConfigValue(value.into())); } } if let Some(builtin_feature) = builtin_features.get(feature) { if let Some(value_function) = builtin_feature.get(option_name) { return Some(value_function(opt, git_config)); } } None } } impl GetOptionValue for Option<String> {} impl GetOptionValue for String {} impl GetOptionValue for bool {} impl GetOptionValue for f64 {} impl GetOptionValue for usize {} #[cfg(test)] pub mod tests { use std::fs::remove_file; use crate::cli::Opt; use crate::env::DeltaEnv; use crate::options::get::get_themes; use crate::tests::integration_test_utils; // fn generic<T>(_s: SGen<T>) {} fn _test_env_var_overrides_git_config_generic( git_config_contents: &[u8], git_config_path: &str, env_value: String, fn_cmp_before: &dyn Fn(Opt), fn_cmp_after: &dyn Fn(Opt), ) { let opt = integration_test_utils::make_options_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path), ); fn_cmp_before(opt); let opt = integration_test_utils::make_options_from_args_and_git_config_honoring_env_var_with_custom_env( DeltaEnv { git_config_parameters: Some(env_value), ..DeltaEnv::default() }, &[], Some(git_config_contents), Some(git_config_path), ); fn_cmp_after(opt); remove_file(git_config_path).unwrap(); } #[test] fn test_env_var_overrides_git_config_simple_string() { let git_config_contents = b" [delta] plus-style = blue "; let git_config_path = "delta__test_simple_string_env_var_overrides_git_config.gitconfig"; _test_env_var_overrides_git_config_generic( git_config_contents, git_config_path, "'delta.plus-style=green'".into(), &|opt: Opt| assert_eq!(opt.plus_style, "blue"), &|opt: Opt| assert_eq!(opt.plus_style, "green"), ); } #[test] fn test_env_var_overrides_git_config_complex_string() { let git_config_contents = br##" [delta] minus-style = red bold ul "#ffeeee" "##; let git_config_path = "delta__test_complex_string_env_var_overrides_git_config.gitconfig"; _test_env_var_overrides_git_config_generic( git_config_contents, git_config_path, r##"'delta.minus-style=magenta italic ol "#aabbcc"'"##.into(), &|opt: Opt| assert_eq!(opt.minus_style, r##"red bold ul #ffeeee"##), &|opt: Opt| assert_eq!(opt.minus_style, r##"magenta italic ol "#aabbcc""##,), ); } #[test] fn test_env_var_overrides_git_config_option_string() { let git_config_contents = b" [delta] plus-style = blue "; let git_config_path = "delta__test_option_string_env_var_overrides_git_config.gitconfig"; _test_env_var_overrides_git_config_generic( git_config_contents, git_config_path, "'delta.plus-style=green'".into(), &|opt: Opt| assert_eq!(opt.plus_style, "blue"), &|opt: Opt| assert_eq!(opt.plus_style, "green"), ); } #[test] fn test_env_var_overrides_git_config_bool() { let git_config_contents = b" [delta] side-by-side = true "; let git_config_path = "delta__test_bool_env_var_overrides_git_config.gitconfig"; _test_env_var_overrides_git_config_generic( git_config_contents, git_config_path, "'delta.side-by-side=false'".into(), &|opt: Opt| assert!(opt.side_by_side), &|opt: Opt| assert!(!opt.side_by_side), ); } #[test] fn test_env_var_overrides_git_config_int() { let git_config_contents = b" [delta] max-line-length = 1 "; let git_config_path = "delta__test_int_env_var_overrides_git_config.gitconfig"; _test_env_var_overrides_git_config_generic( git_config_contents, git_config_path, "'delta.max-line-length=2'".into(), &|opt: Opt| assert_eq!(opt.max_line_length, 1), &|opt: Opt| assert_eq!(opt.max_line_length, 2), ); } #[test] fn test_env_var_overrides_git_config_float() { let git_config_contents = b" [delta] max-line-distance = 0.6 "; let git_config_path = "delta__test_float_env_var_overrides_git_config.gitconfig"; _test_env_var_overrides_git_config_generic( git_config_contents, git_config_path, "'delta.max-line-distance=0.7'".into(), &|opt: Opt| assert_eq!(opt.max_line_distance, 0.6), &|opt: Opt| assert_eq!(opt.max_line_distance, 0.7), ); } #[test] fn test_delta_features_env_var() { let git_config_contents = b" [delta] features = feature-from-gitconfig "; let git_config_path = "delta__test_delta_features_env_var.gitconfig"; let opt = integration_test_utils::make_options_from_args_and_git_config( &[], Some(git_config_contents), Some(git_config_path), ); assert_eq!(opt.features.unwrap(), "feature-from-gitconfig"); assert!(!opt.side_by_side); let opt = integration_test_utils::make_options_from_args_and_git_config_with_custom_env( DeltaEnv { features: Some("side-by-side".into()), ..DeltaEnv::default() }, &[], Some(git_config_contents), Some(git_config_path), ); // `line-numbers` is a builtin feature induced by side-by-side assert_eq!(opt.features.unwrap(), "line-numbers side-by-side"); assert!(opt.side_by_side); let opt = integration_test_utils::make_options_from_args_and_git_config_with_custom_env( DeltaEnv { features: Some("+side-by-side".into()), ..DeltaEnv::default() }, &[], Some(git_config_contents), Some(git_config_path), ); assert_eq!( opt.features.unwrap(), "feature-from-gitconfig line-numbers side-by-side" ); assert!(opt.side_by_side); remove_file(git_config_path).unwrap(); } #[test] fn test_get_themes_from_config() { let git_config_contents = r#" [delta "dark-theme"] max-line-distance = 0.6 dark = true [delta "light-theme"] max-line-distance = 0.6 light = true [delta "light-and-dark-theme"] max-line-distance = 0.6 light = true dark = true [delta "Uppercase-Theme"] light = true [delta "not-a-theme"] max-line-distance = 0.6 "#; let git_config_path = "delta__test_get_themes_git_config.gitconfig"; let git_config = Some(integration_test_utils::make_git_config( &DeltaEnv::default(), git_config_contents.as_bytes(), git_config_path, false, )); let themes = get_themes(git_config); assert_eq!( themes, [ "dark-theme", "light-and-dark-theme", "light-theme", "Uppercase-Theme" ] ); remove_file(git_config_path).unwrap(); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/tests/test_example_diffs.rs
src/tests/test_example_diffs.rs
#[cfg(test)] mod tests { use crate::ansi::{self, strip_ansi_codes}; use crate::cli::InspectRawLines; use crate::delta::{DiffType, State}; use crate::handlers::hunk_header::ParsedHunkHeader; use crate::style; use crate::tests::ansi_test_utils::ansi_test_utils; use crate::tests::integration_test_utils; use crate::tests::integration_test_utils::DeltaTest; use insta::assert_snapshot; #[test] fn test_added_file() { DeltaTest::with_args(&[]) .with_input(ADDED_FILE_INPUT) .expect_contains("\nadded: a.py\n"); } #[test] fn test_added_empty_file() { DeltaTest::with_args(&[]) .with_input(ADDED_EMPTY_FILE) .expect_contains("\nadded: file\n"); } #[test] fn test_added_file_directory_path_containing_space() { DeltaTest::with_args(&[]) .with_input(ADDED_FILES_DIRECTORY_PATH_CONTAINING_SPACE) .expect_contains("\nadded: with space/file1\n") .expect_contains("\nadded: nospace/file2\n"); } #[test] fn test_renamed_file() { DeltaTest::with_args(&[]) .with_input(RENAMED_FILE_INPUT) .expect_contains_once("\nrenamed: a.py ⟶ b.py\n"); } #[test] fn test_copied_file() { DeltaTest::with_args(&[]) .with_input(GIT_DIFF_WITH_COPIED_FILE) .expect_contains_once("\ncopied: first_file ⟶ copied_file\n"); } #[test] fn test_renamed_file_with_changes() { let t = DeltaTest::with_args(&[]) .with_input(RENAMED_FILE_WITH_CHANGES_INPUT) .expect_contains_once( "\nrenamed: Casks/font-dejavusansmono-nerd-font.rb ⟶ Casks/font-dejavu-sans-mono-nerd-font.rb\n" ); println!("{}", t.output); } #[test] fn test_recognized_file_type() { // In addition to the background color, the code has language syntax highlighting. let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::get_line_of_code_from_delta( ADDED_FILE_INPUT, 14, "class X:", &config, ); ansi_test_utils::assert_has_color_other_than_plus_color(&output, &config); } #[test] fn test_unrecognized_file_type_with_syntax_theme() { // In addition to the background color, the code has the foreground color using the default // .txt syntax under the theme. let config = integration_test_utils::make_config_from_args(&[]); let input = ADDED_FILE_INPUT.replace("a.py", "a"); let output = integration_test_utils::get_line_of_code_from_delta(&input, 14, "class X:", &config); ansi_test_utils::assert_has_color_other_than_plus_color(&output, &config); } #[test] fn test_unrecognized_file_type_no_syntax_theme() { // The code has the background color only. (Since there is no theme, the code has no // foreground ansi color codes.) let config = integration_test_utils::make_config_from_args(&[ "--syntax-theme", "none", "--width", "variable", ]); let input = ADDED_FILE_INPUT.replace("a.py", "a"); let output = integration_test_utils::get_line_of_code_from_delta(&input, 14, "class X:", &config); ansi_test_utils::assert_has_plus_color_only(&output, &config); } #[test] fn test_default_language_is_used_for_syntax_highlighting() { // Note: default-language will be used for files with no extension, but also // for files with an extension, but for which the language was not detected. // Use color-only so that we can refer to the line numbers from the input diff. let config = integration_test_utils::make_config_from_args(&[ "--color-only", "--default-language", "bash", ]); let output = integration_test_utils::run_delta(MODIFIED_BASH_AND_CSHARP_FILES, &config); ansi_test_utils::assert_line_has_syntax_highlighted_substring( &output, 12, 1, " rsync -avu --delete $src/ $dst", "abc.bash", State::HunkZero(DiffType::Unified, None), &config, ); } #[test] fn test_default_language_is_not_used_when_other_language_is_detected() { // Use color-only so that we can refer to the line numbers from the input diff. let config = integration_test_utils::make_config_from_args(&[ "--color-only", "--default-language", "bash", ]); let output = integration_test_utils::run_delta(MODIFIED_BASH_AND_CSHARP_FILES, &config); ansi_test_utils::assert_line_has_syntax_highlighted_substring( &output, 19, 1, " static void Main(string[] args)", "abc.cs", State::HunkZero(DiffType::Unified, None), &config, ); } #[test] fn test_full_filename_used_to_detect_language() { let config = integration_test_utils::make_config_from_args(&[ "--color-only", "--default-language", "txt", ]); let output = integration_test_utils::run_delta(MODIFIED_DOCKER_AND_RS_FILES, &config); let ansi = ansi::explain_ansi(&output, false); // Ensure presence and absence of highlighting. Do not use `assert_line_has_syntax_highlighted_substring` // because it uses the same code path as the one to be tested here. let expected = r"(normal)diff --git a/Dockerfile b/Dockerfile index 0123456..1234567 100644 --- a/Dockerfile +++ b/Dockerfile @@ -0,0 +2 @@ (normal 22)+(203)FROM(231) foo(normal) (normal 22)+(203)COPY(231) bar baz(normal) diff --git a/rs b/rs index 0123456..1234567 100644 --- a/rs +++ b/rs @@ -0,0 +2 @@ (normal 22)+(231)fn foobar() -> i8 {(normal) (normal 22)+(231) 8(normal) (normal 22)+(231)}(normal) "; assert_eq!(expected, ansi); } #[test] fn test_diff_unified_two_files() { let config = integration_test_utils::make_config_from_args(&["--file-modified-label", "comparing:"]); let output = integration_test_utils::run_delta(DIFF_UNIFIED_TWO_FILES, &config); let output = strip_ansi_codes(&output); let mut lines = output.lines(); // Header assert_eq!(lines.nth(1).unwrap(), "comparing: one.rs ⟶ src/two.rs"); // Change assert_eq!(lines.nth(7).unwrap(), "println!(\"Hello ruster\");"); // Unchanged in second chunk assert_eq!(lines.nth(7).unwrap(), "Unchanged"); } #[test] fn test_diff_unified_two_directories() { let config = integration_test_utils::make_config_from_args(&["--width", "80", "--navigate"]); let output = integration_test_utils::run_delta(DIFF_UNIFIED_TWO_DIRECTORIES, &config); let output = strip_ansi_codes(&output); let mut lines = output.lines(); // Header assert_eq!(lines.nth(1).unwrap(), "Δ a/different ⟶ b/different"); // Change assert_eq!(lines.nth(7).unwrap(), "This is different from b"); // File uniqueness assert_eq!(lines.nth(2).unwrap(), "Only in a/: just_a"); // DiffHeader divider assert!(lines.next().unwrap().starts_with("───────")); // Next hunk assert_eq!( lines.nth(4).unwrap(), "Δ a/more_difference ⟶ b/more_difference" ); } #[test] fn test_diff_unified_concatenated() { // See #1002. Line buffers were not being flushed correctly, leading to material from first // file last hunk appearing at beginning of second file first hunk. DeltaTest::with_args(&[]) .with_input(DIFF_UNIFIED_CONCATENATED) .expect_contains("\nLINES.\n\n1/y 2022-03-06"); } #[test] #[ignore] // Ideally, delta would make this test pass. See #121. fn test_delta_ignores_non_diff_input() { let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta(NOT_A_DIFF_OUTPUT, &config); let output = strip_ansi_codes(&output); assert_eq!(output, NOT_A_DIFF_OUTPUT.to_owned() + "\n"); } #[test] fn test_certain_bugs_are_not_present() { for input in [ DIFF_EXHIBITING_PARSE_FILE_NAME_BUG, DIFF_EXHIBITING_STATE_MACHINE_PARSER_BUG, DIFF_EXHIBITING_TRUNCATION_BUG, ] { let config = integration_test_utils::make_config_from_args(&["--raw"]); let output = integration_test_utils::run_delta(input, &config); assert_eq!(strip_ansi_codes(&output), input); assert_ne!(output, input); } } #[test] fn test_delta_paints_diff_when_there_is_unrecognized_initial_content() { for input in [ DIFF_WITH_UNRECOGNIZED_PRECEDING_MATERIAL_1, DIFF_WITH_UNRECOGNIZED_PRECEDING_MATERIAL_2, ] { let config = integration_test_utils::make_config_from_args(&["--raw"]); let output = integration_test_utils::run_delta(input, &config); assert_eq!(strip_ansi_codes(&output), input); assert_ne!(output, input); } } #[test] fn test_diff_with_merge_conflict_is_not_truncated() { let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta(DIFF_WITH_MERGE_CONFLICT, &config); println!("{}", strip_ansi_codes(&output)); } #[test] fn test_diff_with_merge_conflict_is_passed_on_unchanged_under_raw() { let config = integration_test_utils::make_config_from_args(&["--raw"]); let output = integration_test_utils::run_delta(DIFF_WITH_MERGE_CONFLICT, &config); assert_eq!(strip_ansi_codes(&output), DIFF_WITH_MERGE_CONFLICT); } #[test] fn test_simple_dirty_submodule_diff() { DeltaTest::with_args(&["--width", "30"]) .with_input(SUBMODULE_DIRTY) .inspect() .expect_after_skip( 1, r#" some_submodule ────────────────────────────── ca030fd1a022..803be42ca46a"#, ); } #[test] fn test_submodule_diff_log() { // See etc/examples/662-submodules // diff.submodule = log let config = integration_test_utils::make_config_from_args(&["--width", "49"]); let output = integration_test_utils::run_delta(SUBMODULE_DIFF_LOG, &config); let output = strip_ansi_codes(&output); assert_eq!(output, SUBMODULE_DIFF_LOG_EXPECTED_OUTPUT); } #[test] fn test_submodule_contains_untracked_content() { let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta(SUBMODULE_CONTAINS_UNTRACKED_CONTENT_INPUT, &config); let output = strip_ansi_codes(&output); assert!(output.contains("\nSubmodule x/y/z contains untracked content\n")); } #[test] fn test_triple_dash_at_beginning_of_line_in_code() { let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta(TRIPLE_DASH_AT_BEGINNING_OF_LINE_IN_CODE, &config); let output = strip_ansi_codes(&output); assert!(output.contains("-- instance (Category p, Category q) => Category (p ∧ q) where\n")); } #[test] fn test_binary_files_differ() { let output = DeltaTest::with_args(&["--file-modified-label", "modified:"]) .with_input(BINARY_FILES_DIFFER) .skip_header(); assert_snapshot!(output, @r###" modified: foo (binary file) ─────────────────────────────────────────── "###); } #[test] fn test_binary_file_added() { let output = DeltaTest::with_args(&[]) .with_input(BINARY_FILE_ADDED) .skip_header(); assert_snapshot!(output, @r###" added: foo (binary file) ─────────────────────────────────────────── "###); } #[test] fn test_binary_file_removed() { let output = DeltaTest::with_args(&[]) .with_input(BINARY_FILE_REMOVED) .skip_header(); assert_snapshot!(output, @r###" removed: foo (binary file) ─────────────────────────────────────────── "###); } #[test] fn test_binary_files_differ_after_other() { let output = DeltaTest::with_args(&["--file-modified-label", "modified:"]) .with_input(BINARY_FILES_DIFFER_AFTER_OTHER) .output; assert_snapshot!(output, @r###" renamed: foo ⟶ bar ─────────────────────────────────────────── modified: qux (binary file) ─────────────────────────────────────────── "###); } #[test] fn test_diff_in_diff() { let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta(DIFF_IN_DIFF, &config); let output = strip_ansi_codes(&output); assert!(output.contains("\n---\n")); assert!(output.contains("\nSubject: [PATCH] Init\n")); } #[test] fn test_standalone_diff_files_are_identical() { let diff = "Files foo and bar are identical\n"; let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta(diff, &config); assert_eq!(strip_ansi_codes(&output), diff); } #[test] fn test_standalone_diff_binary_files_differ() { let diff = "Binary files foo and bar differ\n"; let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta(diff, &config); assert_eq!(strip_ansi_codes(&output), diff); } #[test] fn test_diff_no_index_binary_files_differ() { let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta(DIFF_NO_INDEX_BINARY_FILES_DIFFER, &config); assert_eq!( strip_ansi_codes(&output), "Binary files foo bar and sub dir/foo bar baz differ\n" ); } #[test] fn test_commit_style_raw_no_decoration() { let config = integration_test_utils::make_config_from_args(&[ "--commit-style", "raw", "--commit-decoration-style", "omit", ]); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); ansi_test_utils::assert_line_has_no_color( &output, 0, "commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e", ); assert!(output.contains( "\ commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e " )); } #[test] fn test_commit_style_colored_input_color_is_stripped_under_normal() { let config = integration_test_utils::make_config_from_args(&[ "--commit-style", "normal", "--commit-decoration-style", "omit", ]); let output = integration_test_utils::run_delta( GIT_DIFF_SINGLE_HUNK_WITH_ANSI_ESCAPE_SEQUENCES, &config, ); ansi_test_utils::assert_line_has_no_color( &output, 0, "commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e", ); } #[test] fn test_commit_style_colored_input_color_is_preserved_under_raw() { let config = integration_test_utils::make_config_from_args(&[ "--commit-style", "raw", "--commit-decoration-style", "omit", ]); let output = integration_test_utils::run_delta( GIT_DIFF_SINGLE_HUNK_WITH_ANSI_ESCAPE_SEQUENCES, &config, ); ansi_test_utils::assert_line_has_4_bit_color_style( &output, 0, "commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e", "bold 31", &config, ); } #[test] fn test_orphan_carriage_return_is_stripped() { let config = integration_test_utils::make_config_from_args(&[]); let output = integration_test_utils::run_delta( GIT_DIFF_SINGLE_HUNK_WITH_SEQUENCE_OF_CR_ESCAPE_SEQUENCES_LF, &config, ); assert!(output.bytes().all(|b: u8| b != b'\r')); } #[test] fn test_commit_decoration_style_omit() { _do_test_commit_style_no_decoration(&[ "--commit-style", "blue", "--commit-decoration-style", "omit", ]); } #[test] fn test_commit_decoration_style_empty_string() { _do_test_commit_style_no_decoration(&[ "--commit-style", "blue", "--commit-decoration-style", "", ]); } fn _do_test_commit_style_no_decoration(args: &[&str]) { let config = integration_test_utils::make_config_from_args(args); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); if false { // `--commit-style xxx` is not honored yet: always behaves like xxx=raw ansi_test_utils::assert_line_has_style( &output, 0, "commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e", "blue", &config, ); } let output = strip_ansi_codes(&output); assert!(output.contains("commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e")); assert!(!output.contains("commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e │")); assert!(!output.contains( "\ commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e ───────────────────────────────────────────────" )); } #[test] fn test_commit_style_omit() { let config = integration_test_utils::make_config_from_args(&["--commit-style", "omit"]); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); let output = strip_ansi_codes(&output); assert!(!output.contains( "\ commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e " )); } #[test] fn test_commit_style_box() { _do_test_commit_style_box(&[ "--commit-style", "blue", "--commit-decoration-style", "blue box", ]); } #[test] fn test_commit_style_box_ul() { _do_test_commit_style_box_ul(&[ "--commit-style", "blue", "--commit-decoration-style", "blue box ul", "--width=64", ]); } #[ignore] #[test] fn test_commit_style_box_ol() { _do_test_commit_style_box_ol(&[ "--commit-style", "blue", "--commit-decoration-style", "blue box ol", ]); } fn _do_test_commit_style_box(args: &[&str]) { let config = integration_test_utils::make_config_from_args(args); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); ansi_test_utils::assert_line_has_style( &output, 0, "────────────────────────────────────────────────┐", "blue", &config, ); ansi_test_utils::assert_line_has_style( &output, 1, "commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e │", "blue", &config, ); ansi_test_utils::assert_line_has_style( &output, 2, "────────────────────────────────────────────────┘", "blue", &config, ); let output = strip_ansi_codes(&output); assert!(output.contains( "\ ────────────────────────────────────────────────┐ commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e │ ────────────────────────────────────────────────┘ " )); } fn _do_test_commit_style_box_ul(args: &[&str]) { let config = integration_test_utils::make_config_from_args(args); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); ansi_test_utils::assert_line_has_style( &output, 0, "────────────────────────────────────────────────┐", "blue", &config, ); ansi_test_utils::assert_line_has_style( &output, 1, "commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e │", "blue", &config, ); ansi_test_utils::assert_line_has_style( &output, 2, "────────────────────────────────────────────────┴─", "blue", &config, ); let output = strip_ansi_codes(&output); assert!(output.contains( "\ ────────────────────────────────────────────────┐ commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e │ ────────────────────────────────────────────────┴─" )); } fn _do_test_commit_style_box_ol(args: &[&str]) { let config = integration_test_utils::make_config_from_args(args); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); ansi_test_utils::assert_line_has_style( &output, 0, "────────────────────────────────────────────────┬─", "blue", &config, ); ansi_test_utils::assert_line_has_style( &output, 1, "commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e │", "blue", &config, ); ansi_test_utils::assert_line_has_style( &output, 2, "────────────────────────────────────────────────┘", "blue", &config, ); let output = strip_ansi_codes(&output); assert!(output.contains( "\ ────────────────────────────────────────────────┬─ commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e │ ────────────────────────────────────────────────┘ " )); } #[test] fn test_commit_style_box_raw() { let config = integration_test_utils::make_config_from_args(&[ "--commit-style", "raw", "--commit-decoration-style", "box ul", "--width=64", ]); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); ansi_test_utils::assert_line_has_no_color( &output, 1, "commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e │", ); assert!(output.contains( "\ ────────────────────────────────────────────────┐ commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e │ ────────────────────────────────────────────────┴─" )); } // TODO: test overline #[test] fn test_commit_style_underline() { _do_test_commit_style_underline(&[ "--commit-style", "yellow", "--commit-decoration-style", "yellow underline", ]); } fn _do_test_commit_style_underline(args: &[&str]) { let config = integration_test_utils::make_config_from_args(args); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); ansi_test_utils::assert_line_has_style( &output, 0, "commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e", "yellow", &config, ); ansi_test_utils::assert_line_has_style( &output, 1, "───────────────────────────────────────────────", "yellow", &config, ); let output = strip_ansi_codes(&output); assert!(output.contains( "\ commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e ───────────────────────────────────────────────" )); } #[test] fn test_file_style_raw_no_decoration() { let config = integration_test_utils::make_config_from_args(&[ "--file-style", "raw", "--file-decoration-style", "omit", ]); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); for (i, line) in [ "diff --git a/src/align.rs b/src/align.rs", "index 8e37a9e..6ce4863 100644", "--- a/src/align.rs", "+++ b/src/align.rs", ] .iter() .enumerate() { ansi_test_utils::assert_line_has_no_color(&output, 6 + i, line); } assert!(output.contains( " diff --git a/src/align.rs b/src/align.rs index 8e37a9e..6ce4863 100644 --- a/src/align.rs +++ b/src/align.rs " )); } #[test] fn test_file_style_colored_input_color_is_stripped_under_normal() { let config = integration_test_utils::make_config_from_args(&[ "--file-style", "normal", "--file-decoration-style", "omit", ]); let output = integration_test_utils::run_delta( GIT_DIFF_SINGLE_HUNK_WITH_ANSI_ESCAPE_SEQUENCES, &config, ); ansi_test_utils::assert_line_has_no_color(&output, 7, "src/align.rs"); } #[test] fn test_file_style_colored_input_color_is_preserved_under_raw() { let config = integration_test_utils::make_config_from_args(&[ "--file-style", "raw", "--file-decoration-style", "omit", ]); let output = integration_test_utils::run_delta( GIT_DIFF_SINGLE_HUNK_WITH_ANSI_ESCAPE_SEQUENCES, &config, ); for (i, line) in [ "diff --git a/src/align.rs b/src/align.rs", "index 8e37a9e..6ce4863 100644", "--- a/src/align.rs", "+++ b/src/align.rs", ] .iter() .enumerate() { ansi_test_utils::assert_line_has_4_bit_color_style(&output, 6 + i, line, "31", &config) } } #[test] fn test_file_decoration_style_omit() { _do_test_file_style_no_decoration(&[ "--file-style", "green", "--file-decoration-style", "omit", ]); } #[test] fn test_file_decoration_style_empty_string() { _do_test_file_style_no_decoration(&[ "--file-style", "green", "--file-decoration-style", "", ]); } fn _do_test_file_style_no_decoration(args: &[&str]) { let config = integration_test_utils::make_config_from_args(args); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); ansi_test_utils::assert_line_has_style(&output, 7, "src/align.rs", "green", &config); let output = strip_ansi_codes(&output); assert!(output.contains("src/align.rs")); assert!(!output.contains("src/align.rs │")); assert!(!output.contains( " src/align.rs ────────────" )); } #[test] fn test_file_style_omit() { let config = integration_test_utils::make_config_from_args(&["--file-style", "omit"]); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); assert!(!output.contains("src/align.rs")); } #[test] fn test_file_style_box() { _do_test_file_style_box(&[ "--file-style", "green", "--file-decoration-style", "green box", ]); } #[test] fn test_file_style_box_ul() { _do_test_file_style_box_ul(&[ "--file-style", "green", "--file-decoration-style", "green box ul", ]); } #[ignore] #[test] fn test_file_style_box_ol() { _do_test_file_style_box_ol(&[ "--file-style", "green", "--file-decoration-style", "green box ol", ]); } fn _do_test_file_style_box(args: &[&str]) { let config = integration_test_utils::make_config_from_args(args); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); ansi_test_utils::assert_line_has_style(&output, 7, "─────────────┐", "green", &config); ansi_test_utils::assert_line_has_style(&output, 8, "src/align.rs │", "green", &config); ansi_test_utils::assert_line_has_style(&output, 9, "─────────────┘", "green", &config); let output = strip_ansi_codes(&output); assert!(output.contains( " ─────────────┐ src/align.rs │ ─────────────┘ " )); } fn _do_test_file_style_box_ul(args: &[&str]) { let config = integration_test_utils::make_config_from_args(args); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); ansi_test_utils::assert_line_has_style(&output, 7, "─────────────┐", "green", &config); ansi_test_utils::assert_line_has_style(&output, 8, "src/align.rs │", "green", &config); ansi_test_utils::assert_line_has_style(&output, 9, "─────────────┴─", "green", &config); let output = strip_ansi_codes(&output); assert!(output.contains( " ─────────────┐ src/align.rs │ ─────────────┴─" )); } fn _do_test_file_style_box_ol(args: &[&str]) { let config = integration_test_utils::make_config_from_args(args); let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config); ansi_test_utils::assert_line_has_style(&output, 7, "─────────────┬─", "green", &config); ansi_test_utils::assert_line_has_style(&output, 8, "src/align.rs │", "green", &config);
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
true
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/tests/integration_test_utils.rs
src/tests/integration_test_utils.rs
#![cfg(test)] use std::borrow::Cow; use std::fs::File; use std::io::{BufReader, Write}; use std::path::Path; use bytelines::ByteLines; use itertools::Itertools; use crate::ansi; use crate::cli; use crate::config; use crate::delta::delta; use crate::env::DeltaEnv; use crate::git_config::GitConfig; use crate::tests::test_utils; use crate::utils::process::tests::FakeParentArgs; pub fn make_options_from_args_and_git_config( args: &[&str], git_config_contents: Option<&[u8]>, git_config_path: Option<&str>, ) -> cli::Opt { _make_options_from_args_and_git_config( DeltaEnv::default(), args, git_config_contents, git_config_path, false, ) } pub fn make_options_from_args_and_git_config_with_custom_env( env: DeltaEnv, args: &[&str], git_config_contents: Option<&[u8]>, git_config_path: Option<&str>, ) -> cli::Opt { _make_options_from_args_and_git_config(env, args, git_config_contents, git_config_path, false) } pub fn make_options_from_args_and_git_config_honoring_env_var_with_custom_env( env: DeltaEnv, args: &[&str], git_config_contents: Option<&[u8]>, git_config_path: Option<&str>, ) -> cli::Opt { _make_options_from_args_and_git_config(env, args, git_config_contents, git_config_path, true) } fn _make_options_from_args_and_git_config( env: DeltaEnv, args: &[&str], git_config_contents: Option<&[u8]>, git_config_path: Option<&str>, honor_env_var: bool, ) -> cli::Opt { let mut args: Vec<&str> = itertools::chain(&["/dev/null", "/dev/null"], args) .copied() .collect(); let git_config = match (git_config_contents, git_config_path) { (Some(contents), Some(path)) => Some(make_git_config(&env, contents, path, honor_env_var)), _ => { args.push("--no-gitconfig"); None } }; cli::Opt::from_iter_and_git_config(&env, args, git_config) } pub fn make_options_from_args(args: &[&str]) -> cli::Opt { make_options_from_args_and_git_config(args, None, None) } #[allow(dead_code)] pub fn make_config_from_args_and_git_config( args: &[&str], git_config_contents: Option<&[u8]>, git_config_path: Option<&str>, ) -> config::Config { config::Config::from(make_options_from_args_and_git_config( args, git_config_contents, git_config_path, )) } pub fn make_config_from_args(args: &[&str]) -> config::Config { config::Config::from(make_options_from_args(args)) } pub fn make_git_config( env: &DeltaEnv, contents: &[u8], path: &str, honor_env_var: bool, ) -> GitConfig { let path = Path::new(path); let mut file = File::create(path).unwrap(); file.write_all(contents).unwrap(); GitConfig::from_path(env, path, honor_env_var) } pub fn get_line_of_code_from_delta( input: &str, line_number: usize, expected_text: &str, config: &config::Config, ) -> String { let output = run_delta(input, config); let line_of_code = output.lines().nth(line_number).unwrap(); assert!(ansi::strip_ansi_codes(line_of_code) == expected_text); line_of_code.to_string() } // Given an `expected` block as a raw string like: `r#" // #indent_mark [optional] // line1"#;` // line 2 etc. // ignore the first newline and compare the following `lines()` to those produced // by `have`, `skip`-ping the first few. The leading spaces of the first line // to indicate the last line in the list). The leading spaces of the first line // are stripped from every following line (and verified), unless the first line // marks the indentation level with `#indent_mark`. pub fn assert_lines_match_after_skip(skip: usize, expected: &str, have: &str) { let mut exp = expected.lines().peekable(); let mut line1 = exp.next().unwrap(); let allow_partial = line1 == "#partial"; assert!( allow_partial || line1.is_empty(), "first line must be empty or \"#partial\"" ); line1 = exp.peek().unwrap(); let indentation = line1.find(|c| c != ' ').unwrap_or(0); let ignore_indent = &line1[indentation..] == "#indent_mark"; if ignore_indent { let _indent_mark = exp.next(); } let mut it = have.lines().skip(skip); for (i, expected) in exp.enumerate() { if !ignore_indent { let next_indentation = expected.find(|c| c != ' ').unwrap_or(0); assert!( indentation == next_indentation, "The expected block has mixed indentation (use #indent_mark if that is on purpose)" ); } assert_eq!( &expected[indentation..], it.next().unwrap(), "on line {} of input:\n{}", i + 1, delineated_string(have), ); } if !allow_partial { assert_eq!(it.next(), None, "more input than expected"); } } pub fn assert_lines_match(expected: &str, have: &str) { assert_lines_match_after_skip(0, expected, have) } pub fn delineated_string(txt: &str) -> String { let top = "▼".repeat(100); let btm = "▲".repeat(100); let nl = "\n"; top + nl + txt + nl + &btm } pub struct DeltaTest<'a> { config: Cow<'a, config::Config>, calling_process: Option<String>, explain_ansi_: bool, } impl<'a> DeltaTest<'a> { pub fn with_args(args: &[&str]) -> Self { Self { config: Cow::Owned(make_config_from_args(args)), calling_process: None, explain_ansi_: false, } } pub fn with_config(config: &'a config::Config) -> Self { Self { config: Cow::Borrowed(config), calling_process: None, explain_ansi_: false, } } pub fn set_config<F>(mut self, f: F) -> Self where F: Fn(&mut config::Config), { let mut owned_config = self.config.into_owned(); f(&mut owned_config); self.config = Cow::Owned(owned_config); self } pub fn with_calling_process(mut self, command: &str) -> Self { self.calling_process = Some(command.to_string()); self } pub fn explain_ansi(mut self) -> Self { self.explain_ansi_ = true; self } pub fn with_input(&self, input: &str) -> DeltaTestOutput { let _args = FakeParentArgs::for_scope(self.calling_process.as_deref().unwrap_or("")); let raw = run_delta(input, &self.config); let cooked = if self.explain_ansi_ { ansi::explain_ansi(&raw, false) } else { ansi::strip_ansi_codes(&raw) }; DeltaTestOutput { raw_output: raw, output: cooked, } } } pub struct DeltaTestOutput { pub raw_output: String, pub output: String, } impl DeltaTestOutput { /// Print output, either without ANSI escape sequences or, if explain_ansi() has been called, /// with ASCII explanation of ANSI escape sequences. #[allow(unused)] pub fn inspect(self) -> Self { eprintln!("{}", delineated_string(&self.output)); self } /// Print raw output, with any ANSI escape sequences. #[allow(unused)] pub fn inspect_raw(self) -> Self { eprintln!("{}", delineated_string(&self.raw_output)); self } pub fn expect_after_skip(self, skip: usize, expected: &str) -> Self { assert_lines_match_after_skip(skip, expected, &self.output); self } pub fn expect(self, expected: &str) -> Self { self.expect_after_skip(0, expected) } pub fn expect_after_header(self, expected: &str) -> Self { self.expect_after_skip(crate::config::HEADER_LEN, expected) } pub fn skip_header(self) -> String { self.output.lines().skip(config::HEADER_LEN).join("\n") } pub fn expect_contains(self, expected: &str) -> Self { assert!( self.output.contains(expected), "Output does not contain \"{}\":\n{}\n", expected, delineated_string(&self.output) ); self } pub fn expect_raw_contains(self, expected: &str) -> Self { assert!( self.raw_output.contains(expected), "Raw output does not contain \"{}\":\n{}\n", expected, delineated_string(&self.raw_output) ); self } pub fn expect_contains_once(self, expected: &str) -> Self { assert!( test_utils::contains_once(&self.output, expected), "Output does not contain \"{}\" exactly once:\n{}\n", expected, delineated_string(&self.output) ); self } } pub fn run_delta(input: &str, config: &config::Config) -> String { let mut writer: Vec<u8> = Vec::new(); delta( ByteLines::new(BufReader::new(input.as_bytes())), &mut writer, config, ) .unwrap(); String::from_utf8(writer).unwrap() } pub mod tests { use super::*; #[test] fn test_lines_match_ok() { let expected = r#" one two three"#; assert_lines_match(expected, "one\ntwo\nthree"); let expected = r#" #indent_mark one 2 three"#; assert_lines_match(expected, "one\n 2\nthree"); let expected = r#" #indent_mark 1 2 3"#; assert_lines_match(expected, " 1 \n 2 \n 3"); let expected = r#" #indent_mark 1 ignored! 2 3"#; assert_lines_match(expected, " 1 \n 2 \n 3"); let expected = "\none\ntwo\nthree"; assert_lines_match(expected, "one\ntwo\nthree"); } #[test] #[should_panic] fn test_lines_match_no_nl() { let expected = r#"bad lines"#; assert_lines_match(expected, "bad\nlines"); } #[test] #[should_panic] fn test_lines_match_iter_not_consumed() { let expected = r#" one two three"#; assert_lines_match(expected, "one\ntwo\nthree\nFOUR"); } #[test] #[should_panic] fn test_lines_match_no_indent_mark_1() { let expected = r#" ok wrong_indent "#; assert_lines_match(expected, "ok"); } #[test] #[should_panic] fn test_lines_match_no_indent_mark_2() { let expected = r#" ok wrong_indent "#; assert_lines_match(expected, "ok"); } #[test] fn test_delta_test() { let input = "@@ -1,1 +1,1 @@ fn foo() {\n-1\n+2\n"; DeltaTest::with_args(&["--raw"]) .set_config(|c| c.pager = None) .set_config(|c| c.line_numbers = true) .with_input(input) .expect( r#" #indent_mark @@ -1,1 +1,1 @@ fn foo() { 1 ⋮ │-1 ⋮ 1 │+2"#, ); DeltaTest::with_args(&[]) .with_input(input) .expect_after_skip( 4, r#" 1 2"#, ); DeltaTest::with_args(&["--raw"]) .explain_ansi() .with_input(input) .expect( "\n\ (normal)@@ -1,1 +1,1 @@ fn foo() {\n\ (red)-1(normal)\n\ (green)+2(normal)", ); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/tests/ansi_test_utils.rs
src/tests/ansi_test_utils.rs
#[cfg(test)] #[allow(clippy::module_inception)] pub mod ansi_test_utils { use ansi_term; use crate::ansi; use crate::config::Config; use crate::delta::State; use crate::paint; use crate::style::Style; // Check if `output[line_number]` start with `expected_prefix` // Then check if the first style in the line is the `expected_style` pub fn assert_line_has_style( output: &str, line_number: usize, expected_prefix: &str, expected_style: &str, config: &Config, ) { assert!(_line_has_style( output, line_number, expected_prefix, expected_style, config, false, )); } // Check if `output[line_number]` start with `expected_prefix` // Then check if it contains the `expected_substring` with the corresponding `expected_style` // If the line contains multiples times the `expected_style`, will only compare with the first // item found pub fn assert_line_contain_substring_style( output: &str, line_number: usize, expected_prefix: &str, expected_substring: &str, expected_style: &str, config: &Config, ) { assert_eq!( expected_substring, _line_get_substring_matching_style( output, line_number, expected_prefix, expected_style, config, ) .unwrap() ); } // Check if `output[line_number]` start with `expected_prefix` // Then check if the line does not contains the `expected_style` pub fn assert_line_does_not_contain_substring_style( output: &str, line_number: usize, expected_prefix: &str, expected_style: &str, config: &Config, ) { assert!(_line_get_substring_matching_style( output, line_number, expected_prefix, expected_style, config, ) .is_none()); } pub fn assert_line_does_not_have_style( output: &str, line_number: usize, expected_prefix: &str, expected_style: &str, config: &Config, ) { assert!(!_line_has_style( output, line_number, expected_prefix, expected_style, config, false, )); } pub fn assert_line_has_4_bit_color_style( output: &str, line_number: usize, expected_prefix: &str, expected_style: &str, config: &Config, ) { assert!(_line_has_style( output, line_number, expected_prefix, expected_style, config, true, )); } pub fn assert_line_has_no_color(output: &str, line_number: usize, expected_prefix: &str) { let line = output.lines().nth(line_number).unwrap(); let stripped_line = ansi::strip_ansi_codes(line); assert!(stripped_line.starts_with(expected_prefix)); assert_eq!(line, stripped_line); } /// Assert that the specified line number of output (a) has, after stripping ANSI codes, a /// substring starting at `substring_begin` equal to `expected_substring` and (b) in its raw /// form contains a version of that substring syntax-highlighted according to /// `language_extension`. pub fn assert_line_has_syntax_highlighted_substring( output: &str, line_number: usize, substring_begin: usize, expected_substring: &str, filename_for_highlighting: &str, state: State, config: &Config, ) { assert!( filename_for_highlighting.contains('.'), "expecting filename, not just a file extension" ); let line = output.lines().nth(line_number).unwrap(); let substring_end = substring_begin + expected_substring.len(); let substring = &ansi::strip_ansi_codes(line)[substring_begin..substring_end]; assert_eq!(substring, expected_substring); let painted_substring = paint_line(substring, filename_for_highlighting, state, config); // remove trailing newline appended by paint::paint_lines. assert!(line.contains(painted_substring.trim_end())); } pub fn assert_has_color_other_than_plus_color(string: &str, config: &Config) { let (string_without_any_color, string_with_plus_color_only) = get_color_variants(string, config); assert_ne!(string, string_without_any_color); assert_ne!(string, string_with_plus_color_only); } pub fn assert_has_plus_color_only(string: &str, config: &Config) { let (string_without_any_color, string_with_plus_color_only) = get_color_variants(string, config); assert_ne!(string, string_without_any_color); assert_eq!(string, string_with_plus_color_only); } pub fn get_color_variants(string: &str, config: &Config) -> (String, String) { let string_without_any_color = ansi::strip_ansi_codes(string); let string_with_plus_color_only = config .plus_style .ansi_term_style .paint(&string_without_any_color); ( string_without_any_color.to_string(), string_with_plus_color_only.to_string(), ) } pub fn paint_line( line: &str, filename_for_highlighting: &str, state: State, config: &Config, ) -> String { let mut output_buffer = String::new(); let mut unused_writer = Vec::<u8>::new(); let mut painter = paint::Painter::new(&mut unused_writer, config); let syntax_highlighted_style = Style { is_syntax_highlighted: true, ..Style::new() }; painter.set_syntax(Some(filename_for_highlighting)); painter.set_highlighter(); let lines = vec![(line.to_string(), state)]; let syntax_style_sections = paint::get_syntax_style_sections_for_lines( &lines, painter.highlighter.as_mut(), config, ); let diff_style_sections = vec![vec![(syntax_highlighted_style, lines[0].0.as_str())]]; paint::Painter::paint_lines( &lines, &syntax_style_sections, &diff_style_sections, &[false], &mut output_buffer, config, &mut None, None, paint::BgShouldFill::default(), ); output_buffer } fn _line_extract<'a>(output: &'a str, line_number: usize, expected_prefix: &str) -> &'a str { let line = output.lines().nth(line_number).unwrap(); assert!(ansi::strip_ansi_codes(line).starts_with(expected_prefix)); line } fn _line_get_substring_matching_style<'a>( output: &'a str, line_number: usize, expected_prefix: &str, expected_style: &str, config: &Config, ) -> Option<&'a str> { let line = _line_extract(output, line_number, expected_prefix); let style = Style::from_str( expected_style, None, None, config.true_color, config.git_config.as_ref(), ); style.get_matching_substring(line) } fn _line_has_style( output: &str, line_number: usize, expected_prefix: &str, expected_style: &str, config: &Config, _4_bit_color: bool, ) -> bool { let line = _line_extract(output, line_number, expected_prefix); let mut style = Style::from_str( expected_style, None, None, config.true_color, config.git_config(), ); if _4_bit_color { style.ansi_term_style.foreground = style .ansi_term_style .foreground .map(ansi_term_fixed_foreground_to_4_bit_color); } style.is_applied_to(line) } fn ansi_term_fixed_foreground_to_4_bit_color(color: ansi_term::Color) -> ansi_term::Color { match color { ansi_term::Color::Fixed(30) => ansi_term::Color::Black, ansi_term::Color::Fixed(31) => ansi_term::Color::Red, ansi_term::Color::Fixed(32) => ansi_term::Color::Green, ansi_term::Color::Fixed(33) => ansi_term::Color::Yellow, ansi_term::Color::Fixed(34) => ansi_term::Color::Blue, ansi_term::Color::Fixed(35) => ansi_term::Color::Purple, ansi_term::Color::Fixed(36) => ansi_term::Color::Cyan, ansi_term::Color::Fixed(37) => ansi_term::Color::White, color => panic!( "Invalid 4-bit color: {:?}. \ (Add bright color entries to this map if needed for tests.", color ), } } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/tests/test_utils.rs
src/tests/test_utils.rs
#![cfg(test)] /// Return true iff `s` contains exactly one occurrence of substring `t`. pub fn contains_once(s: &str, t: &str) -> bool { match (s.find(t), s.rfind(t)) { (Some(i), Some(j)) => i == j, _ => false, } } #[allow(dead_code)] pub fn print_with_line_numbers(s: &str) { for (i, t) in s.lines().enumerate() { println!("{:>2}│ {}", i + 1, t); } } #[cfg(test)] mod tests { use crate::tests::test_utils::*; #[test] fn test_contains_once_1() { assert!(contains_once("", "")); } #[test] fn test_contains_once_2() { assert!(contains_once("a", "a")); } #[test] fn test_contains_once_3() { assert!(!contains_once("", "a")); } #[test] fn test_contains_once_4() { assert!(!contains_once("a", "b")); } #[test] fn test_contains_once_5() { assert!(!contains_once("a a", "a")); } #[test] fn test_contains_once_6() { assert!(contains_once("a b", "b")); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/tests/mod.rs
src/tests/mod.rs
pub mod ansi_test_utils; pub mod integration_test_utils; pub mod test_example_diffs; pub mod test_utils; #[cfg(not(test))] pub const TESTING: bool = false; #[cfg(test)] pub const TESTING: bool = true; #[test] #[allow(clippy::assertions_on_constants)] fn am_testing() { assert!(TESTING); }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/round_char_boundary.rs
src/utils/round_char_boundary.rs
// Taken from https://github.com/rust-lang/rust/pull/86497 // TODO: Remove when this is in the version of the Rust standard library that delta is building // against. #[inline] const fn is_utf8_char_boundary(b: u8) -> bool { // This is bit magic equivalent to: b < 128 || b >= 192 (b as i8) >= -0x40 } #[inline] pub fn floor_char_boundary(s: &str, index: usize) -> usize { if index >= s.len() { s.len() } else { let lower_bound = index.saturating_sub(3); let new_index = s.as_bytes()[lower_bound..=index] .iter() .rposition(|b| is_utf8_char_boundary(*b)); // SAFETY: we know that the character boundary will be within four bytes unsafe { lower_bound + new_index.unwrap_unchecked() } } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/path.rs
src/utils/path.rs
use std::path::{Component, Path, PathBuf}; use crate::config::Config; use super::process::calling_process; // Infer absolute path to `relative_path`. pub fn absolute_path(relative_path: &str, config: &Config) -> Option<PathBuf> { match ( &config.cwd_of_delta_process, &config.cwd_of_user_shell_process, calling_process().paths_in_input_are_relative_to_cwd() || config.relative_paths, ) { // Note that if we were invoked by git then cwd_of_delta_process == repo_root (Some(cwd_of_delta_process), _, false) => Some(cwd_of_delta_process.join(relative_path)), (_, Some(cwd_of_user_shell_process), true) => { Some(cwd_of_user_shell_process.join(relative_path)) } (Some(cwd_of_delta_process), None, true) => { // This might occur when piping from git to delta? Some(cwd_of_delta_process.join(relative_path)) } _ => None, } .map(normalize_path) } #[allow(clippy::needless_borrows_for_generic_args)] // Lint has known problems, &path != path /// Relativize `path` if delta `config` demands that and paths are not already relativized by git. pub fn relativize_path_maybe(path: &mut String, config: &Config) { let mut inner_relativize = || -> Option<()> { let base = config.cwd_relative_to_repo_root.as_deref()?; let relative_path = pathdiff::diff_paths(&path, base)?; if relative_path.is_relative() { #[cfg(target_os = "windows")] // '/dev/null' is converted to '\dev\null' and considered relative. Work // around that by leaving all paths like that untouched: if relative_path.starts_with(Path::new(r"\")) { return None; } *path = relative_path.to_string_lossy().into_owned(); } Some(()) }; if config.relative_paths && !calling_process().paths_in_input_are_relative_to_cwd() { let _ = inner_relativize(); } } /// Return current working directory of the user's shell process. I.e. the directory which they are /// in when delta exits. This is the directory relative to which the file paths in delta output are /// constructed if they are using either (a) delta's relative-paths option or (b) git's --relative /// flag. pub fn cwd_of_user_shell_process( cwd_of_delta_process: Option<&PathBuf>, cwd_relative_to_repo_root: Option<&str>, ) -> Option<PathBuf> { match (cwd_of_delta_process, cwd_relative_to_repo_root) { (Some(cwd), None) => { // We are not a child process of git Some(PathBuf::from(cwd)) } (Some(repo_root), Some(cwd_relative_to_repo_root)) => { // We are a child process of git; git spawned us from repo_root and preserved the user's // original cwd in the GIT_PREFIX env var (available as config.cwd_relative_to_repo_root) Some(PathBuf::from(repo_root).join(cwd_relative_to_repo_root)) } (None, _) => { // Unexpected None } } } // Copied from // https://github.com/rust-lang/cargo/blob/c6745a3d7fcea3a949c3e13e682b8ddcbd213add/crates/cargo-util/src/paths.rs#L73-L106 // as suggested by matklad: https://www.reddit.com/r/rust/comments/hkkquy/comment/fwtw53s/?utm_source=share&utm_medium=web2x&context=3 fn normalize_path<P>(path: P) -> PathBuf where P: AsRef<Path>, { let mut components = path.as_ref().components().peekable(); let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() { components.next(); PathBuf::from(c.as_os_str()) } else { PathBuf::new() }; for component in components { match component { Component::Prefix(..) => unreachable!(), Component::RootDir => { ret.push(component.as_os_str()); } Component::CurDir => {} Component::ParentDir => { ret.pop(); } Component::Normal(c) => { ret.push(c); } } } ret } #[cfg(test)] pub fn fake_delta_cwd_for_tests() -> PathBuf { #[cfg(not(target_os = "windows"))] { PathBuf::from("/fake/delta/cwd") } #[cfg(target_os = "windows")] { PathBuf::from(r"C:\fake\delta\cwd") } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/tabs.rs
src/utils/tabs.rs
use unicode_segmentation::UnicodeSegmentation; #[derive(Debug, Clone)] pub struct TabCfg { replacement: String, } impl TabCfg { pub fn new(width: usize) -> Self { TabCfg { replacement: " ".repeat(width), } } pub fn width(&self) -> usize { self.replacement.len() } pub fn replace(&self) -> bool { !self.replacement.is_empty() } } /// Expand tabs as spaces. pub fn expand(line: &str, tab_cfg: &TabCfg) -> String { if tab_cfg.replace() && line.as_bytes().contains(&b'\t') { itertools::join(line.split('\t'), &tab_cfg.replacement) } else { line.to_string() } } /// Remove `prefix` chars from `line`, then call `tabs::expand()`. pub fn remove_prefix_and_expand(prefix: usize, line: &str, tab_cfg: &TabCfg) -> String { let line_bytes = line.as_bytes(); // The to-be-removed prefixes are almost always ascii +/- (or ++/ +/.. for merges) for // which grapheme clusters are not required. if line_bytes.len() >= prefix && line_bytes[..prefix].is_ascii() { // Safety: slicing into the utf-8 line-str is ok, upto `prefix` only ascii was present. expand(&line[prefix..], tab_cfg) } else { let cut_line = line.graphemes(true).skip(prefix).collect::<String>(); expand(&cut_line, tab_cfg) } } #[cfg(test)] pub mod tests { use super::*; #[test] fn test_remove_prefix_and_expand() { let line = "+-foo\tbar"; let result = remove_prefix_and_expand(2, line, &TabCfg::new(3)); assert_eq!(result, "foo bar"); let result = remove_prefix_and_expand(2, line, &TabCfg::new(0)); assert_eq!(result, "foo\tbar"); let utf8_prefix = "-│-foo\tbar"; let n = 3; let result = remove_prefix_and_expand(n, utf8_prefix, &TabCfg::new(1)); assert_eq!(result, "foo bar"); // ensure non-ascii chars were removed: assert!(utf8_prefix.len() - result.len() > n); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/process.rs
src/utils/process.rs
use std::collections::{HashMap, HashSet}; use std::path::Path; use std::sync::atomic::AtomicUsize; use std::sync::{Arc, Condvar, Mutex, MutexGuard}; use lazy_static::lazy_static; use sysinfo::{Pid, PidExt, Process, ProcessExt, ProcessRefreshKind, SystemExt}; use crate::utils::DELTA_ATOMIC_ORDERING; pub type DeltaPid = u32; #[derive(Clone, Debug, PartialEq, Eq)] pub enum CallingProcess { GitDiff(CommandLine), GitShow(CommandLine, Option<String>), // element 2 is filename GitLog(CommandLine), GitReflog(CommandLine), GitBlame(CommandLine), GitGrep(CommandLine), OtherGrep, // rg, grep, ag, ack, etc None, // no matching process could be found Pending, // calling process is currently being determined } // The information where the calling process info comes from *should* be inside // `CallingProcess`, but that is handed out (within a MutexGuard) to callers. // To keep the interface simple, store it here: static CALLER_INFO_SOURCE: AtomicUsize = AtomicUsize::new(CALLER_GUESSED); const CALLER_GUESSED: usize = 1; const CALLER_KNOWN: usize = 2; impl CallingProcess { pub fn paths_in_input_are_relative_to_cwd(&self) -> bool { match self { CallingProcess::GitDiff(cmd) if cmd.long_options.contains("--relative") => true, CallingProcess::GitShow(cmd, _) if cmd.long_options.contains("--relative") => true, CallingProcess::GitLog(cmd) if cmd.long_options.contains("--relative") => true, CallingProcess::GitBlame(_) | CallingProcess::GitGrep(_) | CallingProcess::OtherGrep => true, _ => false, } } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct CommandLine { pub long_options: HashSet<String>, pub short_options: HashSet<String>, pub last_arg: Option<String>, } lazy_static! { static ref CALLER: Arc<(Mutex<CallingProcess>, Condvar)> = Arc::new((Mutex::new(CallingProcess::Pending), Condvar::new())); } // delta was called by this process (or called by something which called delta and it), // try looking up this information in the process tree. pub fn start_determining_calling_process_in_thread() { // The handle is neither kept nor returned nor joined but dropped, so the main // thread can exit early if it does not need to know its parent process. std::thread::Builder::new() .name("find_calling_process".into()) .spawn(move || { let calling_process = determine_calling_process(); let (caller_mutex, determine_done) = &**CALLER; let mut caller = caller_mutex.lock().unwrap(); if CALLER_INFO_SOURCE.load(DELTA_ATOMIC_ORDERING) <= CALLER_GUESSED { *caller = calling_process; } determine_done.notify_all(); }) .unwrap(); } // delta starts the process, so it is known. pub fn set_calling_process(args: &[String]) { if let ProcessArgs::Args(result) = describe_calling_process(args) { let (caller_mutex, determine_done) = &**CALLER; let mut caller = caller_mutex.lock().unwrap(); *caller = result; CALLER_INFO_SOURCE.store(CALLER_KNOWN, DELTA_ATOMIC_ORDERING); determine_done.notify_all(); } } #[cfg(not(test))] pub fn calling_process() -> MutexGuard<'static, CallingProcess> { let (caller_mutex, determine_done) = &**CALLER; determine_done .wait_while(caller_mutex.lock().unwrap(), |caller| { *caller == CallingProcess::Pending }) .unwrap() } // The return value is duck-typed to work in place of a MutexGuard when testing. #[cfg(test)] pub fn calling_process() -> Box<CallingProcess> { type _UnusedImport = MutexGuard<'static, i8>; if crate::utils::process::tests::FakeParentArgs::are_set() { // If the (thread-local) FakeParentArgs are set, then the following command returns // these, so the cached global real ones can not be used. Box::new(determine_calling_process()) } else { let (caller_mutex, _) = &**CALLER; let mut caller = caller_mutex.lock().unwrap(); if *caller == CallingProcess::Pending { *caller = determine_calling_process(); } Box::new(caller.clone()) } } fn determine_calling_process() -> CallingProcess { calling_process_cmdline(ProcInfo::new(), describe_calling_process) .unwrap_or(CallingProcess::None) } // Return value of `extract_args(args: &[String]) -> ProcessArgs<T>` function which is // passed to `calling_process_cmdline()`. #[derive(Debug, PartialEq, Eq)] pub enum ProcessArgs<T> { // A result has been successfully extracted from args. Args(T), // The extraction has failed. ArgError, // The process does not match, others may be inspected. OtherProcess, } pub fn describe_calling_process(args: &[String]) -> ProcessArgs<CallingProcess> { let mut args = args.iter().map(|s| s.as_str()); fn is_any_of<'a, I>(cmd: Option<&str>, others: I) -> bool where I: IntoIterator<Item = &'a str>, { cmd.map(|cmd| others.into_iter().any(|o| o.eq_ignore_ascii_case(cmd))) .unwrap_or(false) } match args.next() { Some(command) => match Path::new(command).file_stem() { Some(s) if s.to_str().map(is_git_binary).unwrap_or(false) => { let mut args = args.skip_while(|s| { *s != "diff" && *s != "show" && *s != "log" && *s != "reflog" && *s != "grep" && *s != "blame" }); match args.next() { Some("diff") => { ProcessArgs::Args(CallingProcess::GitDiff(parse_command_line(args))) } Some("show") => { let command_line = parse_command_line(args); let filename = if let Some(last_arg) = &command_line.last_arg { match last_arg.split_once(':') { Some((_, filename)) => Path::new(filename) .file_name() .map(|f| f.to_string_lossy().to_string()), None => None, } } else { None }; ProcessArgs::Args(CallingProcess::GitShow(command_line, filename)) } Some("log") => { ProcessArgs::Args(CallingProcess::GitLog(parse_command_line(args))) } Some("reflog") => { ProcessArgs::Args(CallingProcess::GitReflog(parse_command_line(args))) } Some("grep") => { ProcessArgs::Args(CallingProcess::GitGrep(parse_command_line(args))) } Some("blame") => { ProcessArgs::Args(CallingProcess::GitBlame(parse_command_line(args))) } _ => { // It's git, but not a subcommand that we parse. Don't // look at any more processes. ProcessArgs::ArgError } } } // TODO: parse_style_sections is failing to parse ANSI escape sequences emitted by // grep (BSD and GNU), ag, pt. See #794 Some(s) if is_any_of(s.to_str(), ["rg", "ack", "sift"]) => { ProcessArgs::Args(CallingProcess::OtherGrep) } Some(_) => { // It's not git, and it's not another grep tool. Keep // looking at other processes. ProcessArgs::OtherProcess } _ => { // Could not parse file stem (not expected); keep looking at // other processes. ProcessArgs::OtherProcess } }, _ => { // Empty arguments (not expected); keep looking. ProcessArgs::OtherProcess } } } fn is_git_binary(git: &str) -> bool { // Ignore case, for e.g. NTFS or APFS file systems Path::new(git) .file_stem() .and_then(|os_str| os_str.to_str()) .map(|s| s.eq_ignore_ascii_case("git")) .unwrap_or(false) } // Given `--aa val -bc -d val e f -- ...` return // ({"--aa"}, {"-b", "-c", "-d"}) fn parse_command_line<'a>(args: impl Iterator<Item = &'a str>) -> CommandLine { let mut long_options = HashSet::new(); let mut short_options = HashSet::new(); let mut last_arg = None; let mut after_double_dash = false; for s in args { if after_double_dash { last_arg = Some(s); } else if s == "--" { after_double_dash = true; } else if s.starts_with("--") { long_options.insert(s.split('=').next().unwrap().to_owned()); } else if let Some(suffix) = s.strip_prefix('-') { short_options.extend(suffix.chars().map(|c| format!("-{c}"))); } else { last_arg = Some(s); } } CommandLine { long_options, short_options, last_arg: last_arg.map(|s| s.to_string()), } } struct ProcInfo { info: sysinfo::System, } impl ProcInfo { fn new() -> Self { // On Linux sysinfo optimizes for repeated process queries and keeps per-process // /proc file descriptors open. This caching is not needed here, so // set this to zero (this does nothing on other platforms). // Also, there is currently a kernel bug which slows down syscalls when threads are // involved (here: the ctrlc handler) and a lot of files are kept open. sysinfo::set_open_files_limit(0); ProcInfo { info: sysinfo::System::new(), } } } trait ProcActions { fn cmd(&self) -> &[String]; fn parent(&self) -> Option<DeltaPid>; fn pid(&self) -> DeltaPid; fn start_time(&self) -> u64; } impl<T> ProcActions for T where T: ProcessExt, { fn cmd(&self) -> &[String] { ProcessExt::cmd(self) } fn parent(&self) -> Option<DeltaPid> { ProcessExt::parent(self).map(|p| p.as_u32()) } fn pid(&self) -> DeltaPid { ProcessExt::pid(self).as_u32() } fn start_time(&self) -> u64 { ProcessExt::start_time(self) } } trait ProcessInterface { type Out: ProcActions; fn my_pid(&self) -> DeltaPid; fn process(&self, pid: DeltaPid) -> Option<&Self::Out>; fn processes(&self) -> &HashMap<Pid, Self::Out>; fn refresh_process(&mut self, pid: DeltaPid) -> bool; fn refresh_processes(&mut self); fn parent_process(&mut self, pid: DeltaPid) -> Option<&Self::Out> { self.refresh_process(pid).then_some(())?; let parent_pid = self.process(pid)?.parent()?; self.refresh_process(parent_pid).then_some(())?; self.process(parent_pid) } fn naive_sibling_process(&mut self, pid: DeltaPid) -> Option<&Self::Out> { let sibling_pid = pid - 1; self.refresh_process(sibling_pid).then_some(())?; self.process(sibling_pid) } fn find_sibling_in_refreshed_processes<F, T>( &mut self, pid: DeltaPid, extract_args: &F, ) -> Option<T> where F: Fn(&[String]) -> ProcessArgs<T>, Self: Sized, { /* $ start_blame_of.sh src/main.rs | delta \_ /usr/bin/some-terminal-emulator | \_ common_git_and_delta_ancestor | \_ /bin/sh /opt/git/start_blame_of.sh src/main.rs | | \_ /bin/sh /opt/some/wrapper git blame src/main.rs | | \_ /usr/bin/git blame src/main.rs | \_ /bin/sh /opt/some/wrapper delta | \_ delta Walk up the process tree of delta and of every matching other process, counting the steps along the way. Find the common ancestor processes, calculate the distance, and select the one with the shortest. */ let this_start_time = self.process(pid)?.start_time(); let mut pid_distances = HashMap::<DeltaPid, usize>::new(); let mut collect_parent_pids = |pid, distance| { pid_distances.insert(pid, distance); }; iter_parents(self, pid, &mut collect_parent_pids); let process_start_time_difference_less_than_3s = |a, b| (a as i64 - b as i64).abs() < 3; let cmdline_of_closest_matching_process = self .processes() .iter() .filter(|(_, proc)| { process_start_time_difference_less_than_3s(this_start_time, proc.start_time()) }) .filter_map(|(&pid, proc)| match extract_args(proc.cmd()) { ProcessArgs::Args(args) => { let mut length_of_process_chain = usize::MAX; let mut sum_distance = |pid, distance| { if length_of_process_chain == usize::MAX { if let Some(distance_to_first_common_parent) = pid_distances.get(&pid) { length_of_process_chain = distance_to_first_common_parent + distance; } } }; iter_parents(self, pid.as_u32(), &mut sum_distance); if length_of_process_chain == usize::MAX { None } else { Some((length_of_process_chain, args)) } } _ => None, }) .min_by_key(|(distance, _)| *distance) .map(|(_, result)| result); cmdline_of_closest_matching_process } } impl ProcessInterface for ProcInfo { type Out = Process; fn my_pid(&self) -> DeltaPid { std::process::id() } fn refresh_process(&mut self, pid: DeltaPid) -> bool { self.info .refresh_process_specifics(Pid::from_u32(pid), ProcessRefreshKind::new()) } fn process(&self, pid: DeltaPid) -> Option<&Self::Out> { self.info.process(Pid::from_u32(pid)) } fn processes(&self) -> &HashMap<Pid, Self::Out> { self.info.processes() } fn refresh_processes(&mut self) { self.info .refresh_processes_specifics(ProcessRefreshKind::new()) } } fn calling_process_cmdline<P, F, T>(mut info: P, extract_args: F) -> Option<T> where P: ProcessInterface, F: Fn(&[String]) -> ProcessArgs<T>, { #[cfg(test)] { if let Some(args) = tests::FakeParentArgs::get() { match extract_args(&args) { ProcessArgs::Args(result) => return Some(result), _ => return None, } } } let my_pid = info.my_pid(); // 1) Try the parent process(es). If delta is set as the pager in git, then git is the parent process. // If delta is started by a script check the parent's parent as well. let mut current_pid = my_pid; 'parent_iter: for depth in [1, 2, 3] { let parent = match info.parent_process(current_pid) { None => { break 'parent_iter; } Some(parent) => parent, }; let parent_pid = parent.pid(); match extract_args(parent.cmd()) { ProcessArgs::Args(result) => return Some(result), ProcessArgs::ArgError => return None, // 2) The 1st parent process was something else, this can happen if git output is piped into delta, e.g. // `git blame foo.txt | delta`. When the shell sets up the pipe it creates the two processes, the pids // are usually consecutive, so naively check if the process with `my_pid - 1` matches. ProcessArgs::OtherProcess if depth == 1 => { let sibling = info.naive_sibling_process(current_pid); if let Some(proc) = sibling { if let ProcessArgs::Args(result) = extract_args(proc.cmd()) { return Some(result); } } } // This check is not done for the parent's parent etc. ProcessArgs::OtherProcess => {} } current_pid = parent_pid; } /* 3) Neither parent(s) nor the direct sibling were a match. The most likely case is that the input program of the pipe wrote all its data and exited before delta started, so no command line can be parsed. Same if the data was piped from an input file. There might also be intermediary scripts in between or piped input with a gap in pids or (rarely) randomized pids, so check processes for the closest match in the process tree. The size of this process tree can be reduced by only refreshing selected processes. 100 /usr/bin/some-terminal-emulator 124 \_ -shell 301 | \_ /usr/bin/git blame src/main.rs 302 | \_ wraps_delta.sh 303 | \_ delta 304 | \_ less --RAW-CONTROL-CHARS --quit-if-one-screen 125 \_ -shell 800 | \_ /usr/bin/git blame src/main.rs 200 | \_ delta 400 | \_ less --RAW-CONTROL-CHARS --quit-if-one-screen 126 \_ -shell 501 | \_ /bin/sh /wrapper/for/git blame src/main.rs 555 | | \_ /usr/bin/git blame src/main.rs 502 | \_ delta 567 | \_ less --RAW-CONTROL-CHARS --quit-if-one-screen */ // Also `add` because `A_has_pid101 | delta_has_pid102`, but if A is a wrapper which then calls // git (no `exec`), then the final pid of the git process might be 103 or greater. let pid_range = my_pid.saturating_sub(10)..my_pid.saturating_add(10); for p in pid_range { // Processes which were not refreshed do not exist for sysinfo, so by selectively // letting it know about processes the `find_sibling..` function will only // consider these. if info.process(p).is_none() { info.refresh_process(p); } } match info.find_sibling_in_refreshed_processes(my_pid, &extract_args) { None => { #[cfg(not(target_os = "linux"))] let full_scan = true; // The full scan is expensive on Linux and rarely successful, so disable it by default. #[cfg(target_os = "linux")] let full_scan = std::env::var("DELTA_CALLING_PROCESS_QUERY_ALL") .is_ok_and(|v| !["0", "false", "no"].iter().any(|&n| n == v)); if full_scan { info.refresh_processes(); info.find_sibling_in_refreshed_processes(my_pid, &extract_args) } else { None } } some => some, } } // Walk up the process tree, calling `f` with the pid and the distance to `starting_pid`. // Prerequisite: `info.refresh_processes()` has been called. fn iter_parents<P, F>(info: &P, starting_pid: DeltaPid, f: F) where P: ProcessInterface, F: FnMut(DeltaPid, usize), { fn inner_iter_parents<P, F>(info: &P, pid: DeltaPid, mut f: F, distance: usize) where P: ProcessInterface, F: FnMut(u32, usize), { // Probably bad input, not a tree: if distance > 2000 { return; } if let Some(proc) = info.process(pid) { if let Some(pid) = proc.parent() { f(pid, distance); inner_iter_parents(info, pid, f, distance + 1) } } } inner_iter_parents(info, starting_pid, f, 1) } #[cfg(test)] pub mod tests { use super::*; use itertools::Itertools; use std::cell::RefCell; use std::rc::Rc; thread_local! { static FAKE_ARGS: RefCell<TlsState<Vec<String>>> = const { RefCell::new(TlsState::None) }; } #[derive(Debug, PartialEq)] enum TlsState<T> { Once(T), Scope(T), With(usize, Rc<Vec<T>>), None, Invalid, ErrorAlreadyHandled, } // When calling `FakeParentArgs::get()`, it can return `Some(values)` which were set earlier // during in the #[test]. Otherwise returns None. // This value can be valid once: `FakeParentArgs::once(val)`, for the entire scope: // `FakeParentArgs::for_scope(val)`, or can be different values every time `get()` is called: // `FakeParentArgs::with([val1, val2, val3])`. // It is an error if `once` or `with` values remain unused, or are overused. // Note: The values are stored per-thread, so the expectation is that no thread boundaries are // crossed. pub struct FakeParentArgs {} impl FakeParentArgs { pub fn once(args: &str) -> Self { Self::new(args, TlsState::Once, "once") } pub fn for_scope(args: &str) -> Self { Self::new(args, TlsState::Scope, "for_scope") } fn new<F>(args: &str, initial: F, from_: &str) -> Self where F: Fn(Vec<String>) -> TlsState<Vec<String>>, { let string_vec = args.split(' ').map(str::to_owned).collect(); if FAKE_ARGS.with(|a| a.replace(initial(string_vec))) != TlsState::None { Self::error(from_); } FakeParentArgs {} } pub fn with(args: &[&str]) -> Self { let with = TlsState::With( 0, Rc::new( args.iter() .map(|a| a.split(' ').map(str::to_owned).collect()) .collect(), ), ); if FAKE_ARGS.with(|a| a.replace(with)) != TlsState::None || args.is_empty() { Self::error("with creation"); } FakeParentArgs {} } pub fn get() -> Option<Vec<String>> { FAKE_ARGS.with(|a| { let old_value = a.replace_with(|old_value| match old_value { TlsState::Once(_) => TlsState::Invalid, TlsState::Scope(args) => TlsState::Scope(args.clone()), TlsState::With(n, args) => TlsState::With(*n + 1, Rc::clone(args)), TlsState::None => TlsState::None, TlsState::Invalid => TlsState::Invalid, TlsState::ErrorAlreadyHandled => TlsState::ErrorAlreadyHandled, }); match old_value { TlsState::Once(args) | TlsState::Scope(args) => Some(args), TlsState::With(n, args) if n < args.len() => Some(args[n].clone()), TlsState::None => None, TlsState::Invalid | TlsState::With(_, _) | TlsState::ErrorAlreadyHandled => { Self::error("get"); None } } }) } pub fn are_set() -> bool { FAKE_ARGS.with(|a| { *a.borrow() != TlsState::None && *a.borrow() != TlsState::ErrorAlreadyHandled }) } fn error(where_: &str) { FAKE_ARGS.with(|a| { let old_value = a.replace(TlsState::ErrorAlreadyHandled); match old_value { TlsState::ErrorAlreadyHandled => (), _ => { panic!( "test logic error (in {}): wrong FakeParentArgs scope?", where_ ); } } }); } } impl Drop for FakeParentArgs { fn drop(&mut self) { // Clears an Invalid state and tests if a Once or With value has been used. FAKE_ARGS.with(|a| { let old_value = a.replace(TlsState::None); match old_value { TlsState::With(n, args) => { if n != args.len() { Self::error("drop with") } } TlsState::Once(_) | TlsState::None => Self::error("drop"), TlsState::Scope(_) | TlsState::Invalid | TlsState::ErrorAlreadyHandled => {} } }); } } #[derive(Debug, Default)] struct FakeProc { #[allow(dead_code)] pid: DeltaPid, start_time: u64, cmd: Vec<String>, ppid: Option<DeltaPid>, } impl FakeProc { fn new(pid: DeltaPid, start_time: u64, cmd: Vec<String>, ppid: Option<DeltaPid>) -> Self { FakeProc { pid, start_time, cmd, ppid, } } } impl ProcActions for FakeProc { fn cmd(&self) -> &[String] { &self.cmd } fn parent(&self) -> Option<DeltaPid> { self.ppid } fn pid(&self) -> DeltaPid { self.pid } fn start_time(&self) -> u64 { self.start_time } } #[derive(Debug, Default)] struct MockProcInfo { delta_pid: DeltaPid, info: HashMap<Pid, FakeProc>, } impl MockProcInfo { fn with(processes: &[(DeltaPid, u64, &str, Option<DeltaPid>)]) -> Self { MockProcInfo { delta_pid: processes.last().map(|p| p.0).unwrap_or(1), info: processes .iter() .map(|(pid, start_time, cmd, ppid)| { let cmd_vec = cmd.split(' ').map(str::to_owned).collect(); ( Pid::from_u32(*pid), FakeProc::new(*pid, *start_time, cmd_vec, *ppid), ) }) .collect(), } } } impl ProcessInterface for MockProcInfo { type Out = FakeProc; fn my_pid(&self) -> DeltaPid { self.delta_pid } fn process(&self, pid: DeltaPid) -> Option<&Self::Out> { self.info.get(&Pid::from_u32(pid)) } fn processes(&self) -> &HashMap<Pid, Self::Out> { &self.info } fn refresh_processes(&mut self) {} fn refresh_process(&mut self, _pid: DeltaPid) -> bool { true } } fn set(arg1: &[&str]) -> HashSet<String> { arg1.iter().map(|&s| s.to_owned()).collect() } #[test] fn test_process_testing() { { let _args = FakeParentArgs::once("git blame hello"); assert_eq!( calling_process_cmdline(ProcInfo::new(), describe_calling_process), Some(CallingProcess::GitBlame(CommandLine { long_options: [].into(), short_options: [].into(), last_arg: Some("hello".into()) })) ); } { let _args = FakeParentArgs::once("git blame world.txt"); assert_eq!( calling_process_cmdline(ProcInfo::new(), describe_calling_process), Some(CallingProcess::GitBlame(CommandLine { long_options: [].into(), short_options: [].into(), last_arg: Some("world.txt".into()) })) ); } { let _args = FakeParentArgs::for_scope("git blame hello world.txt"); assert_eq!( calling_process_cmdline(ProcInfo::new(), describe_calling_process), Some(CallingProcess::GitBlame(CommandLine { long_options: [].into(), short_options: [].into(), last_arg: Some("world.txt".into()) })) ); } } #[test] #[should_panic(expected = "test logic error (in get): wrong FakeParentArgs scope?")] fn test_process_testing_assert() { let _args = FakeParentArgs::once("git blame do.not.panic"); assert_eq!( calling_process_cmdline(ProcInfo::new(), describe_calling_process), Some(CallingProcess::GitBlame(CommandLine { long_options: [].into(), short_options: [].into(), last_arg: Some("do.not.panic".into()) })) ); calling_process_cmdline(ProcInfo::new(), describe_calling_process); } #[test] #[should_panic(expected = "test logic error (in drop): wrong FakeParentArgs scope?")] fn test_process_testing_assert_once_never_used() { let _args = FakeParentArgs::once("never used"); } #[test] #[should_panic(expected = "test logic error (in once): wrong FakeParentArgs scope?")] fn test_process_testing_assert_for_scope_never_used() { let _args = FakeParentArgs::for_scope(&"never used"); let _args = FakeParentArgs::once(&"never used"); } #[test] #[should_panic(expected = "test logic error (in for_scope): wrong FakeParentArgs scope?")] fn test_process_testing_assert_once_never_used2() { let _args = FakeParentArgs::once(&"never used"); let _args = FakeParentArgs::for_scope(&"never used"); } #[test] fn test_process_testing_scope_can_remain_unused() { let _args = FakeParentArgs::for_scope("never used"); } #[test] fn test_process_testing_n_times() { let _args = FakeParentArgs::with(&["git blame once", "git blame twice"]); assert_eq!( calling_process_cmdline(ProcInfo::new(), describe_calling_process), Some(CallingProcess::GitBlame(CommandLine { long_options: [].into(), short_options: [].into(), last_arg: Some("once".into()) })) ); assert_eq!( calling_process_cmdline(ProcInfo::new(), describe_calling_process), Some(CallingProcess::GitBlame(CommandLine { long_options: [].into(), short_options: [].into(), last_arg: Some("twice".into()) })) ); } #[test] #[should_panic(expected = "test logic error (in drop with): wrong FakeParentArgs scope?")] fn test_process_testing_n_times_unused() { let _args = FakeParentArgs::with(&["git blame once", "git blame twice"]); } #[test] #[should_panic(expected = "test logic error (in drop with): wrong FakeParentArgs scope?")] fn test_process_testing_n_times_underused() { let _args = FakeParentArgs::with(&["git blame once", "git blame twice"]); assert_eq!( calling_process_cmdline(ProcInfo::new(), describe_calling_process), Some(CallingProcess::GitBlame(CommandLine { long_options: [].into(), short_options: [].into(), last_arg: Some("once".into()) })) ); } #[test] #[should_panic(expected = "test logic error (in get): wrong FakeParentArgs scope?")] fn test_process_testing_n_times_overused() { let _args = FakeParentArgs::with(&["git blame once"]); assert_eq!( calling_process_cmdline(ProcInfo::new(), describe_calling_process), Some(CallingProcess::GitBlame(CommandLine { long_options: [].into(), short_options: [].into(), last_arg: Some("once".into()) })) ); calling_process_cmdline(ProcInfo::new(), describe_calling_process); } #[test] fn test_describe_calling_process_blame() { let no_processes = MockProcInfo::with(&[]); assert_eq!( calling_process_cmdline(no_processes, describe_calling_process), None ); let two_trees = MockProcInfo::with(&[ (2, 100, "-shell", None), (3, 100, "git blame src/main.rs", Some(2)), (4, 100, "call_delta.sh", None), (5, 100, "delta", Some(4)), ]); assert_eq!( calling_process_cmdline(two_trees, describe_calling_process), None ); let no_options_command_line = CommandLine { long_options: [].into(), short_options: [].into(), last_arg: Some("hello.txt".to_string()), }; let parent = MockProcInfo::with(&[ (2, 100, "-shell", None),
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
true
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/git.rs
src/utils/git.rs
use std::process::Command; pub fn retrieve_git_version() -> Option<(usize, usize)> { if let Ok(git_path) = grep_cli::resolve_binary("git") { let cmd = Command::new(git_path).arg("--version").output().ok()?; parse_git_version(&cmd.stdout) } else { None } } fn parse_git_version(output: &[u8]) -> Option<(usize, usize)> { let mut parts = output.strip_prefix(b"git version ")?.split(|&b| b == b'.'); let major = std::str::from_utf8(parts.next()?).ok()?.parse().ok()?; let minor = std::str::from_utf8(parts.next()?).ok()?.parse().ok()?; Some((major, minor)) } #[cfg(test)] mod tests { use super::parse_git_version; use rstest::rstest; #[rstest] #[case(b"git version 2.46.0", Some((2, 46)))] #[case(b"git version 2.39.3 (Apple Git-146)", Some((2, 39)))] #[case(b"", None)] fn test_parse_git_version(#[case] input: &[u8], #[case] expected: Option<(usize, usize)>) { assert_eq!(parse_git_version(input), expected); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/syntect.rs
src/utils/syntect.rs
use std::str::FromStr; use syntect::highlighting::{Color, FontStyle, Style}; use crate::color; use crate::style as delta_style; pub fn syntect_color_from_ansi_name(name: &str) -> Option<Color> { color::ansi_16_color_name_to_number(name).and_then(syntect_color_from_ansi_number) } pub fn syntect_color_from_name(name: &str) -> Option<Color> { palette::named::from_str(name).map(|color| Color { r: color.red, g: color.green, b: color.blue, a: 0xFF, }) } /// Convert 8-bit ANSI code to #RGBA string with ANSI code in red channel and 0 in alpha channel. // See https://github.com/sharkdp/bat/pull/543 pub fn syntect_color_from_ansi_number(n: u8) -> Option<Color> { Color::from_str(&format!("#{n:02x}000000")).ok() } pub trait FromAnsiTermStyle { fn from_ansi_term_style(ansi_term_style: ansi_term::Style) -> Self; } impl FromAnsiTermStyle for Style { fn from_ansi_term_style(ansi_term_style: ansi_term::Style) -> Self { let default = Self::default(); Self { foreground: if let Some(color) = ansi_term_style.foreground { Color::from_ansi_term_color(color) } else { default.foreground }, background: if let Some(color) = ansi_term_style.background { Color::from_ansi_term_color(color) } else { default.background }, font_style: FontStyle::from_ansi_term_style(ansi_term_style), } } } impl FromAnsiTermStyle for FontStyle { fn from_ansi_term_style(ansi_term_style: ansi_term::Style) -> Self { let mut font_style = FontStyle::empty(); if ansi_term_style.is_bold { font_style |= FontStyle::BOLD } if ansi_term_style.is_italic { font_style |= FontStyle::ITALIC } if ansi_term_style.is_underline { font_style |= FontStyle::UNDERLINE } font_style } } pub trait FromAnsiTermColor { fn from_ansi_term_color(ansi_term_color: ansi_term::Color) -> Self; } impl FromAnsiTermColor for Color { fn from_ansi_term_color(ansi_term_color: ansi_term::Color) -> Self { match ansi_term_color { ansi_term::Color::Black => syntect_color_from_ansi_number(0).unwrap(), ansi_term::Color::Red => syntect_color_from_ansi_number(1).unwrap(), ansi_term::Color::Green => syntect_color_from_ansi_number(2).unwrap(), ansi_term::Color::Yellow => syntect_color_from_ansi_number(3).unwrap(), ansi_term::Color::Blue => syntect_color_from_ansi_number(4).unwrap(), ansi_term::Color::Purple => syntect_color_from_ansi_number(5).unwrap(), ansi_term::Color::Cyan => syntect_color_from_ansi_number(6).unwrap(), ansi_term::Color::White => syntect_color_from_ansi_number(7).unwrap(), ansi_term::Color::Fixed(n) => syntect_color_from_ansi_number(n).unwrap(), ansi_term::Color::RGB(r, g, b) => Self { r, g, b, a: 0xFF }, } } } pub trait FromDeltaStyle { fn from_delta_style(delta_style: delta_style::Style) -> Self; } impl FromDeltaStyle for Style { fn from_delta_style(delta_style: delta_style::Style) -> Self { Self::from_ansi_term_style(delta_style.ansi_term_style) } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/mod.rs
src/utils/mod.rs
#[cfg(not(tarpaulin_include))] pub mod bat; pub mod git; pub mod helpwrap; pub mod path; pub mod process; pub mod regex_replacement; pub mod round_char_boundary; pub mod syntect; pub mod tabs; pub mod workarounds; // Use the most (even overly) strict ordering. Atomics are not used in hot loops so // a one-size-fits-all approach which is never incorrect is okay. pub const DELTA_ATOMIC_ORDERING: std::sync::atomic::Ordering = std::sync::atomic::Ordering::SeqCst;
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/workarounds.rs
src/utils/workarounds.rs
// env var which should disable workarounds const NO_WORKAROUNDS: &str = "DELTA_NO_WORKAROUNDS"; // Work around a bug in the 'console' crate (inherited from 'terminal-size', #25): On Windows // it can not determine the width of an MSYS2 / MINGW64 terminal (e.g. from Git-Bash) correctly. // Instead use the usually included stty util from the MSYS2 distribution. #[cfg(target_os = "windows")] pub fn windows_msys2_width_fix(height_width: (u16, u16), term_stdout: &console::Term) -> usize { fn guess_real_width(current_width: u16, term_stdout: &console::Term) -> Option<u16> { use std::process::{Command, Stdio}; let term_var = std::env::var("TERM").ok()?; // More checks before actually calling stty. if term_var.starts_with("xterm") && term_stdout.is_term() && term_stdout.features().is_msys_tty() { if std::env::var(NO_WORKAROUNDS).is_ok() { return Some(current_width); } // stderr/2 is passed to the Command below. let pseudo_term = "/dev/fd/2"; // Read width via stty helper program (e.g. "C:\Program Files\Git\usr\bin\stty.exe") // which gets both the MSYS2 and cmd.exe width right. let result = Command::new("stty") .stderr(Stdio::inherit()) .arg("-F") .arg(pseudo_term) .arg("size") .output() .ok()?; if result.status.success() { let size = std::str::from_utf8(&result.stdout).ok()?; let mut it = size.split_whitespace(); let _height = it.next()?; return it.next().map(|width| width.parse().ok())?; } } None } // Calling an external binary is slow, so make sure this is actually necessary. // The fallback values of 25 lines by 80 columns (sometimes zero indexed) are a good // indicator. let (height, width) = height_width; match (height, width) { (24..=25, 79..=80) => guess_real_width(width, term_stdout).unwrap_or(width), _ => width, } .into() } #[cfg(not(target_os = "windows"))] pub fn windows_msys2_width_fix(height_width: (u16, u16), _: &console::Term) -> usize { let _ = NO_WORKAROUNDS; height_width.1.into() }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/helpwrap.rs
src/utils/helpwrap.rs
#![allow(clippy::comparison_to_empty)] // no_indent != "", instead of !no_indent.is_empty() use crate::ansi::measure_text_width; /// Wrap `text` at spaces ('` `') to fit into `width`. If `indent_with` is non-empty, indent /// each line with this string. If a line from `text` starts with `no_indent`, do not indent. /// If a line starts with `no_wrap`, do not wrap (empty `no_indent`/`no_wrap` have no effect). /// If both "magic prefix" markers are used, `no_indent` must be first. /// Takes unicode and ANSI into account when calculating width, but won't wrap ANSI correctly. /// Removes trailing spaces. Leading spaces or enumerations with '- ' continue the indentation on /// the wrapped line. /// Example: /// ``` /// let wrapped = wrap("ab cd ef\n!NI!123\n|AB CD EF GH\n!NI!|123 456 789", 7, "_", "!NI!", "|"); /// assert_eq!(wrapped, "\ /// _ab cd\n\ /// _ef\n\ /// 123\n\ /// _AB CD EF GH\n\ /// 123 456 789\n\ /// "); /// ``` pub fn wrap(text: &str, width: usize, indent_with: &str, no_indent: &str, no_wrap: &str) -> String { let mut result = String::with_capacity(text.len()); let indent_len = measure_text_width(indent_with); for line in text.lines() { let line = line.trim_end_matches(' '); let (line, indent) = if let (Some(line), true) = (line.strip_prefix(no_indent), no_indent != "") { (line, "") } else { result.push_str(indent_with); (line, indent_with) }; if let (Some(line), true) = (line.strip_prefix(no_wrap), no_wrap != "") { result.push_str(line); } else { // `"foo bar end".split_inclusive(' ')` => `["foo ", "bar ", " ", " ", "end"]` let mut wordit = line.split_inclusive(' '); let mut curr_len = indent_len; if let Some(word) = wordit.next() { result.push_str(word); curr_len += measure_text_width(word); } while let Some(mut word) = wordit.next() { let word_len = measure_text_width(word); if curr_len + word_len == width + 1 && word.ends_with(' ') { // If just ' ' is over the limit, let the next word trigger the overflow. } else if curr_len + word_len > width { // Remove any trailing whitespace: let pos = result.trim_end_matches(' ').len(); result.truncate(pos); result.push('\n'); // Do not count spaces, skip until next proper word is found. if word == " " { for nextword in wordit.by_ref() { word = nextword; if word != " " { break; } } } // Re-calculates indent for each wrapped line. Could be done only once, maybe // after an early return which just uses .len() (works for fullwidth chars). // If line started with spaces, indent by that much again. let (indent, space_pos) = if let Some(space_prefix_len) = line.find(|c: char| c != ' ') { ( format!("{}{}", indent, " ".repeat(space_prefix_len)), space_prefix_len, ) } else { debug_assert!(false, "line.trim_end_matches() missing?"); (indent.to_string(), 0) }; // If line started with '- ', treat it as a bullet point and increase indentation let indent = if line[space_pos..].starts_with("- ") { format!("{}{}", indent, " ") } else { indent }; result.push_str(&indent); curr_len = measure_text_width(&indent); } curr_len += word_len; result.push_str(word); } } let pos = result.trim_end_matches(' ').len(); result.truncate(pos); result.push('\n'); } #[cfg(test)] if !result.contains("no-sanity") { // sanity check let stripped_input = text .replace(" ", "") .replace("\n", "") .replace(no_wrap, "") .replace(no_indent, ""); let stripped_output = result .replace(" ", "") .replace("\n", "") .replace(indent_with, ""); assert_eq!(stripped_input, stripped_output); } result } #[cfg(test)] mod test { use super::*; use insta::assert_snapshot; #[test] fn simple_ascii_can_not_split() { let input = "000 123456789 abcdefghijklmnopqrstuvwxyz ok"; let result = wrap(input, 5, "", "", ""); assert_snapshot!(result, @r###" 000 123456789 abcdefghijklmnopqrstuvwxyz ok "###); } #[test] fn simple_ascii_just_whitespace() { let input = " \n \n \n \n \n \n"; let result = wrap(input, 3, "__", "", ""); assert_snapshot!(result, @r###" __ __ __ __ __ __ "###); let result = wrap(input, 3, "", "", ""); assert_eq!(result, "\n\n\n\n\n\n"); } #[test] fn simple_ascii_can_not_split_plus_whitespace() { let input = "000 123456789 abcdefghijklmnopqrstuvwxyz ok"; let result = wrap(input, 5, "", "", ""); assert_snapshot!(result, @r###" 000 123456789 abcdefghijklmnopqrstuvwxyz ok "###); } #[test] fn simple_ascii_keep_leading_input_indent() { let input = "abc\n Def ghi jkl mno pqr stuv xyz\n Abc def ghijklm\nok"; let result = wrap(input, 10, "_", "", ""); assert_snapshot!(result, @r###" _abc _ Def ghi _ jkl mno _ pqr _ stuv _ xyz _ Abc _ def _ ghijklm _ok "###); } #[test] fn simple_ascii_indent_and_bullet_points() { let input = "- ABC ABC abc\n def ghi - jkl\n - 1 22 3 4 55 6 7 8 9\n - 1 22 3 4 55 6 7 8 9\n!- 0 0 0 0 0 0 0 \n"; let result = wrap(input, 10, "", "!", ""); assert_snapshot!(result, @r###" - ABC ABC abc def ghi - jkl - 1 22 3 4 55 6 7 8 9 - 1 22 3 4 55 6 7 8 9 - 0 0 0 0 0 0 0 "###); } #[test] fn simple_ascii_all_overlong_after_indent() { let input = "0000 1111 2222"; let result = wrap(input, 5, "__", "", ""); assert_snapshot!(result, @r###" __0000 __1111 __2222 "###); } #[test] fn simple_ascii_one_line() { let input = "123 456 789 abc def ghi jkl mno pqr stu vwx yz"; let result = wrap(input, 10, "__", "", ""); assert_snapshot!(result, @r###" __123 456 __789 abc __def ghi __jkl mno __pqr stu __vwx yz "###); } #[test] fn simple_ascii_trailing_space() { let input = "123 \n\n \n 456 \n a b \n\n"; let result = wrap(input, 10, " ", "", ""); assert_eq!(result, " 123\n\n\n 456\n a\n b\n\n"); } #[test] fn simple_ascii_two_lines() { let input = "123 456 789 abc def\nghi jkl mno pqr stu vwx yz\n1234 567 89 876 54321\n"; let result = wrap(input, 10, "__", "", ""); assert_snapshot!(result, @r###" __123 456 __789 abc __def __ghi jkl __mno pqr __stu vwx __yz __1234 567 __89 876 __54321 "###); } #[test] fn simple_ascii_no_indent() { let input = "123 456 789\n!!abc def ghi jkl mno pqr\nstu vwx yz\n\n"; let result = wrap(input, 10, "__", "!!", ""); assert_snapshot!(result, @r###" __123 456 __789 abc def ghi jkl mno pqr __stu vwx __yz __ "###); } #[test] fn simple_ascii_no_wrap() { let input = "123 456 789\n|abc def ghi jkl mno pqr\nstu vwx yz\n|W\nA B C D E F G H I\n"; let result = wrap(input, 10, "__", "!!", "|"); assert_snapshot!(result, @r###" __123 456 __789 __abc def ghi jkl mno pqr __stu vwx __yz __W __A B C D __E F G H __I "###); } #[test] fn simple_ascii_no_both() { let input = "123 456 789\n!!|abc def ghi jkl mno pqr\nstu vwx yz\n|W\nA B C D E F G H I\n"; let result = wrap(input, 10, "__", "!!", "|"); assert_snapshot!(result, @r###" __123 456 __789 abc def ghi jkl mno pqr __stu vwx __yz __W __A B C D __E F G H __I "###); } #[test] fn simple_ascii_no_both_wrong_order() { let input = "!!|abc def ghi jkl\n|!!ABC DEF GHI JKL + no-sanity\n"; let result = wrap(input, 7, "__", "!!", "|"); assert_snapshot!(result, @r###" abc def ghi jkl __!!ABC DEF GHI JKL + no-sanity "###); let wrapped = wrap( "ab cd ef\n!NI!123\n|AB CD EF GH\n!NI!|123 456 789", 6, "_", "!NI!", "|", ); assert_snapshot!(wrapped, @r###" _ab cd _ef 123 _AB CD EF GH 123 456 789 "###); } #[test] fn simple_ascii_much_whitespace() { let input = "123 456 789\nabc def ghi jkl mno pqr \nstu vwx yz"; let result = wrap(input, 10, "__", "!!", "|"); assert_snapshot!(result, @r###" __123 __456 __789 __abc __def ghi __jkl mno __pqr __stu __vwx yz "###); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/regex_replacement.rs
src/utils/regex_replacement.rs
use std::borrow::Cow; use regex::{Regex, RegexBuilder}; #[derive(Clone, Debug)] pub struct RegexReplacement { regex: Regex, replacement: String, replace_all: bool, } impl RegexReplacement { pub fn from_sed_command(sed_command: &str) -> Option<Self> { let sep = sed_command.chars().nth(1)?; let mut parts = sed_command[2..].split(sep); let regex = parts.next()?; let replacement = parts.next()?.to_string(); let flags = parts.next()?; let mut re_builder = RegexBuilder::new(regex); let mut replace_all = false; for flag in flags.chars() { match flag { 'g' => { replace_all = true; } 'i' => { re_builder.case_insensitive(true); } 'm' => { re_builder.multi_line(true); } 's' => { re_builder.dot_matches_new_line(true); } 'U' => { re_builder.swap_greed(true); } 'x' => { re_builder.ignore_whitespace(true); } _ => {} } } let regex = re_builder.build().ok()?; Some(RegexReplacement { regex, replacement, replace_all, }) } pub fn execute<'t>(&self, s: &'t str) -> Cow<'t, str> { if self.replace_all { self.regex.replace_all(s, &self.replacement) } else { self.regex.replace(s, &self.replacement) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_sed_command() { let command = "s,foo,bar,"; let rr = RegexReplacement::from_sed_command(command).unwrap(); assert_eq!(rr.regex.as_str(), "foo"); assert_eq!(rr.replacement, "bar"); assert!(!rr.replace_all); assert_eq!(rr.execute("foo"), "bar"); } #[test] fn test_sed_command_i_flag() { let command = "s,FOO,bar,"; let rr = RegexReplacement::from_sed_command(command).unwrap(); assert_eq!(rr.execute("foo"), "foo"); let command = "s,FOO,bar,i"; let rr = RegexReplacement::from_sed_command(command).unwrap(); assert_eq!(rr.execute("foo"), "bar"); } #[test] fn test_sed_command_g_flag() { let command = "s,foo,bar,"; let rr = RegexReplacement::from_sed_command(command).unwrap(); assert_eq!(rr.execute("foofoo"), "barfoo"); let command = "s,foo,bar,g"; let rr = RegexReplacement::from_sed_command(command).unwrap(); assert_eq!(rr.execute("foofoo"), "barbar"); } #[test] fn test_sed_command_with_named_captures() { let command = r"s/(?P<last>[^,\s]+),\s+(?P<first>\S+)/$first $last/"; let rr = RegexReplacement::from_sed_command(command).unwrap(); assert_eq!(rr.execute("Springsteen, Bruce"), "Bruce Springsteen"); } #[test] fn test_sed_command_invalid() { assert!(RegexReplacement::from_sed_command("").is_none()); assert!(RegexReplacement::from_sed_command("s").is_none()); assert!(RegexReplacement::from_sed_command("s,").is_none()); assert!(RegexReplacement::from_sed_command("s,,").is_none()); assert!(RegexReplacement::from_sed_command("s,,i").is_none()); assert!(RegexReplacement::from_sed_command("s,,,").is_some()); assert!(RegexReplacement::from_sed_command("s,,,i").is_some()); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/bat/terminal.rs
src/utils/bat/terminal.rs
use ansi_term::Color::{self, Fixed, RGB}; use ansi_term::{self, Style}; use syntect::highlighting::{self, FontStyle}; pub fn to_ansi_color(color: highlighting::Color, true_color: bool) -> Option<ansi_term::Color> { if color.a == 0 { // Themes can specify one of the user-configurable terminal colors by // encoding them as #RRGGBBAA with AA set to 00 (transparent) and RR set // to the 8-bit color palette number. The built-in themes ansi, base16, // and base16-256 use this. Some(match color.r { // For the first 8 colors, use the Color enum to produce ANSI escape // sequences using codes 30-37 (foreground) and 40-47 (background). // For example, red foreground is \x1b[31m. This works on terminals // without 256-color support. 0x00 => Color::Black, 0x01 => Color::Red, 0x02 => Color::Green, 0x03 => Color::Yellow, 0x04 => Color::Blue, 0x05 => Color::Purple, 0x06 => Color::Cyan, 0x07 => Color::White, // For all other colors, use Fixed to produce escape sequences using // codes 38;5 (foreground) and 48;5 (background). For example, // bright red foreground is \x1b[38;5;9m. This only works on // terminals with 256-color support. // // TODO: When ansi_term adds support for bright variants using codes // 90-97 (foreground) and 100-107 (background), we should use those // for values 0x08 to 0x0f and only use Fixed for 0x10 to 0xff. n => Fixed(n), }) } else if color.a == 1 { // Themes can specify the terminal's default foreground/background color // (i.e. no escape sequence) using the encoding #RRGGBBAA with AA set to // 01. The built-in theme ansi uses this. None } else if true_color { Some(RGB(color.r, color.g, color.b)) } else { Some(Fixed(ansi_colours::ansi256_from_rgb(( color.r, color.g, color.b, )))) } } #[allow(dead_code)] pub fn as_terminal_escaped( style: highlighting::Style, text: &str, true_color: bool, colored: bool, italics: bool, background_color: Option<highlighting::Color>, ) -> String { if text.is_empty() { return text.to_string(); } let mut style = if !colored { Style::default() } else { let mut color = Style { foreground: to_ansi_color(style.foreground, true_color), ..Style::default() }; if style.font_style.contains(FontStyle::BOLD) { color = color.bold(); } if style.font_style.contains(FontStyle::UNDERLINE) { color = color.underline(); } if italics && style.font_style.contains(FontStyle::ITALIC) { color = color.italic(); } color }; style.background = background_color.and_then(|c| to_ansi_color(c, true_color)); style.paint(text).to_string() }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/bat/mod.rs
src/utils/bat/mod.rs
pub mod assets; pub mod dirs; mod less; pub mod output; pub mod terminal;
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/bat/dirs.rs
src/utils/bat/dirs.rs
// Based on code from https://github.com/sharkdp/bat e981e974076a926a38f124b7d8746de2ca5f0a28 // See src/utils/bat/LICENSE use lazy_static::lazy_static; use std::path::{Path, PathBuf}; #[cfg(target_os = "macos")] use std::env; /// Wrapper for 'dirs' that treats MacOS more like Linux, by following the XDG specification. /// This means that the `XDG_CACHE_HOME` and `XDG_CONFIG_HOME` environment variables are /// checked first. The fallback directories are `~/.cache/bat` and `~/.config/bat`, respectively. pub struct BatProjectDirs { cache_dir: PathBuf, } impl BatProjectDirs { fn new() -> Option<BatProjectDirs> { #[cfg(target_os = "macos")] let cache_dir_op = env::var_os("XDG_CACHE_HOME") .map(PathBuf::from) .filter(|p| p.is_absolute()) .or_else(|| dirs::home_dir().map(|d| d.join(".cache"))); #[cfg(not(target_os = "macos"))] let cache_dir_op = dirs::cache_dir(); let cache_dir = cache_dir_op.map(|d| d.join("bat"))?; Some(BatProjectDirs { cache_dir }) } pub fn cache_dir(&self) -> &Path { &self.cache_dir } } lazy_static! { pub static ref PROJECT_DIRS: BatProjectDirs = BatProjectDirs::new().unwrap_or_else(|| panic!("Could not get home directory")); }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/bat/less.rs
src/utils/bat/less.rs
use std::path::PathBuf; use std::process::Command; pub fn retrieve_less_version(less_path: PathBuf) -> Option<usize> { let cmd = Command::new(less_path).arg("--version").output().ok()?; parse_less_version(&cmd.stdout) } fn parse_less_version(output: &[u8]) -> Option<usize> { if output.starts_with(b"less ") { let version = std::str::from_utf8(&output[5..]).ok()?; let end = version.find(|c: char| !c.is_ascii_digit())?; version[..end].parse::<usize>().ok() } else { None } } #[cfg(test)] mod tests { use super::parse_less_version; #[test] fn test_parse_less_version_487() { let output = b"less 487 (GNU regular expressions) Copyright (C) 1984-2016 Mark Nudelman less comes with NO WARRANTY, to the extent permitted by law. For information about the terms of redistribution, see the file named README in the less distribution. Homepage: http://www.greenwoodsoftware.com/less"; assert_eq!(Some(487), parse_less_version(output)); } #[test] fn test_parse_less_version_529() { let output = b"less 529 (Spencer V8 regular expressions) Copyright (C) 1984-2017 Mark Nudelman less comes with NO WARRANTY, to the extent permitted by law. For information about the terms of redistribution, see the file named README in the less distribution. Homepage: http://www.greenwoodsoftware.com/less"; assert_eq!(Some(529), parse_less_version(output)); } #[test] fn test_parse_less_version_551() { let output = b"less 551 (PCRE regular expressions) Copyright (C) 1984-2019 Mark Nudelman less comes with NO WARRANTY, to the extent permitted by law. For information about the terms of redistribution, see the file named README in the less distribution. Home page: http://www.greenwoodsoftware.com/less"; assert_eq!(Some(551), parse_less_version(output)); } #[test] fn test_parse_less_version_wrong_program() { let output = b"more from util-linux 2.34"; assert_eq!(None, parse_less_version(output)); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/bat/assets.rs
src/utils/bat/assets.rs
// Based on code from https://github.com/sharkdp/bat a1b9334a44a2c652f52dddaa83dbacba57372468 // See src/utils/bat/LICENSE use std::io::{self, Write}; use ansi_term::Colour::Green; use ansi_term::Style; use bat; use crate::utils; pub fn load_highlighting_assets() -> bat::assets::HighlightingAssets { bat::assets::HighlightingAssets::from_cache(utils::bat::dirs::PROJECT_DIRS.cache_dir()) .unwrap_or_else(|_| bat::assets::HighlightingAssets::from_binary()) } pub fn list_languages() -> std::io::Result<()> { let assets = utils::bat::assets::load_highlighting_assets(); let mut languages = assets .get_syntaxes() .unwrap() .iter() .filter(|syntax| !syntax.hidden && !syntax.file_extensions.is_empty()) .collect::<Vec<_>>(); languages.sort_by_key(|lang| lang.name.to_uppercase()); let loop_through = false; let colored_output = true; let stdout = io::stdout(); let mut stdout = stdout.lock(); if loop_through { for lang in languages { writeln!(stdout, "{}:{}", lang.name, lang.file_extensions.join(","))?; } } else { let longest = languages .iter() .map(|syntax| syntax.name.len()) .max() .unwrap_or(32); // Fallback width if they have no language definitions. let comma_separator = ", "; let separator = " "; // Line-wrapping for the possible file extension overflow. let desired_width = 100; let style = if colored_output { Green.normal() } else { Style::default() }; for lang in languages { write!(stdout, "{:width$}{}", lang.name, separator, width = longest)?; // Number of characters on this line so far, wrap before `desired_width` let mut num_chars = 0; let mut extension = lang.file_extensions.iter().peekable(); while let Some(word) = extension.next() { // If we can't fit this word in, then create a line break and align it in. let new_chars = word.len() + comma_separator.len(); if num_chars + new_chars >= desired_width { num_chars = 0; write!(stdout, "\n{:width$}{}", "", separator, width = longest)?; } num_chars += new_chars; write!(stdout, "{}", style.paint(&word[..]))?; if extension.peek().is_some() { write!(stdout, "{comma_separator}")?; } } writeln!(stdout)?; } } Ok(()) }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/utils/bat/output.rs
src/utils/bat/output.rs
// https://github.com/sharkdp/bat a1b9334a44a2c652f52dddaa83dbacba57372468 // src/output.rs // See src/utils/bat/LICENSE use std::ffi::OsString; use std::io::{self, Write}; use std::path::PathBuf; use std::process::{Child, Command, Stdio}; use super::less::retrieve_less_version; use crate::config; use crate::env::DeltaEnv; use crate::fatal; use crate::features::navigate; #[derive(Debug, Default)] pub struct PagerCfg { pub navigate: bool, pub show_themes: bool, pub navigate_regex: Option<String>, } impl From<&config::Config> for PagerCfg { fn from(cfg: &config::Config) -> Self { PagerCfg { navigate: cfg.navigate, show_themes: cfg.show_themes, navigate_regex: cfg.navigate_regex.clone(), } } } impl From<config::Config> for PagerCfg { fn from(cfg: config::Config) -> Self { (&cfg).into() } } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[allow(dead_code)] pub enum PagingMode { Always, QuitIfOneScreen, #[default] Never, Capture, } const LESSUTFCHARDEF: &str = "LESSUTFCHARDEF"; use crate::errors::*; pub enum OutputType { Pager(Child), Stdout(io::Stdout), Capture, } impl Drop for OutputType { fn drop(&mut self) { if let OutputType::Pager(ref mut command) = *self { let _ = command.wait(); } } } impl OutputType { /// Create a pager and write all data into it. Waits until the pager exits. /// The expectation is that the program will exit afterwards. pub fn oneshot_write(data: String) -> io::Result<()> { let mut output_type = OutputType::from_mode( &DeltaEnv::init(), PagingMode::QuitIfOneScreen, None, &PagerCfg::default(), ) .unwrap(); let mut writer = output_type.handle().unwrap(); write!(&mut writer, "{data}") } pub fn from_mode( env: &DeltaEnv, mode: PagingMode, pager: Option<String>, config: &PagerCfg, ) -> Result<Self> { use self::PagingMode::*; Ok(match mode { Always => OutputType::try_pager(env, false, pager, config)?, QuitIfOneScreen => OutputType::try_pager(env, true, pager, config)?, Capture => OutputType::Capture, _ => OutputType::stdout(), }) } /// Try to launch the pager. Fall back to stdout in case of errors. fn try_pager( env: &DeltaEnv, quit_if_one_screen: bool, pager_from_config: Option<String>, config: &PagerCfg, ) -> Result<Self> { let mut replace_arguments_to_less = false; let pager_from_env = match env.pagers.clone() { (Some(delta_pager), _) => Some(delta_pager), (_, Some(pager)) => { // less needs to be called with the '-R' option in order to properly interpret ANSI // color sequences. If someone has set PAGER="less -F", we therefore need to // overwrite the arguments and add '-R'. // We only do this for PAGER, since it is used in other contexts. replace_arguments_to_less = true; Some(pager) } _ => None, }; if pager_from_config.is_some() { replace_arguments_to_less = false; } let pager_cmd = shell_words::split( &pager_from_config .or(pager_from_env) .unwrap_or_else(|| String::from("less")), ) .context("Could not parse pager command.")?; Ok(match pager_cmd.split_first() { Some((pager_path, args)) => { let pager_path = PathBuf::from(pager_path); let is_less = pager_path.file_stem() == Some(&OsString::from("less")); let process = if is_less { _make_process_from_less_path( pager_path, args, replace_arguments_to_less, quit_if_one_screen, config, ) } else { _make_process_from_pager_path(pager_path, args) }; if let Some(mut process) = process { process .stdin(Stdio::piped()) .spawn() .map(OutputType::Pager) .unwrap_or_else(|_| OutputType::stdout()) } else { OutputType::stdout() } } None => OutputType::stdout(), }) } fn stdout() -> Self { OutputType::Stdout(io::stdout()) } pub fn handle(&mut self) -> Result<&mut dyn Write> { Ok(match *self { OutputType::Pager(ref mut command) => command .stdin .as_mut() .context("Could not open stdin for pager")?, OutputType::Stdout(ref mut handle) => handle, OutputType::Capture => unreachable!("capture can not be set"), }) } } fn _make_process_from_less_path( less_path: PathBuf, args: &[String], replace_arguments_to_less: bool, quit_if_one_screen: bool, config: &PagerCfg, ) -> Option<Command> { if let Ok(less_path) = grep_cli::resolve_binary(less_path) { let mut p = Command::new(less_path.clone()); if args.is_empty() || replace_arguments_to_less { p.args(vec!["--RAW-CONTROL-CHARS"]); // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older // versions of 'less'. Unfortunately, it also breaks mouse-wheel support. // // See: http://www.greenwoodsoftware.com/less/news.530.html // // For newer versions (530 or 558 on Windows), we omit '--no-init' as it // is not needed anymore. match retrieve_less_version(less_path) { None => { p.arg("--no-init"); } Some(version) if (version < 530 || (cfg!(windows) && version < 558)) => { p.arg("--no-init"); } _ => {} } if quit_if_one_screen { p.arg("--quit-if-one-screen"); } } else { p.args(args); } // less >= 633 (from May 2023) prints any characters from the Private Use Area of Unicode // as control characters (e.g. <U+E012> instead of hoping that the terminal can render it). // This means any Nerd Fonts will not be displayed properly. Previous versions of less just // passed these characters through, and terminals usually fall back to a less obtrusive // box. Use this new env var less introduced to restore the previous behavior. This sets all // chars to single width (':p', see less manual). If a user provided env var is present, // use do not override it. // Also see delta issue 1616 and nerd-fonts/issues/1337 if std::env::var(LESSUTFCHARDEF).is_err() { p.env(LESSUTFCHARDEF, "E000-F8FF:p,F0000-FFFFD:p,100000-10FFFD:p"); } p.env("LESSCHARSET", "UTF-8"); p.env("LESSANSIENDCHARS", "mK"); if config.navigate { if let Ok(hist_file) = navigate::copy_less_hist_file_and_append_navigate_regex(config) { p.env("LESSHISTFILE", hist_file); if config.show_themes { p.arg("+n"); } } } Some(p) } else { None } } fn _make_process_from_pager_path(pager_path: PathBuf, args: &[String]) -> Option<Command> { if pager_path.file_stem() == Some(&OsString::from("delta")) { fatal( "\ It looks like you have set delta as the value of $PAGER. \ This would result in a non-terminating recursion. \ delta is not an appropriate value for $PAGER \ (but it is an appropriate value for $GIT_PAGER).", ); } if let Ok(pager_path) = grep_cli::resolve_binary(pager_path) { let mut p = Command::new(pager_path); p.args(args); Some(p) } else { None } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/ansi/console_tests.rs
src/ansi/console_tests.rs
// This file contains some unit tests copied from the `console` project: // https://github.com/mitsuhiko/console // // The MIT License (MIT) // Copyright (c) 2017 Armin Ronacher <armin.ronacher@active-4.com> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. #[cfg(test)] mod tests { use console::{self, style}; use crate::ansi::{measure_text_width, truncate_str}; #[test] fn test_text_width() { let s = style("foo") .red() .on_black() .bold() .force_styling(true) .to_string(); assert_eq!(measure_text_width(&s), 3); } #[test] fn test_truncate_str() { let s = format!("foo {}", style("bar").red().force_styling(true)); assert_eq!( &truncate_str(&s, 5, ""), &format!("foo {}", style("b").red().force_styling(true)) ); let s = format!("foo {}", style("bar").red().force_styling(true)); // DED: I'm changing this test assertion: delta does not move `!` inside the styled region. // assert_eq!( // &truncate_str(&s, 5, "!"), // &format!("foo {}", style("!").red().force_styling(true)) // ); assert_eq!( &truncate_str(&s, 5, "!"), &format!("foo {}!", style("").red().force_styling(true)) ); let s = format!("foo {} baz", style("bar").red().force_styling(true)); assert_eq!( &truncate_str(&s, 10, "..."), &format!("foo {}...", style("bar").red().force_styling(true)) ); // `バ`(width = 2) will be truncate to 1, we use space to fill let s = format!("foo {}", style("バー").red().force_styling(true)); assert_eq!( &truncate_str(&s, 5, ""), &format!("foo {}", style(" ").red().force_styling(true)) ); let s = format!("foo {}", style("バー").red().force_styling(true)); assert_eq!( &truncate_str(&s, 6, ""), &format!("foo {}", style("バ").red().force_styling(true)) ); } #[test] fn test_truncate_str_no_ansi() { assert_eq!(&truncate_str("foo bar", 5, ""), "foo b"); assert_eq!(&truncate_str("foo bar", 5, "!"), "foo !"); assert_eq!(&truncate_str("foo bar baz", 10, "..."), "foo bar..."); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/ansi/mod.rs
src/ansi/mod.rs
mod console_tests; mod iterator; use std::borrow::Cow; use ansi_term::Style; use itertools::Itertools; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; use iterator::{AnsiElementIterator, Element}; pub const ANSI_CSI_CLEAR_TO_EOL: &str = "\x1b[0K"; pub const ANSI_CSI_CLEAR_TO_BOL: &str = "\x1b[1K"; pub const ANSI_SGR_BOLD: &str = "\x1b[1m"; pub const ANSI_SGR_RESET: &str = "\x1b[0m"; pub const ANSI_SGR_REVERSE: &str = "\x1b[7m"; pub const ANSI_SGR_UNDERLINE: &str = "\x1b[4m"; pub fn strip_ansi_codes(s: &str) -> String { strip_ansi_codes_from_strings_iterator(ansi_strings_iterator(s)) } pub fn measure_text_width(s: &str) -> usize { ansi_strings_iterator(s).fold(0, |acc, (element, is_ansi)| { acc + if is_ansi { 0 } else { element.width() } }) } fn truncate_str_impl<'a>( s: &'a str, display_width: usize, tail: &str, fill2w: Option<char>, ) -> Cow<'a, str> { let items = ansi_strings_iterator(s).collect::<Vec<(&str, bool)>>(); let width = strip_ansi_codes_from_strings_iterator(items.iter().copied()).width(); if width <= display_width { return Cow::from(s); } let result_tail = if !tail.is_empty() { truncate_str_impl(tail, display_width, "", fill2w).to_string() } else { String::new() }; let mut used = measure_text_width(&result_tail); let mut result = String::new(); for (t, is_ansi) in items { if !is_ansi { for g in t.graphemes(true) { let width_of_grapheme = g.width(); if used + width_of_grapheme > display_width { // Handle case "2." mentioned in `truncate_str` docs and fill the // hole left by double-width (2w) truncation. if let Some(fillchar) = fill2w { if width_of_grapheme == 2 && used < display_width { result.push(fillchar); } else if width_of_grapheme > 2 { // Should not happen, this means either unicode_segmentation // graphemes are too wide, or the unicode_width is calculated wrong. // Fallback: debug_assert!(width_of_grapheme <= 2, "strange grapheme width"); for _ in 0..display_width.saturating_sub(used) { result.push(fillchar); } } } break; } result.push_str(g); used += width_of_grapheme; } } else { result.push_str(t); } } result.push_str(&result_tail); Cow::from(result) } /// Truncate string such that `tail` is present as a suffix, preceded by as much of `s` as can be /// displayed in the requested width. Even with `tail` empty the result may not be a prefix of `s`. // Return string constructed as follows: // 1. `display_width` characters are available. If the string fits, return it. // // 2. If a double-width (fullwidth) grapheme has to be cut in the following steps, replace the first // half with a space (' '). If this happens the result is no longer a prefix of the input. // // 3. Contribute graphemes and ANSI escape sequences from `tail` until either (1) `tail` is // exhausted, or (2) the display width of the result would exceed `display_width`. // // 4. If tail was exhausted, then contribute graphemes and ANSI escape sequences from `s` until the // display_width of the result would exceed `display_width`. pub fn truncate_str<'a>(s: &'a str, display_width: usize, tail: &str) -> Cow<'a, str> { truncate_str_impl(s, display_width, tail, Some(' ')) } /// Truncate string `s` so it fits into `display_width`, ignoring any ANSI escape sequences when /// calculating the width. If a double-width ("fullwidth") grapheme has to be cut, it is omitted and /// the resulting string is *shorter* than `display_width`. But this way the result is always a /// prefix of the input `s`. pub fn truncate_str_short(s: &str, display_width: usize) -> Cow<'_, str> { truncate_str_impl(s, display_width, "", None) } pub fn parse_style_sections(s: &str) -> Vec<(ansi_term::Style, &str)> { let mut sections = Vec::new(); let mut curr_style = Style::default(); for element in AnsiElementIterator::new(s) { match element { Element::Text(start, end) => sections.push((curr_style, &s[start..end])), Element::Sgr(style, _, _) => curr_style = style, _ => {} } } sections } // Return the first CSI element, if any, as an `ansi_term::Style`. pub fn parse_first_style(s: &str) -> Option<ansi_term::Style> { AnsiElementIterator::new(s).find_map(|el| match el { Element::Sgr(style, _, _) => Some(style), _ => None, }) } pub fn string_starts_with_ansi_style_sequence(s: &str) -> bool { AnsiElementIterator::new(s) .next() .map(|el| matches!(el, Element::Sgr(_, _, _))) .unwrap_or(false) } /// Return string formed from a byte slice starting at byte position `start`, where the index /// counts bytes in non-ANSI-escape-sequence content only. All ANSI escape sequences in the /// original string are preserved. pub fn ansi_preserving_slice(s: &str, start: usize) -> String { AnsiElementIterator::new(s) .scan(0, |index, element| { // `index` is the index in non-ANSI-escape-sequence content. Some(match element { Element::Sgr(_, a, b) => &s[a..b], Element::Csi(a, b) => &s[a..b], Element::Esc(a, b) => &s[a..b], Element::Osc(a, b) => &s[a..b], Element::Text(a, b) => { let i = *index; *index += b - a; if *index <= start { // This text segment ends before start, so contributes no bytes. "" } else if i > start { // This section starts after `start`, so contributes all its bytes. &s[a..b] } else { // This section contributes those bytes that are >= start &s[(a + start - i)..b] } } }) }) .join("") } /// Return the byte index in `s` of the i-th text byte in `s`. I.e. `i` counts /// bytes in non-ANSI-escape-sequence content only. pub fn ansi_preserving_index(s: &str, i: usize) -> Option<usize> { let mut index = 0; for element in AnsiElementIterator::new(s) { if let Element::Text(a, b) = element { index += b - a; if index > i { return Some(b - (index - i)); } } } None } fn ansi_strings_iterator(s: &str) -> impl Iterator<Item = (&str, bool)> { AnsiElementIterator::new(s).map(move |el| match el { Element::Sgr(_, i, j) => (&s[i..j], true), Element::Csi(i, j) => (&s[i..j], true), Element::Esc(i, j) => (&s[i..j], true), Element::Osc(i, j) => (&s[i..j], true), Element::Text(i, j) => (&s[i..j], false), }) } fn strip_ansi_codes_from_strings_iterator<'a>( strings: impl Iterator<Item = (&'a str, bool)>, ) -> String { strings .filter_map(|(el, is_ansi)| if !is_ansi { Some(el) } else { None }) .join("") } pub fn explain_ansi(line: &str, colorful: bool) -> String { use crate::style::Style; parse_style_sections(line) .into_iter() .map(|(ansi_term_style, s)| { let style = Style { ansi_term_style, ..Style::default() }; if colorful { format!("({}){}", style.to_painted_string(), style.paint(s)) } else { format!("({style}){s}") } }) .collect() } #[cfg(test)] mod tests { use unicode_width::UnicodeWidthStr; // Note that src/ansi/console_tests.rs contains additional test coverage for this module. use super::{ ansi_preserving_index, ansi_preserving_slice, measure_text_width, parse_first_style, string_starts_with_ansi_style_sequence, strip_ansi_codes, truncate_str, truncate_str_short, }; #[test] fn test_strip_ansi_codes() { for s in &["src/ansi/mod.rs", "バー", "src/ansi/modバー.rs"] { assert_eq!(strip_ansi_codes(s), *s); } assert_eq!(strip_ansi_codes("\x1b[31mバー\x1b[0m"), "バー"); } #[test] fn test_measure_text_width() { assert_eq!(measure_text_width("src/ansi/mod.rs"), 15); assert_eq!(measure_text_width("バー"), 4); assert_eq!(measure_text_width("src/ansi/modバー.rs"), 19); assert_eq!(measure_text_width("\x1b[31mバー\x1b[0m"), 4); assert_eq!(measure_text_width("a\nb\n"), 2); } #[test] fn test_strip_ansi_codes_osc_hyperlink() { assert_eq!(strip_ansi_codes("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/mod.rs\x1b]8;;\x1b\\\x1b[0m\n"), "src/ansi/mod.rs\n"); } #[test] fn test_measure_text_width_osc_hyperlink() { assert_eq!(measure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/mod.rs\x1b]8;;\x1b\\\x1b[0m"), measure_text_width("src/ansi/mod.rs")); } #[test] fn test_measure_text_width_osc_hyperlink_non_ascii() { assert_eq!(measure_text_width("\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/modバー.rs\x1b]8;;\x1b\\\x1b[0m"), measure_text_width("src/ansi/modバー.rs")); } #[test] fn test_parse_first_style() { let minus_line_from_unconfigured_git = "\x1b[31m-____\x1b[m\n"; let style = parse_first_style(minus_line_from_unconfigured_git); let expected_style = ansi_term::Style { foreground: Some(ansi_term::Color::Red), ..ansi_term::Style::default() }; assert_eq!(Some(expected_style), style); } #[test] fn test_string_starts_with_ansi_escape_sequence() { assert!(!string_starts_with_ansi_style_sequence("")); assert!(!string_starts_with_ansi_style_sequence("-")); assert!(string_starts_with_ansi_style_sequence( "\x1b[31m-XXX\x1b[m\n" )); assert!(string_starts_with_ansi_style_sequence("\x1b[32m+XXX")); } #[test] fn test_ansi_preserving_slice_and_index() { assert_eq!(ansi_preserving_slice("", 0), ""); assert_eq!(ansi_preserving_index("", 0), None); assert_eq!(ansi_preserving_slice("0", 0), "0"); assert_eq!(ansi_preserving_index("0", 0), Some(0)); assert_eq!(ansi_preserving_slice("0", 1), ""); assert_eq!(ansi_preserving_index("0", 1), None); let raw_string = "\x1b[1;35m0123456789\x1b[0m"; assert_eq!( ansi_preserving_slice(raw_string, 1), "\x1b[1;35m123456789\x1b[0m" ); assert_eq!(ansi_preserving_slice(raw_string, 7), "\x1b[1;35m789\x1b[0m"); assert_eq!(ansi_preserving_index(raw_string, 0), Some(7)); assert_eq!(ansi_preserving_index(raw_string, 1), Some(8)); assert_eq!(ansi_preserving_index(raw_string, 7), Some(14)); let raw_string = "\x1b[1;36m0\x1b[m\x1b[1;36m123456789\x1b[m\n"; assert_eq!( ansi_preserving_slice(raw_string, 1), "\x1b[1;36m\x1b[m\x1b[1;36m123456789\x1b[m\n" ); assert_eq!(ansi_preserving_index(raw_string, 0), Some(7)); assert_eq!(ansi_preserving_index(raw_string, 1), Some(18)); assert_eq!(ansi_preserving_index(raw_string, 7), Some(24)); let raw_string = "\x1b[1;36m012345\x1b[m\x1b[1;36m6789\x1b[m\n"; assert_eq!( ansi_preserving_slice(raw_string, 3), "\x1b[1;36m345\x1b[m\x1b[1;36m6789\x1b[m\n" ); assert_eq!(ansi_preserving_index(raw_string, 0), Some(7)); assert_eq!(ansi_preserving_index(raw_string, 1), Some(8)); assert_eq!(ansi_preserving_index(raw_string, 7), Some(24)); } #[test] fn test_truncate_str() { assert_eq!(truncate_str("1", 1, ""), "1"); assert_eq!(truncate_str("12", 1, ""), "1"); assert_eq!(truncate_str("123", 2, "s"), "1s"); assert_eq!(truncate_str("123", 2, "→"), "1→"); assert_eq!(truncate_str("12ݶ", 1, "ݶ"), "ݶ"); } #[test] fn test_truncate_str_at_double_width_grapheme() { let one_double_four = "1#4"; let double = "/"; assert_eq!(one_double_four.width(), 4); assert_eq!(double.width(), 2); assert_eq!(truncate_str(one_double_four, 1, ""), "1"); assert_eq!(truncate_str(one_double_four, 2, ""), "1 "); assert_eq!(truncate_str(one_double_four, 3, ""), "1#"); assert_eq!(truncate_str(one_double_four, 4, ""), "1#4"); assert_eq!(truncate_str_short(one_double_four, 1), "1"); assert_eq!(truncate_str_short(one_double_four, 2), "1"); // !! assert_eq!(truncate_str_short(one_double_four, 3), "1#"); assert_eq!(truncate_str_short(one_double_four, 4), "1#4"); assert_eq!(truncate_str(one_double_four, 1, double), " "); assert_eq!(truncate_str(one_double_four, 2, double), "/"); assert_eq!(truncate_str(one_double_four, 3, double), "1/"); assert_eq!(truncate_str(one_double_four, 4, double), "1#4"); assert_eq!(truncate_str(one_double_four, 0, ""), ""); assert_eq!(truncate_str(one_double_four, 0, double), ""); assert_eq!(truncate_str_short(one_double_four, 0), ""); assert_eq!(truncate_str(double, 0, double), ""); assert_eq!(truncate_str(double, 1, double), " "); assert_eq!(truncate_str(double, 2, double), double); assert_eq!(truncate_str_short(double, 0), ""); assert_eq!(truncate_str_short(double, 1), ""); assert_eq!(truncate_str_short(double, 2), double); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/ansi/iterator.rs
src/ansi/iterator.rs
use anstyle_parse::{Params, ParamsIter}; use core::str::Bytes; use std::convert::TryFrom; use std::iter; pub struct AnsiElementIterator<'a> { // The input bytes bytes: Bytes<'a>, // The state machine machine: anstyle_parse::Parser, // Becomes non-None when the parser finishes parsing an ANSI sequence. // This is never Element::Text. element: Option<Element>, // Number of text bytes seen since the last element was emitted. text_length: usize, // Byte offset of start of current element. start: usize, // Byte offset of most rightward byte processed so far pos: usize, } #[derive(Default)] struct Performer { // Becomes non-None when the parser finishes parsing an ANSI sequence. // This is never Element::Text. element: Option<Element>, // Number of text bytes seen since the last element was emitted. text_length: usize, } #[derive(Clone, Debug, PartialEq)] pub enum Element { Sgr(ansi_term::Style, usize, usize), Csi(usize, usize), Esc(usize, usize), Osc(usize, usize), Text(usize, usize), } impl Element { fn set_range(&mut self, start: usize, end: usize) { let (from, to) = match self { Element::Sgr(_, from, to) => (from, to), Element::Csi(from, to) => (from, to), Element::Esc(from, to) => (from, to), Element::Osc(from, to) => (from, to), Element::Text(from, to) => (from, to), }; *from = start; *to = end; } } impl<'a> AnsiElementIterator<'a> { pub fn new(s: &'a str) -> Self { Self { machine: anstyle_parse::Parser::<anstyle_parse::DefaultCharAccumulator>::new(), bytes: s.bytes(), element: None, text_length: 0, start: 0, pos: 0, } } fn advance_vte(&mut self, byte: u8) { let mut performer = Performer::default(); self.machine.advance(&mut performer, byte); self.element = performer.element; self.text_length += performer.text_length; self.pos += 1; } } impl Iterator for AnsiElementIterator<'_> { type Item = Element; fn next(&mut self) -> Option<Element> { // If the last element emitted was text, then there may be a non-text element waiting // to be emitted. In that case we do not consume a new byte. while self.element.is_none() { match self.bytes.next() { Some(b) => self.advance_vte(b), None => break, } } if let Some(mut element) = self.element.take() { // There is a non-text element waiting to be emitted, but it may have preceding // text, which must be emitted first. if self.text_length > 0 { let start = self.start; self.start += self.text_length; self.text_length = 0; self.element = Some(element); return Some(Element::Text(start, self.start)); } let start = self.start; self.start = self.pos; element.set_range(start, self.pos); return Some(element); } if self.text_length > 0 { self.text_length = 0; return Some(Element::Text(self.start, self.pos)); } None } } // Based on https://github.com/alacritty/vte/blob/v0.9.0/examples/parselog.rs impl anstyle_parse::Perform for Performer { fn csi_dispatch(&mut self, params: &Params, intermediates: &[u8], ignore: bool, byte: u8) { if ignore || intermediates.len() > 1 { return; } let is_sgr = byte == b'm' && intermediates.is_empty(); let element = if is_sgr { if params.is_empty() { // Attr::Reset // Probably doesn't need to be handled: https://github.com/dandavison/delta/pull/431#discussion_r536883568 None } else { let style = ansi_term_style_from_sgr_parameters(&mut params.iter()); Some(Element::Sgr(style, 0, 0)) } } else { Some(Element::Csi(0, 0)) }; self.element = element; } fn print(&mut self, c: char) { self.text_length += c.len_utf8(); } fn execute(&mut self, byte: u8) { // E.g. '\n' if byte < 128 { self.text_length += 1; } } fn hook(&mut self, _params: &Params, _intermediates: &[u8], _ignore: bool, _byte: u8) {} fn put(&mut self, _byte: u8) {} fn unhook(&mut self) {} fn osc_dispatch(&mut self, _params: &[&[u8]], _bell_terminated: bool) { self.element = Some(Element::Osc(0, 0)); } fn esc_dispatch(&mut self, _intermediates: &[u8], _ignore: bool, _byte: u8) { self.element = Some(Element::Esc(0, 0)); } } // Based on https://github.com/alacritty/alacritty/blob/9e71002e40d5487c6fa2571a3a3c4f5c8f679334/alacritty_terminal/src/ansi.rs#L1175 fn ansi_term_style_from_sgr_parameters(params: &mut ParamsIter<'_>) -> ansi_term::Style { let mut style = ansi_term::Style::new(); while let Some(param) = params.next() { match param { // [0] => Some(Attr::Reset), [1] => style.is_bold = true, [2] => style.is_dimmed = true, [3] => style.is_italic = true, [4, ..] => style.is_underline = true, [5] => style.is_blink = true, // blink slow [6] => style.is_blink = true, // blink fast [7] => style.is_reverse = true, [8] => style.is_hidden = true, [9] => style.is_strikethrough = true, // [21] => Some(Attr::CancelBold), // [22] => Some(Attr::CancelBoldDim), // [23] => Some(Attr::CancelItalic), // [24] => Some(Attr::CancelUnderline), // [25] => Some(Attr::CancelBlink), // [27] => Some(Attr::CancelReverse), // [28] => Some(Attr::CancelHidden), // [29] => Some(Attr::CancelStrike), [30] => style.foreground = Some(ansi_term::Color::Black), [31] => style.foreground = Some(ansi_term::Color::Red), [32] => style.foreground = Some(ansi_term::Color::Green), [33] => style.foreground = Some(ansi_term::Color::Yellow), [34] => style.foreground = Some(ansi_term::Color::Blue), [35] => style.foreground = Some(ansi_term::Color::Purple), [36] => style.foreground = Some(ansi_term::Color::Cyan), [37] => style.foreground = Some(ansi_term::Color::White), [38] => { let mut iter = params.map(|param| param[0]); if let Some(color) = parse_sgr_color(&mut iter) { style.foreground = Some(color); } } [38, params @ ..] => { let rgb_start = if params.len() > 4 { 2 } else { 1 }; let rgb_iter = params[rgb_start..].iter().copied(); let mut iter = iter::once(params[0]).chain(rgb_iter); if let Some(color) = parse_sgr_color(&mut iter) { style.foreground = Some(color); } } // [39] => Some(Attr::Foreground(Color::Named(NamedColor::Foreground))), [40] => style.background = Some(ansi_term::Color::Black), [41] => style.background = Some(ansi_term::Color::Red), [42] => style.background = Some(ansi_term::Color::Green), [43] => style.background = Some(ansi_term::Color::Yellow), [44] => style.background = Some(ansi_term::Color::Blue), [45] => style.background = Some(ansi_term::Color::Purple), [46] => style.background = Some(ansi_term::Color::Cyan), [47] => style.background = Some(ansi_term::Color::White), [48] => { let mut iter = params.map(|param| param[0]); if let Some(color) = parse_sgr_color(&mut iter) { style.background = Some(color); } } [48, params @ ..] => { let rgb_start = if params.len() > 4 { 2 } else { 1 }; let rgb_iter = params[rgb_start..].iter().copied(); let mut iter = iter::once(params[0]).chain(rgb_iter); if let Some(color) = parse_sgr_color(&mut iter) { style.background = Some(color); } } // [49] => Some(Attr::Background(Color::Named(NamedColor::Background))), // "bright" colors. ansi_term doesn't offer a way to emit them as, e.g., 90m; instead // that would be 38;5;8. [90] => style.foreground = Some(ansi_term::Color::Fixed(8)), [91] => style.foreground = Some(ansi_term::Color::Fixed(9)), [92] => style.foreground = Some(ansi_term::Color::Fixed(10)), [93] => style.foreground = Some(ansi_term::Color::Fixed(11)), [94] => style.foreground = Some(ansi_term::Color::Fixed(12)), [95] => style.foreground = Some(ansi_term::Color::Fixed(13)), [96] => style.foreground = Some(ansi_term::Color::Fixed(14)), [97] => style.foreground = Some(ansi_term::Color::Fixed(15)), [100] => style.background = Some(ansi_term::Color::Fixed(8)), [101] => style.background = Some(ansi_term::Color::Fixed(9)), [102] => style.background = Some(ansi_term::Color::Fixed(10)), [103] => style.background = Some(ansi_term::Color::Fixed(11)), [104] => style.background = Some(ansi_term::Color::Fixed(12)), [105] => style.background = Some(ansi_term::Color::Fixed(13)), [106] => style.background = Some(ansi_term::Color::Fixed(14)), [107] => style.background = Some(ansi_term::Color::Fixed(15)), _ => {} }; } style } // Based on https://github.com/alacritty/alacritty/blob/57c4ac9145a20fb1ae9a21102503458d3da06c7b/alacritty_terminal/src/ansi.rs#L1258 fn parse_sgr_color(params: &mut dyn Iterator<Item = u16>) -> Option<ansi_term::Color> { match params.next() { Some(2) => { let r = u8::try_from(params.next()?).ok()?; let g = u8::try_from(params.next()?).ok()?; let b = u8::try_from(params.next()?).ok()?; Some(ansi_term::Color::RGB(r, g, b)) } Some(5) => Some(ansi_term::Color::Fixed(u8::try_from(params.next()?).ok()?)), _ => None, } } #[cfg(test)] mod tests { use super::{AnsiElementIterator, Element}; use crate::style; #[test] fn test_iterator_parse_git_style_strings() { for (git_style_string, git_output) in &*style::tests::GIT_STYLE_STRING_EXAMPLES { let mut it = AnsiElementIterator::new(git_output); if *git_style_string == "normal" { // This one has a different pattern assert!( matches!(it.next().unwrap(), Element::Sgr(s, _, _) if s == ansi_term::Style::default()) ); assert!( matches!(it.next().unwrap(), Element::Text(i, j) if &git_output[i..j] == "text") ); assert!( matches!(it.next().unwrap(), Element::Sgr(s, _, _) if s == ansi_term::Style::default()) ); continue; } // First element should be a style let element = it.next().unwrap(); match element { Element::Sgr(style, _, _) => assert!(style::ansi_term_style_equality( style, style::Style::from_git_str(git_style_string).ansi_term_style )), _ => unreachable!(), } // Second element should be text: "+" assert!(matches!( it.next().unwrap(), Element::Text(i, j) if &git_output[i..j] == "+")); // Third element is the reset style assert!(matches!( it.next().unwrap(), Element::Sgr(s, _, _) if s == ansi_term::Style::default())); // Fourth element should be a style let element = it.next().unwrap(); match element { Element::Sgr(style, _, _) => assert!(style::ansi_term_style_equality( style, style::Style::from_git_str(git_style_string).ansi_term_style )), _ => unreachable!(), } // Fifth element should be text: "text" assert!(matches!( it.next().unwrap(), Element::Text(i, j) if &git_output[i..j] == "text")); // Sixth element is the reset style assert!(matches!( it.next().unwrap(), Element::Sgr(s, _, _) if s == ansi_term::Style::default())); assert!(matches!( it.next().unwrap(), Element::Text(i, j) if &git_output[i..j] == "\n")); assert!(it.next().is_none()); } } #[test] fn test_iterator_1() { let minus_line = "\x1b[31m0123\x1b[m\n"; let actual_elements: Vec<Element> = AnsiElementIterator::new(minus_line).collect(); assert_eq!( actual_elements, vec![ Element::Sgr( ansi_term::Style { foreground: Some(ansi_term::Color::Red), ..ansi_term::Style::default() }, 0, 5 ), Element::Text(5, 9), Element::Sgr(ansi_term::Style::default(), 9, 12), Element::Text(12, 13), ] ); assert_eq!("0123", &minus_line[5..9]); assert_eq!("\n", &minus_line[12..13]); } #[test] fn test_iterator_2() { let minus_line = "\x1b[31m0123\x1b[m456\n"; let actual_elements: Vec<Element> = AnsiElementIterator::new(minus_line).collect(); assert_eq!( actual_elements, vec![ Element::Sgr( ansi_term::Style { foreground: Some(ansi_term::Color::Red), ..ansi_term::Style::default() }, 0, 5 ), Element::Text(5, 9), Element::Sgr(ansi_term::Style::default(), 9, 12), Element::Text(12, 16), ] ); assert_eq!("0123", &minus_line[5..9]); assert_eq!("456\n", &minus_line[12..16]); } #[test] fn test_iterator_styled_non_ascii() { let s = "\x1b[31mバー\x1b[0m"; let actual_elements: Vec<Element> = AnsiElementIterator::new(s).collect(); assert_eq!( actual_elements, vec![ Element::Sgr( ansi_term::Style { foreground: Some(ansi_term::Color::Red), ..ansi_term::Style::default() }, 0, 5 ), Element::Text(5, 11), Element::Sgr(ansi_term::Style::default(), 11, 15), ] ); assert_eq!("バー", &s[5..11]); } #[test] fn test_iterator_erase_in_line() { let s = "\x1b[0Kあ.\x1b[m"; let actual_elements: Vec<Element> = AnsiElementIterator::new(s).collect(); assert_eq!( actual_elements, vec![ Element::Csi(0, 4), Element::Text(4, 8), Element::Sgr(ansi_term::Style::default(), 8, 11), ] ); assert_eq!("あ.", &s[4..8]); } #[test] fn test_iterator_erase_in_line_without_n() { let s = "\x1b[Kあ.\x1b[m"; let actual_elements: Vec<Element> = AnsiElementIterator::new(s).collect(); assert_eq!( actual_elements, vec![ Element::Csi(0, 3), Element::Text(3, 7), Element::Sgr(ansi_term::Style::default(), 7, 10), ] ); assert_eq!("あ.", &s[3..7]); } #[test] fn test_iterator_osc_hyperlinks_styled_non_ascii() { let s = "\x1b[38;5;4m\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b\\src/ansi/modバー.rs\x1b]8;;\x1b\\\x1b[0m\n"; assert_eq!(&s[0..9], "\x1b[38;5;4m"); assert_eq!( &s[9..58], "\x1b]8;;file:///Users/dan/src/delta/src/ansi/mod.rs\x1b" ); assert_eq!(&s[58..59], "\\"); assert_eq!(&s[59..80], "src/ansi/modバー.rs"); assert_eq!(&s[80..86], "\x1b]8;;\x1b"); assert_eq!(&s[86..87], "\\"); assert_eq!(&s[87..91], "\x1b[0m"); assert_eq!(&s[91..92], "\n"); let actual_elements: Vec<Element> = AnsiElementIterator::new(s).collect(); assert_eq!( actual_elements, vec![ Element::Sgr( ansi_term::Style { foreground: Some(ansi_term::Color::Fixed(4)), ..ansi_term::Style::default() }, 0, 9 ), Element::Osc(9, 58), Element::Esc(58, 59), Element::Text(59, 80), Element::Osc(80, 86), Element::Esc(86, 87), Element::Sgr(ansi_term::Style::default(), 87, 91), Element::Text(91, 92), ] ); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/features/color_only.rs
src/features/color_only.rs
use std::collections::HashSet; use crate::features::raw; use crate::features::OptionValueFunction; /// color-only is like raw but does not override these styles. pub fn make_feature() -> Vec<(String, OptionValueFunction)> { let styles: HashSet<_> = [ "minus-style", "minus-emph-style", "zero-style", "plus-style", "plus-emph-style", ] .iter() .collect(); raw::make_feature() .into_iter() .filter(|(k, _)| !styles.contains(&k.as_str())) .collect() }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/features/hyperlinks.rs
src/features/hyperlinks.rs
use std::borrow::Cow; use std::path::Path; use lazy_static::lazy_static; use regex::{Match, Matches, Regex}; use crate::config::Config; use crate::features::OptionValueFunction; #[cfg(test)] use crate::git_config::GitConfig; pub fn make_feature() -> Vec<(String, OptionValueFunction)> { builtin_feature!([ ( "hyperlinks", bool, None, _opt => true ) ]) } lazy_static! { // Commit hashes can be abbreviated to 7 characters, these necessarily become longer // when more objects are in a repository. // Note: pure numbers are filtered out later again. static ref COMMIT_HASH_REGEX: Regex = Regex::new(r"\b[0-9a-f]{7,40}\b").unwrap(); } pub fn format_commit_line_with_osc8_commit_hyperlink<'a>( line: &'a str, config: &Config, ) -> Cow<'a, str> { // Given matches in a line, m = matches[0] and pos = 0: store line[pos..m.start()] first, then // store the T(line[m.start()..m.end()]) match transformation, then set pos = m.end(). // Repeat for matches[1..]. Finally, store line[pos..]. struct HyperlinkCommits<T>(T) where T: Fn(&str) -> String; impl<T: for<'b> Fn(&'b str) -> String> HyperlinkCommits<T> { fn _m(&self, result: &mut String, line: &str, m: &Match, prev_pos: usize) -> usize { result.push_str(&line[prev_pos..m.start()]); let commit = &line[m.start()..m.end()]; // Do not link numbers, require at least one non-decimal: if commit.contains(|c| matches!(c, 'a'..='f')) { result.push_str(&format_osc8_hyperlink(&self.0(commit), commit)); } else { result.push_str(commit); } m.end() } fn with_input(&self, line: &str, m0: &Match, matches123: &mut Matches) -> String { let mut result = String::new(); let mut pos = self._m(&mut result, line, m0, 0); // limit number of matches per line, an exhaustive `find_iter` is O(len(line) * len(regex)^2) for m in matches123.take(12) { pos = self._m(&mut result, line, &m, pos); } result.push_str(&line[pos..]); result } } if let Some(commit_link_format) = &config.hyperlinks_commit_link_format { let mut matches = COMMIT_HASH_REGEX.find_iter(line); if let Some(first_match) = matches.next() { let result = HyperlinkCommits(|commit_hash| commit_link_format.replace("{commit}", commit_hash)) .with_input(line, &first_match, &mut matches); return Cow::from(result); } } else if let Some(config) = config.git_config() { if let Some(repo) = config.get_remote_url() { let mut matches = COMMIT_HASH_REGEX.find_iter(line); if let Some(first_match) = matches.next() { let result = HyperlinkCommits(|commit_hash| repo.format_commit_url(commit_hash)) .with_input(line, &first_match, &mut matches); return Cow::from(result); } } } Cow::from(line) } /// Create a file hyperlink, displaying `text`. pub fn format_osc8_file_hyperlink<'a, P>( absolute_path: P, line_number: Option<usize>, text: &str, config: &Config, ) -> Cow<'a, str> where P: AsRef<Path>, P: std::fmt::Debug, { debug_assert!(absolute_path.as_ref().is_absolute()); let mut url = config .hyperlinks_file_link_format .replace("{path}", &absolute_path.as_ref().to_string_lossy()); if let Some(host) = &config.hostname { url = url.replace("{host}", host) } let n = line_number.unwrap_or(1); url = url.replace("{line}", &format!("{n}")); Cow::from(format_osc8_hyperlink(&url, text)) } fn format_osc8_hyperlink(url: &str, text: &str) -> String { format!( "{osc}8;;{url}{st}{text}{osc}8;;{st}", url = url, text = text, osc = "\x1b]", st = "\x1b\\" ) } #[cfg(not(target_os = "windows"))] #[cfg(test)] pub mod tests { use std::iter::FromIterator; use std::path::PathBuf; use pretty_assertions::assert_eq; use super::*; use crate::{ tests::integration_test_utils::{self, make_config_from_args, DeltaTest}, utils, }; #[test] fn test_file_hyperlink_line_number_defaults_to_one() { let config = make_config_from_args(&["--hyperlinks-file-link-format", "file://{path}:{line}"]); let result = format_osc8_file_hyperlink("/absolute/path/to/file.rs", Some(42), "file.rs", &config); assert_eq!( result, "\u{1b}]8;;file:///absolute/path/to/file.rs:42\u{1b}\\file.rs\u{1b}]8;;\u{1b}\\", ); let result = format_osc8_file_hyperlink("/absolute/path/to/file.rs", None, "file.rs", &config); assert_eq!( result, "\u{1b}]8;;file:///absolute/path/to/file.rs:1\u{1b}\\file.rs\u{1b}]8;;\u{1b}\\", ); } #[test] fn test_formatted_hyperlinks() { let config = make_config_from_args(&["--hyperlinks-commit-link-format", "HERE:{commit}"]); let line = "001234abcdf"; let result = format_commit_line_with_osc8_commit_hyperlink(line, &config); assert_eq!( result, "\u{1b}]8;;HERE:001234abcdf\u{1b}\\001234abcdf\u{1b}]8;;\u{1b}\\", ); let line = "a2272718f0b398e48652ace17fca85c1962b3fc22"; // length: 41 > 40 let result = format_commit_line_with_osc8_commit_hyperlink(line, &config); assert_eq!(result, "a2272718f0b398e48652ace17fca85c1962b3fc22",); let line = "a2272718f0+b398e48652ace17f,ca85c1962b3fc2"; let result = format_commit_line_with_osc8_commit_hyperlink(line, &config); assert_eq!(result, "\u{1b}]8;;HERE:a2272718f0\u{1b}\\a2272718f0\u{1b}]8;;\u{1b}\\+\u{1b}]8;;\ HERE:b398e48652ace17f\u{1b}\\b398e48652ace17f\u{1b}]8;;\u{1b}\\,\u{1b}]8;;HERE:ca85c1962b3fc2\ \u{1b}\\ca85c1962b3fc2\u{1b}]8;;\u{1b}\\"); let line = "This 01234abcdf Hash"; let result = format_commit_line_with_osc8_commit_hyperlink(line, &config); assert_eq!( result, "This \u{1b}]8;;HERE:01234abcdf\u{1b}\\01234abcdf\u{1b}]8;;\u{1b}\\ Hash", ); let line = "Another 01234abcdf hash but also this one: dc623b084ad2dd14fe5d90189cacad5d49bfbfd3!"; let result = format_commit_line_with_osc8_commit_hyperlink(line, &config); assert_eq!( result, "Another \u{1b}]8;;HERE:01234abcdf\u{1b}\\01234abcdf\u{1b}]8;;\u{1b}\\ hash but \ also this one: \u{1b}]8;;HERE:dc623b084ad2dd14fe5d90189cacad5d49bfbfd3\u{1b}\ \\dc623b084ad2dd14fe5d90189cacad5d49bfbfd3\u{1b}]8;;\u{1b}\\!" ); let line = "01234abcdf 03043baf30 12abcdef0 12345678"; let result = format_commit_line_with_osc8_commit_hyperlink(line, &config); assert_eq!( result, "\u{1b}]8;;HERE:01234abcdf\u{1b}\\01234abcdf\u{1b}]8;;\u{1b}\\ \u{1b}]8;;\ HERE:03043baf30\u{1b}\\03043baf30\u{1b}]8;;\u{1b}\\ \u{1b}]8;;HERE:12abcdef0\u{1b}\\\ 12abcdef0\u{1b}]8;;\u{1b}\\ 12345678" ); } #[test] fn test_hyperlinks_to_repo() { let mut config = make_config_from_args(&["--hyperlinks"]); config.git_config = GitConfig::for_testing(); let line = "This a589ff9debaefdd delta commit"; let result = format_commit_line_with_osc8_commit_hyperlink(line, &config); assert_eq!( result, "This \u{1b}]8;;https://github.com/dandavison/delta/commit/a589ff9debaefdd\u{1b}\ \\a589ff9debaefdd\u{1b}]8;;\u{1b}\\ delta commit", ); let line = "Another a589ff9debaefdd hash but also this one: c5696757c0827349a87daa95415656!"; let result = format_commit_line_with_osc8_commit_hyperlink(line, &config); assert_eq!( result, "Another \u{1b}]8;;https://github.com/dandavison/delta/commit/a589ff9debaefdd\ \u{1b}\\a589ff9debaefdd\u{1b}]8;;\u{1b}\\ hash but also this one: \u{1b}]8;;\ https://github.com/dandavison/delta/commit/c5696757c0827349a87daa95415656\u{1b}\ \\c5696757c0827349a87daa95415656\u{1b}]8;;\ \u{1b}\\!" ); } #[test] fn test_paths_and_hyperlinks_user_in_repo_root_dir() { // Expectations are uninfluenced by git's --relative and delta's relative_paths options. let input_type = InputType::GitDiff; let true_location_of_file_relative_to_repo_root = PathBuf::from("a"); let git_prefix_env_var = Some(""); for (delta_relative_paths_option, calling_cmd) in [ (false, Some("git diff")), (false, Some("git diff --relative")), (true, Some("git diff")), (true, Some("git diff --relative")), ] { run_test(FilePathsTestCase { name: &format!( "delta relative_paths={delta_relative_paths_option} calling_cmd={calling_cmd:?}", ), true_location_of_file_relative_to_repo_root: true_location_of_file_relative_to_repo_root.as_path(), git_prefix_env_var, delta_relative_paths_option, input_type, calling_cmd, path_in_delta_input: "a", expected_displayed_path: "a", }) } } #[test] fn test_paths_and_hyperlinks_user_in_subdir_file_in_same_subdir() { let input_type = InputType::GitDiff; let true_location_of_file_relative_to_repo_root = PathBuf::from_iter(&["b", "a"]); let git_prefix_env_var = Some("b"); run_test(FilePathsTestCase { name: "b/a from b", input_type, calling_cmd: Some("git diff"), true_location_of_file_relative_to_repo_root: true_location_of_file_relative_to_repo_root.as_path(), git_prefix_env_var, delta_relative_paths_option: false, path_in_delta_input: "b/a", expected_displayed_path: "b/a", }); run_test(FilePathsTestCase { name: "b/a from b", input_type, calling_cmd: Some("git diff --relative"), true_location_of_file_relative_to_repo_root: true_location_of_file_relative_to_repo_root.as_path(), git_prefix_env_var, delta_relative_paths_option: false, path_in_delta_input: "a", // delta saw a and wasn't configured to make any changes expected_displayed_path: "a", }); run_test(FilePathsTestCase { name: "b/a from b", input_type, calling_cmd: Some("git diff"), true_location_of_file_relative_to_repo_root: true_location_of_file_relative_to_repo_root.as_path(), git_prefix_env_var, delta_relative_paths_option: true, path_in_delta_input: "b/a", // delta saw b/a and changed it to a expected_displayed_path: "a", }); run_test(FilePathsTestCase { name: "b/a from b", input_type, calling_cmd: Some("git diff --relative"), true_location_of_file_relative_to_repo_root: true_location_of_file_relative_to_repo_root.as_path(), git_prefix_env_var, delta_relative_paths_option: true, path_in_delta_input: "a", // delta saw a and didn't change it expected_displayed_path: "a", }); } #[test] fn test_paths_and_hyperlinks_user_in_subdir_file_in_different_subdir() { let input_type = InputType::GitDiff; let true_location_of_file_relative_to_repo_root = PathBuf::from_iter(&["b", "a"]); let git_prefix_env_var = Some("c"); run_test(FilePathsTestCase { name: "b/a from c", input_type, calling_cmd: Some("git diff"), delta_relative_paths_option: false, true_location_of_file_relative_to_repo_root: true_location_of_file_relative_to_repo_root.as_path(), git_prefix_env_var, path_in_delta_input: "b/a", expected_displayed_path: "b/a", }); run_test(FilePathsTestCase { name: "b/a from c", input_type, calling_cmd: Some("git diff --relative"), delta_relative_paths_option: false, true_location_of_file_relative_to_repo_root: true_location_of_file_relative_to_repo_root.as_path(), git_prefix_env_var, path_in_delta_input: "../b/a", expected_displayed_path: "../b/a", }); run_test(FilePathsTestCase { name: "b/a from c", input_type, calling_cmd: Some("git diff"), delta_relative_paths_option: true, true_location_of_file_relative_to_repo_root: true_location_of_file_relative_to_repo_root.as_path(), git_prefix_env_var, path_in_delta_input: "b/a", expected_displayed_path: "../b/a", }); } #[test] fn test_paths_and_hyperlinks_git_grep_user_in_root() { let input_type = InputType::Grep; let true_location_of_file_relative_to_repo_root = PathBuf::from_iter(&["b", "a.txt"]); run_test(FilePathsTestCase { name: "git grep: b/a.txt from root dir", input_type, calling_cmd: Some("git grep foo"), delta_relative_paths_option: false, true_location_of_file_relative_to_repo_root: true_location_of_file_relative_to_repo_root.as_path(), git_prefix_env_var: Some(""), path_in_delta_input: "b/a.txt", expected_displayed_path: "b/a.txt:", }); } #[test] fn test_paths_and_hyperlinks_grep_user_in_subdir_file_in_same_subdir() { _run_test_grep_user_in_subdir_file_in_same_subdir(Some("git grep foo")); _run_test_grep_user_in_subdir_file_in_same_subdir(Some("rg foo")); } fn _run_test_grep_user_in_subdir_file_in_same_subdir(calling_cmd: Option<&str>) { let input_type = InputType::Grep; let true_location_of_file_relative_to_repo_root = PathBuf::from_iter(&["b", "a.txt"]); run_test(FilePathsTestCase { name: "git grep: b/a.txt from b/ dir", input_type, calling_cmd, delta_relative_paths_option: false, true_location_of_file_relative_to_repo_root: true_location_of_file_relative_to_repo_root.as_path(), git_prefix_env_var: Some("b/"), path_in_delta_input: "a.txt", expected_displayed_path: "a.txt:", }); } const GIT_DIFF_OUTPUT: &str = r#" diff --git a/__path__ b/__path__ index 587be6b..975fbec 100644 --- a/__path__ +++ b/__path__ @@ -1 +1 @@ -x +y "#; const GIT_GREP_OUTPUT: &str = "\ __path__: some matching line "; struct FilePathsTestCase<'a> { // True location of file in repo true_location_of_file_relative_to_repo_root: &'a Path, // Git spawns delta from repo root, and stores in this env var the cwd in which the user invoked delta. git_prefix_env_var: Option<&'a str>, delta_relative_paths_option: bool, input_type: InputType, calling_cmd: Option<&'a str>, path_in_delta_input: &'a str, expected_displayed_path: &'a str, #[allow(dead_code)] name: &'a str, } #[derive(Debug)] enum GitDiffRelative { Yes, No, } #[derive(Debug)] enum CallingProcess { GitDiff(GitDiffRelative), GitGrep, OtherGrep, } #[derive(Clone, Copy, Debug)] enum InputType { GitDiff, Grep, } impl<'a> FilePathsTestCase<'a> { pub fn get_args(&self) -> Vec<String> { let mut args = vec![ "--navigate", // helps locate the file path in the output "--line-numbers", "--hyperlinks", "--hyperlinks-file-link-format", "{path}", "--grep-file-style", "raw", "--grep-line-number-style", "raw", "--grep-output-type", "classic", "--hunk-header-file-style", "raw", "--hunk-header-line-number-style", "raw", "--line-numbers-plus-style", "raw", "--line-numbers-left-style", "raw", "--line-numbers-right-style", "raw", "--line-numbers-left-format", "{nm}અ", "--line-numbers-right-format", "{np}જ", ]; if self.delta_relative_paths_option { args.push("--relative-paths"); } args.iter().map(|s| s.to_string()).collect() } pub fn calling_process(&self) -> CallingProcess { match (&self.input_type, self.calling_cmd) { (InputType::GitDiff, Some(s)) if s.starts_with("git diff --relative") => { CallingProcess::GitDiff(GitDiffRelative::Yes) } (InputType::GitDiff, Some(s)) if s.starts_with("git diff") => { CallingProcess::GitDiff(GitDiffRelative::No) } (InputType::Grep, Some(s)) if s.starts_with("git grep") => CallingProcess::GitGrep, (InputType::Grep, Some(s)) if s.starts_with("rg") => CallingProcess::OtherGrep, (InputType::Grep, None) => CallingProcess::GitGrep, _ => panic!( "Unexpected calling spec: {:?} {:?}", self.input_type, self.calling_cmd ), } } pub fn path_in_git_output(&self) -> String { match self.calling_process() { CallingProcess::GitDiff(GitDiffRelative::No) => self .true_location_of_file_relative_to_repo_root .to_string_lossy() .to_string(), CallingProcess::GitDiff(GitDiffRelative::Yes) => pathdiff::diff_paths( self.true_location_of_file_relative_to_repo_root, self.git_prefix_env_var.unwrap(), ) .unwrap() .to_string_lossy() .into(), _ => panic!("Unexpected calling process: {:?}", self.calling_process()), } } /// Return the relative path as it would appear in grep output, i.e. accounting for facts /// such as that the user may have invoked the grep command from a non-root directory /// in the repo. pub fn path_in_grep_output(&self) -> String { use CallingProcess::*; match (self.calling_process(), self.git_prefix_env_var) { (GitGrep, None) => self .true_location_of_file_relative_to_repo_root .to_string_lossy() .into(), (GitGrep, Some(dir)) => { // Delta must have been invoked as core.pager since GIT_PREFIX env var is set. // Note that it is possible that `true_location_of_file_relative_to_repo_root` // is not under `git_prefix_env_var` since one can do things like `git grep foo // ..` pathdiff::diff_paths(self.true_location_of_file_relative_to_repo_root, dir) .unwrap() .to_string_lossy() .into() } (OtherGrep, None) => { // Output from e.g. rg has been piped to delta. // Therefore // (a) the cwd that the delta process reports is the user's shell process cwd // (b) the file in question must be under this cwd // (c) grep output will contain the path relative to this cwd // So to compute the path as it would appear in grep output, we could form the // absolute path to the file and strip off the config.cwd_of_delta_process // prefix. The absolute path to the file could be constructed as (absolute path // to repo root) + true_location_of_file_relative_to_repo_root). But I don't // think we know the absolute path to repo root. panic!("Not implemented") } _ => panic!("Not implemented"), } } pub fn expected_hyperlink_path(&self) -> PathBuf { utils::path::fake_delta_cwd_for_tests() .join(self.true_location_of_file_relative_to_repo_root) } } fn run_test(test_case: FilePathsTestCase) { let mut config = integration_test_utils::make_config_from_args( test_case .get_args() .iter() .map(|s| s.as_str()) .collect::<Vec<&str>>() .as_slice(), ); // The test is simulating delta invoked by git hence these are the same config.cwd_relative_to_repo_root = test_case.git_prefix_env_var.map(|s| s.to_string()); config.cwd_of_user_shell_process = utils::path::cwd_of_user_shell_process( config.cwd_of_delta_process.as_ref(), config.cwd_relative_to_repo_root.as_deref(), ); let mut delta_test = DeltaTest::with_config(&config); if let Some(cmd) = test_case.calling_cmd { delta_test = delta_test.with_calling_process(cmd) } let delta_test = match test_case.calling_process() { CallingProcess::GitDiff(_) => { assert_eq!( test_case.path_in_delta_input, test_case.path_in_git_output() ); delta_test .with_input(&GIT_DIFF_OUTPUT.replace("__path__", test_case.path_in_delta_input)) } CallingProcess::GitGrep => { assert_eq!( test_case.path_in_delta_input, test_case.path_in_grep_output() ); delta_test .with_input(&GIT_GREP_OUTPUT.replace("__path__", test_case.path_in_delta_input)) } CallingProcess::OtherGrep => delta_test .with_input(&GIT_GREP_OUTPUT.replace("__path__", test_case.path_in_delta_input)), }; let make_expected_hyperlink = |text| { format_osc8_hyperlink(&test_case.expected_hyperlink_path().to_string_lossy(), text) }; match test_case.calling_process() { CallingProcess::GitDiff(_) => { let line_number = "1"; delta_test .inspect_raw() // file hyperlink .expect_raw_contains(&format!( "Δ {}", make_expected_hyperlink(test_case.expected_displayed_path) )) // hunk header hyperlink .expect_raw_contains(&format!("• {}", make_expected_hyperlink(line_number))) // line number hyperlink .expect_raw_contains(&format!("અ{}જ", make_expected_hyperlink(line_number))); } CallingProcess::GitGrep | CallingProcess::OtherGrep => { delta_test .inspect_raw() .expect_raw_contains(&make_expected_hyperlink( test_case.expected_displayed_path, )); } } } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/features/line_numbers.rs
src/features/line_numbers.rs
use std::cmp::max; use lazy_static::lazy_static; use regex::Regex; use crate::color::ColorMode::*; use crate::config; use crate::delta::State; use crate::features::hyperlinks; use crate::features::side_by_side::ansifill::{self, ODD_PAD_CHAR}; use crate::features::side_by_side::{Left, PanelSide, Right}; use crate::features::OptionValueFunction; use crate::format::{self, Align, Placeholder}; use crate::minusplus::*; use crate::style::Style; use crate::utils; pub fn make_feature() -> Vec<(String, OptionValueFunction)> { builtin_feature!([ ( "line-numbers", bool, None, _opt => true ), ( "line-numbers-left-style", String, None, _opt => "blue" ), ( "line-numbers-right-style", String, None, _opt => "blue" ), ( "line-numbers-minus-style", String, None, opt => match opt.computed.color_mode { Light => "red", Dark => "88", } ), ( "line-numbers-zero-style", String, None, opt => match opt.computed.color_mode { Light => "#dddddd", Dark => "#444444", } ), ( "line-numbers-plus-style", String, None, opt => match opt.computed.color_mode { Light => "green", Dark => "28", } ) ]) } pub fn linenumbers_and_styles<'a>( line_numbers_data: &'a mut LineNumbersData, state: &State, config: &'a config::Config, increment: bool, ) -> Option<(MinusPlus<Option<usize>>, MinusPlus<Style>)> { let nr_left = line_numbers_data.line_number[Left]; let nr_right = line_numbers_data.line_number[Right]; let (minus_style, zero_style, plus_style) = ( config.line_numbers_style_minusplus[Minus], config.line_numbers_zero_style, config.line_numbers_style_minusplus[Plus], ); let ((minus_number, plus_number), (minus_style, plus_style)) = match state { State::HunkMinus(_, _) => { line_numbers_data.line_number[Left] += increment as usize; ((Some(nr_left), None), (minus_style, plus_style)) } State::HunkMinusWrapped => ((None, None), (minus_style, plus_style)), State::HunkZero(_, _) => { line_numbers_data.line_number[Left] += increment as usize; line_numbers_data.line_number[Right] += increment as usize; ((Some(nr_left), Some(nr_right)), (zero_style, zero_style)) } State::HunkZeroWrapped => ((None, None), (zero_style, zero_style)), State::HunkPlus(_, _) => { line_numbers_data.line_number[Right] += increment as usize; ((None, Some(nr_right)), (minus_style, plus_style)) } State::HunkPlusWrapped => ((None, None), (minus_style, plus_style)), _ => return None, }; Some(( MinusPlus::new(minus_number, plus_number), MinusPlus::new(minus_style, plus_style), )) } /// Return a vec of `ansi_term::ANSIGenericString`s representing the left and right fields of the /// two-column line number display. pub fn format_and_paint_line_numbers<'a>( line_numbers_data: &'a LineNumbersData, side_by_side_panel: Option<PanelSide>, styles: MinusPlus<Style>, line_numbers: MinusPlus<Option<usize>>, config: &'a config::Config, ) -> Vec<ansi_term::ANSIGenericString<'a, str>> { let mut formatted_numbers = Vec::new(); let (emit_left, emit_right) = match (config.side_by_side, side_by_side_panel) { (false, _) => (true, true), (true, Some(Left)) => (true, false), (true, Some(Right)) => (false, true), (true, None) => unreachable!(), }; if emit_left { formatted_numbers.extend(format_and_paint_line_number_field( line_numbers_data, Minus, &styles, &line_numbers, config, )); } if emit_right { formatted_numbers.extend(format_and_paint_line_number_field( line_numbers_data, Plus, &styles, &line_numbers, config, )); } formatted_numbers } lazy_static! { static ref LINE_NUMBERS_PLACEHOLDER_REGEX: Regex = format::make_placeholder_regex(&["nm", "np"]); } #[derive(Default, Debug)] pub struct LineNumbersData<'a> { pub format_data: MinusPlus<format::FormatStringData<'a>>, pub line_number: MinusPlus<usize>, pub hunk_max_line_number_width: usize, pub plus_file: String, } pub type SideBySideLineWidth = MinusPlus<usize>; // Although it's probably unusual, a single format string can contain multiple placeholders. E.g. // line-numbers-right-format = "{nm} {np}|" impl<'a> LineNumbersData<'a> { pub fn from_format_strings( format: &'a MinusPlus<String>, use_full_width: ansifill::UseFullPanelWidth, ) -> LineNumbersData<'a> { let insert_center_space_on_odd_width = use_full_width.pad_width(); Self { format_data: MinusPlus::new( format::parse_line_number_format( &format[Left], &LINE_NUMBERS_PLACEHOLDER_REGEX, false, ), format::parse_line_number_format( &format[Right], &LINE_NUMBERS_PLACEHOLDER_REGEX, insert_center_space_on_odd_width, ), ), ..Self::default() } } /// Initialize line number data for a hunk. pub fn initialize_hunk(&mut self, line_numbers: &[(usize, usize)], plus_file: String) { // Typically, line_numbers has length 2: an entry for the minus file, and one for the plus // file. In the case of merge commits, it may be longer. self.line_number = MinusPlus::new(line_numbers[0].0, line_numbers[line_numbers.len() - 1].0); let hunk_max_line_number = line_numbers.iter().map(|(n, d)| n + d).max().unwrap(); self.hunk_max_line_number_width = 1 + (hunk_max_line_number as f64).log10().floor() as usize; self.plus_file = plus_file; } pub fn empty_for_sbs(use_full_width: ansifill::UseFullPanelWidth) -> LineNumbersData<'a> { let insert_center_space_on_odd_width = use_full_width.pad_width(); Self { format_data: if insert_center_space_on_odd_width { let format_left = vec![format::FormatStringPlaceholderData::default()]; let format_right = vec![format::FormatStringPlaceholderData { prefix: format!("{ODD_PAD_CHAR}").into(), prefix_len: 1, ..Default::default() }]; MinusPlus::new(format_left, format_right) } else { MinusPlus::default() }, ..Self::default() } } pub fn formatted_width(&self) -> SideBySideLineWidth { let format_data_width = |format_data: &format::FormatStringData<'a>| { // Provide each Placeholder with the max_line_number_width to calculate the // actual width. Only use prefix and suffix of the last element, otherwise // only the prefix (as the suffix also contains the following prefix). format_data .last() .map(|last| { let (prefix_width, suffix_width) = last.width(self.hunk_max_line_number_width); format_data .iter() .rev() .skip(1) .map(|p| p.width(self.hunk_max_line_number_width).0) .sum::<usize>() + prefix_width + suffix_width }) .unwrap_or(0) }; MinusPlus::new( format_data_width(&self.format_data[Left]), format_data_width(&self.format_data[Right]), ) } } #[allow(clippy::too_many_arguments)] fn format_and_paint_line_number_field<'a>( line_numbers_data: &'a LineNumbersData, side: MinusPlusIndex, styles: &MinusPlus<Style>, line_numbers: &MinusPlus<Option<usize>>, config: &config::Config, ) -> Vec<ansi_term::ANSIGenericString<'a, str>> { let min_field_width = line_numbers_data.hunk_max_line_number_width; let format_data = &line_numbers_data.format_data[side]; let plus_file = &line_numbers_data.plus_file; let style = &config.line_numbers_style_leftright[side]; let mut ansi_strings = Vec::new(); let mut suffix = ""; for placeholder in format_data { ansi_strings.push(style.paint(placeholder.prefix.as_str())); let width = if let Some(placeholder_width) = placeholder.width { max(placeholder_width, min_field_width) } else { min_field_width }; let alignment_spec = placeholder.alignment_spec.unwrap_or(Align::Center); match placeholder.placeholder { Some(Placeholder::NumberMinus) => { ansi_strings.push(styles[Minus].paint(format_line_number( line_numbers[Minus], alignment_spec, width, placeholder.precision, None, config, ))) } Some(Placeholder::NumberPlus) => { ansi_strings.push(styles[Plus].paint(format_line_number( line_numbers[Plus], alignment_spec, width, placeholder.precision, Some(plus_file), config, ))) } None => {} _ => unreachable!("Invalid placeholder"), } suffix = placeholder.suffix.as_str(); } ansi_strings.push(style.paint(suffix)); ansi_strings } /// Return line number formatted according to `alignment` and `width`. fn format_line_number( line_number: Option<usize>, alignment: Align, width: usize, precision: Option<usize>, plus_file: Option<&str>, config: &config::Config, ) -> String { let pad = |n| format::pad(n, width, alignment, precision); match (line_number, config.hyperlinks, plus_file) { (None, _, _) => " ".repeat(width), (Some(n), true, Some(file)) => match utils::path::absolute_path(file, config) { Some(absolute_path) => { hyperlinks::format_osc8_file_hyperlink(absolute_path, line_number, &pad(n), config) .to_string() } None => pad(n), }, (Some(n), _, _) => pad(n), } } #[cfg(test)] pub mod tests { use regex::Captures; use crate::ansi::strip_ansi_codes; use crate::features::side_by_side::ansifill::ODD_PAD_CHAR; use crate::format::FormatStringData; use crate::tests::integration_test_utils::{make_config_from_args, run_delta, DeltaTest}; use super::*; pub fn parse_line_number_format_with_default_regex( format_string: &str, ) -> FormatStringData<'_> { format::parse_line_number_format(format_string, &LINE_NUMBERS_PLACEHOLDER_REGEX, false) } #[test] fn test_line_number_format_regex_1() { assert_eq!( parse_line_number_format_with_default_regex("{nm}"), vec![format::FormatStringPlaceholderData { prefix: "".into(), placeholder: Some(Placeholder::NumberMinus), ..Default::default() }] ) } #[test] fn test_line_number_format_regex_2() { assert_eq!( parse_line_number_format_with_default_regex("{np:4}"), vec![format::FormatStringPlaceholderData { prefix: "".into(), placeholder: Some(Placeholder::NumberPlus), alignment_spec: None, width: Some(4), ..Default::default() }] ) } #[test] fn test_line_number_format_regex_3() { assert_eq!( parse_line_number_format_with_default_regex("{np:>4}"), vec![format::FormatStringPlaceholderData { prefix: "".into(), placeholder: Some(Placeholder::NumberPlus), alignment_spec: Some(Align::Right), width: Some(4), precision: None, ..Default::default() }] ) } #[test] fn test_line_number_format_regex_4() { assert_eq!( parse_line_number_format_with_default_regex("{np:_>4}"), vec![format::FormatStringPlaceholderData { prefix: "".into(), placeholder: Some(Placeholder::NumberPlus), alignment_spec: Some(Align::Right), width: Some(4), ..Default::default() }] ) } #[test] fn test_line_number_format_regex_5() { assert_eq!( parse_line_number_format_with_default_regex("__{np:_>4}@@"), vec![format::FormatStringPlaceholderData { prefix: "__".into(), placeholder: Some(Placeholder::NumberPlus), alignment_spec: Some(Align::Right), width: Some(4), precision: None, suffix: "@@".into(), prefix_len: 2, suffix_len: 2, ..Default::default() }] ) } #[test] fn test_line_number_format_regex_6() { assert_eq!( parse_line_number_format_with_default_regex("__{nm:<3}@@---{np:_>4}**"), vec![ format::FormatStringPlaceholderData { prefix: "__".into(), placeholder: Some(Placeholder::NumberMinus), alignment_spec: Some(Align::Left), width: Some(3), precision: None, suffix: "@@---{np:_>4}**".into(), prefix_len: 2, suffix_len: 15, ..Default::default() }, format::FormatStringPlaceholderData { prefix: "@@---".into(), placeholder: Some(Placeholder::NumberPlus), alignment_spec: Some(Align::Right), width: Some(4), precision: None, suffix: "**".into(), prefix_len: 5, suffix_len: 2, ..Default::default() } ] ) } #[test] fn test_line_number_format_regex_7() { assert_eq!( parse_line_number_format_with_default_regex("__@@---**",), vec![format::FormatStringPlaceholderData { prefix: "".into(), placeholder: None, alignment_spec: None, width: None, precision: None, suffix: "__@@---**".into(), prefix_len: 0, suffix_len: 9, ..Default::default() },] ) } #[test] fn test_line_number_format_odd_width_one() { assert_eq!( format::parse_line_number_format("|{nm:<4}|", &LINE_NUMBERS_PLACEHOLDER_REGEX, true), vec![format::FormatStringPlaceholderData { prefix: format!("{ODD_PAD_CHAR}|").into(), placeholder: Some(Placeholder::NumberMinus), alignment_spec: Some(Align::Left), width: Some(4), precision: None, suffix: "|".into(), prefix_len: 2, suffix_len: 1, ..Default::default() }] ); } #[test] fn test_line_number_format_odd_width_two() { assert_eq!( format::parse_line_number_format( "|{nm:<4}+{np:<4}|", &LINE_NUMBERS_PLACEHOLDER_REGEX, true ), vec![ format::FormatStringPlaceholderData { prefix: format!("{ODD_PAD_CHAR}|").into(), placeholder: Some(Placeholder::NumberMinus), alignment_spec: Some(Align::Left), width: Some(4), precision: None, suffix: "+{np:<4}|".into(), prefix_len: 2, suffix_len: 9, ..Default::default() }, format::FormatStringPlaceholderData { prefix: "+".into(), placeholder: Some(Placeholder::NumberPlus), alignment_spec: Some(Align::Left), width: Some(4), precision: None, suffix: "|".into(), prefix_len: 1, suffix_len: 1, ..Default::default() } ] ); } #[test] fn test_line_number_format_odd_width_none() { assert_eq!( format::parse_line_number_format("|++|", &LINE_NUMBERS_PLACEHOLDER_REGEX, true), vec![format::FormatStringPlaceholderData { prefix: format!("{ODD_PAD_CHAR}").into(), placeholder: None, alignment_spec: None, width: None, precision: None, suffix: "|++|".into(), prefix_len: 1, suffix_len: 4, ..Default::default() }] ); } #[test] fn test_line_number_format_long() { let long = "line number format which is too large for SSO"; assert!(long.len() > std::mem::size_of::<smol_str::SmolStr>()); assert_eq!( parse_line_number_format_with_default_regex(&format!("{long}{{nm}}{long}")), vec![format::FormatStringPlaceholderData { prefix: long.into(), prefix_len: long.len(), placeholder: Some(Placeholder::NumberMinus), alignment_spec: None, width: None, precision: None, suffix: long.into(), suffix_len: long.len(), ..Default::default() },] ) } #[test] fn test_line_number_placeholder_width_one() { let data = parse_line_number_format_with_default_regex(""); assert_eq!(data[0].width(0), (0, 0)); let data = parse_line_number_format_with_default_regex(""); assert_eq!(data[0].width(4), (0, 0)); let data = parse_line_number_format_with_default_regex("│+│"); assert_eq!(data[0].width(4), (0, 3)); let data = parse_line_number_format_with_default_regex("{np}"); assert_eq!(data[0].width(4), (4, 0)); let data = parse_line_number_format_with_default_regex("│{np}│"); assert_eq!(data[0].width(4), (5, 1)); let data = parse_line_number_format_with_default_regex("│{np:2}│"); assert_eq!(data[0].width(4), (5, 1)); let data = parse_line_number_format_with_default_regex("│{np:6}│"); assert_eq!(data[0].width(4), (7, 1)); } #[test] fn test_line_number_placeholder_width_two() { let data = parse_line_number_format_with_default_regex("│{nm}│{np}│"); assert_eq!(data[0].width(1), (2, 6)); assert_eq!(data[1].width(1), (2, 1)); let data = parse_line_number_format_with_default_regex("│{nm:_>5}│{np:1}│"); assert_eq!(data[0].width(1), (6, 8)); assert_eq!(data[1].width(1), (2, 1)); let data = parse_line_number_format_with_default_regex("│{nm}│{np:5}│"); assert_eq!(data[0].width(7), (8, 8)); assert_eq!(data[1].width(7), (8, 1)); } #[test] fn test_line_numbers_data() { use crate::features::side_by_side::ansifill; let w = ansifill::UseFullPanelWidth(false); let format = MinusPlus::new("".into(), "".into()); let mut data = LineNumbersData::from_format_strings(&format, w.clone()); data.initialize_hunk(&[(10, 11), (10000, 100001)], "a".into()); assert_eq!(data.formatted_width(), MinusPlus::new(0, 0)); let format = MinusPlus::new("│".into(), "│+│".into()); let mut data = LineNumbersData::from_format_strings(&format, w.clone()); data.initialize_hunk(&[(10, 11), (10000, 100001)], "a".into()); assert_eq!(data.formatted_width(), MinusPlus::new(1, 3)); let format = MinusPlus::new("│{nm:^3}│".into(), "│{np:^3}│".into()); let mut data = LineNumbersData::from_format_strings(&format, w.clone()); data.initialize_hunk(&[(10, 11), (10000, 100001)], "a".into()); assert_eq!(data.formatted_width(), MinusPlus::new(8, 8)); let format = MinusPlus::new("│{nm:^3}│ │{np:<12}│ │{nm}│".into(), "".into()); let mut data = LineNumbersData::from_format_strings(&format, w.clone()); data.initialize_hunk(&[(10, 11), (10000, 100001)], "a".into()); assert_eq!(data.formatted_width(), MinusPlus::new(32, 0)); let format = MinusPlus::new("│{np:^3}│ │{nm:<12}│ │{np}│".into(), "".into()); let mut data = LineNumbersData::from_format_strings(&format, w); data.initialize_hunk(&[(10, 11), (10000, 100001)], "a".into()); assert_eq!(data.formatted_width(), MinusPlus::new(32, 0)); } fn _get_capture<'a>(i: usize, j: usize, caps: &'a [Captures]) -> &'a str { caps[i].get(j).map_or("", |m| m.as_str()) } #[test] fn test_two_minus_lines() { DeltaTest::with_args(&[ "--line-numbers", "--line-numbers-left-format", "{nm:^4}⋮", "--line-numbers-right-format", "{np:^4}│", "--line-numbers-left-style", "0 1", "--line-numbers-minus-style", "0 2", "--line-numbers-right-style", "0 3", "--line-numbers-plus-style", "0 4", ]) .with_input(TWO_MINUS_LINES_DIFF) .expect_after_header( r#" #indent_mark 1 ⋮ │a = 1 2 ⋮ │b = 23456"#, ); } #[test] fn test_two_plus_lines() { DeltaTest::with_args(&[ "--line-numbers", "--line-numbers-left-format", "{nm:^4}⋮", "--line-numbers-right-format", "{np:^4}│", "--line-numbers-left-style", "0 1", "--line-numbers-minus-style", "0 2", "--line-numbers-right-style", "0 3", "--line-numbers-plus-style", "0 4", ]) .with_input(TWO_PLUS_LINES_DIFF) .expect_after_header( r#" #indent_mark ⋮ 1 │a = 1 ⋮ 2 │b = 234567"#, ); } #[test] fn test_one_minus_one_plus_line() { let config = make_config_from_args(&[ "--line-numbers", "--line-numbers-left-format", "{nm:^4}⋮", "--line-numbers-right-format", "{np:^4}│", "--line-numbers-left-style", "0 1", "--line-numbers-minus-style", "0 2", "--line-numbers-right-style", "0 3", "--line-numbers-plus-style", "0 4", ]); let output = run_delta(ONE_MINUS_ONE_PLUS_LINE_DIFF, &config); let output = strip_ansi_codes(&output); let mut lines = output.lines().skip(crate::config::HEADER_LEN); assert_eq!(lines.next().unwrap(), " 1 ⋮ 1 │a = 1"); assert_eq!(lines.next().unwrap(), " 2 ⋮ │b = 2"); assert_eq!(lines.next().unwrap(), " ⋮ 2 │bb = 2"); } #[test] fn test_repeated_placeholder() { let config = make_config_from_args(&[ "--line-numbers", "--line-numbers-left-format", "{nm:^4} {nm:^4}⋮", "--line-numbers-right-format", "{np:^4}│", "--line-numbers-left-style", "0 1", "--line-numbers-minus-style", "0 2", "--line-numbers-right-style", "0 3", "--line-numbers-plus-style", "0 4", ]); let output = run_delta(ONE_MINUS_ONE_PLUS_LINE_DIFF, &config); let output = strip_ansi_codes(&output); let mut lines = output.lines().skip(crate::config::HEADER_LEN); assert_eq!(lines.next().unwrap(), " 1 1 ⋮ 1 │a = 1"); assert_eq!(lines.next().unwrap(), " 2 2 ⋮ │b = 2"); assert_eq!(lines.next().unwrap(), " ⋮ 2 │bb = 2"); } #[test] fn test_five_digit_line_number() { let config = make_config_from_args(&["--line-numbers"]); let output = run_delta(FIVE_DIGIT_LINE_NUMBER_DIFF, &config); let output = strip_ansi_codes(&output); let mut lines = output.lines().skip(crate::config::HEADER_LEN); assert_eq!(lines.next().unwrap(), "10000⋮10000│a = 1"); assert_eq!(lines.next().unwrap(), "10001⋮ │b = 2"); assert_eq!(lines.next().unwrap(), " ⋮10001│bb = 2"); } #[test] fn test_unequal_digit_line_number() { let config = make_config_from_args(&["--line-numbers"]); let output = run_delta(UNEQUAL_DIGIT_DIFF, &config); let output = strip_ansi_codes(&output); let mut lines = output.lines().skip(crate::config::HEADER_LEN); assert_eq!(lines.next().unwrap(), "10000⋮ 9999│a = 1"); assert_eq!(lines.next().unwrap(), "10001⋮ │b = 2"); assert_eq!(lines.next().unwrap(), " ⋮10000│bb = 2"); } #[test] fn test_color_only() { let config = make_config_from_args(&["--line-numbers", "--color-only"]); let output = run_delta(TWO_MINUS_LINES_DIFF, &config); let mut lines = output.lines().skip(5); let (line_1, line_2) = (lines.next().unwrap(), lines.next().unwrap()); assert_eq!(strip_ansi_codes(line_1), " 1 ⋮ │-a = 1"); assert_eq!(strip_ansi_codes(line_2), " 2 ⋮ │-b = 23456"); } #[test] fn test_hunk_header_style_is_omit() { let config = make_config_from_args(&["--line-numbers", "--hunk-header-style", "omit"]); let output = run_delta(TWO_LINE_DIFFS, &config); let output = strip_ansi_codes(&output); let mut lines = output.lines().skip(4); assert_eq!(lines.next().unwrap(), " 1 ⋮ 1 │a = 1"); assert_eq!(lines.next().unwrap(), " 2 ⋮ │b = 2"); assert_eq!(lines.next().unwrap(), " ⋮ 2 │bb = 2"); assert_eq!(lines.next().unwrap(), ""); assert_eq!(lines.next().unwrap(), " 499⋮ 499│a = 3"); assert_eq!(lines.next().unwrap(), " 500⋮ │b = 4"); assert_eq!(lines.next().unwrap(), " ⋮ 500│bb = 4"); } #[test] fn test_line_numbers_continue_correctly() { DeltaTest::with_args(&["--side-by-side", "--width", "44", "--line-fill-method=ansi"]) .with_input(DIFF_PLUS_MINUS_WITH_1_CONTEXT_DIFF) .expect_after_header( r#" │ 1 │abc │ 1 │abc │ 2 │a = left side │ 2 │a = right side │ 3 │xyz │ 3 │xyz"#, ); } #[test] fn test_line_numbers_continue_correctly_after_wrapping() { DeltaTest::with_args(&[ "--side-by-side", "--width", "32", "--line-fill-method=ansi", "--wrap-left-symbol", "@", "--wrap-right-symbol", "@", "--wrap-right-prefix-symbol", ">", ]) .with_input(DIFF_PLUS_MINUS_WITH_1_CONTEXT_DIFF) .expect_after_header( r#" │ 1 │abc │ 1 │abc │ 2 │a = left @│ 2 │a = right@ │ │side │ │ side │ 3 │xyz │ 3 │xyz"#, ); let cfg = &[ "--side-by-side", "--width", "42", "--line-fill-method=ansi", "--wrap-left-symbol", "@", "--wrap-right-symbol", "@", "--wrap-right-prefix-symbol", ">", ]; DeltaTest::with_args(cfg) .with_input(DIFF_WITH_LONGER_MINUS_1_CONTEXT) .expect_after_header( r#" │ 1 │abc │ 1 │abc │ 2 │a = one side │ 2 │a = one longer@ │ │ │ │ > side │ 3 │xyz │ 3 │xyz"#, ); DeltaTest::with_args(cfg) .with_input(DIFF_WITH_LONGER_PLUS_1_CONTEXT) .expect_after_header( r#" │ 1 │abc │ 1 │abc │ 2 │a = one longer@│ 2 │a = one side │ │ > side│ │ │ 3 │xyz │ 3 │xyz"#, ); DeltaTest::with_args(cfg) .with_input(DIFF_MISMATCH_LONGER_MINUS_1_CONTEXT) .expect_after_header( r#" │ 1 │abc │ 1 │abc │ 2 │a = left side @│ │ │ │which is longer│ │ │ │ │ 2 │a = other one │ 3 │xyz │ 3 │xyz"#, ); DeltaTest::with_args(cfg) .with_input(DIFF_MISMATCH_LONGER_PLUS_1_CONTEXT) .expect_after_header( r#" │ 1 │abc │ 1 │abc │ 2 │a = other one │ │ │ │ │ 2 │a = right side@ │ │ │ │ which is long@ │ │ │ │er │ 3 │xyz │ 3 │xyz"#, ); } pub const TWO_MINUS_LINES_DIFF: &str = "\ diff --git i/a.py w/a.py index 223ca50..e69de29 100644 --- i/a.py +++ w/a.py @@ -1,2 +0,0 @@ -a = 1 -b = 23456 "; pub const TWO_PLUS_LINES_DIFF: &str = "\ diff --git c/a.py i/a.py new file mode 100644 index 0000000..223ca50 --- /dev/null +++ i/a.py @@ -0,0 +1,2 @@ +a = 1 +b = 234567 "; pub const ONE_MINUS_ONE_PLUS_LINE_DIFF: &str = "\ diff --git i/a.py w/a.py index 223ca50..367a6f6 100644 --- i/a.py +++ w/a.py @@ -1,2 +1,2 @@ a = 1 -b = 2 +bb = 2 "; const TWO_LINE_DIFFS: &str = "\ diff --git i/a.py w/a.py index 223ca50..367a6f6 100644 --- i/a.py +++ w/a.py @@ -1,2 +1,2 @@ a = 1 -b = 2 +bb = 2 @@ -499,2 +499,2 @@ a = 3 -b = 4 +bb = 4 "; const FIVE_DIGIT_LINE_NUMBER_DIFF: &str = "\ diff --git i/a.py w/a.py index 223ca50..367a6f6 100644 --- i/a.py +++ w/a.py @@ -10000,2 +10000,2 @@ a = 1 -b = 2 +bb = 2 "; const UNEQUAL_DIGIT_DIFF: &str = "\ diff --git i/a.py w/a.py index 223ca50..367a6f6 100644 --- i/a.py +++ w/a.py @@ -10000,2 +9999,2 @@ a = 1 -b = 2 +bb = 2 "; const DIFF_PLUS_MINUS_WITH_1_CONTEXT_DIFF: &str = "\ --- a/a.py +++ b/b.py @@ -1,3 +1,3 @@ abc -a = left side +a = right side xyz"; const DIFF_WITH_LONGER_MINUS_1_CONTEXT: &str = "\ --- a/a.py +++ b/b.py @@ -1,3 +1,3 @@ abc -a = one side +a = one longer side xyz"; const DIFF_WITH_LONGER_PLUS_1_CONTEXT: &str = "\ --- a/a.py +++ b/b.py @@ -1,3 +1,3 @@ abc -a = one longer side +a = one side xyz"; const DIFF_MISMATCH_LONGER_MINUS_1_CONTEXT: &str = "\ --- a/a.py +++ b/b.py @@ -1,3 +1,3 @@ abc -a = left side which is longer +a = other one xyz"; const DIFF_MISMATCH_LONGER_PLUS_1_CONTEXT: &str = "\ --- a/a.py +++ b/b.py @@ -1,3 +1,3 @@ abc -a = other one +a = right side which is longer xyz"; pub const TWO_MINUS_LINES_UNICODE_DIFF: &str = "\ diff --git a/a.py b/a.py index 8b0d958..e69de29 100644 --- a/a.txt +++ b/b.txt @@ -1,1 +0,0 @@ -一二三 "; }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/features/side_by_side.rs
src/features/side_by_side.rs
use itertools::Itertools; use syntect::highlighting::Style as SyntectStyle; use unicode_width::UnicodeWidthStr; use crate::ansi; use crate::cli; use crate::config::{self, delta_unreachable, Config}; use crate::delta::DiffType; use crate::delta::State; use crate::edits; use crate::features::{line_numbers, OptionValueFunction}; use crate::minusplus::*; use crate::paint::{BgFillMethod, BgShouldFill, LineSections, Painter}; use crate::style::Style; use crate::wrapping::{wrap_minusplus_block, wrap_zero_block}; pub fn make_feature() -> Vec<(String, OptionValueFunction)> { builtin_feature!([ ( "side-by-side", bool, None, _opt => true ), ("features", bool, None, _opt => "line-numbers"), ("line-numbers-left-format", String, None, _opt => "│{nm:^4}│".to_string()), ("line-numbers-right-format", String, None, _opt => "│{np:^4}│".to_string()) ]) } // Aliases for Minus/Plus because Left/Right and PanelSide makes // more sense in a side-by-side context. pub use crate::minusplus::MinusPlusIndex as PanelSide; pub use MinusPlusIndex::Minus as Left; pub use MinusPlusIndex::Plus as Right; use super::line_numbers::LineNumbersData; #[derive(Debug, Clone)] pub struct Panel { pub width: usize, } pub type LeftRight<T> = MinusPlus<T>; pub type SideBySideData = LeftRight<Panel>; impl SideBySideData { /// Create a [`LeftRight<Panel>`](LeftRight<Panel>) named [`SideBySideData`]. pub fn new_sbs(decorations_width: &cli::Width, available_terminal_width: &usize) -> Self { let panel_width = match decorations_width { cli::Width::Fixed(w) => w / 2, _ => available_terminal_width / 2, }; SideBySideData::new(Panel { width: panel_width }, Panel { width: panel_width }) } } pub fn available_line_width( config: &Config, data: &line_numbers::LineNumbersData, ) -> line_numbers::SideBySideLineWidth { let line_numbers_width = data.formatted_width(); // The width can be reduced by the line numbers and/or // a possibly added/restored 1-wide "+/-/ " prefix. let line_width = |side: PanelSide| { config.side_by_side_data[side] .width .saturating_sub(line_numbers_width[side]) .saturating_sub(config.keep_plus_minus_markers as usize) }; LeftRight::new(line_width(Left), line_width(Right)) } pub fn line_is_too_long(line: &str, line_width: usize) -> bool { debug_assert!(line.ends_with('\n')); // graphemes will take care of newlines line.width() > line_width } /// Return whether any of the input lines is too long, and a data /// structure indicating which of the input lines are too long. This avoids /// recalculating the length later. pub fn has_long_lines( lines: &LeftRight<&Vec<(String, State)>>, line_width: &line_numbers::SideBySideLineWidth, ) -> (bool, LeftRight<Vec<bool>>) { let mut wrap_any = LeftRight::default(); let mut wrapping_lines = LeftRight::default(); let mut check_if_too_long = |side| { let lines_side: &[(String, State)] = lines[side]; wrapping_lines[side] = lines_side .iter() .map(|(line, _)| line_is_too_long(line, line_width[side])) .inspect(|b| wrap_any[side] |= b) .collect(); }; check_if_too_long(Left); check_if_too_long(Right); (wrap_any[Left] || wrap_any[Right], wrapping_lines) } #[allow(clippy::too_many_arguments)] pub fn paint_minus_and_plus_lines_side_by_side( lines: LeftRight<&Vec<(String, State)>>, syntax_sections: LeftRight<Vec<LineSections<SyntectStyle>>>, diff_sections: LeftRight<Vec<LineSections<Style>>>, lines_have_homolog: LeftRight<Vec<bool>>, line_alignment: Vec<(Option<usize>, Option<usize>)>, line_numbers_data: &mut Option<LineNumbersData>, output_buffer: &mut String, config: &config::Config, ) { let line_states = LeftRight::new( lines[Left].iter().map(|(_, state)| state.clone()).collect(), lines[Right] .iter() .map(|(_, state)| state.clone()) .collect(), ); let line_numbers_data = line_numbers_data .as_mut() .unwrap_or_else(|| delta_unreachable("side-by-side requires Some(line_numbers_data)")); let bg_should_fill = LeftRight::new( // Using an ANSI sequence to fill the left panel would not work. BgShouldFill::With(BgFillMethod::Spaces), // Use what is configured for the right side. BgShouldFill::With(config.line_fill_method), ); // Only set `should_wrap` to true if wrapping is wanted and lines which are // too long are found. // If so, remember the calculated line width and which of the lines are too // long for later re-use. let (should_wrap, line_width, long_lines) = { if config.wrap_config.max_lines == 1 { (false, LeftRight::default(), LeftRight::default()) } else { let line_width = available_line_width(config, line_numbers_data); let (should_wrap, long_lines) = has_long_lines(&lines, &line_width); (should_wrap, line_width, long_lines) } }; let (line_alignment, line_states, syntax_sections, diff_sections) = if should_wrap { // Calculated for syntect::highlighting::style::Style and delta::Style wrap_minusplus_block( config, syntax_sections, diff_sections, &line_alignment, &line_width, &long_lines, ) } else { (line_alignment, line_states, syntax_sections, diff_sections) }; let lines_have_homolog = if should_wrap { edits::make_lines_have_homolog(&line_alignment) } else { lines_have_homolog }; for (minus_line_index, plus_line_index) in line_alignment { let left_state = match minus_line_index { Some(i) => &line_states[Left][i], None => &State::HunkMinus(DiffType::Unified, None), }; output_buffer.push_str(&paint_left_panel_minus_line( minus_line_index, &syntax_sections[Left], &diff_sections[Left], &lines_have_homolog[Left], left_state, &mut Some(line_numbers_data), bg_should_fill[Left], config, )); let right_state = match plus_line_index { Some(i) => &line_states[Right][i], None => &State::HunkPlus(DiffType::Unified, None), }; output_buffer.push_str(&paint_right_panel_plus_line( plus_line_index, &syntax_sections[Right], &diff_sections[Right], &lines_have_homolog[Right], right_state, &mut Some(line_numbers_data), bg_should_fill[Right], config, )); output_buffer.push('\n'); // HACK: The left line number is not getting incremented in `linenumbers_and_styles()` // when the alignment matches a minus with a plus line, so fix that here and take // wrapped lines into account. // Similarly an increment happens when it should not, so undo that. // TODO: Pass this information down into `paint_line()` to set `increment` accordingly. match (left_state, right_state, minus_line_index, plus_line_index) { (State::HunkMinusWrapped, State::HunkPlus(_, _), Some(_), None) => { line_numbers_data.line_number[Left] = line_numbers_data.line_number[Left].saturating_sub(1) } // Duplicating the logic from `linenumbers_and_styles()` a bit: (State::HunkMinusWrapped | State::HunkPlusWrapped, _, _, _) => {} (_, _, Some(_), Some(_)) => line_numbers_data.line_number[Left] += 1, _ => {} } } } #[allow(clippy::too_many_arguments)] pub fn paint_zero_lines_side_by_side<'a>( line: &str, syntax_style_sections: Vec<LineSections<'a, SyntectStyle>>, diff_style_sections: Vec<LineSections<'a, Style>>, output_buffer: &mut String, config: &Config, line_numbers_data: &mut Option<&mut line_numbers::LineNumbersData>, painted_prefix: Option<ansi_term::ANSIString>, background_color_extends_to_terminal_width: BgShouldFill, ) { let states = vec![State::HunkZero(DiffType::Unified, None)]; let (states, syntax_style_sections, diff_style_sections) = wrap_zero_block( config, line, states, syntax_style_sections, diff_style_sections, line_numbers_data, ); for (line_index, ((syntax_sections, diff_sections), state)) in syntax_style_sections .into_iter() .zip_eq(diff_style_sections.iter()) .zip_eq(states.into_iter()) .enumerate() { for panel_side in &[Left, Right] { let (mut panel_line, panel_line_is_empty) = Painter::paint_line( &syntax_sections, diff_sections, &state, line_numbers_data, Some(*panel_side), painted_prefix.clone(), config, ); pad_panel_line_to_width( &mut panel_line, panel_line_is_empty, Some(line_index), &diff_style_sections, None, &state, *panel_side, background_color_extends_to_terminal_width, config, ); output_buffer.push_str(&panel_line); } output_buffer.push('\n'); } } #[allow(clippy::too_many_arguments)] fn paint_left_panel_minus_line<'a>( line_index: Option<usize>, syntax_style_sections: &[LineSections<'a, SyntectStyle>], diff_style_sections: &[LineSections<'a, Style>], lines_have_homolog: &[bool], state: &'a State, line_numbers_data: &mut Option<&mut line_numbers::LineNumbersData>, background_color_extends_to_terminal_width: BgShouldFill, config: &Config, ) -> String { let (mut panel_line, panel_line_is_empty) = paint_minus_or_plus_panel_line( line_index, syntax_style_sections, diff_style_sections, state, line_numbers_data, Left, config, ); pad_panel_line_to_width( &mut panel_line, panel_line_is_empty, line_index, diff_style_sections, Some(lines_have_homolog), state, Left, background_color_extends_to_terminal_width, config, ); panel_line } #[allow(clippy::too_many_arguments)] fn paint_right_panel_plus_line<'a>( line_index: Option<usize>, syntax_style_sections: &[LineSections<'a, SyntectStyle>], diff_style_sections: &[LineSections<'a, Style>], lines_have_homolog: &[bool], state: &'a State, line_numbers_data: &mut Option<&mut line_numbers::LineNumbersData>, background_color_extends_to_terminal_width: BgShouldFill, config: &Config, ) -> String { let (mut panel_line, panel_line_is_empty) = paint_minus_or_plus_panel_line( line_index, syntax_style_sections, diff_style_sections, state, line_numbers_data, Right, config, ); pad_panel_line_to_width( &mut panel_line, panel_line_is_empty, line_index, diff_style_sections, Some(lines_have_homolog), state, Right, background_color_extends_to_terminal_width, config, ); panel_line } #[allow(clippy::too_many_arguments)] fn get_right_fill_style_for_panel( line_is_empty: bool, line_index: Option<usize>, diff_style_sections: &[LineSections<'_, Style>], lines_have_homolog: Option<&[bool]>, state: &State, panel_side: PanelSide, background_color_extends_to_terminal_width: BgShouldFill, config: &Config, ) -> (Option<BgFillMethod>, Style) { // If in the left panel then it must be filled with spaces. let none_or_override = if panel_side == Left { Some(BgFillMethod::Spaces) } else { None }; match (line_is_empty, line_index) { (true, _) => (none_or_override, config.null_style), (false, None) => (none_or_override, config.null_style), (false, Some(index)) => { let (bg_fill_mode, fill_style) = Painter::get_should_right_fill_background_color_and_fill_style( &diff_style_sections[index], lines_have_homolog.map(|h| h[index]), state, background_color_extends_to_terminal_width, config, ); match bg_fill_mode { None => (none_or_override, config.null_style), _ if panel_side == Left => (Some(BgFillMethod::Spaces), fill_style), _ => (bg_fill_mode, fill_style), } } } } /// Construct half of a minus or plus line under side-by-side mode, i.e. the half line that /// goes in one or other panel. Return a tuple `(painted_half_line, is_empty)`. // Suppose the line being displayed is a minus line with a paired plus line. Then both times // this function is called, `line_index` will be `Some`. This case proceeds as one would // expect: on the first call, we are constructing the left panel line, and we are passed // `(Some(index), HunkMinus, Left)`. We pass `(HunkMinus, Left)` to // `paint_line`. This has two consequences: // 1. `format_and_paint_line_numbers` will increment the minus line number. // 2. `format_and_paint_line_numbers` will emit the left line number field, and not the right. // // The second call does the analogous thing for the plus line to be displayed in the right panel: // we are passed `(Some(index), HunkPlus, Right)` and we pass `(HunkPlus, Right)` to `paint_line`, // causing it to increment the plus line number and emit the right line number field. // // Now consider the case where the line being displayed is a minus line with no paired plus line. // The first call is as before. On the second call, we are passed `(None, HunkPlus, Right)` and we // wish to display the right panel, with its line number container, but without any line number // (and without any line contents). We do this by passing (HunkMinus, Right) to `paint_line`, since // what this will do is set the line number pair in that function to `(Some(minus_number), None)`, // and then only emit the right field (which has a None number, i.e. blank). #[allow(clippy::too_many_arguments)] fn paint_minus_or_plus_panel_line<'a>( line_index: Option<usize>, syntax_style_sections: &[LineSections<'a, SyntectStyle>], diff_style_sections: &[LineSections<'a, Style>], state: &State, line_numbers_data: &mut Option<&mut line_numbers::LineNumbersData>, panel_side: PanelSide, config: &Config, ) -> (String, bool) { let (empty_line_syntax_sections, empty_line_diff_sections) = (Vec::new(), Vec::new()); let (line_syntax_sections, line_diff_sections, state_for_line_numbers_field) = if let Some(index) = line_index { ( &syntax_style_sections[index], &diff_style_sections[index], state.clone(), ) } else { let opposite_state = match state { State::HunkMinus(DiffType::Unified, s) => { State::HunkPlus(DiffType::Unified, s.clone()) } State::HunkPlus(DiffType::Unified, s) => { State::HunkMinus(DiffType::Unified, s.clone()) } _ => unreachable!(), }; ( &empty_line_syntax_sections, &empty_line_diff_sections, opposite_state, ) }; let painted_prefix = match (config.keep_plus_minus_markers, panel_side, state) { (true, _, State::HunkPlusWrapped) => Some(config.plus_style.paint(" ")), (true, _, State::HunkMinusWrapped) => Some(config.minus_style.paint(" ")), (true, Left, _) => Some(config.minus_style.paint("-")), (true, Right, _) => Some(config.plus_style.paint("+")), _ => None, }; let (line, line_is_empty) = Painter::paint_line( line_syntax_sections, line_diff_sections, &state_for_line_numbers_field, line_numbers_data, Some(panel_side), painted_prefix, config, ); (line, line_is_empty) } /// Right-fill the background color of a line in a panel. If in the left panel this is always /// done with spaces. The right panel can be filled with spaces or using ANSI sequences /// instructing the terminal emulator to fill the background color rightwards. #[allow(clippy::too_many_arguments, clippy::comparison_chain)] fn pad_panel_line_to_width( panel_line: &mut String, panel_line_is_empty: bool, line_index: Option<usize>, diff_style_sections: &[LineSections<'_, Style>], lines_have_homolog: Option<&[bool]>, state: &State, panel_side: PanelSide, background_color_extends_to_terminal_width: BgShouldFill, config: &Config, ) { // Emit empty line marker if the panel line is empty but not empty-by-construction. IOW if the // other panel contains a real line, and we are currently emitting an empty counterpart panel // to form the other half of the line, then don't emit the empty line marker. if panel_line_is_empty && line_index.is_some() { match state { State::HunkMinus(_, _) => Painter::mark_empty_line( &config.minus_empty_line_marker_style, panel_line, Some(" "), ), State::HunkPlus(_, _) => Painter::mark_empty_line( &config.plus_empty_line_marker_style, panel_line, Some(" "), ), State::HunkZero(_, _) => {} _ => unreachable!(), }; }; let text_width = ansi::measure_text_width(panel_line); let panel_width = config.side_by_side_data[panel_side].width; if text_width > panel_width { *panel_line = ansi::truncate_str(panel_line, panel_width, &config.truncation_symbol).to_string(); } let (bg_fill_mode, fill_style) = get_right_fill_style_for_panel( panel_line_is_empty, line_index, diff_style_sections, lines_have_homolog, state, panel_side, background_color_extends_to_terminal_width, config, ); match bg_fill_mode { Some(BgFillMethod::TryAnsiSequence) => { Painter::right_fill_background_color(panel_line, fill_style) } Some(BgFillMethod::Spaces) if text_width >= panel_width => (), Some(BgFillMethod::Spaces) => panel_line.push_str( #[allow(clippy::unnecessary_to_owned)] &fill_style .paint(" ".repeat(panel_width - text_width)) .to_string(), ), None => (), } } pub mod ansifill { use super::SideBySideData; use crate::config::Config; use crate::paint::BgFillMethod; pub const ODD_PAD_CHAR: char = ' '; // Panels in side-by-side mode always sum up to an even number, so when the terminal // has an odd width an extra column is left over. // If the background color is extended with an ANSI sequence (which only knows "fill // this row until the end") instead of spaces (see `BgFillMethod`), then the coloring // extends into that column. This becomes noticeable when the displayed content reaches // the right side of the right panel to be truncated or wrapped. // However using an ANSI sequence instead of spaces is generally preferable because // small changes to the terminal width are less noticeable. /// The solution in this case is to add `ODD_PAD_CHAR` before the first line number in /// the right panel and increasing its width by one, thus using the full terminal width /// with the two panels. /// This also means line numbers can not be disabled in side-by-side mode, but they may /// not actually paint numbers. #[derive(Clone, Debug)] pub struct UseFullPanelWidth(pub bool); impl UseFullPanelWidth { pub fn new(config: &Config) -> Self { Self( config.side_by_side && Self::is_odd_with_ansi(&config.decorations_width, &config.line_fill_method), ) } pub fn sbs_odd_fix( width: &crate::cli::Width, method: &BgFillMethod, sbs_data: SideBySideData, ) -> SideBySideData { if Self::is_odd_with_ansi(width, method) { Self::adapt_sbs_data(sbs_data) } else { sbs_data } } pub fn pad_width(&self) -> bool { self.0 } fn is_odd_with_ansi(width: &crate::cli::Width, method: &BgFillMethod) -> bool { method == &BgFillMethod::TryAnsiSequence && matches!(&width, crate::cli::Width::Fixed(width) if width % 2 == 1) } fn adapt_sbs_data(mut sbs_data: SideBySideData) -> SideBySideData { sbs_data[super::Right].width += 1; sbs_data } } } #[cfg(test)] pub mod tests { use crate::ansi::strip_ansi_codes; use crate::features::line_numbers::tests::*; use crate::tests::integration_test_utils::{make_config_from_args, run_delta, DeltaTest}; use insta::assert_snapshot; #[test] fn test_two_fitting_minus_lines() { // rustfmt ignores the assert macro arguments, so do the setup outside let result = DeltaTest::with_args(&["--side-by-side"]) .with_input(TWO_MINUS_LINES_DIFF) .skip_header(); assert_snapshot!(result, @r###" │ 1 │a = 1 │ │ │ 2 │b = 23456 │ │ "### ); } #[test] fn test_two_minus_lines_truncated() { DeltaTest::with_args(&[ "--side-by-side", "--wrap-max-lines", "0", "--width", "28", "--line-fill-method=spaces", ]) .set_config(|cfg| cfg.truncation_symbol = ">".into()) .with_input(TWO_MINUS_LINES_DIFF) .expect_after_header( r#" │ 1 │a = 1 │ │ │ 2 │b = 234>│ │"#, ); } #[test] fn test_two_plus_lines() { DeltaTest::with_args(&[ "--side-by-side", "--width", "41", "--line-fill-method=spaces", ]) .with_input(TWO_PLUS_LINES_DIFF) .expect_after_header( r#" │ │ │ 1 │a = 1 │ │ │ 2 │b = 234567 "#, ); } #[test] fn test_two_plus_lines_spaces_and_ansi() { DeltaTest::with_args(&[ "--side-by-side", "--width", "41", "--line-fill-method=spaces", ]) .explain_ansi() .with_input(TWO_PLUS_LINES_DIFF) .expect_after_header(r#" (blue)│(88) (blue)│(normal) (blue)│(28) 1 (blue)│(231 22)a (203)=(231) (141)1(normal 22) (normal) (blue)│(88) (blue)│(normal) (blue)│(28) 2 (blue)│(231 22)b (203)=(231) (141)234567(normal 22) (normal)"#); DeltaTest::with_args(&[ "--side-by-side", "--width", "41", "--line-fill-method=ansi", ]) .explain_ansi() .with_input(TWO_PLUS_LINES_DIFF) .expect_after_header(r#" (blue)│(88) (blue)│(normal) (blue) │(28) 1 (blue)│(231 22)a (203)=(231) (141)1(normal) (blue)│(88) (blue)│(normal) (blue) │(28) 2 (blue)│(231 22)b (203)=(231) (141)234567(normal)"#); } #[test] fn test_two_plus_lines_truncated() { let mut config = make_config_from_args(&[ "--side-by-side", "--wrap-max-lines", "0", "--width", "30", "--line-fill-method=spaces", ]); config.truncation_symbol = ">".into(); let output = run_delta(TWO_PLUS_LINES_DIFF, &config); let mut lines = output.lines().skip(crate::config::HEADER_LEN); let (line_1, line_2) = (lines.next().unwrap(), lines.next().unwrap()); assert_eq!("│ │ │ 1 │a = 1 ", strip_ansi_codes(line_1)); assert_eq!("│ │ │ 2 │b = 2345>", strip_ansi_codes(line_2)); } #[test] fn test_two_plus_lines_exact_fit() { let config = make_config_from_args(&["--side-by-side", "--width", "33", "--line-fill-method=ansi"]); let output = run_delta(TWO_PLUS_LINES_DIFF, &config); let mut lines = output.lines().skip(crate::config::HEADER_LEN); let (line_1, line_2) = (lines.next().unwrap(), lines.next().unwrap()); let sac = strip_ansi_codes; // alias to help with `cargo fmt`-ing: assert_eq!("│ │ │ 1 │a = 1", sac(line_1)); assert_eq!("│ │ │ 2 │b = 234567", sac(line_2)); } #[test] fn test_one_minus_one_plus_line() { DeltaTest::with_args(&[ "--side-by-side", "--width", "40", "--line-fill-method=spaces", ]) .with_input(ONE_MINUS_ONE_PLUS_LINE_DIFF) .expect_after_header( r#" │ 1 │a = 1 │ 1 │a = 1 │ 2 │b = 2 │ 2 │bb = 2 "#, ); } #[test] fn test_two_minus_lines_unicode_truncated() { DeltaTest::with_args(&[ "--side-by-side", "--wrap-max-lines", "2", "--width", "16", "--line-fill-method=spaces", ]) .set_config(|cfg| cfg.truncation_symbol = ">".into()) .with_input(TWO_MINUS_LINES_UNICODE_DIFF) .expect_after_header( r#" │ 1 │↵ │ │ │ │↵ │ │ │ │ >│ │"#, ); DeltaTest::with_args(&[ "--side-by-side", "--wrap-max-lines", "2", "--width", "17", "--line-fill-method=spaces", ]) .set_config(|cfg| cfg.truncation_symbol = ">".into()) .with_input(TWO_MINUS_LINES_UNICODE_DIFF) .expect_after_header( r#" │ 1 │↵ │ │ │ │↵ │ │ │ │ >│ │"#, ); DeltaTest::with_args(&[ "--side-by-side", "--wrap-max-lines", "2", "--width", "18", "--line-fill-method=spaces", ]) .set_config(|cfg| cfg.truncation_symbol = ">".into()) .with_input(TWO_MINUS_LINES_UNICODE_DIFF) .expect_after_header( r#" │ 1 │一↵│ │ │ │二↵│ │ │ │三 │ │"#, ); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/features/diff_so_fancy.rs
src/features/diff_so_fancy.rs
use crate::features::diff_highlight; use crate::features::OptionValueFunction; pub fn make_feature() -> Vec<(String, OptionValueFunction)> { let mut feature = diff_highlight::_make_feature(true); feature.extend(builtin_feature!([ ( "minus-emph-style", String, Some("color.diff-highlight.oldHighlight"), _opt => "bold red 52" ), ( "plus-emph-style", String, Some("color.diff-highlight.newHighlight"), _opt => "bold green 22" ), ( "file-style", String, Some("color.diff.meta"), _opt => "11" ), ( "file-decoration-style", String, None, _opt => "bold yellow ul ol" ), ( "hunk-header-style", String, Some("color.diff.frag"), _opt => "file line-number bold syntax" ), ( "hunk-header-decoration-style", String, None, _opt => "magenta box" ) ])); feature } #[cfg(test)] pub mod tests { use std::fs::remove_file; use crate::tests::integration_test_utils; #[test] fn test_diff_so_fancy_defaults() { let opt = integration_test_utils::make_options_from_args_and_git_config( &["--features", "diff-so-fancy"], None, None, ); assert_eq!(opt.commit_style, "raw"); assert_eq!(opt.commit_decoration_style, "none"); assert_eq!(opt.file_style, "11"); assert_eq!(opt.file_decoration_style, "bold yellow ul ol"); assert_eq!(opt.hunk_header_style, "file line-number bold syntax"); assert_eq!(opt.hunk_header_decoration_style, "magenta box"); } #[test] fn test_diff_so_fancy_respects_git_config() { let git_config_contents = b" [color \"diff\"] meta = 11 frag = magenta bold commit = purple bold old = red bold new = green bold whitespace = red reverse "; let git_config_path = "delta__test_diff_so_fancy.gitconfig"; let opt = integration_test_utils::make_options_from_args_and_git_config( &["--features", "diff-so-fancy some-other-feature"], Some(git_config_contents), Some(git_config_path), ); assert_eq!(opt.commit_style, "purple bold"); assert_eq!(opt.file_style, "11"); assert_eq!(opt.hunk_header_style, "magenta bold"); assert_eq!(opt.commit_decoration_style, "none"); assert_eq!(opt.file_decoration_style, "bold yellow ul ol"); assert_eq!(opt.hunk_header_decoration_style, "magenta box"); remove_file(git_config_path).unwrap(); } #[test] fn test_diff_so_fancy_obeys_feature_precedence_rules() { let git_config_contents = b" [color \"diff\"] meta = 11 frag = magenta bold commit = yellow bold old = red bold new = green bold whitespace = red reverse [delta \"decorations\"] commit-decoration-style = bold box ul file-style = bold 19 ul file-decoration-style = none "; let git_config_path = "delta__test_diff_so_fancy_obeys_feature_precedence_rules.gitconfig"; let opt = integration_test_utils::make_options_from_args_and_git_config( &["--features", "decorations diff-so-fancy"], Some(git_config_contents), Some(git_config_path), ); assert_eq!(opt.file_style, "11"); assert_eq!(opt.file_decoration_style, "bold yellow ul ol"); let opt = integration_test_utils::make_options_from_args_and_git_config( &["--features", "diff-so-fancy decorations"], Some(git_config_contents), Some(git_config_path), ); assert_eq!(opt.file_style, "bold 19 ul"); assert_eq!(opt.file_decoration_style, "none"); remove_file(git_config_path).unwrap(); } }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false
dandavison/delta
https://github.com/dandavison/delta/blob/acd758f7a08df6c2ac5542a2c5a4034c664a9ed8/src/features/raw.rs
src/features/raw.rs
use crate::features::OptionValueFunction; pub fn make_feature() -> Vec<(String, OptionValueFunction)> { builtin_feature!([ ( "commit-decoration-style", String, None, _opt => "none" ), ( "commit-style", String, None, _opt => "raw" ), ( "file-decoration-style", String, None, _opt => "none" ), ( "file-style", String, None, _opt => "raw" ), ( "hunk-header-decoration-style", String, None, _opt => "none" ), ( "hunk-header-style", String, None, _opt => "raw" ), ( "minus-style", String, Some("color.diff.old"), _opt => "red" ), ( "minus-emph-style", String, Some("color.diff.old"), _opt => "red" ), ( "zero-style", String, None, _opt => "normal" ), ( "plus-style", String, Some("color.diff.new"), _opt => "green" ), ( "plus-emph-style", String, Some("color.diff.new"), _opt => "green" ), ( "keep-plus-minus-markers", bool, None, _opt => true ), ( "tabs", usize, None, _opt => 0 ) ]) }
rust
MIT
acd758f7a08df6c2ac5542a2c5a4034c664a9ed8
2026-01-04T15:34:43.859751Z
false