forked from alash3al/sqler
-
Notifications
You must be signed in to change notification settings - Fork 1
/
manager.go
78 lines (64 loc) · 1.56 KB
/
manager.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
// Copyright 2018 The SQLer Authors. All rights reserved.
// Use of this source code is governed by a Apache 2.0
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"text/template"
"github.com/hashicorp/hcl"
)
// Manager - a macros manager
type Manager struct {
macros map[string]*Macro
compiled *template.Template
}
// NewManager - initialize a new manager
func NewManager(configpath string) (*Manager, error) {
manager := new(Manager)
manager.macros = make(map[string]*Macro)
manager.compiled = template.New("main")
for _, p := range strings.Split(configpath, ",") {
files, _ := filepath.Glob(p)
if len(files) < 1 {
return nil, fmt.Errorf("invalid path (%s)", p)
}
for _, file := range files {
data, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
var config map[string]*Macro
if err := hcl.Unmarshal(data, &config); err != nil {
return nil, err
}
for k, v := range config {
manager.macros[k] = v
_, err := manager.compiled.New(k).Parse(v.Exec)
if err != nil {
return nil, err
}
v.manager = manager
v.name = k
}
}
}
return manager, nil
}
// Get - fetches the required macro
func (m *Manager) Get(macro string) *Macro {
return m.macros[macro]
}
// Size - return the size of the currently loaded configs
func (m *Manager) Size() int {
return len(m.macros)
}
// List - return a list of registered macros
func (m *Manager) List() (ret []string) {
for k := range m.macros {
ret = append(ret, k)
}
return ret
}