Skip to content

Commit

Permalink
Implement str.splitlines
Browse files Browse the repository at this point in the history
  • Loading branch information
mitsuhiko committed Jun 11, 2024
1 parent d47f4ba commit 77dd1bd
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
18 changes: 18 additions & 0 deletions minijinja-contrib/src/pycompat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ use minijinja::{Error, ErrorKind, State, Value};
/// * `str.replace`
/// * `str.rstrip`
/// * `str.split`
/// * `str.splitlines`
/// * `str.strip`
/// * `str.title`
/// * `str.upper`
Expand Down Expand Up @@ -123,6 +124,23 @@ fn string_methods(value: &Value, method: &str, args: &[Value]) -> Result<Value,
.try_iter()?
.collect::<Value>())
}
"splitlines" => {
let (keepends,): (Option<bool>,) = from_args(args)?;
if !keepends.unwrap_or(false) {
Ok(s.lines().map(Value::from).collect())
} else {
let mut rv = Vec::new();
let mut rest = s;
while let Some(offset) = rest.find('\n') {
rv.push(Value::from(&rest[..offset + 1]));
rest = &rest[offset + 1..];
}
if !rest.is_empty() {
rv.push(Value::from(rest));
}
Ok(Value::from(rv))
}
}
"capitalize" => {
from_args(args)?;
// one shall not call into these filters. However we consider ourselves
Expand Down
2 changes: 2 additions & 0 deletions minijinja-contrib/tests/pycompat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ fn test_string_methods() {
assert!(eval_expr("'a b c'.split() == ['a', 'b', 'c']").is_true());
assert!(eval_expr("'a b c'.split(none, 1) == ['a', 'b c']").is_true());
assert!(eval_expr("'abcbd'.split('b', 1) == ['a', 'cbd']").is_true());
assert!(eval_expr("'a\\nb\\r\\nc'.splitlines() == ['a', 'b', 'c']").is_true());
assert!(eval_expr("'a\\nb\\r\\nc'.splitlines(true) == ['a\\n', 'b\\r\\n', 'c']").is_true());
}

#[test]
Expand Down

0 comments on commit 77dd1bd

Please sign in to comment.