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.
()
| 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 := os.CreateTemp(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 = os.WriteFile(tempConfigFileName, rawConfig, 0600) |
| 43 | if err != nil { |
| 44 | return err |
| 45 | } |
| 46 | |
| 47 | for i := 0; i < 5; i++ { |
| 48 | if err := os.Rename(tempConfigFileName, ConfigFilePath()); err == nil { |
| 49 | return nil |
| 50 | } |
| 51 | |
| 52 | time.Sleep(50 * time.Millisecond) |
| 53 | } |
| 54 | |
| 55 | return os.Rename(tempConfigFileName, ConfigFilePath()) |
| 56 | } |
| 57 | |
| 58 | // catchSignal tries to catch SIGHUP, SIGINT, SIGKILL, SIGQUIT and SIGTERM, and |
| 59 | // Interrupt for removing temporarily created config files before the program |
nothing calls this directly
no test coverage detected