// Simple example always updates the config when file changes are detected. func simple(parser *args.ArgParser) args.WatchCancelFunc { // Get our current config appConf := parser.GetOpts() configFile := appConf.String("config-file") // Watch the file every time.Second and call func(err error){} when the file is modified cancelWatch, err := args.WatchFile(configFile, time.Second, func(err error) { if err != nil { fmt.Printf("Watch Error %s\n", err.Error()) return } // You can safely ignore the returned Options{} object here. // the next call to GetOpts() from within the handler will // pick up the newly parsed config appConf, err = parser.FromINIFile(configFile) if err != nil { fmt.Printf("Failed to load updated config - %s\n", err.Error()) return } }) if err != nil { fmt.Printf("Unable to start watch '%s' - %s", configFile, err.Error()) } return cancelWatch }
// The complex example allows a user to write the config file multiple times, possibly applying edits incrementally. // When the user is ready for the application to apply the config changes, modify the 'version' value and the // new config is applied. func complex(parser *args.ArgParser) args.WatchCancelFunc { // Get our current config appConf := parser.GetOpts() configFile := appConf.String("config-file") // Watch the file every time.Second and call func(err error){} when the file is modified cancelWatch, err := args.WatchFile(configFile, time.Second, func(err error) { if err != nil { fmt.Printf("Watch Error %s\n", err.Error()) return } // load the file from disk content, err := args.LoadFile(configFile) if err != nil { fmt.Printf("Failed to load config - %s\n", err.Error()) } // Parse the file contents newConfig, err := parser.ParseINI(content) if err != nil { fmt.Printf("Failed to update config - %s\n", err.Error()) return } // Only "Apply" the newConfig when the version changes if appConf.Int("version") != newConfig.Int("version") { // Apply the newConfig values to the parser rules appConf, err = parser.Apply(newConfig) if err != nil { fmt.Printf("Probably a type cast error - %s\n", err.Error()) return } } }) if err != nil { log.Fatal(fmt.Sprintf("Failed to watch '%s' - %s", configFile, err.Error())) } return cancelWatch }
// Load the INI file content, err := args.LoadFile(iniFile.Name()) if err != nil { Fail(err.Error()) } // Parse the ini file opt, err = parser.FromINI(content) Expect(err).To(BeNil()) Expect(log.GetEntry()).To(Equal("")) Expect(opt.String("value")).To(Equal("my-value")) Expect(opt.Int("version")).To(Equal(1)) done := make(chan struct{}) cancelWatch, err := args.WatchFile(iniFile.Name(), time.Second, func(err error) { parser.FromINIFile(iniFile.Name()) // Tell the test to continue, Change event was handled close(done) }) if err != nil { Fail(err.Error()) } if err := saveFile(iniFile.Name(), iniVersion2); err != nil { Fail(err.Error()) } // Wait until the new file was loaded <-done // Stop the watch cancelWatch() // Get the updated options opts := parser.GetOpts()