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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use crate::errors::{ErrorKind, GuidonError, Result};
use crate::helpers::{decrypt, encrypt};
use crate::{append, default, low, prepend, replace, up};
use handlebars::Handlebars;
use log::{debug, error, info};
use serde_derive::Deserialize;
use std::collections::BTreeMap;
use std::ffi::OsStr;
use std::fs::{copy, create_dir_all, read_to_string, remove_file, File};
use std::marker::Sized;
use std::path::{Path, PathBuf};
pub type VariablesCallback<'a> = dyn Fn(&mut BTreeMap<String, String>) + 'a;
pub type RenderCallback<'a> = dyn Fn(String) -> String + 'a;
static TEMPLATE_FILE: &str = "template.toml";
static TEMPLATE_DIR: &str = "template";
#[derive(Deserialize)]
pub struct Template {
pub variables: BTreeMap<String, String>,
}
/// Try to initialize Guidon from different sources
pub trait TryNew<A> {
/// Try to initialize from an object A
fn try_new(src: A) -> Result<Self>
where
Self: Sized;
}
/// The Guidon structure
#[derive(Default)]
pub struct Guidon<'a> {
/// Directory containing files to be templatized
pub(crate) dir_path: PathBuf,
/// File with variables values
template_path: PathBuf,
use_lax_mode: bool,
pub(crate) variables: BTreeMap<String, String>,
variables_callback: Option<Box<VariablesCallback<'a>>>,
render_callback: Option<Box<RenderCallback<'a>>>,
}
pub struct CustomTemplate<'a> {
pub dir_path: &'a Path,
pub template_path: &'a Path,
}
impl<'a> Default for CustomTemplate<'a> {
fn default() -> Self {
CustomTemplate {
dir_path: Path::new(""),
template_path: Path::new(""),
}
}
}
impl<'a> TryNew<CustomTemplate<'a>> for Guidon<'a> {
/// Initialization from a directory and a custom template file
///
/// # Arguments
/// * dir_path: the base directory of templatized files
/// * template_path: the path of the template file to apply. Must respect `template.toml` syntax
fn try_new(src: CustomTemplate<'a>) -> Result<Self> {
let tplt_str = read_to_string(src.template_path).map_err(|_| {
GuidonError::from_string(&format!(
"No template found at {}",
src.template_path.to_string_lossy()
))
})?;
let tplt: Template = toml::from_str(&tplt_str)?;
let guidon = Guidon {
dir_path: src.dir_path.to_path_buf(),
template_path: src.template_path.to_path_buf(),
variables: tplt.variables,
..Default::default()
};
Ok(guidon)
}
}
impl<'a, P: 'a + AsRef<Path>> TryNew<P> for Guidon<'a> {
/// Initialization from a folder path or a file path
/// * dir_path: the base directory for guidon-cli template. The file `template.toml` is
/// searched in this directory, and templates files in `template` dir.
/// * file_path: the path of the template file. The working dir is the current dir.
fn try_new(path: P) -> Result<Self> {
// Path is a dir. Let find template.toml in it
let g = if path.as_ref().is_dir() {
let tplt_file_path = path.as_ref().join(TEMPLATE_FILE);
let tplt_str = read_to_string(&tplt_file_path).map_err(|_| {
GuidonError::from_string(&format!(
"No template found at {}",
tplt_file_path.to_string_lossy()
))
})?;
let tplt: Template = toml::from_str(&tplt_str)?;
let guidon = Guidon {
dir_path: path.as_ref().to_path_buf().join(TEMPLATE_DIR),
template_path: path.as_ref().join(TEMPLATE_FILE),
variables: tplt.variables,
..Default::default()
};
guidon
} else {
// Path point to the variable file. Working dir is assumed to be the parent dir
let tplt_str = read_to_string(path.as_ref())?;
let tplt: Template = toml::from_str(&tplt_str)?;
let guidon = Guidon {
dir_path: path
.as_ref()
.parent()
.ok_or_else(|| {
GuidonError::new(
ErrorKind::Io,
&format!("Path not found: {}", path.as_ref().display()),
)
})?
.to_path_buf(),
template_path: path.as_ref().to_path_buf(),
variables: tplt.variables,
..Default::default()
};
guidon
};
Ok(g)
}
}
impl<'a> Guidon<'a> {
/// Creates a new Guidon from a path
pub fn new(path: PathBuf) -> Self {
Guidon {
dir_path: path.join("template"),
template_path: path.join("template.toml"),
..Default::default()
}
}
/// Sets the substitutions variables
pub fn variables(&mut self, vars: BTreeMap<String, String>) {
self.variables = vars;
}
/// Wether to use or no Handlebars strict mode.
///
/// If set to `true` (default value), an error will be raised if a variable is not defined.
/// If set to `false` missing variables will be set to an empty string.
pub fn use_strict_mode(&mut self, strict: bool) -> &mut Self {
self.use_lax_mode = !strict;
self
}
/// Provides a callback to perform an operation on the variables map.
/// Can be used to change default variables values.
///
/// # Arguments
/// * `cb`: callback. A closure with takes a `BTreeMap<String, String>` as parameter and returns
/// a `BTreeMap<String, String>`.
///
/// # Example
/// ```rust, no_run
/// use guidon::Guidon;
/// use std::collections::BTreeMap;
/// use std::path::PathBuf;
///
/// let cb = |h: &mut BTreeMap<String, String>| {
/// h.iter_mut().for_each(|(_, v)| *v +=" cb");
/// };
/// let mut guidon = Guidon::new(PathBuf::from("template/path"));
/// guidon.set_variables_callback(cb);
/// ```
pub fn set_variables_callback<F>(&mut self, cb: F)
where
F: Fn(&mut BTreeMap<String, String>) + 'a,
{
self.variables_callback = Some(Box::new(cb) as Box<VariablesCallback>);
}
/// Provides a callback to be called when a variables is not found in the configuration file.
///
/// # Arguments
/// * `cb`: callback. A closure with takes the expected key as a `String` parameter and returns
/// the value to use as a `String`.
///
/// # Example
/// ```rust, no_run
/// use guidon::Guidon;
/// use std::collections::BTreeMap;
/// use std::path::PathBuf;
///
/// // this callback will add `-cb` to the key as a value
/// let cb = |h: String| {
/// let mut s = h.clone();
/// s.push_str("-cb");
/// s
/// };
/// let mut guidon = Guidon::new(PathBuf::from("template/path"));
/// guidon.set_render_callback(cb);
/// ```
pub fn set_render_callback<F>(&mut self, cb: F)
where
F: Fn(String) -> String + 'a,
{
self.render_callback = Some(Box::new(cb) as Box<RenderCallback>);
}
/// Apply template.
/// The substitution will be performed with variables provided in the config file.
/// The input dir is deduced from the path given at guidon-cli initialization:
/// * `given/path/template` (default behaviour)
/// * `given/path`
///
/// # Arguments
/// * `to_dir` : the directory where the templated file structure will be created.
pub fn apply_template<T>(&mut self, to_dir: T) -> Result<()>
where
T: AsRef<Path>,
{
info!(
"Applying template for {} with file {}",
self.dir_path.display().to_string(),
self.template_path.display().to_string()
);
// 1 - Check substition values (callback)
// call callback
if let Some(cb) = &self.variables_callback {
debug!("Calling variable callback");
cb(&mut self.variables);
}
// 2 - Create destination directory
// Fails if the destination dir doesn't exists
create_dir_all(to_dir.as_ref())?;
// 3 - Parse template dirs, apply template and copy to destination
let mut handlebars = Handlebars::new();
handlebars.register_helper("replace", Box::new(replace));
handlebars.register_helper("append", Box::new(append));
handlebars.register_helper("prepend", Box::new(prepend));
handlebars.register_helper("up", Box::new(up));
handlebars.register_helper("down", Box::new(low));
handlebars.register_helper("default", Box::new(default));
#[cfg(feature = "crypto")]
{
handlebars.register_helper("encrypt", Box::new(encrypt));
handlebars.register_helper("decrypt", Box::new(decrypt));
}
handlebars.set_strict_mode(!self.use_lax_mode);
self.parse_dir(
&self.dir_path.canonicalize()?,
&to_dir.as_ref().canonicalize()?,
&handlebars,
)?;
info!("Template applied.");
Ok(())
}
// Convert a file or folder name if its templated (my-{{wonderful}}-name)
// Current limitation: don't handle name with several substitution
// placeholders (like my-{{very}}-{{beautiful}}-name)
// TODO: Consider the use of regex
fn convert_file_name(&self, entry_path: &Path, hb: &Handlebars) -> Result<String> {
let name = entry_path
.file_name()
.and_then(OsStr::to_str)
.ok_or_else(|| GuidonError::new(ErrorKind::NotFound, "Can't extract dir name"))?
.to_string();
hb.render_template(&name, &self.variables)
.map_err(|e| GuidonError::new(ErrorKind::Error, &e.as_render_error().unwrap().desc))
}
// Recursively parse the files and folder in the given directory,
// trying to apply handlebars substitution
// TODOÂ Consider the use of walkdir
fn parse_dir(&mut self, dir: &Path, to: &Path, hb: &Handlebars) -> Result<()> {
debug!("Parsing dir {}", dir.display().to_string());
if !dir.is_dir() {
return Err(GuidonError::new(ErrorKind::NotAFolder, "Not a directory"));
}
// for each entry…
for entry in dir.read_dir()? {
match entry {
Ok(entry) => {
// … performs name substitution if necessary…
let entry_path = entry.path();
debug!("Parsing entry {}", entry_path.display().to_string());
let name = self.convert_file_name(&entry_path, hb)?;
// … if it's a directory, creates the target directory…
if entry_path.is_dir() {
let target_path = to.join(name);
debug!("Creating folder {}", target_path.display().to_string());
create_dir_all(&target_path)?;
self.parse_dir(&entry_path, &target_path, hb)?;
} else {
// … if it's a file…
debug!("Entry is a file");
if name.ends_with("hbs") {
//… call handlebars and write the processed file to target…
debug!("Entry is a template source");
let mut source_template = File::open(entry.path())?;
let t = dir.join(name);
let target_file_name = t.file_stem().unwrap();
let target_path = to.join(target_file_name);
debug!("Copying entry to {}", target_path.display().to_string());
// … if a variable is not found, execute the callback…
if let Some(cb) = &self.render_callback {
loop {
if target_path.exists() {
remove_file(&target_path)?;
}
let mut output_file = File::create(&target_path)?;
match hb.render_template_source_to_write(
&mut source_template,
&self.variables,
&mut output_file,
) {
Err(e) => {
if let Some(error) = e.as_render_error() {
//TODO : propose commit to handlebars to retrieve the key
debug!("Missing value for key : {}", error.desc);
let variable: &str =
error.desc.split('"').nth(1).ok_or_else(
|| GuidonError::from_string(&*error.desc),
)?;
let value = cb(variable.to_string());
self.variables.insert(variable.to_string(), value);
source_template = File::open(entry.path())?;
} else {
debug!("Handlebars error");
return Err(e.into());
}
}
Ok(_) => {
debug!(
"Mapping done for {}",
target_file_name.to_string_lossy()
);
break;
}
}
}
} else {
let mut output_file = File::create(&target_path)?;
hb.render_template_source_to_write(
&mut source_template,
&self.variables,
&mut output_file,
)?;
}
} else {
// If no substitution, direct copy of the file
let target_path = to.join(name);
debug!("Copying entry to {}", target_path.display().to_string());
copy(&entry_path, to.join(target_path))?;
}
}
}
Err(e) => error!("Unparsable dir entry : {}", e.to_string()),
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::guidon::Template;
use crate::Guidon;
use handlebars::to_json;
use log::LevelFilter;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Once;
static INIT: Once = Once::new();
fn setup() {
INIT.call_once(|| {
let _ = env_logger::builder()
.is_test(true)
.filter_level(LevelFilter::Trace)
.try_init();
});
}
#[test]
fn should_parse_toml() {
setup();
let toml_content = r#"
[variables]
key1 = "value1"
key2 = "value2"
"#;
let tplt: Template = toml::from_str(toml_content).unwrap();
let mut guidon = Guidon::default();
guidon.variables = tplt.variables;
assert_eq!(guidon.render_callback.is_none(), true);
assert_eq!(guidon.variables["key1"], "value1".to_string())
}
#[test]
fn test_variables_callback() {
let cb = |h: &mut BTreeMap<String, String>| {
h.iter_mut().for_each(|(_, v)| *v += " cb");
};
setup();
let mut guidon = Guidon::default();
guidon.set_variables_callback(cb);
let mut map: BTreeMap<String, String> = BTreeMap::new();
map.insert("toto".to_owned(), "tutu".to_string());
map.insert("titi".to_string(), "tata".to_string());
map.insert("riri".to_string(), "fifi".to_string());
cb(&mut map);
assert_eq!(map["toto"], "tutu cb".to_string());
assert_eq!(map["titi"], "tata cb".to_string());
assert_eq!(map["riri"], "fifi cb");
}
#[test]
fn should_convert_file_name2() {
let path = PathBuf::from("test/my-{{plop}}-file.{{ext}}.hbs");
let mut map = BTreeMap::new();
map.insert("plop", "beautiful");
map.insert("ext", "txt");
let data = to_json(&map);
let hb = handlebars::Handlebars::new();
let out = hb.render_template(path.to_str().unwrap(), &data).unwrap();
assert_eq!("test/my-beautiful-file.txt.hbs", out);
}
}