package main import ( "io/ioutil" "github.com/urfave/cli/v2" "gopkg.in/yaml.v3" ) var DefaultConfigFile = ".drone.yml" func Init(c *cli.Context) error { // 读取配置 configFileName := c.String("config") if configFileName != "" { DefaultConfigFile = configFileName } if err := ReadConfig(); err != nil { return err } appList := c.Args().Slice() config.HasApi = config.Api.HasApp(appList) config.HasService = config.Service.HasApp(appList) return nil } type Config struct { Kind string `json:"kind" yaml:"kind"` Type string `json:"type" yaml:"type"` Name string `json:"name" yaml:"name"` Api ApiList `json:"api" yaml:"api"` Service ServiceList `json:"service" yaml:"service"` HasApi ApiList `json:"-" yaml:"-"` HasService ServiceList `json:"-" yaml:"-"` } type ( ApiList []Api Api struct { Name string `json:"name" yaml:"name"` Root string `json:"root" yaml:"root"` Type string `json:"type" yaml:"type"` Port string `json:"port" yaml:"port"` Host string `json:"host,omitempty" yaml:"host,omitempty"` Path string `json:"path,omitempty" yaml:"path,omitempty"` } ) type ( ServiceList []Service Service struct { Name string `json:"name" yaml:"name"` Root string `json:"root" yaml:"root"` Type string `json:"type" yaml:"type"` Port string `json:"port" yaml:"port"` } ) var config Config func ReadConfig() error { configFile, err := ioutil.ReadFile(DefaultConfigFile) if err != nil { return err } err = yaml.Unmarshal(configFile, &config) if err != nil { return err } return nil } func (al ApiList) HasApp(appNameList []string) ApiList { if len(appNameList) == 0 { return al } hasApp := make(ApiList, 0, len(al)) al: for _, api := range al { for _, a := range appNameList { if a == api.Name { hasApp = append(hasApp, api) continue al } } } return hasApp } func (sl ServiceList) HasApp(appNameList []string) ServiceList { if len(appNameList) == 0 { return sl } hasApp := make(ServiceList, 0, len(sl)) sl: for _, service := range sl { for _, a := range appNameList { if a == service.Name { hasApp = append(hasApp, service) continue sl } } } return hasApp }