/
config.go
48 lines (41 loc) · 1.14 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
// Copyright 2017 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package config
import (
"bytes"
"encoding/json"
"fmt"
"os"
"regexp"
"github.com/google/syzkaller/pkg/osutil"
)
func LoadFile(filename string, cfg interface{}) error {
if filename == "" {
return fmt.Errorf("no config file specified")
}
data, err := os.ReadFile(filename)
if err != nil {
return fmt.Errorf("failed to read config file: %w", err)
}
return LoadData(data, cfg)
}
func LoadData(data []byte, cfg interface{}) error {
// Remove comment lines starting with #.
data = regexp.MustCompile(`(^|\n)\s*#[^\n]*`).ReplaceAll(data, nil)
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
if err := dec.Decode(cfg); err != nil {
return fmt.Errorf("failed to parse config file: %w", err)
}
return nil
}
func SaveFile(filename string, cfg interface{}) error {
data, err := SaveData(cfg)
if err != nil {
return err
}
return osutil.WriteFile(filename, data)
}
func SaveData(cfg interface{}) ([]byte, error) {
return json.MarshalIndent(cfg, "", "\t")
}