github.com/erroneousboat/dot@v0.0.0-20170402193747-d2fd504d98ec/config.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"os"
     7  )
     8  
     9  const (
    10  	// name of the file, where the configuration will reside
    11  	ConfigFileName = ".dotconfig"
    12  )
    13  
    14  var (
    15  	PathDotConfig = fmt.Sprintf("%s/%s", HomeDir(), ConfigFileName)
    16  )
    17  
    18  type Config struct {
    19  	// folder where the files that are tracked will reside
    20  	DotPath string `json:"dot_path"`
    21  
    22  	// map with the individual files that are being tracked
    23  	Files map[string]string `json:"files"`
    24  }
    25  
    26  // Constructor for the Config struct
    27  func NewConfig(path string) (*Config, error) {
    28  	c := &Config{}
    29  	err := c.load(path)
    30  	return c, err
    31  }
    32  
    33  // Pointer receiver for the Config struct load the config file
    34  func (c *Config) load(path string) error {
    35  	file, err := os.Open(path)
    36  	if err != nil {
    37  		return err
    38  	}
    39  
    40  	if err := json.NewDecoder(file).Decode(&c); err != nil {
    41  		return err
    42  	}
    43  
    44  	return nil
    45  }
    46  
    47  // Pointer receiver for the config struct that will save the config file
    48  func (c *Config) Save() error {
    49  	// truncate existing file if it exists
    50  	f, err := os.Create(PathDotConfig)
    51  	if err != nil {
    52  		return err
    53  	}
    54  	defer f.Close()
    55  
    56  	b, err := json.MarshalIndent(c, "", "\t")
    57  	if err != nil {
    58  		return err
    59  	}
    60  
    61  	if _, err := f.Write(b); err != nil {
    62  		return err
    63  	}
    64  
    65  	return nil
    66  }