Skip to content

Commit

Permalink
WIP: Add helpers registration
Browse files Browse the repository at this point in the history
  • Loading branch information
olorin37 committed Feb 9, 2020
1 parent aa7d3a3 commit 830f8e9
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 51 deletions.
52 changes: 6 additions & 46 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ edition = "2018"

[dependencies]
structopt = "0.3"
handlebars = "2.0" # "3.0.0-beta.4"
handlebars = "3.0.1"
serde = "1.0"
serde_yaml = "0.8"
glob = "0.3"
48 changes: 44 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,26 @@ use std::error::Error;
use std::fs;
use std::fs::File;
use std::path::Path;
use std::path::PathBuf;
use std::str::from_utf8;
use std::process::Command;


extern crate structopt;
extern crate handlebars;
extern crate serde_yaml;
#[macro_use] extern crate handlebars;

use structopt::StructOpt;
use std::path::PathBuf;

use serde_yaml::Value;

//use handlebars as hbs;
use handlebars::Handlebars;
use handlebars::Helper;
use handlebars::RenderError;
use handlebars::Output;
use handlebars::Context;
use handlebars::RenderContext;
use handlebars::HelperResult;

use glob::glob;

#[derive(Debug, StructOpt)]
Expand Down Expand Up @@ -42,6 +53,13 @@ struct Opt {
/// Make error output verobse
verbose: bool,

#[structopt(short = "h", long)]
/// Register helper
register_helper: Option<String>,

#[structopt(short = "E", long)]
/// Use environment variables as data source
env: bool,
}

fn main() -> Result<(), Box<dyn Error>> {
Expand All @@ -65,6 +83,28 @@ fn main() -> Result<(), Box<dyn Error>> {
let data: Value = serde_yaml::from_reader(propsfile)?;
let template = fs::read_to_string(opt.template)?;

// try helpers:
handlebars_helper!(hex: |v: i64| format!("0x{:x}", v));
reg.register_helper("hex", Box::new(hex));

reg.register_helper("sh-cat",
Box::new(
| h: &Helper, _r: &Handlebars, _: &Context, _rc: &mut RenderContext,
out: &mut dyn Output| -> HelperResult {
let param = h.param(0).ok_or(RenderError::new("param not found"))?;
let param = param.value().as_str().unwrap_or("");

let proc = Command::new("cat")
.args(&[ param ])
.output()
.expect("Failed to execute process `cat`");
out.write(from_utf8(&proc.stdout).unwrap())?;

Ok(())
}));
// end, TODO registration should be moved to the other function
// and applied to each -h value and -H pattern matchings

let text = reg.render_template(&template, &data)?;
match opt.output {
Some(path) => fs::write(path, text)?,
Expand Down

0 comments on commit 830f8e9

Please sign in to comment.