github.com/go-swagger/go-swagger@v0.31.0/generator/config.go (about)

     1  package generator
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/spf13/viper"
    10  )
    11  
    12  // LanguageDefinition in the configuration file.
    13  type LanguageDefinition struct {
    14  	Layout SectionOpts `mapstructure:"layout"`
    15  }
    16  
    17  // ConfigureOpts for generation
    18  func (d *LanguageDefinition) ConfigureOpts(opts *GenOpts) error {
    19  	opts.Sections = d.Layout
    20  	if opts.LanguageOpts == nil {
    21  		opts.LanguageOpts = GoLangOpts()
    22  	}
    23  	return nil
    24  }
    25  
    26  // LanguageConfig structure that is obtained from parsing a config file
    27  type LanguageConfig map[string]LanguageDefinition
    28  
    29  // ReadConfig at the specified path, when no path is specified it will look into
    30  // the current directory and load a .swagger.{yml,json,hcl,toml,properties} file
    31  // Returns a viper config or an error
    32  func ReadConfig(fpath string) (*viper.Viper, error) {
    33  	v := viper.New()
    34  	if fpath != "" {
    35  		if !fileExists(fpath, "") {
    36  			return nil, fmt.Errorf("can't find file for %q", fpath)
    37  		}
    38  		file, err := os.Open(fpath)
    39  		if err != nil {
    40  			return nil, err
    41  		}
    42  		defer func() { _ = file.Close() }()
    43  		ext := filepath.Ext(fpath)
    44  		if len(ext) > 0 {
    45  			ext = ext[1:]
    46  		}
    47  		v.SetConfigType(ext)
    48  		if err := v.ReadConfig(file); err != nil {
    49  			return nil, err
    50  		}
    51  		return v, nil
    52  	}
    53  
    54  	v.SetConfigName(".swagger")
    55  	v.AddConfigPath(".")
    56  	if err := v.ReadInConfig(); err != nil {
    57  		var e viper.UnsupportedConfigError
    58  		if !errors.As(err, &e) && v.ConfigFileUsed() != "" {
    59  			return nil, err
    60  		}
    61  	}
    62  	return v, nil
    63  }