github.com/daixiang0/gci@v0.13.0/pkg/config/config.go (about) 1 package config 2 3 import ( 4 "sort" 5 "strings" 6 7 "gopkg.in/yaml.v3" 8 9 "github.com/daixiang0/gci/pkg/section" 10 ) 11 12 var defaultOrder = map[string]int{ 13 section.StandardType: 0, 14 section.DefaultType: 1, 15 section.CustomType: 2, 16 section.BlankType: 3, 17 section.DotType: 4, 18 section.AliasType: 5, 19 section.LocalModuleType: 6, 20 } 21 22 type BoolConfig struct { 23 NoInlineComments bool `yaml:"no-inlineComments"` 24 NoPrefixComments bool `yaml:"no-prefixComments"` 25 Debug bool `yaml:"-"` 26 SkipGenerated bool `yaml:"skipGenerated"` 27 SkipVendor bool `yaml:"skipVendor"` 28 CustomOrder bool `yaml:"customOrder"` 29 } 30 31 type Config struct { 32 BoolConfig 33 Sections section.SectionList 34 SectionSeparators section.SectionList 35 } 36 37 type YamlConfig struct { 38 Cfg BoolConfig `yaml:",inline"` 39 SectionStrings []string `yaml:"sections"` 40 SectionSeparatorStrings []string `yaml:"sectionseparators"` 41 } 42 43 func (g YamlConfig) Parse() (*Config, error) { 44 var err error 45 46 sections, err := section.Parse(g.SectionStrings) 47 if err != nil { 48 return nil, err 49 } 50 if sections == nil { 51 sections = section.DefaultSections() 52 } 53 if err := configureSections(sections); err != nil { 54 return nil, err 55 } 56 57 // if default order sorted sections 58 if !g.Cfg.CustomOrder { 59 sort.Slice(sections, func(i, j int) bool { 60 sectionI, sectionJ := sections[i].Type(), sections[j].Type() 61 62 if strings.Compare(sectionI, sectionJ) == 0 { 63 return strings.Compare(sections[i].String(), sections[j].String()) < 0 64 } 65 return defaultOrder[sectionI] < defaultOrder[sectionJ] 66 }) 67 } 68 69 sectionSeparators, err := section.Parse(g.SectionSeparatorStrings) 70 if err != nil { 71 return nil, err 72 } 73 if sectionSeparators == nil { 74 sectionSeparators = section.DefaultSectionSeparators() 75 } 76 77 return &Config{g.Cfg, sections, sectionSeparators}, nil 78 } 79 80 func ParseConfig(in string) (*Config, error) { 81 config := YamlConfig{} 82 83 err := yaml.Unmarshal([]byte(in), &config) 84 if err != nil { 85 return nil, err 86 } 87 88 gciCfg, err := config.Parse() 89 if err != nil { 90 return nil, err 91 } 92 93 return gciCfg, nil 94 } 95 96 func configureSections(sections section.SectionList) error { 97 for _, sec := range sections { 98 switch s := sec.(type) { 99 case *section.LocalModule: 100 if err := s.Configure(); err != nil { 101 return err 102 } 103 } 104 } 105 return nil 106 }