1// Copyright 2020 Google LLC 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// https://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15// Package config reads and writes hacksaw configuration data to io 16package config 17 18import ( 19 "encoding/json" 20 "io" 21 "io/ioutil" 22 "os" 23 "sync" 24) 25 26type Config struct { 27 DefaultCodebase string 28 Codebases map[string]string //key: name, value: path 29 Workspaces map[string]string //key: name, value: codebase 30} 31 32//Read the configuration from an io.Reader 33func (c *Config) Read(input io.Reader) error { 34 cfgBytes, err := ioutil.ReadAll(input) 35 if err != nil { 36 return err 37 } 38 return json.Unmarshal(cfgBytes, &c) 39} 40 41//Write the configuration to an io.Writer 42func (c Config) Write(output io.Writer) error { 43 cfgBytes, err := json.MarshalIndent(c, "", " ") 44 if err != nil { 45 return err 46 } 47 _, err = output.Write(cfgBytes) 48 return err 49} 50 51func (c *Config) ReadConfigFromFile(filePath string) error { 52 _, err := os.Stat(filePath) 53 if err != nil { 54 return err 55 } 56 cfgFile, err := os.Open(filePath) 57 if err != nil { 58 return err 59 } 60 defer cfgFile.Close() 61 err = c.Read(cfgFile) 62 return err 63} 64 65func (c Config) WriteConfigToFile(filePath string) error { 66 cfgFile, err := os.Create(filePath) 67 if err != nil { 68 return err 69 } 70 defer cfgFile.Close() 71 return c.Write(cfgFile) 72} 73 74//Config gets a copy of the config 75func (c Config) Copy() Config { 76 cfgCopy := Config{ 77 DefaultCodebase: c.DefaultCodebase, 78 Codebases: map[string]string{}, 79 Workspaces: map[string]string{}} 80 for name, path := range c.Codebases { 81 cfgCopy.Codebases[name] = path 82 } 83 for name, codebase := range c.Workspaces { 84 cfgCopy.Workspaces[name] = codebase 85 } 86 return cfgCopy 87} 88 89//Reset sets the config to zero values 90func (c *Config) Reset() { 91 *c = Config{ 92 DefaultCodebase: "", 93 Codebases: map[string]string{}, 94 Workspaces: map[string]string{}} 95} 96 97var singleton *Config 98var once sync.Once 99 100//Config gets the singleton config instance 101func GetConfig() *Config { 102 once.Do(func() { 103 singleton = &Config{ 104 DefaultCodebase: "", 105 Codebases: map[string]string{}, 106 Workspaces: map[string]string{}} 107 }) 108 return singleton 109} 110