github.com/davidmanzanares/dsd@v0.1.2-0.20210106152357-a35988f5d245/dsdl/config.go (about)

     1  package dsdl
     2  
     3  import (
     4  	"crypto/rand"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"strings"
     9  )
    10  
    11  // Config is a set of targets
    12  type Config struct {
    13  	Targets map[string]*Target
    14  }
    15  
    16  // Target is a combination of an alias name to deploy,
    17  // a provider service,
    18  // and a list of glob patterns
    19  type Target struct {
    20  	Name     string `json:"-"`
    21  	Service  string
    22  	Patterns []string
    23  }
    24  
    25  // AddTarget loads the config from the default path, adds the new target, and saves the new config file
    26  func AddTarget(target Target) error {
    27  	conf, _ := LoadConfig()
    28  	conf.Targets[target.Name] = &target
    29  	return SaveConfig(conf)
    30  }
    31  
    32  func (t Target) String() string {
    33  	var patterns []string
    34  	for _, p := range t.Patterns {
    35  		patterns = append(patterns, `"`+p+`"`)
    36  	}
    37  	return fmt.Sprintf("\"%s\" (%s) {%s}", t.Name, t.Service, strings.Join(patterns, ", "))
    38  }
    39  
    40  // LoadConfig loads the config from the default path
    41  func LoadConfig() (Config, error) {
    42  	var conf Config
    43  	conf.Targets = make(map[string]*Target)
    44  	buffer, err := ioutil.ReadFile(".dsd.json")
    45  	if err != nil {
    46  		return conf, err
    47  	}
    48  	err = json.Unmarshal(buffer, &conf)
    49  	for k := range conf.Targets {
    50  		conf.Targets[k].Name = k
    51  	}
    52  	if err != nil {
    53  		return conf, err
    54  	}
    55  	return conf, nil
    56  }
    57  
    58  // SaveConfig saves conf on the default path
    59  func SaveConfig(conf Config) error {
    60  	buffer, err := json.MarshalIndent(conf, "", "\t")
    61  	if err != nil {
    62  		return err
    63  	}
    64  	ioutil.WriteFile(".dsd.json", buffer, 0660)
    65  	return nil
    66  }
    67  
    68  func uid() []byte {
    69  	buff := make([]byte, 8)
    70  	rand.Read(buff)
    71  	return buff
    72  }