templater: fix crash on "".first_line()

This commit is contained in:
Yuya Nishihara 2023-01-31 18:49:28 +09:00
parent 6e9d3879fd
commit e4cb1afd61
2 changed files with 14 additions and 1 deletions

View file

@ -191,7 +191,9 @@ fn parse_string_method<'a>(name: Pair<Rule>, _args: Pairs<Rule>) -> Property<'a,
}
// TODO: validate arguments
match name.as_str() {
"first_line" => Property::String(wrap_fn(|s| s.lines().next().unwrap().to_string())),
"first_line" => Property::String(wrap_fn(|s| {
s.lines().next().unwrap_or_default().to_string()
})),
name => panic!("no such string method: {name}"),
}
}

View file

@ -105,6 +105,17 @@ fn test_templater_parsed_tree() {
insta::assert_snapshot!(render(r#"if((divergent), "t", "f")"#), @"f");
}
#[test]
fn test_templater_string_method() {
let test_env = TestEnvironment::default();
test_env.jj_cmd_success(test_env.env_root(), &["init", "repo", "--git"]);
let repo_path = test_env.env_root().join("repo");
let render = |template| get_template_output(&test_env, &repo_path, "@-", template);
insta::assert_snapshot!(render(r#""".first_line()"#), @"");
insta::assert_snapshot!(render(r#""foo\nbar".first_line()"#), @"foo");
}
fn get_template_output(
test_env: &TestEnvironment,
repo_path: &Path,