...

Source file src/github.com/prometheus/alertmanager/cli/config/config.go

Documentation: github.com/prometheus/alertmanager/cli/config

     1  // Copyright 2018 Prometheus Team
     2  // Licensed under the Apache License, Version 2.0 (the "License");
     3  // you may not use this file except in compliance with the License.
     4  // You may obtain a copy of the License at
     5  //
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package config
    15  
    16  import (
    17  	"os"
    18  
    19  	"gopkg.in/alecthomas/kingpin.v2"
    20  	"gopkg.in/yaml.v2"
    21  )
    22  
    23  type getFlagger interface {
    24  	GetFlag(name string) *kingpin.FlagClause
    25  }
    26  
    27  // Resolver represents a configuration file resolver for kingpin.
    28  type Resolver struct {
    29  	flags map[string]string
    30  }
    31  
    32  // NewResolver returns a Resolver structure.
    33  func NewResolver(files []string, legacyFlags map[string]string) (*Resolver, error) {
    34  	flags := map[string]string{}
    35  	for _, f := range files {
    36  		if _, err := os.Stat(f); err != nil {
    37  			continue
    38  		}
    39  		b, err := os.ReadFile(f)
    40  		if err != nil {
    41  			if os.IsNotExist(err) {
    42  				continue
    43  			}
    44  			return nil, err
    45  		}
    46  
    47  		var m map[string]string
    48  		err = yaml.Unmarshal(b, &m)
    49  		if err != nil {
    50  			return nil, err
    51  		}
    52  		for k, v := range m {
    53  			if flag, ok := legacyFlags[k]; ok {
    54  				if _, ok := m[flag]; ok {
    55  					continue
    56  				}
    57  				k = flag
    58  			}
    59  			if _, ok := flags[k]; !ok {
    60  				flags[k] = v
    61  			}
    62  		}
    63  	}
    64  
    65  	return &Resolver{flags: flags}, nil
    66  }
    67  
    68  func (c *Resolver) setDefault(v getFlagger) {
    69  	for name, value := range c.flags {
    70  		f := v.GetFlag(name)
    71  		if f != nil {
    72  			f.Default(value)
    73  		}
    74  	}
    75  }
    76  
    77  // Bind sets active flags with their default values from the configuration file(s).
    78  func (c *Resolver) Bind(app *kingpin.Application, args []string) error {
    79  	// Parse the command line arguments to get the selected command.
    80  	pc, err := app.ParseContext(args)
    81  	if err != nil {
    82  		return err
    83  	}
    84  
    85  	c.setDefault(app)
    86  	if pc.SelectedCommand != nil {
    87  		c.setDefault(pc.SelectedCommand)
    88  	}
    89  
    90  	return nil
    91  }
    92  

View as plain text