NewFromFile returns a new Config from the specified YAML file.
(rootDir string, cfgFilename string)
| 69 | |
| 70 | // NewFromFile returns a new Config from the specified YAML file. |
| 71 | func NewFromFile(rootDir string, cfgFilename string) (*Config, error) { |
| 72 | if !filepath.IsAbs(cfgFilename) { |
| 73 | cfgFilename = filepath.Join(rootDir, cfgFilename) |
| 74 | } |
| 75 | cfgYAML := filepath.Clean(cfgFilename) |
| 76 | cfgBytes, err := os.ReadFile(cfgYAML) // nolint:gosec // false positive |
| 77 | if err != nil { |
| 78 | return nil, err |
| 79 | } |
| 80 | cfg := &Config{} |
| 81 | if err = yaml.Unmarshal(cfgBytes, cfg); err != nil { |
| 82 | return nil, err |
| 83 | } |
| 84 | |
| 85 | cfg.ConfigYAML = cfgYAML |
| 86 | cfg.EntriesDir = makeAbs(rootDir, cfg.EntriesDir, DefaultEntriesDir) |
| 87 | cfg.TemplateYAML = makeAbs(rootDir, cfg.TemplateYAML, filepath.Join(DefaultEntriesDir, DefaultTemplateYAML)) |
| 88 | |
| 89 | if err = validateChangeTypes(cfg.ChangeTypes); err != nil { |
| 90 | return nil, err |
| 91 | } |
| 92 | |
| 93 | if len(cfg.ChangeLogs) == 0 && len(cfg.DefaultChangeLogs) > 0 { |
| 94 | return nil, errors.New("cannot specify 'default_change_logs' without 'change_logs'") |
| 95 | } |
| 96 | |
| 97 | if len(cfg.ChangeLogs) == 0 { |
| 98 | // 'change_logs' was omitted; initialize the map before writing the default |
| 99 | // (yaml.Unmarshal leaves it nil when the key is absent). |
| 100 | cfg.ChangeLogs = map[string]string{ |
| 101 | DefaultChangeLogKey: filepath.Join(rootDir, DefaultChangeLogFilename), |
| 102 | } |
| 103 | cfg.DefaultChangeLogs = []string{DefaultChangeLogKey} |
| 104 | return cfg, nil |
| 105 | } |
| 106 | |
| 107 | // The user specified at least one changelog. Interpret filename as a relative path from rootDir |
| 108 | // (unless they specified an absolute path including rootDir) |
| 109 | for key, filename := range cfg.ChangeLogs { |
| 110 | if !filepath.IsAbs(filename) { |
| 111 | cfg.ChangeLogs[key] = filepath.Join(rootDir, filename) |
| 112 | } |
| 113 | cfg.ChangeLogs[key] = filepath.Clean(cfg.ChangeLogs[key]) |
| 114 | } |
| 115 | |
| 116 | for _, key := range cfg.DefaultChangeLogs { |
| 117 | if _, ok := cfg.ChangeLogs[key]; !ok { |
| 118 | return nil, fmt.Errorf("'default_change_logs' contains key %q which is not defined in 'change_logs'", key) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | return cfg, nil |
| 123 | } |
| 124 | |
| 125 | // validateChangeTypes fails fast on a malformed 'change_types' configuration: |
| 126 | // empty keys or headings, or duplicate keys. An empty list is valid (the |