aboutsummaryrefslogtreecommitdiff
path: root/template.go
blob: a98abb1704e799332c511f1d8341517f13b88e96 (plain)
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
package main

import (
	"bytes"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"text/template"

	"github.com/BurntSushi/toml"
)

type TemplateData struct {
	OS       string
	Arch     string
	Hostname string
	Home     string
	Vars     map[string]interface{}
}

func buildFuncMap() template.FuncMap {
	return map[string]interface{}{
		"pass": lookupPassword,
		"env":  os.Getenv,
	}
}

func lookupPassword(name string) (string, error) {
	out, err := exec.Command("pass", name).CombinedOutput()
	if err != nil {
		return "", err
	}
	buf := bytes.NewBuffer(out)
	line, err := buf.ReadBytes('\n')
	if err != nil {
		return "", err
	}
	return strings.TrimRight(string(line), "\n"), nil
}

func getTemplateData(conf *Conf) (*TemplateData, error) {
	vars, err := readVars(conf)
	if err != nil {
		return nil, err
	}
	data := &TemplateData{
		OS:   runtime.GOOS,
		Arch: runtime.GOARCH,
		Vars: vars,
	}
	if host, err := os.Hostname(); err != nil {
		return nil, err
	} else {
		data.Hostname = host
	}
	if home, err := os.UserHomeDir(); err != nil {
		return nil, err
	} else {
		data.Home = home
	}
	return data, nil
}

func readVars(conf *Conf) (map[string]interface{}, error) {
	var vars map[string]interface{}
	if _, err := toml.DecodeFile(filepath.Join(conf.Source, "vars.toml"), &vars); err != nil {
		return nil, err
	}
	return vars, nil
}