| 1 |
package core |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"fmt" |
| 6 |
"io/fs" |
| 7 |
"os" |
| 8 |
"path/filepath" |
| 9 |
|
| 10 |
"github.com/Masterminds/semver/v3" |
| 11 |
"gopkg.in/yaml.v3" |
| 12 |
) |
| 13 |
|
| 14 |
const ( |
| 15 |
configEnvVar = "CHANGIE_CONFIG_PATH" |
| 16 |
timeFormat string = "20060102-150405" |
| 17 |
|
| 18 |
CreateFileMode os.FileMode = 0644 |
| 19 |
CreateDirMode os.FileMode = 0755 |
| 20 |
|
| 21 |
AutoLevel = "auto" |
| 22 |
MajorLevel = "major" |
| 23 |
MinorLevel = "minor" |
| 24 |
PatchLevel = "patch" |
| 25 |
NoneLevel = "none" |
| 26 |
EmptyLevel = "" |
| 27 |
) |
| 28 |
|
| 29 |
var ConfigPaths []string = []string{ |
| 30 |
".changie.yaml", |
| 31 |
".changie.yml", |
| 32 |
} |
| 33 |
|
| 34 |
var ( |
| 35 |
ErrConfigNotFound = errors.New("no changie config found") |
| 36 |
ErrInvalidAutoLevel = errors.New("auto level must resolve to major, minor, patch or none") |
| 37 |
) |
| 38 |
|
| 39 |
// GetVersions will return, in semver sorted order, all released versions |
| 40 |
type GetVersions func(Config) ([]*semver.Version, error) |
| 41 |
|
| 42 |
// Kind config allows you to customize the options depending on what kind was selected. |
| 43 |
type KindConfig struct { |
| 44 |
// Key is the value used for lookups and file names for kinds. |
| 45 |
// By default it will use label if no key is provided. |
| 46 |
// example: yaml |
| 47 |
// key: feature |
| 48 |
Key string `yaml:"key,omitempty"` |
| 49 |
// Label is the value used in the prompt when selecting a kind. |
| 50 |
// example: yaml |
| 51 |
// label: Feature |
| 52 |
Label string `yaml:"label,omitempty" required:"true"` |
| 53 |
// Format will override the root kind format when building the kind header. |
| 54 |
// example: yaml |
| 55 |
// format: '### {{.Kind}} **Breaking Changes**' |
| 56 |
Format string `yaml:"format,omitempty"` |
| 57 |
// Change format will override the root change format when building changes specific to this kind. |
| 58 |
// example: yaml |
| 59 |
// changeFormat: 'Breaking: {{.Custom.Body}} |
| 60 |
ChangeFormat string `yaml:"changeFormat,omitempty"` |
| 61 |
// Additional choices allows adding choices per kind |
| 62 |
AdditionalChoices []Custom `yaml:"additionalChoices,omitempty"` |
| 63 |
// Post process options when saving a new change fragment specific to this kind. |
| 64 |
Post []PostProcessConfig `yaml:"post,omitempty"` |
| 65 |
// Skip global choices allows skipping the parent choices options. |
| 66 |
SkipGlobalChoices bool `yaml:"skipGlobalChoices,omitempty" default:"false"` |
| 67 |
// Skip body allows skipping the parent body prompt. |
| 68 |
SkipBody bool `yaml:"skipBody,omitempty" default:"false"` |
| 69 |
// Skip global post allows skipping the parent post processing. |
| 70 |
SkipGlobalPost bool `yaml:"skipGlobalPost,omitempty" default:"false"` |
| 71 |
// Auto determines what value to bump when using `batch auto` or `next auto`. |
| 72 |
// Possible values are major, minor, patch or none and the highest one is used if |
| 73 |
// multiple changes are found. none will not bump the version. |
| 74 |
// Only none changes is not a valid bump and will fail to batch. |
| 75 |
// Auto also supports go templates using the change as the template data, so the |
| 76 |
// level can be calculated from custom values. The rendered value must be one of |
| 77 |
// the possible values listed above. |
| 78 |
// example: yaml |
| 79 |
// auto: '{{if eq .Custom.Breaking "Yes"}}major{{else}}patch{{end}}' |
| 80 |
AutoLevel string `yaml:"auto,omitempty" templateType:"Change"` |
| 81 |
} |
| 82 |
|
| 83 |
// KeyOrLabel returns the kind config key if set, otherwise the label |
| 84 |
func (kc *KindConfig) KeyOrLabel() string { |
| 85 |
if kc.Key != "" { |
| 86 |
return kc.Key |
| 87 |
} |
| 88 |
|
| 89 |
return kc.Label |
| 90 |
} |
| 91 |
|
| 92 |
// AutoLevelForChange resolves the auto bump level for the provided change. |
| 93 |
// The auto value supports go templates using the change as the template data, |
| 94 |
// so the level can be derived from custom values. |
| 95 |
func (kc *KindConfig) AutoLevelForChange(cache *TemplateCache, change Change) (string, error) { |
| 96 |
if kc.AutoLevel == "" { |
| 97 |
return EmptyLevel, ErrMissingAutoLevel |
| 98 |
} |
| 99 |
|
| 100 |
level, err := cache.ExecuteString(kc.AutoLevel, change) |
| 101 |
if err != nil { |
| 102 |
return EmptyLevel, err |
| 103 |
} |
| 104 |
|
| 105 |
switch level { |
| 106 |
case MajorLevel, MinorLevel, PatchLevel, NoneLevel: |
| 107 |
return level, nil |
| 108 |
default: |
| 109 |
return EmptyLevel, fmt.Errorf("kind %q wit auto config %q: %w", kc.KeyOrLabel(), kc.AutoLevel, ErrInvalidAutoLevel) |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
// Body config allows you to customize the default body prompt |
| 114 |
type BodyConfig struct { |
| 115 |
// Min length specifies the minimum body length |
| 116 |
MinLength *int64 `yaml:"minLength,omitempty" default:"no min"` |
| 117 |
// Max length specifies the maximum body length |
| 118 |
MaxLength *int64 `yaml:"maxLength,omitempty" default:"no max"` |
| 119 |
// Block allows multiline text inputs for body messages |
| 120 |
UseBlock bool `yaml:"block,omitempty" default:"false"` |
| 121 |
} |
| 122 |
|
| 123 |
func (b BodyConfig) CreateCustom() *Custom { |
| 124 |
customType := CustomString |
| 125 |
if b.UseBlock { |
| 126 |
customType = CustomBlock |
| 127 |
} |
| 128 |
|
| 129 |
return &Custom{ |
| 130 |
Label: "Body", |
| 131 |
Type: customType, |
| 132 |
MinLength: b.MinLength, |
| 133 |
MaxLength: b.MaxLength, |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
func (b BodyConfig) Validate(input string) error { |
| 138 |
c := Custom{ |
| 139 |
Label: "Body", |
| 140 |
Type: CustomString, |
| 141 |
MinLength: b.MinLength, |
| 142 |
MaxLength: b.MaxLength, |
| 143 |
} |
| 144 |
|
| 145 |
return c.Validate(input) |
| 146 |
} |
| 147 |
|
| 148 |
// Configuration options for newlines before and after different elements. |
| 149 |
type NewlinesConfig struct { |
| 150 |
// Add newlines after change fragment |
| 151 |
AfterChange int `yaml:"afterChange,omitempty" default:"0"` |
| 152 |
// Add newlines after the header file in the merged changelog |
| 153 |
AfterChangelogHeader int `yaml:"afterChangelogHeader,omitempty" default:"0"` |
| 154 |
// Add newlines after adding a version to the changelog |
| 155 |
AfterChangelogVersion int `yaml:"afterChangelogVersion,omitempty" default:"0"` |
| 156 |
// Add newlines after component |
| 157 |
AfterComponent int `yaml:"afterComponent,omitempty" default:"0"` |
| 158 |
// Add newlines after footer file |
| 159 |
AfterFooterFile int `yaml:"afterFooterFile,omitempty" default:"0"` |
| 160 |
// Add newlines after footer template |
| 161 |
AfterFooterTemplate int `yaml:"afterFooter,omitempty" default:"0"` |
| 162 |
// Add newlines after header file |
| 163 |
AfterHeaderFile int `yaml:"afterHeaderFile,omitempty" default:"0"` |
| 164 |
// Add newlines after header template |
| 165 |
AfterHeaderTemplate int `yaml:"afterHeaderTemplate,omitempty" default:"0"` |
| 166 |
// Add newlines after kind |
| 167 |
AfterKind int `yaml:"afterKind,omitempty" default:"0"` |
| 168 |
// Add newlines after release notes |
| 169 |
AfterReleaseNotes int `yaml:"afterReleaseNotes,omitempty" default:"0"` |
| 170 |
// Add newlines after version |
| 171 |
AfterVersion int `yaml:"afterVersion,omitempty" default:"0"` |
| 172 |
// Add newlines before change fragment |
| 173 |
BeforeChange int `yaml:"beforeChange,omitempty" default:"0"` |
| 174 |
// Add newlines before adding a version to the changelog |
| 175 |
BeforeChangelogVersion int `yaml:"beforeChangelogVersion,omitempty" default:"0"` |
| 176 |
// Add newlines before component |
| 177 |
BeforeComponent int `yaml:"beforeComponent,omitempty" default:"0"` |
| 178 |
// Add newlines before footer file |
| 179 |
BeforeFooterFile int `yaml:"beforeFooterFile,omitempty" default:"0"` |
| 180 |
// Add newlines before footer template |
| 181 |
BeforeFooterTemplate int `yaml:"beforeFooterTemplate,omitempty" default:"0"` |
| 182 |
// Add newlines before header file |
| 183 |
BeforeHeaderFile int `yaml:"beforeHeaderFile,omitempty" default:"0"` |
| 184 |
// Add newlines before header template |
| 185 |
BeforeHeaderTemplate int `yaml:"beforeHeaderTemplate,omitempty" default:"0"` |
| 186 |
// Add newlines before kind |
| 187 |
BeforeKind int `yaml:"beforeKind,omitempty" default:"0"` |
| 188 |
// Add newlines before version |
| 189 |
BeforeVersion int `yaml:"beforeVersion,omitempty" default:"0"` |
| 190 |
// Add newlines at the end of the version file |
| 191 |
EndOfVersion int `yaml:"endOfVersion,omitempty" default:"0"` |
| 192 |
} |
| 193 |
|
| 194 |
// PostProcessConfig allows adding additional custom values to a change fragment |
| 195 |
// after all the other inputs are complete. |
| 196 |
// This will add additional keys to the `custom` section of the fragment. |
| 197 |
// If the key already exists as part of a custom choice the value will be overridden. |
| 198 |
type PostProcessConfig struct { |
| 199 |
// Key to save the custom value with |
| 200 |
Key string `yaml:"key"` |
| 201 |
// Value of the custom value as a go template |
| 202 |
Value string `yaml:"value" templateType:"Change"` |
| 203 |
} |
| 204 |
|
| 205 |
// ProjectConfig extends changie to support multiple changelog files for different projects |
| 206 |
// inside one repository. |
| 207 |
// example: yaml |
| 208 |
// projects: |
| 209 |
// - label: UI |
| 210 |
// key: ui |
| 211 |
// changelog: ui/CHANGELOG.md |
| 212 |
// - label: Email Sender |
| 213 |
// key: email_sender |
| 214 |
// changelog: services/email/CHANGELOG.md |
| 215 |
type ProjectConfig struct { |
| 216 |
// Label is the value used in the prompt when selecting a project. |
| 217 |
// example: yaml |
| 218 |
// label: Frontend |
| 219 |
Label string `yaml:"label"` |
| 220 |
// Key is the value used for unreleased and version output paths. |
| 221 |
// example: yaml |
| 222 |
// key: frontend |
| 223 |
Key string `yaml:"key"` |
| 224 |
// ChangelogPath is the path to the changelog for this project. |
| 225 |
// example: yaml |
| 226 |
// changelog: src/frontend/CHANGELOG.md |
| 227 |
ChangelogPath string `yaml:"changelog"` |
| 228 |
// Replacements to run when merging a changelog for our project. |
| 229 |
// example: yaml |
| 230 |
// # nodejs package.json replacement |
| 231 |
// replacements: |
| 232 |
// - path: ui/package.json |
| 233 |
// find: ' "version": ".*",' |
| 234 |
// replace: ' "version": "{{.VersionNoPrefix}}",' |
| 235 |
Replacements []Replacement `yaml:"replacements"` |
| 236 |
} |
| 237 |
|
| 238 |
// Config handles configuration for a project. |
| 239 |
// |
| 240 |
// Custom configuration path: |
| 241 |
// |
| 242 |
// By default Changie will try and load ".changie.yaml" and ".changie.yml" before running commands. |
| 243 |
// If you want to change this path set the environment variable `CHANGIE_CONFIG_PATH` to the desired file. |
| 244 |
// |
| 245 |
// `export CHANGIE_CONFIG_PATH=./tools/changie.yaml` |
| 246 |
// |
| 247 |
// [Template Cache](#templatecache-type) handles all the template executions. |
| 248 |
// |
| 249 |
// When batching changes into a version, the headers and footers are placed as such: |
| 250 |
// |
| 251 |
// 1. Header file |
| 252 |
// 1. Header template |
| 253 |
// 1. All changes |
| 254 |
// 1. Footer template |
| 255 |
// 1. Footer file |
| 256 |
// |
| 257 |
// All elements are optional and will be added together if all are provided. |
| 258 |
type Config struct { |
| 259 |
// Directory for change files, header file and unreleased files. |
| 260 |
// Relative to project root. |
| 261 |
// example: yaml |
| 262 |
// changesDir: .changes |
| 263 |
ChangesDir string `yaml:"changesDir" required:"true"` |
| 264 |
// Directory for all unreleased change files. |
| 265 |
// Relative to [changesDir](#config-changesdir). |
| 266 |
// example: yaml |
| 267 |
// unreleasedDir: unreleased |
| 268 |
UnreleasedDir string `yaml:"unreleasedDir" required:"true"` |
| 269 |
// Header content included at the top of the merged changelog. |
| 270 |
// A default header file is created when initializing that follows "Keep a Changelog". |
| 271 |
// |
| 272 |
// Filepath for your changelog header file. |
| 273 |
// Relative to [changesDir](#config-changesdir). |
| 274 |
// example: yaml |
| 275 |
// headerPath: header.tpl.md |
| 276 |
HeaderPath string `yaml:"headerPath,omitempty"` |
| 277 |
// Filepath for the generated changelog file. |
| 278 |
// Relative to project root. |
| 279 |
// ChangelogPath is not required if you are using projects. |
| 280 |
// example: yaml |
| 281 |
// changelogPath: CHANGELOG.md |
| 282 |
ChangelogPath string `yaml:"changelogPath,omitempty"` |
| 283 |
// File extension for generated version files. |
| 284 |
// This should probably match your changelog path file. |
| 285 |
// Must not include the period. |
| 286 |
// example: yaml |
| 287 |
// # for markdown changelogs |
| 288 |
// versionExt: md |
| 289 |
VersionExt string `yaml:"versionExt" required:"true"` |
| 290 |
// Filepath for your version header file relative to [unreleasedDir](#config-unreleaseddir). |
| 291 |
// It is also possible to use the '--header-path' parameter when using the [batch command](../cli/changie_batch.md). |
| 292 |
VersionHeaderPath string `yaml:"versionHeaderPath,omitempty"` |
| 293 |
// Filepath for your version footer file relative to [unreleasedDir](#config-unreleaseddir). |
| 294 |
// It is also possible to use the '--footer-path' parameter when using the [batch command](../cli/changie_batch.md). |
| 295 |
VersionFooterPath string `yaml:"versionFooterPath,omitempty"` |
| 296 |
// Customize the file name generated for new versions or release note files. |
| 297 |
// The file is placed in the [changesDir](#config-changesdir), so the full path is: |
| 298 |
// `{{.ChangesDir}}/{{.VersionFileFormat}}` |
| 299 |
VersionFileFormat string `yaml:"versionFileFormat,omitempty" default:"{{.Version}}.{{config.VersionExt}}" templateType:"BatchData"` //nolint:lll |
| 300 |
// Customize the file name generated for new fragments. |
| 301 |
// The default uses the component and kind only if configured for your project. |
| 302 |
// The file is placed in the unreleased directory, so the full path is: |
| 303 |
// |
| 304 |
// `{{.ChangesDir}}/{{.UnreleasedDir}}/{{.FragmentFileFormat}}.yaml` |
| 305 |
// example: yaml |
| 306 |
// fragmentFileFormat: "{{.Kind}}-{{.Custom.Issue}}" |
| 307 |
FragmentFileFormat string `yaml:"fragmentFileFormat,omitempty" default:"{{.Project}}-{{.Component}}-{{.Kind}}-{{.Time.Format \"20060102-150405\"}}" templateType:"Change"` //nolint:lll |
| 308 |
// Template used to generate version headers. |
| 309 |
VersionFormat string `yaml:"versionFormat,omitempty" templateType:"BatchData"` |
| 310 |
// Template used to generate component headers. |
| 311 |
// If format is empty no header will be included. |
| 312 |
// If components are disabled, the format is unused. |
| 313 |
ComponentFormat string `yaml:"componentFormat,omitempty" templateType:"ComponentData"` |
| 314 |
// Template used to generate kind headers. |
| 315 |
// If format is empty no header will be included. |
| 316 |
// If kinds are disabled, the format is unused. |
| 317 |
KindFormat string `yaml:"kindFormat,omitempty" templateType:"KindData"` |
| 318 |
// Template used to generate change lines in version files and changelog. |
| 319 |
// Custom values are created through custom choices and can be accessible through the Custom argument. |
| 320 |
// example: yaml |
| 321 |
// changeFormat: '* [#{{.Custom.Issue}}](https://github.com/miniscruff/changie/issues/{{.Custom.Issue}}) {{.Body}}' |
| 322 |
ChangeFormat string `yaml:"changeFormat" templateType:"Change"` |
| 323 |
// Template used to generate a version header. |
| 324 |
HeaderFormat string `yaml:"headerFormat,omitempty" templateType:"BatchData"` |
| 325 |
// Template used to generate a version footer. |
| 326 |
// example: yaml |
| 327 |
// # config yaml |
| 328 |
// custom: |
| 329 |
// - key: Author |
| 330 |
// type: string |
| 331 |
// minLength: 3 |
| 332 |
// footerFormat: | |
| 333 |
// ### Contributors |
| 334 |
// {{- range (customs .Changes "Author" | uniq) }} |
| 335 |
// * [{{.}}](https://github.com/{{.}}) |
| 336 |
// {{- end}} |
| 337 |
FooterFormat string `yaml:"footerFormat,omitempty" templateType:"BatchData"` |
| 338 |
// Options to customize the body prompt |
| 339 |
Body BodyConfig `yaml:"body,omitempty"` |
| 340 |
// Components are an additional layer of organization suited for projects that want to split |
| 341 |
// change fragments by an area or tag of the project. |
| 342 |
// An example could be splitting your changelogs by packages for a monorepo. |
| 343 |
// If no components are listed then the component prompt will be skipped and no component header included. |
| 344 |
// By default no components are configured. |
| 345 |
// example: yaml |
| 346 |
// components: |
| 347 |
// - API |
| 348 |
// - CLI |
| 349 |
// - Frontend |
| 350 |
Components []string `yaml:"components,omitempty"` |
| 351 |
// Kinds are another optional layer of changelogs suited for specifying what type of change we are |
| 352 |
// making. |
| 353 |
// If configured, developers will be prompted to select a kind. |
| 354 |
// |
| 355 |
// The default list comes from keep a changelog and includes; added, changed, removed, deprecated, fixed, and security. |
| 356 |
// example: yaml |
| 357 |
// kinds: |
| 358 |
// - label: Added |
| 359 |
// - label: Changed |
| 360 |
// - label: Deprecated |
| 361 |
// - label: Removed |
| 362 |
// - label: Fixed |
| 363 |
// - label: Security |
| 364 |
Kinds []KindConfig `yaml:"kinds,omitempty"` |
| 365 |
// Custom choices allow you to ask for additional information when creating a new change fragment. |
| 366 |
// These custom choices are included in the [change custom](#change-custom) value. |
| 367 |
// example: yaml |
| 368 |
// # github issue and author name |
| 369 |
// custom: |
| 370 |
// - key: Issue |
| 371 |
// type: int |
| 372 |
// minInt: 1 |
| 373 |
// - key: Author |
| 374 |
// label: GitHub Name |
| 375 |
// type: string |
| 376 |
// minLength: 3 |
| 377 |
CustomChoices []Custom `yaml:"custom,omitempty"` |
| 378 |
// Replacements to run when merging a changelog. |
| 379 |
// example: yaml |
| 380 |
// # nodejs package.json replacement |
| 381 |
// replacements: |
| 382 |
// - path: package.json |
| 383 |
// find: ' "version": ".*",' |
| 384 |
// replace: ' "version": "{{.VersionNoPrefix}}",' |
| 385 |
Replacements []Replacement `yaml:"replacements,omitempty"` |
| 386 |
// Newline options allow you to add extra lines between elements written by changie. |
| 387 |
Newlines NewlinesConfig `yaml:"newlines,omitempty"` |
| 388 |
// Post process options when saving a new change fragment. |
| 389 |
// example: yaml |
| 390 |
// # build a GitHub link from author choice |
| 391 |
// post: |
| 392 |
// - key: AuthorLink |
| 393 |
// value: "https://github.com/{{.Custom.Author}} |
| 394 |
// changeFormat: "* {{.Body}} by [{{.Custom.Author}}]({{.Custom.AuthorLink}})" |
| 395 |
Post []PostProcessConfig `yaml:"post,omitempty"` |
| 396 |
// Prefix of environment variables to load for templates. |
| 397 |
// The prefix is removed from resulting key map. |
| 398 |
// example: yaml |
| 399 |
// # if we have an environment variable like so: |
| 400 |
// # export CHANGIE_PROJECT=changie |
| 401 |
// # we can use that in our templates if we set the prefix |
| 402 |
// envPrefix: "CHANGIE_" |
| 403 |
// versionFormat: "New release for {{.Env.PROJECT}}" |
| 404 |
EnvPrefix string `yaml:"envPrefix,omitempty"` |
| 405 |
// Projects allow you to specify child projects as part of a monorepo setup. |
| 406 |
// example: yaml |
| 407 |
// projects: |
| 408 |
// - label: UI |
| 409 |
// key: ui |
| 410 |
// changelog: ui/CHANGELOG.md |
| 411 |
// - label: Email Sender |
| 412 |
// key: email_sender |
| 413 |
// changelog: services/email/CHANGELOG.md |
| 414 |
Projects []ProjectConfig `yaml:"projects,omitempty"` |
| 415 |
// ProjectsVersionSeparator is used to determine the final version when using projects. |
| 416 |
// The result is: project key + projectVersionSeparator + latest/next version. |
| 417 |
// example: yaml |
| 418 |
// projectsVersionSeparator: "_" |
| 419 |
ProjectsVersionSeparator string `yaml:"projectsVersionSeparator,omitempty"` |
| 420 |
|
| 421 |
cachedEnvVars map[string]string |
| 422 |
} |
| 423 |
|
| 424 |
func (c *Config) KindFromKeyOrLabel(keyOrLabel string) *KindConfig { |
| 425 |
for _, kc := range c.Kinds { |
| 426 |
if kc.KeyOrLabel() == keyOrLabel { |
| 427 |
return &kc |
| 428 |
} |
| 429 |
} |
| 430 |
|
| 431 |
return nil |
| 432 |
} |
| 433 |
|
| 434 |
func (c *Config) KindHeader(keyOrLabel string) string { |
| 435 |
for _, kc := range c.Kinds { |
| 436 |
if kc.Format != "" && (kc.Key == keyOrLabel || kc.Label == keyOrLabel) { |
| 437 |
return kc.Format |
| 438 |
} |
| 439 |
} |
| 440 |
|
| 441 |
return c.KindFormat |
| 442 |
} |
| 443 |
|
| 444 |
func (c *Config) ChangeFormatForKind(keyOrLabel string) string { |
| 445 |
for _, kc := range c.Kinds { |
| 446 |
if kc.ChangeFormat != "" && (kc.Key == keyOrLabel || kc.Label == keyOrLabel) { |
| 447 |
return kc.ChangeFormat |
| 448 |
} |
| 449 |
} |
| 450 |
|
| 451 |
return c.ChangeFormat |
| 452 |
} |
| 453 |
|
| 454 |
func (c *Config) EnvVars() map[string]string { |
| 455 |
if c.cachedEnvVars == nil { |
| 456 |
c.cachedEnvVars = LoadEnvVars(c, os.Environ()) |
| 457 |
} |
| 458 |
|
| 459 |
return c.cachedEnvVars |
| 460 |
} |
| 461 |
|
| 462 |
// Save will save the config as a yaml file to the default path |
| 463 |
func (c *Config) Save() error { |
| 464 |
bs, _ := yaml.Marshal(&c) |
| 465 |
return os.WriteFile(ConfigPaths[0], bs, CreateFileMode) |
| 466 |
} |
| 467 |
|
| 468 |
func (c *Config) Project(labelOrKey string) (*ProjectConfig, error) { |
| 469 |
if len(c.Projects) == 0 { |
| 470 |
return &ProjectConfig{}, nil |
| 471 |
} |
| 472 |
|
| 473 |
if len(labelOrKey) == 0 { |
| 474 |
return nil, errProjectRequired |
| 475 |
} |
| 476 |
|
| 477 |
for _, pc := range c.Projects { |
| 478 |
if labelOrKey == pc.Label || labelOrKey == pc.Key { |
| 479 |
return &pc, nil |
| 480 |
} |
| 481 |
} |
| 482 |
|
| 483 |
return nil, errProjectNotFound |
| 484 |
} |
| 485 |
|
| 486 |
func (c *Config) ProjectLabels() []string { |
| 487 |
projectLabels := make([]string, len(c.Projects)) |
| 488 |
|
| 489 |
for i, pc := range c.Projects { |
| 490 |
if len(pc.Label) > 0 { |
| 491 |
projectLabels[i] = pc.Label |
| 492 |
} else { |
| 493 |
projectLabels[i] = pc.Key |
| 494 |
} |
| 495 |
} |
| 496 |
|
| 497 |
return projectLabels |
| 498 |
} |
| 499 |
|
| 500 |
// Exists returns whether or not a config already exists |
| 501 |
func (c *Config) Exists() (bool, error) { |
| 502 |
for _, p := range ConfigPaths { |
| 503 |
if exists, err := FileExists(p); exists || err != nil { |
| 504 |
return exists, err |
| 505 |
} |
| 506 |
} |
| 507 |
|
| 508 |
return false, nil |
| 509 |
} |
| 510 |
|
| 511 |
// findConfigUpwards will recursively look up until we find a changie config file |
| 512 |
func findConfigUpwards() ([]byte, error) { |
| 513 |
currDir, err := os.Getwd() |
| 514 |
if err != nil { |
| 515 |
return nil, err |
| 516 |
} |
| 517 |
|
| 518 |
for { |
| 519 |
for _, path := range ConfigPaths { |
| 520 |
bs, err := os.ReadFile(filepath.Join(currDir, path)) |
| 521 |
if err == nil || !errors.Is(err, fs.ErrNotExist) { |
| 522 |
return bs, nil |
| 523 |
} |
| 524 |
} |
| 525 |
|
| 526 |
err := os.Chdir("..") |
| 527 |
if err != nil { |
| 528 |
return nil, err |
| 529 |
} |
| 530 |
|
| 531 |
lastDir := currDir |
| 532 |
|
| 533 |
currDir, err = os.Getwd() |
| 534 |
if err != nil { |
| 535 |
return nil, err |
| 536 |
} |
| 537 |
|
| 538 |
// Keep going up, until going up is unchanged. |
| 539 |
if lastDir == currDir { |
| 540 |
return nil, ErrConfigNotFound |
| 541 |
} |
| 542 |
} |
| 543 |
} |
| 544 |
|
| 545 |
// LoadConfig will load the config from the default path |
| 546 |
func LoadConfig() (*Config, error) { |
| 547 |
var ( |
| 548 |
c Config |
| 549 |
bs []byte |
| 550 |
err error |
| 551 |
) |
| 552 |
|
| 553 |
customPath := os.Getenv(configEnvVar) |
| 554 |
if customPath != "" { |
| 555 |
// The config path is intentionally chosen by the user via the env var. |
| 556 |
// #nosec G304,G703 |
| 557 |
bs, err = os.ReadFile(customPath) |
| 558 |
} else { |
| 559 |
bs, err = findConfigUpwards() |
| 560 |
} |
| 561 |
|
| 562 |
if err != nil { |
| 563 |
return nil, err |
| 564 |
} |
| 565 |
|
| 566 |
err = yaml.Unmarshal(bs, &c) |
| 567 |
if err != nil { |
| 568 |
return nil, err |
| 569 |
} |
| 570 |
|
| 571 |
// load backward incompatible configs |
| 572 |
if c.FragmentFileFormat == "" { |
| 573 |
if len(c.Projects) > 0 { |
| 574 |
c.FragmentFileFormat += "{{.Project}}-" |
| 575 |
} |
| 576 |
|
| 577 |
if len(c.Components) > 0 { |
| 578 |
c.FragmentFileFormat += "{{.Component}}-" |
| 579 |
} |
| 580 |
|
| 581 |
if len(c.Kinds) > 0 { |
| 582 |
c.FragmentFileFormat += "{{.Kind}}-" |
| 583 |
} |
| 584 |
|
| 585 |
c.FragmentFileFormat += fmt.Sprintf("{{.Time.Format \"%v\"}}", timeFormat) |
| 586 |
} |
| 587 |
|
| 588 |
if c.VersionFileFormat == "" { |
| 589 |
c.VersionFileFormat = "{{.Version}}." + c.VersionExt |
| 590 |
} |
| 591 |
|
| 592 |
return &c, nil |
| 593 |
} |