namsral/flag

using config file by default

amitu opened this issue · 6 comments

amitu commented

I always need a config file, and the location of config file is known. I tried setting the config param default value to point to that file, but this package is not looking at it unless I specify the flag again on the command line.

flag.String("config", "settings.conf", "help message for config")

This to me is a bug. Default values are precisely that: default unless over-ridden by command line.

I agree, this is unexpected behaviour and therefore a bug.

Can you confirm d6e73b7 from the parse-default-config-file branch fixes your issue?

amitu commented

It does. Kind of. Problem: If the setting file is missing, it goes through without complaining.

Please try 71ceffb.

I was going for mainstream cli behaviour; traverse common config paths and silently fail when none are available but that would be out of the scope of this project.

amitu commented

In this case 1. it picks up the file if present, 2. it fails if such file is not present (without any error message), and 3. does not allow me to overwrite config file from command line (it does not show --config as option with I do -h).

Create a new FlagSet when you want to catch the error, working example:

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/namsral/flag"
)

func main() {
	var (
		age    int
		config string
	)

	f := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
	f.IntVar(&age, "age", 0, "age value")
	f.StringVar(&config, flag.DefaultConfigFlagname, "gopher.conf", "path to config file")
	if err := f.Parse(os.Args[1:]); err != nil {
		log.Fatal(err)
	}

	fmt.Print("age:", age)
}
amitu commented

This works exactly how I want. Thanks :-)