Skip to content

Commit 186dec7

Browse files
authored
Convert the global settings to correct type when reading them from file (#399)
Signed-off-by: Cosmin Cojocar <[email protected]>
1 parent e680875 commit 186dec7

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

config.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,22 @@ func NewConfig() Config {
3838
return cfg
3939
}
4040

41+
func (c Config) keyToGlobalOptions(key string) GlobalOption {
42+
return GlobalOption(key)
43+
}
44+
45+
func (c Config) convertGlobals() {
46+
if globals, ok := c[Globals]; ok {
47+
if settings, ok := globals.(map[string]interface{}); ok {
48+
validGlobals := map[GlobalOption]string{}
49+
for k, v := range settings {
50+
validGlobals[c.keyToGlobalOptions(k)] = fmt.Sprintf("%v", v)
51+
}
52+
c[Globals] = validGlobals
53+
}
54+
}
55+
}
56+
4157
// ReadFrom implements the io.ReaderFrom interface. This
4258
// should be used with io.Reader to load configuration from
4359
//file or from string etc.
@@ -49,6 +65,7 @@ func (c Config) ReadFrom(r io.Reader) (int64, error) {
4965
if err = json.Unmarshal(data, &c); err != nil {
5066
return int64(len(data)), err
5167
}
68+
c.convertGlobals()
5269
return int64(len(data)), nil
5370
}
5471

@@ -87,7 +104,6 @@ func (c Config) GetGlobal(option GlobalOption) (string, error) {
87104
}
88105
}
89106
return "", fmt.Errorf("no global config options found")
90-
91107
}
92108

93109
// SetGlobal associates a value with a global configuration option

config_test.go

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package gosec_test
22

33
import (
44
"bytes"
5+
"strings"
56

67
. "github.com/onsi/ginkgo"
78
. "github.com/onsi/gomega"
@@ -106,6 +107,36 @@ var _ = Describe("Configuration", func() {
106107
Expect(err).Should(BeNil())
107108
Expect(enabled).Should(BeTrue())
108109
})
109-
})
110110

111+
It("should parse the global settings of type string from file", func() {
112+
config := `
113+
{
114+
"global": {
115+
"nosec": "enabled"
116+
}
117+
}`
118+
cfg := gosec.NewConfig()
119+
_, err := cfg.ReadFrom(strings.NewReader(config))
120+
Expect(err).Should(BeNil())
121+
122+
value, err := cfg.GetGlobal(gosec.Nosec)
123+
Expect(err).Should(BeNil())
124+
Expect(value).Should(Equal("enabled"))
125+
})
126+
It("should parse the global settings of other types from file", func() {
127+
config := `
128+
{
129+
"global": {
130+
"nosec": true
131+
}
132+
}`
133+
cfg := gosec.NewConfig()
134+
_, err := cfg.ReadFrom(strings.NewReader(config))
135+
Expect(err).Should(BeNil())
136+
137+
value, err := cfg.GetGlobal(gosec.Nosec)
138+
Expect(err).Should(BeNil())
139+
Expect(value).Should(Equal("true"))
140+
})
141+
})
111142
})

0 commit comments

Comments
 (0)