github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/easy/yamlx/options.go (about)

     1  package yamlx
     2  
     3  // Option customizes the behavior of the extended YAML parser.
     4  type Option struct {
     5  	apply func(*extOptions)
     6  }
     7  
     8  type extOptions struct {
     9  	EnableEnv     bool
    10  	EnableInclude bool
    11  	IncludeDirs   []string
    12  	FuncMap       FuncMap
    13  }
    14  
    15  func (o *extOptions) apply(opts ...Option) *extOptions {
    16  	for _, opt := range opts {
    17  		opt.apply(o)
    18  	}
    19  	return o
    20  }
    21  
    22  // EnableEnv enables reading environment variables.
    23  // By default, it is disabled for security considerations.
    24  func EnableEnv() Option {
    25  	return Option{
    26  		apply: func(options *extOptions) {
    27  			options.EnableEnv = true
    28  		}}
    29  }
    30  
    31  // EnableInclude enables including other files.
    32  // By default, it is disabled for security considerations.
    33  func EnableInclude() Option {
    34  	return Option{
    35  		apply: func(options *extOptions) {
    36  			options.EnableInclude = true
    37  		}}
    38  }
    39  
    40  // WithIncludeDirs optionally specifies the directories to find include files.
    41  // By default, the current working directory is used to search include files.
    42  func WithIncludeDirs(dirs ...string) Option {
    43  	return Option{
    44  		apply: func(options *extOptions) {
    45  			options.IncludeDirs = dirs
    46  		}}
    47  }
    48  
    49  // FuncMap is the type of the map defining the mapping from names to functions.
    50  // Each function must have either a single return value, or two return values of
    51  // which the second is an error.
    52  // In case the second return value evaluates to a non-nil error during execution,
    53  // the execution terminates and the error will be returned.
    54  type FuncMap map[string]any
    55  
    56  // WithFuncMap specifies additional functions to use with the "@@fn" directive.
    57  func WithFuncMap(funcMap FuncMap) Option {
    58  	return Option{
    59  		apply: func(options *extOptions) {
    60  			options.FuncMap = funcMap
    61  		}}
    62  }