github.com/snyk/vervet/v3@v3.7.0/config/project.go (about)

     1  package config
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"io/ioutil"
     7  	"sort"
     8  
     9  	"github.com/ghodss/yaml"
    10  )
    11  
    12  // Project defines collection of APIs and the standards they adhere to.
    13  type Project struct {
    14  	Version    string     `json:"version"`
    15  	Linters    Linters    `json:"linters,omitempty"`
    16  	Generators Generators `json:"generators,omitempty"`
    17  	APIs       APIs       `json:"apis"`
    18  }
    19  
    20  // APINames returns the API names in deterministic ascending order.
    21  func (p *Project) APINames() []string {
    22  	var result []string
    23  	for k := range p.APIs {
    24  		result = append(result, k)
    25  	}
    26  	sort.Strings(result)
    27  	return result
    28  }
    29  
    30  func (p *Project) init() {
    31  	if p.Linters == nil {
    32  		p.Linters = Linters{}
    33  	}
    34  	if p.Generators == nil {
    35  		p.Generators = Generators{}
    36  	}
    37  	if p.APIs == nil {
    38  		p.APIs = APIs{}
    39  	}
    40  }
    41  
    42  func (p *Project) validate() error {
    43  	if p.Version == "" {
    44  		p.Version = "1"
    45  	}
    46  	if p.Version != "1" {
    47  		return fmt.Errorf("unsupported version %q", p.Version)
    48  	}
    49  	err := p.Linters.init()
    50  	if err != nil {
    51  		return err
    52  	}
    53  	err = p.Generators.init()
    54  	if err != nil {
    55  		return err
    56  	}
    57  	err = p.APIs.init(p)
    58  	if err != nil {
    59  		return err
    60  	}
    61  	return nil
    62  }
    63  
    64  // Load loads a Project configuration from its YAML representation.
    65  func Load(r io.Reader) (*Project, error) {
    66  	var p Project
    67  	buf, err := ioutil.ReadAll(r)
    68  	if err != nil {
    69  		return nil, fmt.Errorf("failed to read project configuration: %w", err)
    70  	}
    71  	err = yaml.Unmarshal(buf, &p)
    72  	if err != nil {
    73  		return nil, fmt.Errorf("failed to unmarshal project configuration: %w", err)
    74  	}
    75  	p.init()
    76  	return &p, p.validate()
    77  }
    78  
    79  // Save saves a Project configuration to YAML.
    80  func Save(w io.Writer, proj *Project) error {
    81  	buf, err := yaml.Marshal(proj)
    82  	if err != nil {
    83  		return err
    84  	}
    85  	_, err = w.Write(buf)
    86  	return err
    87  }