-
Notifications
You must be signed in to change notification settings - Fork 3
/
productversion.go
85 lines (71 loc) · 2.25 KB
/
productversion.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package crt
import (
"strings"
"github.com/hashicorp/go-version"
)
type ProductVersion struct {
// Full is the full version string made up of Core + Meta.
// If this is set externally, then `Meta` must not also be set, if it is
// that's a validation error.
Full string `env:"PRODUCT_VERSION"`
// Core is the base version + prerelease, not including any metadata.
// It is used alongside Name to derive default names for the zip package,
// deb and rpm packages, and container image tags.
Core string
// Meta is the metadata portion of the version string.
Meta string `env:"PRODUCT_VERSION_META"`
}
func (p ProductVersion) String() string { return p.Full }
// NewProductVersion accepts a coreVersion and a fullVersion. The fullVersion may
// be empty, in which case the full version will be set to coreVersion-local indicating
// a "local" build, without proper version information.
// If the coreVersion is also empty, then we set it to 0.0.0-unversioned.
func NewProductVersion(coreVersion, fullVersion string) (ProductVersion, error) {
fullVersion = strings.TrimSpace(fullVersion)
coreVersion = strings.TrimSpace(coreVersion)
return ProductVersion{
Full: fullVersion,
Core: coreVersion,
}.Init()
}
// trimSpace trims leading and trailing space from fields read from external inputs
// only.
func (pv ProductVersion) trimSpace() ProductVersion {
pv.Full = strings.TrimSpace(pv.Full)
pv.Meta = strings.TrimSpace(pv.Meta)
return pv
}
// Init ensures that all fields in the ProductVersion are consistent, and fills in
// any missing fields.
func (pv ProductVersion) Init() (ProductVersion, error) {
if pv.Full != "" {
v, err := version.NewVersion(pv.Full)
if err != nil {
return pv, err
}
pv.Core = v.Core().String()
if p := v.Prerelease(); p != "" {
pv.Core += "-" + p
}
pv.Meta = v.Metadata()
return pv, nil
}
if pv.Core == "" && pv.Meta == "" {
pv.Meta = "local"
}
if pv.Core == "" {
pv.Full = "0.0.0-unversioned"
pv.Core = "0.0.0-unversioned"
}
pv.Full = pv.Core
if pv.Meta != "" {
pv.Full += "+" + pv.Meta
}
return pv, nil
}
func (pv ProductVersion) InitWithCoreVersion(coreVersion string) (ProductVersion, error) {
pv.Core = coreVersion
return pv.Init()
}