Skip to content

Commit cefe5a4

Browse files
committed
[feature] Generate default config file, if file is missing
1 parent 157bf06 commit cefe5a4

File tree

2 files changed

+25
-15
lines changed

2 files changed

+25
-15
lines changed

internal/app/config/config.go

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ package config
33
import (
44
"github.com/pkg/errors"
55
"gopkg.in/yaml.v2"
6+
"io/ioutil"
67
"os"
8+
"path/filepath"
79
"time"
810
)
911

@@ -103,20 +105,34 @@ func LoadControllerConfig(fileName string) (config Controller, err error) {
103105
if err != nil {
104106
return
105107
}
106-
107-
b, err := readAll(f)
108+
b, err := ioutil.ReadAll(f)
108109
if err != nil {
109110
return
110111
}
111112

112113
err = yaml.Unmarshal(b, &config)
113114
if err != nil {
114-
err = errors.Errorf("Could not unmarshal config file %v. %v", fileName, err)
115+
err = errors.Wrapf(err, "Could not unmarshal config file %v. %v", fileName)
115116
}
116117

117118
return
118119
}
119120

121+
func (c *Controller) WriteTo(fileName string) (err error) {
122+
b, err := yaml.Marshal(c)
123+
if err != nil {
124+
err = errors.Wrapf(err, "Could not marshal config %v", c)
125+
return
126+
}
127+
err = os.MkdirAll(filepath.Dir(fileName), 0755)
128+
if err != nil {
129+
err = errors.Wrapf(err, "Could not create directly for config file: %v", fileName)
130+
return
131+
}
132+
err = ioutil.WriteFile(fileName, b, 0600)
133+
return
134+
}
135+
120136
// DefaultControllerConfig creates a config with default values
121137
func DefaultControllerConfig() (c Controller) {
122138
c.Network.PublishAddress = "224.5.23.1:10003"
@@ -180,15 +196,3 @@ func DefaultControllerConfig() (c Controller) {
180196

181197
return
182198
}
183-
184-
func readAll(f *os.File) ([]byte, error) {
185-
b := make([]byte, 10000)
186-
n, err := f.Read(b)
187-
if err != nil {
188-
return []byte{}, errors.Errorf("Can not read config files: %v", err)
189-
}
190-
if n == len(b) {
191-
return []byte{}, errors.New("Buffer size for reading config file is too small")
192-
}
193-
return b[:n], nil
194-
}

internal/app/controller/controller.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,12 @@ func loadConfig() config.Controller {
202202
cfg, err := config.LoadControllerConfig(configFileName)
203203
if err != nil {
204204
log.Printf("Could not load config: %v", err)
205+
err = cfg.WriteTo(configFileName)
206+
if err != nil {
207+
log.Printf("Failed to write a default config file to %v: %v", configFileName, err)
208+
} else {
209+
log.Println("New default config has been written to ", configFileName)
210+
}
205211
}
206212
return cfg
207213
}

0 commit comments

Comments
 (0)