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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use std::path::{Path, PathBuf};

#[derive(Clone, Debug)]
pub struct Config {
    pub delimiter: char,
    pub escape: bool,
    pub rm_whitespace: bool,
    pub template_dirs: Vec<PathBuf>,
    #[doc(hidden)]
    pub cache_dir: PathBuf,
    #[doc(hidden)]
    pub _non_exhaustive: (),
}

impl Default for Config {
    fn default() -> Self {
        Self {
            template_dirs: Vec::new(),
            delimiter: '%',
            escape: true,
            cache_dir: Path::new(env!("OUT_DIR")).join("cache"),
            rm_whitespace: false,
            _non_exhaustive: (),
        }
    }
}

#[cfg(feature = "config")]
mod config {
    use std::fs;
    use yaml_rust::yaml::{Yaml, YamlLoader};

    use super::*;
    use crate::error::*;

    impl Config {
        pub fn search_file_and_read(base: &Path) -> Result<Config, Error> {
            // search config file
            let mut path = PathBuf::new();
            let mut config = Config::default();

            for component in base.iter() {
                path.push(component);
                path.push("sailfish.yml");

                if path.is_file() {
                    let config_file =
                        ConfigFile::read_from_file(&*path).map_err(|mut e| {
                            e.source_file = Some(path.to_owned());
                            e
                        })?;

                    if let Some(template_dirs) = config_file.template_dirs {
                        for template_dir in template_dirs.into_iter().rev() {
                            if template_dir.is_absolute() {
                                config.template_dirs.push(template_dir);
                            } else {
                                config
                                    .template_dirs
                                    .push(path.parent().unwrap().join(template_dir));
                            }
                        }
                    }

                    if let Some(delimiter) = config_file.delimiter {
                        config.delimiter = delimiter;
                    }

                    if let Some(escape) = config_file.escape {
                        config.escape = escape;
                    }

                    if let Some(rm_whitespace) = config_file.rm_whitespace {
                        config.rm_whitespace = rm_whitespace;
                    }
                }

                path.pop();
            }

            Ok(config)
        }
    }

    #[derive(Default)]
    struct ConfigFile {
        template_dirs: Option<Vec<PathBuf>>,
        delimiter: Option<char>,
        escape: Option<bool>,
        rm_whitespace: Option<bool>,
    }

    impl ConfigFile {
        fn read_from_file(path: &Path) -> Result<Self, Error> {
            let mut config = Self::default();
            let content = fs::read_to_string(path)
                .chain_err(|| format!("Failed to read configuration file {:?}", path))?;

            let entries = YamlLoader::load_from_str(&*content)
                .map_err(|e| ErrorKind::ConfigError(e.to_string()))?;
            drop(content);

            for entry in entries {
                config.visit_global(entry)?
            }

            Ok(config)
        }

        fn visit_global(&mut self, entry: Yaml) -> Result<(), Error> {
            let hash = entry.into_hash().ok_or_else(|| {
                ErrorKind::ConfigError("Invalid configuration format".to_owned())
            })?;

            for (k, v) in hash {
                match k {
                    Yaml::String(ref s) => match &**s {
                        "template_dir" => self.visit_template_dir(v)?,
                        "delimiter" => self.visit_delimiter(v)?,
                        "escape" => self.visit_escape(v)?,
                        "optimization" => self.visit_optimization(v)?,
                        _ => return Err(Self::error(format!("Unknown key ({})", s))),
                    },
                    _ => {
                        return Err(Self::error("Invalid configuration format"));
                    }
                }
            }

            Ok(())
        }

        fn visit_template_dir(&mut self, value: Yaml) -> Result<(), Error> {
            if self.template_dirs.is_some() {
                return Err(Self::error("Duplicate key (template_dir)"));
            }

            match value {
                Yaml::String(s) => self.template_dirs = Some(vec![PathBuf::from(s)]),
                Yaml::Array(v) => {
                    let mut template_dirs = Vec::new();
                    for e in v {
                        if let Yaml::String(s) = e {
                            template_dirs.push(PathBuf::from(s));
                        } else {
                            return Err(Self::error(
                                "Arguments of `template_dir` must be string",
                            ));
                        }
                    }
                    self.template_dirs = Some(template_dirs);
                }
                _ => {
                    return Err(Self::error(
                        "Arguments of `template_dir` must be string",
                    ));
                }
            }

            Ok(())
        }

        fn visit_delimiter(&mut self, value: Yaml) -> Result<(), Error> {
            if self.delimiter.is_some() {
                return Err(Self::error("Duplicate key (delimiter)"));
            }

            if let Yaml::String(s) = value {
                if s.chars().count() == 1 {
                    self.delimiter = Some(s.chars().next().unwrap());
                    Ok(())
                } else {
                    Err(Self::error("`escape` must be single character"))
                }
            } else {
                Err(Self::error("`escape` must be single character"))
            }
        }

        fn visit_escape(&mut self, value: Yaml) -> Result<(), Error> {
            if self.escape.is_some() {
                return Err(Self::error("Duplicate key (escape)"));
            }

            if let Yaml::Boolean(b) = value {
                self.escape = Some(b);
                Ok(())
            } else {
                Err(Self::error("`escape` must be boolean"))
            }
        }

        fn visit_optimization(&mut self, entry: Yaml) -> Result<(), Error> {
            let hash = entry.into_hash().ok_or_else(|| {
                ErrorKind::ConfigError("Invalid configuration format".to_owned())
            })?;

            for (k, v) in hash {
                match k {
                    Yaml::String(ref s) => match &**s {
                        "rm_whitespace" => self.visit_rm_whitespace(v)?,
                        _ => {
                            return Err(Self::error(format!(
                                "Unknown key (optimization.{})",
                                s
                            )));
                        }
                    },
                    _ => {
                        return Err(Self::error("Invalid configuration format"));
                    }
                }
            }

            Ok(())
        }

        fn visit_rm_whitespace(&mut self, value: Yaml) -> Result<(), Error> {
            if self.rm_whitespace.is_some() {
                return Err(Self::error("Duplicate key (rm_whitespace)"));
            }

            if let Yaml::Boolean(b) = value {
                self.rm_whitespace = Some(b);
                Ok(())
            } else {
                Err(Self::error("`rm_whitespace` must be boolean"))
            }
        }

        fn error<T: Into<String>>(msg: T) -> Error {
            make_error!(ErrorKind::ConfigError(msg.into()))
        }
    }
}