github.com/josephspurrier/go-swagger@v0.2.1-0.20221129144919-1f672a142a00/generator/config.go (about)

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