-
Notifications
You must be signed in to change notification settings - Fork 0
/
hapfile.go
129 lines (115 loc) · 2.46 KB
/
hapfile.go
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
// Hap - the simple and effective provisioner
// Copyright (c) 2015 Garrett Woodworth (https://github.com/gwoo)
// The BSD License http://opensource.org/licenses/bsd-license.php.
package hap
import (
"encoding/json"
"sort"
"code.google.com/p/gcfg"
)
// The Hapfile
type Hapfile struct {
Default Default
Hosts map[string]*Host `gcfg:"host"`
Builds map[string]*Build `gcfg:"build"`
}
// Get list of hosts
func (h Hapfile) GetHosts(name string, all bool) map[string]*Host {
if all == false {
if host := h.Host(name); host != nil {
return map[string]*Host{name: host}
}
return nil
}
hosts := h.Hosts
keys := []string{}
for key, _ := range hosts {
keys = append(keys, key)
}
sort.Strings(keys)
results := make(map[string]*Host)
for _, key := range keys {
results[key] = h.Host(key)
}
return results
}
// Get a host based on the name
// If the name is empty, and if default addr exists, return default
// otherwise return a random host
func (h Hapfile) Host(name string) *Host {
if host, ok := h.Hosts[name]; ok {
host.Name = name
host.SetDefaults(h.Default)
host.BuildCmds(h.Builds)
return host
}
if h.Default.Addr != "" {
host := Host(h.Default)
host.Name = "default"
host.BuildCmds(h.Builds)
return &host
}
return nil
}
// Return the hapfile config as json
func (h Hapfile) String() string {
b, err := json.Marshal(h)
if err != nil {
return ""
}
return string(b)
}
// The default settings
type Default Host
// A remote machine
type Host struct {
Name string
Addr string
Username string
Identity string
Password string
Build []string
Cmd []string
cmds []string
}
// Use the defaults to fill in missing host specific config
func (h *Host) SetDefaults(d Default) {
if h.Username == "" {
h.Username = d.Username
}
if h.Identity == "" {
h.Identity = d.Identity
}
if h.Password == "" {
h.Password = d.Password
}
if len(h.Build) < 1 {
h.Build = d.Build
}
if len(h.Cmd) < 1 {
h.Cmd = d.Cmd
}
}
// Combine the builds and cmds
func (h *Host) BuildCmds(builds map[string]*Build) {
h.cmds = []string{}
for _, build := range h.Build {
if b, ok := builds[build]; ok {
h.cmds = append(h.cmds, b.Cmd...)
}
}
h.cmds = append(h.cmds, h.Cmd...)
}
// Get the cmds to build
func (h *Host) Cmds() []string {
return h.cmds
}
type Build struct {
Cmd []string
}
// Construct a new hapfile config
func NewHapfile() (Hapfile, error) {
var hf Hapfile
err := gcfg.ReadFileInto(&hf, "Hapfile")
return hf, err
}