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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
extern crate console;
extern crate dialoguer;
extern crate directories;
extern crate failure;
extern crate git2;
extern crate globset;
extern crate handlebars;
extern crate indicatif;
extern crate inflector;
extern crate lazy_static;
extern crate regex;
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_yaml;
extern crate slog;
extern crate structopt;
extern crate walkdir;

#[cfg(test)]
extern crate spectral;

mod cmd_opt;
mod git;
mod hbs;
mod source_uri;
mod template_cfg;
mod ui;

pub use crate::cmd_opt::*;
use crate::template_cfg::TemplateCfg;
use failure::format_err;
use failure::Error;
use slog::{debug, o, warn};
use source_uri::SourceUri;
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use walkdir::WalkDir;

const FILEEXT_HANDLEBARS: &'static str = ".ffizer.hbs";

pub type Variables = BTreeMap<String, String>;

#[derive(Debug, Clone)]
pub struct Ctx {
    pub logger: slog::Logger,
    pub cmd_opt: CmdOpt,
}

impl Default for Ctx {
    fn default() -> Ctx {
        Ctx {
            logger: slog::Logger::root(slog::Discard, o!()),
            cmd_opt: CmdOpt::default(),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum FileOperation {
    Nothing,
    Ignore,
    Keep,
    MkDir,
    CopyRaw,
    CopyRender,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Action {
    pub src_path: ChildPath,
    pub dst_path: ChildPath,
    // template: TemplateDef,
    pub operation: FileOperation,
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct ChildPath {
    pub relative: PathBuf,
    pub base: PathBuf,
    pub is_symlink: bool,
}

impl<'a> From<&'a ChildPath> for PathBuf {
    fn from(v: &ChildPath) -> Self {
        v.base.join(&v.relative)
    }
}

pub fn process(ctx: &Ctx) -> Result<(), Error> {
    let template_base_path = as_local_path(
        &ctx.cmd_opt.src_uri,
        &ctx.cmd_opt.src_rev,
        &ctx.cmd_opt.src_folder,
        ctx.cmd_opt.offline,
    )?;
    let variables_from_cli = extract_variables(&ctx)?;
    // update cfg with variables defined by user
    let mut template_cfg = TemplateCfg::from_template_folder(&template_base_path)?;
    // update cfg with variables defined by cli (use to update default_value)
    template_cfg = render_cfg(&ctx, &template_cfg, &variables_from_cli, false)?;
    let variables = ui::ask_variables(&ctx, &template_cfg, variables_from_cli)?;
    // update cfg with variables defined by user (use to update ignore)
    template_cfg = render_cfg(&ctx, &template_cfg, &variables, true)?;
    let input_paths = find_childpaths(template_base_path, &template_cfg);
    let actions = plan(ctx, input_paths, &variables)?;
    if ui::confirm_plan(&ctx, &actions)? {
        execute(ctx, &actions, &variables)
    } else {
        Ok(())
    }
}

pub fn extract_variables(ctx: &Ctx) -> Result<Variables, Error> {
    let mut variables = Variables::new();
    variables.insert(
        "ffizer_dst_folder".to_owned(),
        ctx.cmd_opt
            .dst_folder
            .to_str()
            .expect("dst_folder to converted via to_str")
            .to_owned(),
    );
    variables.insert("ffizer_src_uri".to_owned(), ctx.cmd_opt.src_uri.raw.clone());
    variables.insert("ffizer_src_rev".to_owned(), ctx.cmd_opt.src_rev.clone());
    Ok(variables)
}

fn render_cfg(
    ctx: &Ctx,
    template_cfg: &TemplateCfg,
    variables: &Variables,
    log_warning: bool,
) -> Result<TemplateCfg, Error> {
    let handlebars = hbs::new_hbs()?;
    template_cfg.transforms_values(|v| {
        let r = handlebars.render_template(v, variables);
        match r {
            Ok(s) => s,
            Err(e) => {
                if log_warning { warn!(ctx.logger, "failed to convert"; "input" => v, "error" => format!("{:?}", e))}
                v.into()
            }
        }
    })
}

/// list actions to execute
fn plan(ctx: &Ctx, src_paths: Vec<ChildPath>, variables: &Variables) -> Result<Vec<Action>, Error> {
    let mut actions = src_paths
        .into_iter()
        .map(|src_path| {
            let dst_path = compute_dst_path(ctx, &src_path, variables).expect("TODO");
            Action {
                src_path,
                dst_path,
                operation: FileOperation::Nothing,
            }
        }).collect::<Vec<_>>();
    // TODO sort input_paths by priority (*.ffizer(.*) first, alphabetical)
    actions.sort_by(cmp_path_for_plan);
    let actions_count = actions.len();
    actions = actions
        .into_iter()
        .fold(Vec::with_capacity(actions_count), |mut acc, e| {
            let operation = select_operation(ctx, &e.src_path, &e.dst_path, &acc);
            acc.push(Action { operation, ..e });
            acc
        });
    Ok(actions)
}

// TODO add test
// TODO add priority for generated file name / folder name
// TODO document priority (via test ?)
fn cmp_path_for_plan(a: &Action, b: &Action) -> Ordering {
    let cmp_dst = a.dst_path.relative.cmp(&b.dst_path.relative);
    if cmp_dst != Ordering::Equal {
        cmp_dst
    } else if a
        .src_path
        .relative
        .to_str()
        .map(|s| s.contains("{{"))
        .unwrap_or(false)
    {
        Ordering::Greater
    } else if is_ffizer_handlebars(&a.src_path.relative) {
        Ordering::Less
    } else if is_ffizer_handlebars(&b.src_path.relative) {
        Ordering::Greater
    } else {
        a.src_path.relative.cmp(&b.src_path.relative)
    }
}

//TODO accumulate Result (and error)
fn execute(ctx: &Ctx, actions: &Vec<Action>, variables: &Variables) -> Result<(), Error> {
    use indicatif::ProgressBar;

    let pb = ProgressBar::new(actions.len() as u64);
    let handlebars = hbs::new_hbs()?;
    debug!(ctx.logger, "execute"; "variables" => format!("{:?}", variables));

    for a in pb.wrap_iter(actions.iter()) {
        match a.operation {
            // TODO bench performance vs create_dir (and keep create_dir_all for root aka relative is empty)
            FileOperation::MkDir => fs::create_dir_all(&PathBuf::from(&a.dst_path))?,
            FileOperation::CopyRaw => {
                fs::copy(&PathBuf::from(&a.src_path), &PathBuf::from(&a.dst_path))?;
            }
            FileOperation::CopyRender => {
                let src = fs::read_to_string(&PathBuf::from(&a.src_path))?;
                let dst = fs::File::create(PathBuf::from(&a.dst_path))?;
                handlebars.render_template_to_write(&src, variables, dst)?;
            }
            _ => (),
        };
    }
    Ok(())
}

fn as_local_path(
    uri: &SourceUri,
    rev: &str,
    subfolder: &Option<PathBuf>,
    offline: bool,
) -> Result<PathBuf, Error> {
    let mut path = match uri.host {
        None => PathBuf::from(uri.path.clone()),
        Some(_) => remote_as_local(&uri, rev, offline)?,
    };
    if let Some(f) = subfolder {
        path = path.join(f);
    }
    if !path.exists() {
        Err(format_err!(
            "Path not found for {}{}",
            &uri.raw,
            subfolder
                .clone()
                .and_then(|s| s.to_str().map(|v| format!(" and subfolder {}", v)))
                .unwrap_or("".to_owned()) //path.to_str().unwrap_or("??")
        ))
    } else {
        Ok(path)
    }
}

fn remote_as_local(uri: &SourceUri, rev: &str, offline: bool) -> Result<PathBuf, Error> {
    let app_name = std::env::var("CARGO_PKG_NAME").unwrap_or("".into());
    let project_dirs = directories::ProjectDirs::from("net", "alchim31", &app_name)
        .ok_or(format_err!("Home directory not found"))?;
    let cache_base = project_dirs.cache_dir();
    let cache_uri = cache_base
        .join("git")
        .join(&uri.host.clone().unwrap_or("no_host".to_owned()))
        .join(&uri.path)
        .join(rev);
    if !offline {
        git::retrieve(&cache_uri, &uri.raw, rev)?;
    }
    Ok(cache_uri)
}

fn find_childpaths<P>(base: P, cfg: &TemplateCfg) -> Vec<ChildPath>
where
    P: AsRef<Path>,
{
    let base = base.as_ref();
    WalkDir::new(base)
        .follow_links(false)
        .into_iter()
        .filter_entry(|e| {
            e.clone()
                .into_path()
                .strip_prefix(base)
                .expect("scanned child path to be under base")
                .to_str()
                .map(|s| !cfg.ignores.iter().any(|f| f.is_match(s)))
                // .map(|s| true)
                .unwrap_or(true)
        }).filter_map(|e| e.ok())
        .map(|entry| ChildPath {
            base: base.to_path_buf(),
            is_symlink: entry.path_is_symlink(),
            relative: entry
                .into_path()
                .strip_prefix(base)
                .expect("scanned child path to be under base")
                .to_path_buf(),
        }).collect::<Vec<_>>()
}

//TODO optimise / bench to avoid creation and rendering of path handlebars
fn compute_dst_path(ctx: &Ctx, src: &ChildPath, variables: &Variables) -> Result<ChildPath, Error> {
    let rendered_relative = src
        .relative
        .to_str()
        .ok_or(format_err!("failed to stringify path"))
        .and_then(|s| {
            let handlebars = hbs::new_hbs()?;
            let p = handlebars.render_template(&s, variables)?;
            Ok(PathBuf::from(p))
        })?;
    let relative = if is_ffizer_handlebars(&rendered_relative) {
        let mut file_name = rendered_relative
            .file_name()
            .and_then(|v| v.to_str())
            .ok_or(format_err!("failed to extract file_name"))?;
        file_name = file_name
            .get(..file_name.len() - FILEEXT_HANDLEBARS.len())
            .ok_or(format_err!(
                "failed to remove {} from file_name",
                FILEEXT_HANDLEBARS
            ))?;
        rendered_relative.with_file_name(file_name)
    } else {
        rendered_relative
    };

    Ok(ChildPath {
        base: ctx.cmd_opt.dst_folder.clone(),
        relative,
        is_symlink: src.is_symlink,
    })
}

fn select_operation(
    _ctx: &Ctx,
    src_path: &ChildPath,
    dst_path: &ChildPath,
    actions: &Vec<Action>,
) -> FileOperation {
    let src_full_path = PathBuf::from(src_path);
    let dest_full_path = PathBuf::from(dst_path);
    if dest_full_path.exists() || actions
        .iter()
        .any(|a| a.dst_path.relative == dst_path.relative)
    // optim: propably the last
    {
        FileOperation::Keep
    // } else if src_path
    //     .relative
    //     .to_str()
    //     .map(|s| cfg.ignores.iter().any(|f| f.is_match(s)))
    //     .unwrap_or(false)
    // {
    //     FileOperation::Ignore
    } else if src_full_path.is_dir() {
        FileOperation::MkDir
    } else if is_ffizer_handlebars(&src_full_path) {
        FileOperation::CopyRender
    } else {
        FileOperation::CopyRaw
    }
}

fn is_ffizer_handlebars(path: &Path) -> bool {
    path.file_name()
        .and_then(|s| s.to_str())
        .map(|str| str.ends_with(FILEEXT_HANDLEBARS))
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use spectral::prelude::*;

    #[test]
    fn test_cmp_path_for_plan() {
        let a = Action {
            src_path: ChildPath {
                relative: PathBuf::from("file_2.txt"),
                base: PathBuf::from("./tests/test_1/template"),
                is_symlink: false,
            },
            dst_path: ChildPath {
                relative: PathBuf::from("file_2.txt"),
                base: PathBuf::from("/tmp/.tmpYPoYTW"),
                is_symlink: false,
            },
            operation: FileOperation::Nothing,
        };
        let b = Action {
            src_path: ChildPath {
                relative: PathBuf::from("file_2.txt.ffizer.hbs"),
                base: PathBuf::from("./tests/test_1/template"),
                is_symlink: false,
            },
            dst_path: ChildPath {
                relative: PathBuf::from("file_2.txt"),
                base: PathBuf::from("/tmp/.tmpYPoYTW"),
                is_symlink: false,
            },
            operation: FileOperation::Nothing,
        };
        assert_that!(cmp_path_for_plan(&a, &b)).is_equal_to(&Ordering::Greater);
        assert_that!(cmp_path_for_plan(&b, &a)).is_equal_to(&Ordering::Less);
    }

    #[test]
    fn test_compute_dst_path_asis() {
        let ctx = Ctx {
            cmd_opt: CmdOpt {
                dst_folder: PathBuf::from("test/dst"),
                ..Default::default()
            },
            ..Default::default()
        };
        let variables = BTreeMap::new();
        let src = ChildPath {
            relative: PathBuf::from("hello/sample.txt"),
            base: PathBuf::from("test/src"),
            is_symlink: false,
        };
        let expected = ChildPath {
            relative: PathBuf::from("hello/sample.txt"),
            base: ctx.cmd_opt.dst_folder.clone(),
            is_symlink: false,
        };
        let actual = compute_dst_path(&ctx, &src, &variables).unwrap();
        assert_that!(&actual).is_equal_to(&expected);
    }

    #[test]
    fn test_compute_dst_path_ffizer_handlebars() {
        let ctx = Ctx {
            cmd_opt: CmdOpt {
                dst_folder: PathBuf::from("test/dst"),
                ..Default::default()
            },
            ..Default::default()
        };
        let variables = BTreeMap::new();

        let src = ChildPath {
            relative: PathBuf::from("hello/sample.txt.ffizer.hbs"),
            base: PathBuf::from("test/src"),
            is_symlink: false,
        };
        let expected = ChildPath {
            relative: PathBuf::from("hello/sample.txt"),
            base: ctx.cmd_opt.dst_folder.clone(),
            is_symlink: false,
        };
        let actual = compute_dst_path(&ctx, &src, &variables).unwrap();
        assert_that!(&actual).is_equal_to(&expected);
    }

    #[test]
    fn test_compute_dst_path_rendered_filename() {
        let ctx = Ctx {
            cmd_opt: CmdOpt {
                dst_folder: PathBuf::from("test/dst"),
                ..Default::default()
            },
            ..Default::default()
        };
        let mut variables = BTreeMap::new();
        variables.insert("prj".to_owned(), "myprj".to_owned());

        let src = ChildPath {
            relative: PathBuf::from("hello/{{ prj }}.txt"),
            base: PathBuf::from("test/src"),
            is_symlink: false,
        };
        let expected = ChildPath {
            relative: PathBuf::from("hello/myprj.txt"),
            base: ctx.cmd_opt.dst_folder.clone(),
            is_symlink: false,
        };
        let actual = compute_dst_path(&ctx, &src, &variables).unwrap();
        assert_that!(&actual).is_equal_to(&expected);
    }

    #[test]
    fn test_compute_dst_path_rendered_folder() {
        let ctx = Ctx {
            cmd_opt: CmdOpt {
                dst_folder: PathBuf::from("test/dst"),
                ..Default::default()
            },
            ..Default::default()
        };
        let mut variables = BTreeMap::new();
        variables.insert("prj".to_owned(), "myprj".to_owned());

        let src = ChildPath {
            relative: PathBuf::from("hello/{{ prj }}/sample.txt"),
            base: PathBuf::from("test/src"),
            is_symlink: false,
        };
        let expected = ChildPath {
            relative: PathBuf::from("hello/myprj/sample.txt"),
            base: ctx.cmd_opt.dst_folder.clone(),
            is_symlink: false,
        };
        let actual = compute_dst_path(&ctx, &src, &variables).unwrap();
        assert_that!(&actual).is_equal_to(&expected);
    }

    #[test]
    fn test_path_extension_extraction() {
        use std::ffi::OsStr;

        assert_that!(PathBuf::from("foo.ext1").extension()).is_equal_to(&Some(OsStr::new("ext1")));
        assert_that!(PathBuf::from("foo.ext2.ext1").extension())
            .is_equal_to(&Some(OsStr::new("ext1")));
    }

    #[test]
    fn test_is_ffizer_handlebars() {
        assert_that!(is_ffizer_handlebars(&PathBuf::from("foo.hbs"))).is_false();
        assert_that!(is_ffizer_handlebars(&PathBuf::from("foo.ffizer.hbs/bar"))).is_false();
        assert_that!(is_ffizer_handlebars(&PathBuf::from("foo_ffizer.hbs"))).is_false();
        assert_that!(is_ffizer_handlebars(&PathBuf::from("fooffizer.hbs"))).is_false();

        assert_that!(is_ffizer_handlebars(&PathBuf::from("foo.ffizer.hbs"))).is_true();
        assert_that!(is_ffizer_handlebars(&PathBuf::from("bar/foo.ffizer.hbs"))).is_true();
    }
}