github.com/joshdk/godel@v0.0.0-20170529232908-862138a45aee/apps/gonform/config/config.go (about) 1 // Copyright 2016 Palantir Technologies, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package config 16 17 import ( 18 "encoding/json" 19 "io/ioutil" 20 21 "github.com/palantir/pkg/matcher" 22 "github.com/pkg/errors" 23 "gopkg.in/yaml.v2" 24 25 "github.com/palantir/godel/apps/gonform/params" 26 ) 27 28 type Gonform struct { 29 // Formatters specifies the configuration used by the formatters. The key is the name of the formatter and the 30 // value is the custom configuration for that formatter. 31 Formatters map[string]Formatter `yaml:"formatters" json:"formatters"` 32 33 // Exclude specifies the files that should be excluded from formatting. 34 Exclude matcher.NamesPathsCfg `yaml:"exclude" json:"exclude"` 35 } 36 37 type Formatter struct { 38 // Args specifies the command-line arguments that are provided to the formatter. 39 Args []string `yaml:"args" json:"args"` 40 } 41 42 func (r *Gonform) ToParams() params.Formatters { 43 m := make(map[string]params.Formatter, len(r.Formatters)) 44 for k, v := range r.Formatters { 45 m[k] = v.ToParams() 46 } 47 return params.Formatters{ 48 Formatters: m, 49 Exclude: r.Exclude.Matcher(), 50 } 51 } 52 53 func (r *Formatter) ToParams() params.Formatter { 54 return params.Formatter{ 55 Args: r.Args, 56 } 57 } 58 59 func Load(cfgPath, jsonContent string) (params.Formatters, error) { 60 var yml []byte 61 if cfgPath != "" { 62 var err error 63 yml, err = ioutil.ReadFile(cfgPath) 64 if err != nil { 65 return params.Formatters{}, errors.Wrapf(err, "failed to read file %s", cfgPath) 66 } 67 } 68 cfg, err := LoadRawConfig(string(yml), jsonContent) 69 if err != nil { 70 return params.Formatters{}, err 71 } 72 return cfg.ToParams(), nil 73 } 74 75 func LoadRawConfig(ymlContent, jsonContent string) (Gonform, error) { 76 cfg := Gonform{} 77 if ymlContent != "" { 78 if err := yaml.Unmarshal([]byte(ymlContent), &cfg); err != nil { 79 return Gonform{}, errors.Wrapf(err, "failed to unmarshal YML %s", ymlContent) 80 } 81 } 82 if jsonContent != "" { 83 jsonCfg := Gonform{} 84 if err := json.Unmarshal([]byte(jsonContent), &jsonCfg); err != nil { 85 return Gonform{}, err 86 } 87 cfg.Exclude.Add(jsonCfg.Exclude) 88 } 89 return cfg, nil 90 }