github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/pkg/config/config.go (about)

     1  // Copyright 2017 syzkaller project authors. All rights reserved.
     2  // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
     3  
     4  package config
     5  
     6  import (
     7  	"bytes"
     8  	"encoding/json"
     9  	"fmt"
    10  	"os"
    11  	"regexp"
    12  
    13  	"github.com/google/syzkaller/pkg/osutil"
    14  )
    15  
    16  func LoadFile(filename string, cfg interface{}) error {
    17  	if filename == "" {
    18  		return fmt.Errorf("no config file specified")
    19  	}
    20  	data, err := os.ReadFile(filename)
    21  	if err != nil {
    22  		return fmt.Errorf("failed to read config file: %w", err)
    23  	}
    24  	return LoadData(data, cfg)
    25  }
    26  
    27  func LoadData(data []byte, cfg interface{}) error {
    28  	// Remove comment lines starting with #.
    29  	data = regexp.MustCompile(`(^|\n)\s*#[^\n]*`).ReplaceAll(data, nil)
    30  	dec := json.NewDecoder(bytes.NewReader(data))
    31  	dec.DisallowUnknownFields()
    32  	if err := dec.Decode(cfg); err != nil {
    33  		return fmt.Errorf("failed to parse config file: %w", err)
    34  	}
    35  	return nil
    36  }
    37  
    38  func SaveFile(filename string, cfg interface{}) error {
    39  	data, err := SaveData(cfg)
    40  	if err != nil {
    41  		return err
    42  	}
    43  	return osutil.WriteFile(filename, data)
    44  }
    45  
    46  func SaveData(cfg interface{}) ([]byte, error) {
    47  	return json.MarshalIndent(cfg, "", "\t")
    48  }