forked from qur/withmock
/
config.go
118 lines (96 loc) · 2.03 KB
/
config.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
// Copyright 2013 Julian Phillips. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lib
import (
"bufio"
"io/ioutil"
"os"
"strings"
"gopkg.in/yaml.v1"
)
func readPackages(path string) ([]string, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
pkgs := []string{}
s := bufio.NewScanner(f)
for s.Scan() {
line := strings.TrimSpace(s.Text())
if len(line) == 0 || line[0] == '#' {
continue
}
pkgs = append(pkgs, line)
}
if err := s.Err(); err != nil {
return nil, err
}
return pkgs, nil
}
type MockConfig struct {
// Local configuration
MockPrototypes bool // Mock prototypes (i.e. functions without bodies)
IgnoreInits bool // Don't call the original init functions
MatchOSArch bool // only use files for GOOS & GOARCH
IgnoreNonGoFiles bool // Don't copy non-go files into the mocked package
// File based configuration
MOCK string `yaml:"MOCK"`
EXPECT string `yaml:"EXPECT"`
ObjEXPECT string `yaml:"obj.EXPECT"`
}
type Config struct {
Mocks map[string]*MockConfig
}
func (c *Config) Mock(path string) *MockConfig {
m := &MockConfig{
MOCK: "MOCK",
EXPECT: "EXPECT",
ObjEXPECT: "EXPECT",
}
dc, found := c.Mocks["DEFAULT"]
if !found {
dc = &MockConfig{}
}
mc, found := c.Mocks[path]
if !found {
mc = &MockConfig{}
}
switch {
case mc.MOCK != "":
m.MOCK = mc.MOCK
case dc.MOCK != "":
m.MOCK = dc.MOCK
}
switch {
case mc.EXPECT != "":
m.EXPECT = mc.EXPECT
case dc.EXPECT != "":
m.EXPECT = dc.EXPECT
}
switch {
case mc.ObjEXPECT != "":
m.ObjEXPECT = mc.ObjEXPECT
case dc.ObjEXPECT != "":
m.ObjEXPECT = dc.ObjEXPECT
}
return m
}
func ReadConfig(path string) (*Config, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
cfg := &Config{}
err = yaml.Unmarshal(data, cfg)
if err != nil {
return nil, err
}
return cfg, nil
}