-
Notifications
You must be signed in to change notification settings - Fork 13
/
write.go
53 lines (43 loc) · 1.01 KB
/
write.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2019 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package configuration
import (
"encoding/json"
"fmt"
"os"
"strings"
)
// Save - update configuration file with current data
func Save(filename string, configuration *Configuration) error {
tempFile := filename + ".new"
previousFile := filename + ".bk"
os.Remove(tempFile)
f, err := os.Create(tempFile)
if nil != err {
fmt.Printf("Create file fail: %s\n", err)
return err
}
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
err = enc.Encode(configuration)
if nil != err {
f.Close()
return err
}
f.Close()
err = os.Remove(previousFile)
if nil != err && !strings.Contains(err.Error(), "no such file") {
return err
}
err = os.Rename(filename, previousFile)
if nil != err && !strings.Contains(err.Error(), "no such file") {
return err
}
err = os.Rename(tempFile, filename)
if nil != err {
return err
}
return nil
}