forked from cloudfoundry-community/cloudfoundry-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
write_config.go
60 lines (51 loc) · 1.63 KB
/
write_config.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
54
55
56
57
58
59
60
package configv3
import (
"encoding/json"
"io/ioutil"
"os"
"os/signal"
"syscall"
)
// WriteConfig creates the .cf directory and then writes the config.json. The
// location of .cf directory is written in the same way LoadConfig reads .cf
// directory.
func WriteConfig(c *Config) error {
rawConfig, err := json.MarshalIndent(c.ConfigFile, "", " ")
if err != nil {
return err
}
dir := configDirectory()
err = os.MkdirAll(dir, 0700)
if err != nil {
return err
}
// Developer Note: The following is untested! Change at your own risk.
// Setup notifications of termination signals to channel sig, create a process to
// watch for these signals so we can remove transient config temp files.
sig := make(chan os.Signal, 10)
signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGKILL, syscall.SIGQUIT, syscall.SIGTERM, os.Interrupt)
defer signal.Stop(sig)
tempConfigFile, err := ioutil.TempFile(dir, "temp-config")
if err != nil {
return err
}
tempConfigFile.Close()
tempConfigFileName := tempConfigFile.Name()
go catchSignal(sig, tempConfigFileName)
err = ioutil.WriteFile(tempConfigFileName, rawConfig, 0600)
if err != nil {
return err
}
return os.Rename(tempConfigFileName, ConfigFilePath())
}
// catchSignal tries to catch SIGHUP, SIGINT, SIGKILL, SIGQUIT and SIGTERM, and
// Interrupt for removing temporarily created config files before the program
// ends. Note: we cannot intercept a `kill -9`, so a well-timed `kill -9`
// will allow a temp config file to linger.
func catchSignal(sig chan os.Signal, tempConfigFileName string) {
select {
case <-sig:
_ = os.Remove(tempConfigFileName)
os.Exit(2)
}
}