This repository has been archived by the owner on Nov 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender_comment.rs
78 lines (67 loc) · 2.28 KB
/
render_comment.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use crate::filters::invalid_input;
use liquid_core::Expression;
use liquid_core::Result;
use liquid_core::Runtime;
use liquid_core::{
Display_filter, Filter, FilterParameters, FilterReflection, FromFilterParameters, ParseFilter,
};
use liquid_core::{Value, ValueView};
#[derive(Debug, FilterParameters)]
struct RenderCommentArgs {
#[parameter(description = "Line prefix.", arg_type = "str")]
prefix: Option<Expression>,
#[parameter(description = "Line offset.", arg_type = "integer")]
offset: Option<Expression>,
}
#[derive(Clone, ParseFilter, FilterReflection)]
#[filter(
name = "render_comment",
description = "Renders comment with prefix/offset params.",
parameters(RenderCommentArgs),
parsed(RenderCommentFilter)
)]
pub struct RenderComment;
#[derive(Debug, FromFilterParameters, Display_filter)]
#[name = "render_comment"]
struct RenderCommentFilter {
#[parameters]
args: RenderCommentArgs,
}
impl Filter for RenderCommentFilter {
fn evaluate(&self, input: &dyn ValueView, runtime: &dyn Runtime) -> Result<Value> {
let args = self.args.evaluate(runtime)?;
let prefix = args
.prefix
.ok_or_else(|| invalid_input("prefix argument is required"))?;
let offset = args
.offset
.ok_or_else(|| invalid_input("offset argument is required"))?;
let input = input
.as_array()
.ok_or_else(|| invalid_input("Array of strings expected"))?;
let lines = input.values().map(|x| x.to_kstr());
let rendered = lines
.enumerate()
.map(|(idx, line)| {
let mut line = line.to_string();
if !line.is_empty() {
line = format!(" {}", line);
}
let spaces = if idx == 0 {
// Do not add prefix to the first line
String::from("")
} else {
" ".repeat(offset as usize)
};
format!(
"{spaces}{prefix}{line}",
spaces = spaces,
prefix = prefix,
line = line
)
})
.collect::<Vec<_>>()
.join("\n");
Ok(Value::scalar(rendered))
}
}