From d6cba44b604b3e744b5076fe5cbff192e0262444 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Wed, 15 Mar 2023 00:53:26 +0300 Subject: [PATCH] allow to override Struct on Save/Load/Init Signed-off-by: Vasiliy Tolstov --- flag.go | 48 +++++++++++++++++++++++++++++++++++++++++++++--- go.mod | 4 +++- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/flag.go b/flag.go index a98e11d..b89a278 100644 --- a/flag.go +++ b/flag.go @@ -43,11 +43,24 @@ func (c *flagConfig) Init(opts ...config.Option) error { for _, o := range opts { o(&c.opts) } + + if err := config.DefaultBeforeInit(c.opts.Context, c); err != nil && !c.opts.AllowFail { + return err + } + c.configure() fields, err := rutil.StructFields(c.opts.Struct) if err != nil { - return err + if !c.opts.AllowFail { + return err + } + + if err := config.DefaultAfterInit(c.opts.Context, c); err != nil && !c.opts.AllowFail { + return err + } + + return nil } for _, sf := range fields { @@ -84,10 +97,13 @@ func (c *flagConfig) Init(opts ...config.Option) error { } if err != nil { - c.opts.Logger.Errorf(c.opts.Context, "flag init error: %v", err) if !c.opts.AllowFail { return err } + if err := config.DefaultAfterInit(c.opts.Context, c); err != nil && !c.opts.AllowFail { + return err + } + return nil } @@ -120,26 +136,52 @@ func (c *flagConfig) Init(opts ...config.Option) error { err = c.flagMap(sf.Value, fn, fv, fd) } if err != nil { - c.opts.Logger.Errorf(c.opts.Context, "flag init error: %v", err) if !c.opts.AllowFail { return err } + + if err := config.DefaultAfterInit(c.opts.Context, c); err != nil && !c.opts.AllowFail { + return err + } + return nil } } + if err := config.DefaultAfterInit(c.opts.Context, c); err != nil && !c.opts.AllowFail { + return err + } + return nil } func (c *flagConfig) Load(ctx context.Context, opts ...config.LoadOption) error { options := config.NewLoadOptions(opts...) _ = options + + if err := config.DefaultBeforeLoad(ctx, c); err != nil && !c.opts.AllowFail { + return err + } + + if err := config.DefaultAfterLoad(ctx, c); err != nil && !c.opts.AllowFail { + return err + } + // TODO: allow merge, append and so flag.Parse() + return nil } func (c *flagConfig) Save(ctx context.Context, opts ...config.SaveOption) error { + if err := config.DefaultBeforeSave(ctx, c); err != nil && !c.opts.AllowFail { + return err + } + + if err := config.DefaultAfterSave(ctx, c); err != nil && !c.opts.AllowFail { + return err + } + return nil } diff --git a/go.mod b/go.mod index 4e9709f..19bf822 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,7 @@ module go.unistack.org/micro-config-flag/v3 -go 1.16 +go 1.18 require go.unistack.org/micro/v3 v3.10.16 + +require github.com/imdario/mergo v0.3.13 // indirect