| 1 |
package core |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"io" |
| 9 |
"io/fs" |
| 10 |
"os" |
| 11 |
"os/exec" |
| 12 |
"path/filepath" |
| 13 |
"sort" |
| 14 |
"strings" |
| 15 |
"time" |
| 16 |
|
| 17 |
"github.com/Masterminds/semver/v3" |
| 18 |
|
| 19 |
shellquote "github.com/kballard/go-shellquote" |
| 20 |
) |
| 21 |
|
| 22 |
// TimeNow is a func type for time.Now |
| 23 |
type TimeNow func() time.Time |
| 24 |
|
| 25 |
type EditorRunner interface { |
| 26 |
Run() error |
| 27 |
} |
| 28 |
|
| 29 |
var ( |
| 30 |
ErrBadVersionOrPart = errors.New("part string is not a supported version or version increment") |
| 31 |
ErrMissingAutoLevel = errors.New("kind config missing auto level value for auto bumping") |
| 32 |
ErrNoChangesFoundForAuto = errors.New("no unreleased changes found for automatic bumping") |
| 33 |
ErrKindNotFound = errors.New("kind not found but configuration expects one") |
| 34 |
) |
| 35 |
|
| 36 |
var ( |
| 37 |
bom = []byte{0xef, 0xbb, 0xbf} |
| 38 |
) |
| 39 |
|
| 40 |
func AppendFile(rootFile io.Writer, path string) error { |
| 41 |
otherFile, err := os.Open(path) |
| 42 |
if err != nil { |
| 43 |
return err |
| 44 |
} |
| 45 |
defer otherFile.Close() |
| 46 |
|
| 47 |
_, err = io.Copy(rootFile, otherFile) |
| 48 |
|
| 49 |
return err |
| 50 |
} |
| 51 |
|
| 52 |
func GetAllVersions( |
| 53 |
config *Config, |
| 54 |
skipPrereleases bool, |
| 55 |
projectKey string, |
| 56 |
) ([]*semver.Version, error) { |
| 57 |
allVersions := make([]*semver.Version, 0) |
| 58 |
|
| 59 |
versionsPath := config.ChangesDir |
| 60 |
if len(projectKey) > 0 { |
| 61 |
versionsPath = filepath.Join(versionsPath, projectKey) |
| 62 |
} |
| 63 |
|
| 64 |
fileInfos, err := os.ReadDir(versionsPath) |
| 65 |
if err != nil && errors.Is(err, fs.ErrNotExist) { |
| 66 |
return allVersions, nil |
| 67 |
} |
| 68 |
|
| 69 |
if err != nil { |
| 70 |
return allVersions, fmt.Errorf("reading files from '%s': %w", versionsPath, err) |
| 71 |
} |
| 72 |
|
| 73 |
for _, file := range fileInfos { |
| 74 |
if file.Name() == config.HeaderPath || file.IsDir() { |
| 75 |
continue |
| 76 |
} |
| 77 |
|
| 78 |
versionString := strings.TrimSuffix(file.Name(), filepath.Ext(file.Name())) |
| 79 |
|
| 80 |
v, err := semver.NewVersion(versionString) |
| 81 |
if err != nil { |
| 82 |
continue |
| 83 |
} |
| 84 |
|
| 85 |
if skipPrereleases && v.Prerelease() != "" { |
| 86 |
continue |
| 87 |
} |
| 88 |
|
| 89 |
allVersions = append(allVersions, v) |
| 90 |
} |
| 91 |
|
| 92 |
sort.Sort(sort.Reverse(semver.Collection(allVersions))) |
| 93 |
|
| 94 |
return allVersions, nil |
| 95 |
} |
| 96 |
|
| 97 |
func GetLatestVersion( |
| 98 |
config *Config, |
| 99 |
skipPrereleases bool, |
| 100 |
projectKey string, |
| 101 |
) (*semver.Version, error) { |
| 102 |
allVersions, err := GetAllVersions(config, skipPrereleases, projectKey) |
| 103 |
if err != nil { |
| 104 |
return nil, err |
| 105 |
} |
| 106 |
|
| 107 |
// if no versions exist default to v0.0.0 |
| 108 |
if len(allVersions) == 0 { |
| 109 |
return semver.MustParse("v0.0.0"), nil |
| 110 |
} |
| 111 |
|
| 112 |
return allVersions[0], nil |
| 113 |
} |
| 114 |
|
| 115 |
func ValidBumpLevel(level string) bool { |
| 116 |
return level == MajorLevel || |
| 117 |
level == MinorLevel || |
| 118 |
level == PatchLevel || |
| 119 |
level == AutoLevel |
| 120 |
} |
| 121 |
|
| 122 |
func HighestAutoLevel(config *Config, cache *TemplateCache, allChanges []Change) (string, error) { |
| 123 |
if len(allChanges) == 0 { |
| 124 |
return "", ErrNoChangesFoundForAuto |
| 125 |
} |
| 126 |
|
| 127 |
highestLevel := EmptyLevel |
| 128 |
|
| 129 |
for _, change := range allChanges { |
| 130 |
for _, kc := range config.Kinds { |
| 131 |
if kc.KeyOrLabel() != change.Kind { |
| 132 |
continue |
| 133 |
} |
| 134 |
|
| 135 |
level, err := kc.AutoLevelForChange(cache, change) |
| 136 |
if err != nil { |
| 137 |
return EmptyLevel, err |
| 138 |
} |
| 139 |
|
| 140 |
switch level { |
| 141 |
case MajorLevel: |
| 142 |
// major is the highest one, so we can just return it |
| 143 |
return MajorLevel, nil |
| 144 |
case PatchLevel: |
| 145 |
if highestLevel == EmptyLevel { |
| 146 |
highestLevel = PatchLevel |
| 147 |
} |
| 148 |
case MinorLevel: |
| 149 |
// bump to minor if we have a minor level |
| 150 |
if highestLevel == PatchLevel || highestLevel == EmptyLevel { |
| 151 |
highestLevel = MinorLevel |
| 152 |
} |
| 153 |
case EmptyLevel: |
| 154 |
return EmptyLevel, ErrMissingAutoLevel |
| 155 |
} |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
if highestLevel == EmptyLevel { |
| 160 |
return EmptyLevel, ErrNoChangesFoundForAuto |
| 161 |
} |
| 162 |
|
| 163 |
return highestLevel, nil |
| 164 |
} |
| 165 |
|
| 166 |
func GetNextVersion( |
| 167 |
config *Config, |
| 168 |
cache *TemplateCache, |
| 169 |
partOrVersion string, |
| 170 |
prerelease, meta []string, |
| 171 |
allChanges []Change, |
| 172 |
projectKey string, |
| 173 |
) (*semver.Version, error) { |
| 174 |
var ( |
| 175 |
err error |
| 176 |
next *semver.Version |
| 177 |
ver semver.Version |
| 178 |
) |
| 179 |
|
| 180 |
// if part or version is a valid version, then return it |
| 181 |
next, err = semver.NewVersion(partOrVersion) |
| 182 |
if err != nil { |
| 183 |
if !ValidBumpLevel(partOrVersion) { |
| 184 |
return nil, ErrBadVersionOrPart |
| 185 |
} |
| 186 |
|
| 187 |
// otherwise use a bump type command |
| 188 |
next, err = GetLatestVersion(config, false, projectKey) |
| 189 |
if err != nil { |
| 190 |
return nil, err |
| 191 |
} |
| 192 |
|
| 193 |
if partOrVersion == AutoLevel { |
| 194 |
partOrVersion, err = HighestAutoLevel(config, cache, allChanges) |
| 195 |
if err != nil { |
| 196 |
return nil, err |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
switch partOrVersion { |
| 201 |
case MajorLevel: |
| 202 |
ver = next.IncMajor() |
| 203 |
case MinorLevel: |
| 204 |
ver = next.IncMinor() |
| 205 |
case PatchLevel: |
| 206 |
ver = next.IncPatch() |
| 207 |
} |
| 208 |
|
| 209 |
next = &ver |
| 210 |
} |
| 211 |
|
| 212 |
if len(prerelease) > 0 { |
| 213 |
ver, err = next.SetPrerelease(strings.Join(prerelease, ".")) |
| 214 |
if err != nil { |
| 215 |
return nil, err |
| 216 |
} |
| 217 |
|
| 218 |
next = &ver |
| 219 |
} |
| 220 |
|
| 221 |
if len(meta) > 0 { |
| 222 |
ver, err = next.SetMetadata(strings.Join(meta, ".")) |
| 223 |
if err != nil { |
| 224 |
return nil, err |
| 225 |
} |
| 226 |
|
| 227 |
next = &ver |
| 228 |
} |
| 229 |
|
| 230 |
return next, nil |
| 231 |
} |
| 232 |
|
| 233 |
func FindChangeFiles( |
| 234 |
config *Config, |
| 235 |
searchPaths []string, |
| 236 |
) ([]string, error) { |
| 237 |
var yamlFiles []string |
| 238 |
|
| 239 |
// add the unreleased path to any search paths included |
| 240 |
searchPaths = append(searchPaths, config.UnreleasedDir) |
| 241 |
|
| 242 |
// read all yaml files from our search paths |
| 243 |
for _, searchPath := range searchPaths { |
| 244 |
rootPath := filepath.Join(config.ChangesDir, searchPath) |
| 245 |
|
| 246 |
fileInfos, err := os.ReadDir(rootPath) |
| 247 |
if err != nil { |
| 248 |
return yamlFiles, err |
| 249 |
} |
| 250 |
|
| 251 |
for _, file := range fileInfos { |
| 252 |
if filepath.Ext(file.Name()) != ".yaml" { |
| 253 |
continue |
| 254 |
} |
| 255 |
|
| 256 |
path := filepath.Join(rootPath, file.Name()) |
| 257 |
yamlFiles = append(yamlFiles, path) |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
return yamlFiles, nil |
| 262 |
} |
| 263 |
|
| 264 |
func WriteNewlines(writer io.Writer, lines int) error { |
| 265 |
if lines == 0 { |
| 266 |
return nil |
| 267 |
} |
| 268 |
|
| 269 |
_, err := writer.Write([]byte(strings.Repeat("\n", lines))) |
| 270 |
|
| 271 |
return err |
| 272 |
} |
| 273 |
|
| 274 |
func EnvVarMap(environ []string) map[string]string { |
| 275 |
ret := make(map[string]string) |
| 276 |
|
| 277 |
for _, env := range environ { |
| 278 |
split := strings.SplitN(env, "=", 2) |
| 279 |
ret[split[0]] = split[1] |
| 280 |
} |
| 281 |
|
| 282 |
return ret |
| 283 |
} |
| 284 |
|
| 285 |
func LoadEnvVars(config *Config, envs []string) map[string]string { |
| 286 |
ret := make(map[string]string) |
| 287 |
if config.EnvPrefix == "" { |
| 288 |
return ret |
| 289 |
} |
| 290 |
|
| 291 |
for k, v := range EnvVarMap(envs) { |
| 292 |
key, found := strings.CutPrefix(k, config.EnvPrefix) |
| 293 |
if found { |
| 294 |
ret[key] = v |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
return ret |
| 299 |
} |
| 300 |
|
| 301 |
func GetChanges( |
| 302 |
cfg *Config, |
| 303 |
searchPaths []string, |
| 304 |
projectKey string, |
| 305 |
) ([]Change, error) { |
| 306 |
var changes []Change |
| 307 |
|
| 308 |
changeFiles, err := FindChangeFiles(cfg, searchPaths) |
| 309 |
if err != nil { |
| 310 |
return changes, err |
| 311 |
} |
| 312 |
|
| 313 |
for _, cf := range changeFiles { |
| 314 |
c, err := LoadChange(cf) |
| 315 |
if err != nil { |
| 316 |
return changes, err |
| 317 |
} |
| 318 |
|
| 319 |
if len(projectKey) > 0 && c.Project != projectKey { |
| 320 |
continue |
| 321 |
} |
| 322 |
|
| 323 |
c.Env = cfg.EnvVars() |
| 324 |
|
| 325 |
kc := cfg.KindFromKeyOrLabel(c.KindKey) |
| 326 |
if kc != nil { |
| 327 |
c.KindLabel = kc.Label |
| 328 |
} else if len(cfg.Kinds) > 0 { |
| 329 |
return nil, fmt.Errorf("%w: '%s'", ErrKindNotFound, c.KindKey) |
| 330 |
} |
| 331 |
|
| 332 |
changes = append(changes, c) |
| 333 |
} |
| 334 |
|
| 335 |
sort.Slice(changes, ChangeLess(cfg, changes)) |
| 336 |
|
| 337 |
return changes, nil |
| 338 |
} |
| 339 |
|
| 340 |
func FileExists(path string) (bool, error) { |
| 341 |
fi, err := os.Stat(path) |
| 342 |
if err == nil { |
| 343 |
return !fi.IsDir(), nil |
| 344 |
} |
| 345 |
|
| 346 |
if os.IsNotExist(err) { |
| 347 |
return false, nil |
| 348 |
} |
| 349 |
|
| 350 |
return false, err |
| 351 |
} |
| 352 |
|
| 353 |
// createTempFile will create a new temporary file, writing a BOM header if we need to. |
| 354 |
// It will return the path to that file or an error. |
| 355 |
func createTempFile(runtime string, ext string) (string, error) { |
| 356 |
file, err := os.CreateTemp("", "changie-body-txt-*."+ext) |
| 357 |
if err != nil { |
| 358 |
return "", err |
| 359 |
} |
| 360 |
|
| 361 |
defer file.Close() |
| 362 |
|
| 363 |
// The reason why we do this is because notepad.exe on Windows determines the |
| 364 |
// encoding of an "empty" text file by the locale, for example, GBK in China, |
| 365 |
// while golang string only handles utf8 well. However, a text file with utf8 |
| 366 |
// BOM header is not considered "empty" on Windows, and the encoding will then |
| 367 |
// be determined utf8 by notepad.exe, instead of GBK or other encodings. |
| 368 |
// This could be enhanced in the future by doing this only when a non-utf8 |
| 369 |
// locale is in use, and possibly doing that for any OS, not just windows. |
| 370 |
if runtime == "windows" { |
| 371 |
if _, err = file.Write(bom); err != nil { |
| 372 |
return "", err |
| 373 |
} |
| 374 |
} |
| 375 |
|
| 376 |
return file.Name(), nil |
| 377 |
} |
| 378 |
|
| 379 |
// BuildCommand will create an exec command to run our editor. |
| 380 |
func BuildCommand(editorFilePath string) (EditorRunner, error) { |
| 381 |
editor := os.Getenv("EDITOR") |
| 382 |
if editor == "" { |
| 383 |
return nil, errors.New("'EDITOR' env variable not set") |
| 384 |
} |
| 385 |
|
| 386 |
args, err := shellquote.Split(editor) |
| 387 |
if err != nil { |
| 388 |
return nil, err |
| 389 |
} |
| 390 |
|
| 391 |
args = append(args, editorFilePath) |
| 392 |
|
| 393 |
// The editor command is intentionally taken from the user's 'EDITOR' env variable. |
| 394 |
// #nosec G204,G702 |
| 395 |
cmd := exec.CommandContext(context.Background(), args[0], args[1:]...) |
| 396 |
|
| 397 |
// Set the stdin and stdout of the command to the current process's stdin and stdout |
| 398 |
cmd.Stdin = os.Stdin |
| 399 |
cmd.Stdout = os.Stdout |
| 400 |
|
| 401 |
return cmd, nil |
| 402 |
} |
| 403 |
|
| 404 |
// getBodyTextWithEditor will run the provided editor runner and read the final file. |
| 405 |
func getBodyTextWithEditor(runner EditorRunner, editorFile string) (string, error) { |
| 406 |
if err := runner.Run(); err != nil { |
| 407 |
return "", fmt.Errorf("opening the editor: %w", err) |
| 408 |
} |
| 409 |
|
| 410 |
buf, err := os.ReadFile(editorFile) |
| 411 |
if err != nil { |
| 412 |
return "", err |
| 413 |
} |
| 414 |
|
| 415 |
return strings.TrimSpace(string(bytes.TrimPrefix(buf, bom))), nil |
| 416 |
} |