Skip to content

Commit

Permalink
templater: add .escape_json method to string
Browse files Browse the repository at this point in the history
  • Loading branch information
HKalbasi committed Feb 12, 2025
1 parent e83b328 commit 272955f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
`ellipsis` parameter; passing this prepends or appends the ellipsis to the
content if it is truncated to fit the maximum width.

* Templates now support additional string method `.escape_json(x)` which serializes
the string in JSON format. It is useful for making machine-readable templates
by escaping problematic characters like `\n`.

### Fixed bugs

* `jj status` now shows untracked files under untracked directories.
Expand Down
11 changes: 11 additions & 0 deletions cli/src/template_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,14 @@ fn builtin_string_methods<'a, L: TemplateLanguage<'a> + ?Sized>(
Ok(L::wrap_string(out_property))
},
);
map.insert(
"escape_json",
|_language, _diagnostics, _build_ctx, self_property, function| {
function.expect_no_arguments()?;
let out_property = self_property.map(|s| serde_json::to_string(&s).unwrap());
Ok(L::wrap_string(out_property))
},
);
map
}

Expand Down Expand Up @@ -2659,6 +2667,9 @@ mod tests {
// ranges with end > start are empty
insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(4, 2)"#), @"");
insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(-2, -4)"#), @"");

insta::assert_snapshot!(env.render_ok(r#""hello".escape_json()"#), @r#""hello""#);
insta::assert_snapshot!(env.render_ok(r#""he \n ll \n \" o".escape_json()"#), @r#""he \n ll \n \" o""#);
}

#[test]
Expand Down
5 changes: 5 additions & 0 deletions docs/templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,11 @@ defined.
* `.substr(start: Integer, end: Integer) -> String`: Extract substring. The
`start`/`end` indices should be specified in UTF-8 bytes. Negative values
count from the end of the string.
* `.escape_json() -> String`: Serializes the string in JSON format. This
function is useful for making machine-readable templates. For example, you
can use it in a template like `"{ \"foo\": " ++ self.foo().escape_json() ++ "}"` to
return a JSON/JSONL.


#### String literals

Expand Down

0 comments on commit 272955f

Please sign in to comment.