github.com/octohelm/cuemod@v0.9.4/pkg/cuemod/options.go (about)

     1  package cuemod
     2  
     3  import "context"
     4  
     5  type Opts struct {
     6  	Upgrade bool
     7  	Verbose bool
     8  	Import  string
     9  }
    10  
    11  type OptFn = func(o *Opts)
    12  
    13  func OptUpgrade(b bool) OptFn {
    14  	return func(o *Opts) {
    15  		o.Upgrade = b
    16  	}
    17  }
    18  
    19  func OptImport(b string) OptFn {
    20  	return func(o *Opts) {
    21  		o.Import = b
    22  	}
    23  }
    24  
    25  func OptVerbose(v bool) OptFn {
    26  	return func(o *Opts) {
    27  		o.Verbose = v
    28  	}
    29  }
    30  
    31  type contextKeyForOpts int
    32  
    33  func OptsFromContext(ctx context.Context) Opts {
    34  	if o, ok := ctx.Value(contextKeyForOpts(0)).(Opts); ok {
    35  		return o
    36  	}
    37  	return Opts{}
    38  }
    39  
    40  func WithOpts(ctx context.Context, fns ...OptFn) context.Context {
    41  	o := OptsFromContext(ctx)
    42  
    43  	for _, fn := range fns {
    44  		if fn != nil {
    45  			fn(&o)
    46  		}
    47  	}
    48  
    49  	return context.WithValue(ctx, contextKeyForOpts(0), o)
    50  }