-
Notifications
You must be signed in to change notification settings - Fork 315
/
mod.rs
418 lines (342 loc) · 14 KB
/
mod.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
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod config;
mod context;
pub mod helpers;
pub mod hooks;
pub mod package;
pub mod test_helpers;
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::result;
use handlebars::{Handlebars, RenderError};
use serde::Serialize;
use serde_json;
use crate::error::{Error, Result};
use crate::hcore::fs;
use crate::hcore::package::PackageInstall;
use crate::templating::hooks::{Hook, InstallHook};
pub use self::context::RenderContext;
/// A convenience method that compiles a package's install hook
/// and any configuration templates in its config_install folder
pub fn compile_for_package_install(package: &PackageInstall) -> Result<()> {
let pkg = package::Pkg::from_install(package)?;
fs::SvcDir::new(&pkg.name, &pkg.svc_user, &pkg.svc_group).create()?;
let cfg = config::Cfg::new(&pkg, None)?;
let ctx = RenderContext::new(&pkg, &cfg);
let cfg_renderer = config::CfgRenderer::new(pkg.path.join("config_install"))?;
cfg_renderer.compile(&pkg.name, &pkg, &pkg.svc_config_install_path, &ctx)?;
if let Some(ref hook) = InstallHook::load(
&pkg.name,
&fs::svc_hooks_path(&pkg.name),
&package.installed_path.join("hooks"),
) {
hook.compile(&pkg.name, &ctx)?;
};
Ok(())
}
pub type RenderResult<T> = result::Result<T, RenderError>;
pub struct TemplateRenderer(Handlebars);
impl TemplateRenderer {
pub fn new() -> Self {
let mut handlebars = Handlebars::new();
handlebars.register_helper("eachAlive", Box::new(helpers::EACH_ALIVE));
handlebars.register_helper("pkgPathFor", Box::new(helpers::PKG_PATH_FOR));
handlebars.register_helper("strConcat", Box::new(helpers::STR_CONCAT));
handlebars.register_helper("strJoin", Box::new(helpers::STR_JOIN));
handlebars.register_helper("strReplace", Box::new(helpers::STR_REPLACE));
handlebars.register_helper("toUppercase", Box::new(helpers::TO_UPPERCASE));
handlebars.register_helper("toLowercase", Box::new(helpers::TO_LOWERCASE));
handlebars.register_helper("toJson", Box::new(helpers::TO_JSON));
handlebars.register_helper("toToml", Box::new(helpers::TO_TOML));
handlebars.register_helper("toYaml", Box::new(helpers::TO_YAML));
handlebars.register_escape_fn(never_escape);
TemplateRenderer(handlebars)
}
pub fn render<T>(&self, template: &str, ctx: &T) -> Result<String>
where
T: Serialize,
{
let raw = serde_json::to_value(ctx).map_err(Error::RenderContextSerialization)?;
debug!("Rendering template with context, {}, {}", template, raw);
self.0
.render(template, &raw)
.map_err(|e| Error::TemplateRenderError(format!("{}", e)))
}
}
impl fmt::Debug for TemplateRenderer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Handlebars TemplateRenderer")
}
}
impl Deref for TemplateRenderer {
type Target = Handlebars;
fn deref(&self) -> &Handlebars {
&self.0
}
}
impl DerefMut for TemplateRenderer {
fn deref_mut(&mut self) -> &mut Handlebars {
&mut self.0
}
}
/// Disables HTML escaping which is enabled by default in Handlebars.
fn never_escape(data: &str) -> String {
String::from(data)
}
#[cfg(test)]
mod test {
use super::*;
use crate::hcore::fs::{pkg_root_path, FS_ROOT_PATH};
use crate::hcore::package::PackageIdent;
use crate::templating::test_helpers::*;
use serde_json;
use std::collections::BTreeMap;
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use tempfile::TempDir;
use toml;
pub fn root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests")
}
pub fn fixtures() -> PathBuf {
root().join("fixtures")
}
pub fn templates() -> PathBuf {
fixtures().join("templates")
}
pub fn sample_configs() -> PathBuf {
fixtures().join("sample_configs")
}
pub fn service_config_json_from_toml_file(filename: &str) -> serde_json::Value {
let mut file = File::open(sample_configs().join(filename)).unwrap();
let mut config = String::new();
let _ = file.read_to_string(&mut config).unwrap();
let toml = toml::de::from_str(&config).unwrap();
toml_to_json(toml::Value::Table(toml))
}
fn toml_vec_to_json(toml: Vec<toml::Value>) -> serde_json::Value {
serde_json::Value::Array(toml.into_iter().map(toml_to_json).collect())
}
// Translates a toml table to a mustache data structure.
fn toml_table_to_json(toml: BTreeMap<String, toml::Value>) -> serde_json::Value {
serde_json::Value::Object(
toml.into_iter()
.map(|(k, v)| (k, toml_to_json(v)))
.collect(),
)
}
pub fn toml_to_json(value: toml::Value) -> serde_json::Value {
match value {
toml::Value::String(s) => serde_json::Value::String(s.to_string()),
toml::Value::Integer(i) => serde_json::Value::from(i as i64),
toml::Value::Float(i) => serde_json::Value::from(i as f64),
toml::Value::Boolean(b) => serde_json::Value::Bool(b),
toml::Value::Datetime(s) => serde_json::Value::String(s.to_string()),
toml::Value::Array(a) => toml_vec_to_json(a),
toml::Value::Table(t) => toml_table_to_json(t),
}
}
#[test]
fn test_handlebars_json_helper() {
let content = "{{toJson x}}".to_string();
let mut data = BTreeMap::new();
data.insert("test".into(), "something".into());
let mut renderer = TemplateRenderer::new();
renderer.register_template_string("t", content).unwrap();
let mut m: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
m.insert("x".into(), data);
let r = renderer.render("t", &m);
assert_eq!(
r.ok().unwrap(),
r#"{
"test": "something"
}"#
.to_string()
);
}
#[test]
fn test_handlebars_toml_helper() {
let content = "{{toToml x}}".to_string();
let mut data = BTreeMap::new();
data.insert("test".into(), "something".into());
let mut renderer = TemplateRenderer::new();
renderer.register_template_string("t", content).unwrap();
let mut m: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
m.insert("x".into(), data);
let r = renderer.render("t", &m);
assert_eq!(
r.ok().unwrap(),
r#"test = "something"
"#
.to_string()
);
}
#[test]
fn test_handlebars_yaml_helper() {
let content = "{{toYaml x}}".to_string();
let mut data = BTreeMap::new();
data.insert("test".into(), "something".into());
let mut renderer = TemplateRenderer::new();
renderer.register_template_string("t", content).unwrap();
let mut m: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
m.insert("x".into(), data);
let r = renderer.render("t", &m);
assert_eq!(
r.ok().unwrap(),
r#"---
test: something"#
.to_string()
);
}
#[test]
fn to_uppercase_helper() {
let content = "{{toUppercase var}}".to_string();
let mut renderer = TemplateRenderer::new();
renderer.register_template_string("t", content).unwrap();
let mut m: BTreeMap<String, String> = BTreeMap::new();
m.insert("var".into(), "value".into());
let rendered = renderer.render("t", &m).unwrap();
assert_eq!(rendered, "VALUE".to_string());
}
#[test]
fn to_lowercase_helper() {
let content = "{{toLowercase var}}".to_string();
let mut renderer = TemplateRenderer::new();
renderer.register_template_string("t", content).unwrap();
let mut m: BTreeMap<String, String> = BTreeMap::new();
m.insert("var".into(), "VALUE".into());
let rendered = renderer.render("t", &m).unwrap();
assert_eq!(rendered, "value".to_string());
}
#[test]
fn str_replace_helper() {
let content = "{{strReplace var old new}}".to_string();
let mut renderer = TemplateRenderer::new();
renderer.register_template_string("t", content).unwrap();
let mut m: BTreeMap<String, String> = BTreeMap::new();
m.insert("var".into(), "this is old".into());
m.insert("old".into(), "old".into());
m.insert("new".into(), "new".into());
let rendered = renderer.render("t", &m).unwrap();
assert_eq!(rendered, "this is new".to_string());
}
#[test]
fn bind_variable() {
let content = "{{bind.foo.members[0].sys.ip}}";
let mut renderer = TemplateRenderer::new();
let data = service_config_json_from_toml_file("complex_config.toml");
renderer.register_template_string("t", content).unwrap();
let rendered = renderer.render("t", &data).unwrap();
assert_eq!(rendered, "172.17.0.5");
}
#[test]
fn pkg_path_for_helper() {
let content = "{{pkgPathFor \"core/acl\"}}".to_string();
let mut renderer = TemplateRenderer::new();
renderer.register_template_string("t", content).unwrap();
let data = service_config_json_from_toml_file("complex_config.toml");
let rendered = renderer.render("t", &data).unwrap();
assert_eq!(
PathBuf::from(rendered),
pkg_root_path(Some(&*FS_ROOT_PATH)).join("core/acl/2.2.52/20161208223311",)
);
}
#[test]
fn each_alive_helper_content() {
let mut renderer = TemplateRenderer::new();
// template using the new `eachAlive` helper
renderer
.register_template_file("each_alive", templates().join("each_alive.txt"))
.unwrap();
// template using an each block with a nested if block filtering on `alive`
renderer
.register_template_file("all_members", templates().join("all_members.txt"))
.unwrap();
let data = service_config_json_from_toml_file("multiple_supervisors_config.toml");
let each_alive_render = renderer.render("each_alive", &data).unwrap();
let each_if_render = renderer.render("all_members", &data).unwrap();
assert_eq!(each_alive_render, each_if_render);
}
#[test]
fn each_alive_helper_first_node() {
let mut renderer = TemplateRenderer::new();
// template using the new `eachAlive` helper
renderer
.register_template_file("each_alive", templates().join("each_alive.txt"))
.unwrap();
// template using an each block with a nested if block filtering on `alive`
renderer
.register_template_file("all_members", templates().join("all_members.txt"))
.unwrap();
let data = service_config_json_from_toml_file("one_supervisor_not_started.toml");
let each_alive_render = renderer.render("each_alive", &data).unwrap();
let each_if_render = renderer.render("all_members", &data).unwrap();
assert_eq!(each_alive_render, each_if_render);
}
#[test]
fn each_alive_helper_with_identifier_alias() {
let mut renderer = TemplateRenderer::new();
// template using the new `eachAlive` helper
renderer
.register_template_file(
"each_alive",
templates().join("each_alive_with_identifier.txt"),
)
.unwrap();
// template using an each block with a nested if block filtering on `alive`
renderer
.register_template_file("all_members", templates().join("all_members.txt"))
.unwrap();
let data = service_config_json_from_toml_file("multiple_supervisors_config.toml");
let each_alive_render = renderer.render("each_alive", &data).unwrap();
let each_if_render = renderer.render("all_members", &data).unwrap();
assert_eq!(each_alive_render, each_if_render);
}
#[test]
fn render_package_install() {
let root = TempDir::new().expect("create temp dir").into_path();
env::set_var(fs::FS_ROOT_ENVVAR, &root);
let pg_id = PackageIdent::new("testing", "test", Some("1.0.0"), Some("20170712000000"));
let pkg_install =
PackageInstall::new_from_parts(pg_id.clone(), root.clone(), root.clone(), root.clone());
let toml_path = root.join("default.toml");
create_with_content(toml_path, &String::from("message = \"Hello\""));
let hooks_path = root.join("hooks");
std::fs::create_dir_all(&hooks_path).unwrap();
create_with_content(
hooks_path.join("install"),
&String::from("install message is {{cfg.message}}"),
);
let config_path = root.join("config_install");
std::fs::create_dir_all(&config_path).unwrap();
create_with_content(
config_path.join("config.txt"),
&String::from("config message is {{cfg.message}}"),
);
compile_for_package_install(&pkg_install).expect("compile package");
assert_eq!(
file_content(fs::svc_config_install_path(&pkg_install.ident().name).join("config.txt")),
"config message is Hello"
);
assert_eq!(
file_content(fs::svc_hooks_path(&pkg_install.ident().name).join("install")),
"install message is Hello"
);
env::remove_var(fs::FS_ROOT_ENVVAR);
std::fs::remove_dir_all(root).expect("removing temp root");
}
}