Skip to content

Instantly share code, notes, and snippets.

@sleepiecappy
Created December 26, 2018 05:28
Show Gist options
  • Save sleepiecappy/af5729313d820e70e0d1ddf9362e2556 to your computer and use it in GitHub Desktop.
Save sleepiecappy/af5729313d820e70e0d1ddf9362e2556 to your computer and use it in GitHub Desktop.
quick script to generate files
  • Create file on .templates folder at user home: mkdir ~/.templates/elixir && touch ~/.templates/elixir/module
  • Contents:
defmodule {{mod}} do
end

Usage: bob -tpl elixir/module -d ./person.ex -v mod=Person

Templates are based on handlebars rendered by aymerick/raymond

package main
import (
"flag"
"fmt"
"github.com/aymerick/raymond"
"io/ioutil"
"os"
"os/user"
"path"
"strings"
)
func main() {
// bob elixir/supervisor ./sample_file.ex -module SomeModule
tpl := flag.String("tpl", "", "Template file based on '~/.templates'")
dest := flag.String("d", "./file", "Destination File")
vars := flag.String("v", "", "Variables to pass to template as: some=var another=var")
flag.Parse()
// load template file
path := path.Join(templateFolder(), *tpl)
data, err := ioutil.ReadFile(path)
if err != nil {
fmt.Printf("Error ocurred: %v", err)
os.Exit(1)
}
ctx := make(map[string]string)
for _, pair := range strings.Split(*vars, " ") {
fmt.Println(pair)
keyVal := strings.Split(pair, "=")
if len(keyVal) != 2 {
fmt.Println("Can not form arguments for the template, use: my_template_var=MyValue")
os.Exit(1)
}
ctx[keyVal[0]] = keyVal[1]
}
res, err := raymond.Render(string(data), ctx)
if err != nil {
fmt.Printf("Can not render template, verify and try again, error: %v", err)
os.Exit(1)
}
err = ioutil.WriteFile(*dest, []byte(res), 0777)
if err != nil {
fmt.Printf("Could not write file, %v", err)
}
}
func templateFolder() string {
usr, _ := user.Current()
dir := usr.HomeDir
return path.Join(dir, ".templates")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment