github.com/wrgl/wrgl@v0.14.0/pkg/conf/fs/store.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright © 2022 Wrangle Ltd
     3  
     4  package conffs
     5  
     6  import (
     7  	"fmt"
     8  	"io"
     9  	"os"
    10  	"path/filepath"
    11  
    12  	"github.com/wrgl/wrgl/pkg/conf"
    13  	"gopkg.in/yaml.v3"
    14  )
    15  
    16  type Source int
    17  
    18  const (
    19  	UnspecifiedSource Source = iota
    20  	FileSource
    21  	LocalSource
    22  	GlobalSource
    23  	SystemSource
    24  	AggregateSource
    25  )
    26  
    27  type Store struct {
    28  	rootDir string
    29  	source  Source
    30  	fp      string
    31  }
    32  
    33  func NewStore(rootDir string, source Source, fp string) *Store {
    34  	if fp != "" {
    35  		source = FileSource
    36  	}
    37  	return &Store{
    38  		rootDir: rootDir,
    39  		source:  source,
    40  		fp:      fp,
    41  	}
    42  }
    43  
    44  func (s *Store) readConfig(fp string) (*conf.Config, error) {
    45  	c := &conf.Config{}
    46  	f, err := os.Open(fp)
    47  	if err == nil {
    48  		defer f.Close()
    49  		b, err := io.ReadAll(f)
    50  		if err != nil {
    51  			return nil, err
    52  		}
    53  		err = yaml.Unmarshal(b, c)
    54  		if err != nil {
    55  			return nil, err
    56  		}
    57  	} else if !os.IsNotExist(err) {
    58  		return nil, err
    59  	}
    60  	return c, nil
    61  }
    62  
    63  func (s *Store) Open() (*conf.Config, error) {
    64  	if s.source == AggregateSource {
    65  		return s.aggregateConfig()
    66  	}
    67  	fp, err := s.path()
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  	return s.readConfig(fp)
    72  }
    73  
    74  func (s *Store) Save(c *conf.Config) error {
    75  	if s.source == AggregateSource {
    76  		return fmt.Errorf("attempt to save aggregated config")
    77  	}
    78  	fp, err := s.path()
    79  	if err != nil {
    80  		return err
    81  	}
    82  	if fp == "" {
    83  		return fmt.Errorf("empty config path")
    84  	}
    85  	err = os.MkdirAll(filepath.Dir(fp), 0755)
    86  	if err != nil {
    87  		return err
    88  	}
    89  	f, err := os.OpenFile(fp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
    90  	if err != nil {
    91  		return err
    92  	}
    93  	defer f.Close()
    94  
    95  	enc := yaml.NewEncoder(f)
    96  	defer enc.Close()
    97  	enc.SetIndent(2)
    98  	return enc.Encode(c)
    99  }