This repository has been archived by the owner on Dec 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
76 lines (59 loc) · 1.35 KB
/
main.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
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/spf13/viper"
)
type input struct {
key, file string
}
func (i input) config() {
viper.SetConfigType("yaml")
viper.SetConfigName(i.filename())
viper.AddConfigPath(i.dir())
}
func (i input) value() (string, error) {
i.config()
keyWithoutFirstDot := strings.Replace(i.key, ".", "", 1)
err := viper.ReadInConfig()
if err != nil {
return "", fmt.Errorf("fatal error config file: %v", err)
}
value := fmt.Sprintf("%v", viper.Get(keyWithoutFirstDot))
if value == "<nil>" {
return "", fmt.Errorf("File: %v does not contain key: %v", i.file, i.key)
}
return value, nil
}
func (i input) dir() string {
return filepath.Dir(i.file)
}
func (i input) filename() string {
basename := filepath.Base(i.file)
filename := strings.TrimSuffix(basename, filepath.Ext(basename))
return filepath.Base(filename)
}
func (i input) verifyKey() error {
if !strings.HasPrefix(i.key, ".") {
return fmt.Errorf("Key should start with a dot, i.e.: .%s, but was: %s", i.key, i.key)
}
return nil
}
func main() {
if len(os.Args) <= 2 {
log.Fatal("Usage: go-yq <key e.g. .foo.bar> <filename e.g. input.yaml>")
}
i := input{key: os.Args[1], file: os.Args[2]}
err := i.verifyKey()
if err != nil {
log.Fatal(err)
}
v, err := i.value()
if err != nil {
log.Fatal(err)
}
fmt.Println(v)
}