github.com/mook-as/cf-cli@v7.0.0-beta.28.0.20200120190804-b91c115fae48+incompatible/util/configv3/write_config.go (about) 1 package configv3 2 3 import ( 4 "encoding/json" 5 "io/ioutil" 6 "os" 7 "os/signal" 8 "syscall" 9 ) 10 11 // WriteConfig creates the .cf directory and then writes the config.json. The 12 // location of .cf directory is written in the same way LoadConfig reads .cf 13 // directory. 14 func (c *Config) WriteConfig() error { 15 rawConfig, err := json.MarshalIndent(c.ConfigFile, "", " ") 16 if err != nil { 17 return err 18 } 19 20 dir := configDirectory() 21 err = os.MkdirAll(dir, 0700) 22 if err != nil { 23 return err 24 } 25 26 // Developer Note: The following is untested! Change at your own risk. 27 // Setup notifications of termination signals to channel sig, create a process to 28 // watch for these signals so we can remove transient config temp files. 29 sig := make(chan os.Signal, 10) 30 signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM, os.Interrupt) 31 defer signal.Stop(sig) 32 33 tempConfigFile, err := ioutil.TempFile(dir, "temp-config") 34 if err != nil { 35 return err 36 } 37 tempConfigFile.Close() 38 tempConfigFileName := tempConfigFile.Name() 39 40 go catchSignal(sig, tempConfigFileName) 41 42 err = ioutil.WriteFile(tempConfigFileName, rawConfig, 0600) 43 if err != nil { 44 return err 45 } 46 47 return os.Rename(tempConfigFileName, ConfigFilePath()) 48 } 49 50 // catchSignal tries to catch SIGHUP, SIGINT, SIGKILL, SIGQUIT and SIGTERM, and 51 // Interrupt for removing temporarily created config files before the program 52 // ends. Note: we cannot intercept a `kill -9`, so a well-timed `kill -9` 53 // will allow a temp config file to linger. 54 func catchSignal(sig chan os.Signal, tempConfigFileName string) { 55 <-sig 56 _ = os.Remove(tempConfigFileName) 57 os.Exit(2) 58 }