Пример #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
}
Пример #2
0
		Expect(opt.String("value")).To(Equal(""))
		Expect(opt.Int("version")).To(Equal(0))

		iniFile, err = ioutil.TempFile("/tmp", "args-test")
		if err != nil {
			Fail(err.Error())
		}
		defer os.Remove(iniFile.Name())

		// Write version 1 of the ini file
		if err := saveFile(iniFile.Name(), iniVersion1); err != nil {
			Fail(err.Error())
		}

		// 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)