]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/version/version.go
go/version: add new package
[gostls13.git] / src / go / version / version.go
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package version provides operations on [Go versions].
6 //
7 // [Go versions]: https://go.dev/doc/toolchain#version
8 package version // import "go/version"
9
10 import "internal/gover"
11
12 // stripGo converts from a "go1.21" version to a "1.21" version.
13 // If v does not start with "go", stripGo returns the empty string (a known invalid version).
14 func stripGo(v string) string {
15         if len(v) < 2 || v[:2] != "go" {
16                 return ""
17         }
18         return v[2:]
19 }
20
21 // Lang returns the Go language version for version x.
22 // If x is not a valid version, Lang returns the empty string.
23 // For example:
24 //
25 //      Lang("go1.21rc2") = "go1.21"
26 //      Lang("go1.21.2") = "go1.21"
27 //      Lang("go1.21") = "go1.21"
28 //      Lang("go1") = "go1"
29 //      Lang("bad") = ""
30 //      Lang("1.21") = ""
31 func Lang(x string) string {
32         v := gover.Lang(stripGo(x))
33         if v == "" {
34                 return ""
35         }
36         return x[:2+len(v)] // "go"+v without allocation
37 }
38
39 // Compare returns -1, 0, or +1 depending on whether
40 // x < y, x == y, or x > y, interpreted as Go versions.
41 // The versions x and y must begin with a "go" prefix: "go1.21" not "1.21".
42 // Invalid versions, including the empty string, compare less than
43 // valid versions and equal to each other.
44 // The language version "go1.21" compares less than the
45 // release candidate and eventual releases "go1.21rc1" and "go1.21.0".
46 // Custom toolchain suffixes are ignored during comparison:
47 // "go1.21.0" and "go1.21.0-bigcorp" are equal.
48 func Compare(x, y string) int {
49         return gover.Compare(stripGo(x), stripGo(y))
50 }
51
52 // IsValid reports whether the version x is valid.
53 func IsValid(x string) bool {
54         return gover.IsValid(stripGo(x))
55 }