Example #1
0
// 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
}