hashicorp/go-version
GitHub: hashicorp/go-version
一个用于 Go 语言中解析、比较、排序版本号及校验版本约束条件的轻量级库。
Stars: 1766 | Forks: 161
# Go 的版本控制库

[](https://pkg.go.dev/github.com/hashicorp/go-version)
go-version 是一个用于解析版本和版本约束的库,
并可根据一组约束来验证版本。go-version
能够正确地对版本集合进行排序,处理预发布/beta
版本,递增版本等。
## 安装与使用
包文档可以在
[Go Reference](https://pkg.go.dev/github.com/hashicorp/go-version) 上找到。
可以通过标准的 `go get` 进行安装:
```
$ go get github.com/hashicorp/go-version
```
#### 版本解析与比较
```
v1, err := version.NewVersion("1.2")
v2, err := version.NewVersion("1.5+metadata")
// Comparison example. There is also GreaterThan, Equal, and just
// a simple Compare that returns an int allowing easy >=, <=, etc.
if v1.LessThan(v2) {
fmt.Printf("%s is less than %s", v1, v2)
}
```
#### 带前缀的版本解析与比较
该库也支持解析带有自定义前缀的版本。
使用 `WithPrefix` 选项,你可以指定一个前缀,在解析版本前将其去除。
当你的输入字符串包含已知的发布前缀(例如
`deployment-`、`controller-` 等)时,请使用 `WithPrefix`。
解析后,该前缀不属于规范版本值的一部分。这
意味着常规的比较方法(如 `Compare`、`LessThan`、`Equal`
和 `GreaterThan`)仅比较去除前缀后的版本。如果你通过这些方法
比较来自不同前缀的版本,前缀将被忽略。如果你
需要拒绝跨前缀的比较,请在比较版本之前检查解析出的前缀。
```
v1, _ := version.NewVersion("deployment-v1.2.3-beta+metadata", version.WithPrefix("deployment-"))
v2, _ := version.NewVersion("deployment-v1.2.4", version.WithPrefix("deployment-"))
if v1.LessThan(v2) {
fmt.Printf("%s (%s) is less than %s (%s)\n", v1, v1.Original(), v2, v2.Original())
// Outputs: 1.2.3-beta+metadata (deployment-v1.2.3-beta+metadata) is less than 1.2.4 (deployment-v1.2.4)
}
```
#### 版本约束
```
v1, err := version.NewVersion("1.2")
// Constraints example.
constraints, err := version.NewConstraint(">= 1.0, < 1.4")
if constraints.Check(v1) {
fmt.Printf("%s satisfies constraints %s", v1, constraints)
}
```
#### 版本排序
```
versionsRaw := []string{"1.1", "0.7.1", "1.4-beta", "1.4", "2"}
versions := make([]*version.Version, len(versionsRaw))
for i, raw := range versionsRaw {
v, _ := version.NewVersion(raw)
versions[i] = v
}
// After this, the versions are properly sorted
sort.Sort(version.Collection(versions))
```
标签:EVTX分析, 日志审计