aconfig icon indicating copy to clipboard operation
aconfig copied to clipboard

Update example for cobra

Open cristaloleg opened this issue 3 years ago • 5 comments

Current version is outdated https://play.golang.org/p/OsCR8qTCN0H

Probably there will be another repository which will contains all the examples with external dependencies for https://github.com/cristalhq libraries, with a CI on cron

cristaloleg avatar Apr 23 '21 08:04 cristaloleg

[update] The following example works, for a new playground link.

package main

import (
	"os"

	"github.com/cristalhq/aconfig"
	"github.com/spf13/cobra"
)

type MyConfig struct {
	User string `usage:"user of the app" default:"john"`
}

func main() {
	var cfg MyConfig
	loader := aconfig.LoaderFor(&cfg, aconfig.Config{})
	args := struct {
		logLevel string
	}{}
	cmd := &cobra.Command{
		Use: "hello",
		RunE: func(cmd *cobra.Command, _ []string) error {
			if err := loader.Load(); err != nil {
				return err
			}

			cmd.Printf("Hello World, %s!", cfg.User)
			return nil
		},
	}
	cmd.PersistentFlags().AddGoFlagSet(loader.Flags())
	cmd.PersistentFlags().StringVar(&args.logLevel, "log-level", "info", "log level: debug, info, warning")

	if err := cmd.Execute(); err != nil {
		os.Exit(1)
	}
}

abh avatar Apr 23 '22 10:04 abh

Oh, great! Link: https://go.dev/play/p/zyXtrtL7NBu

Do you want to make a PR ? 😄 (if so, I have started adding GUIDE.md file such things, see example https://github.com/cristalhq/acmd/blob/main/GUIDE.md + link to the guide in readme.md) and if no - I will add it a bit later.

Thank you once more.

cristaloleg avatar Apr 23 '22 10:04 cristaloleg

I didn't make a PR because the thing I posted compiles and works, but outside the example it doesn't work super great having the configuration data and the command line arguments separated.

abh avatar May 29 '22 05:05 abh

Can you clarify what is exactly not ok?

cristaloleg avatar May 29 '22 06:05 cristaloleg

@cristaloleg I might be missing something, but with the cobra integration the configuration gets loaded into the aconfig "system", but the parameters get loaded into the cobra parameter system.

For my use case I'd like just the aconfig system and to ignore the cobra stuff except for integration in the help text, etc.

abh avatar Jun 04 '22 16:06 abh