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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use std::fmt;
use std::io::Write;

use itertools;

use error::{Error, Result, ResultLiquidChainExt, ResultLiquidExt};
use value::Value;

use super::Argument;
use super::Context;
use super::Renderable;

/// A `Value` filter.
#[derive(Clone, Debug, PartialEq)]
pub struct FilterCall {
    name: String,
    arguments: Vec<Argument>,
}

impl FilterCall {
    /// Create filter expression.
    pub fn new(name: &str, arguments: Vec<Argument>) -> FilterCall {
        FilterCall {
            name: name.to_owned(),
            arguments,
        }
    }
}

impl fmt::Display for FilterCall {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}: {}",
            self.name,
            itertools::join(&self.arguments, ", ")
        )
    }
}

/// A `Value` expression.
#[derive(Clone, Debug, PartialEq)]
pub struct FilterChain {
    entry: Argument,
    filters: Vec<FilterCall>,
}

impl FilterChain {
    /// Create a new expression.
    pub fn new(entry: Argument, filters: Vec<FilterCall>) -> Self {
        Self { entry, filters }
    }

    /// Process `Value` expression within `context`'s stack.
    pub fn evaluate(&self, context: &Context) -> Result<Value> {
        // take either the provided value or the value from the provided variable
        let mut entry = self.entry.evaluate(context)?;

        // apply all specified filters
        for filter in &self.filters {
            let f = context.get_filter(&filter.name).ok_or_else(|| {
                Error::with_msg("Unsupported filter").context("filter", filter.name.clone())
            })?;

            let arguments: Result<Vec<Value>> = filter
                .arguments
                .iter()
                .map(|a| a.evaluate(context))
                .collect();
            let arguments = arguments?;
            entry = f
                .filter(&entry, &*arguments)
                .chain("Filter error")
                .context_with(|| ("input".to_owned(), format!("{}", &entry)))
                .context_with(|| ("args".to_owned(), itertools::join(&arguments, ", ")))?;
        }

        Ok(entry)
    }
}

impl fmt::Display for FilterChain {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{} | {}",
            self.entry,
            itertools::join(&self.filters, " | ")
        )
    }
}

impl Renderable for FilterChain {
    fn render_to(&self, writer: &mut Write, context: &mut Context) -> Result<()> {
        let entry = self.evaluate(context)?;
        write!(writer, "{}", entry).chain("Failed to render")?;
        Ok(())
    }
}