Debian Codegraph @

gopls/internal/vulncheck/semver/semver.go

raw symbols SCIP
1 // Copyright 2022 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 semver provides shared utilities for manipulating
6 // Go semantic versions.
7 package semver
8
9 import (
10 "strings"
11
12 "golang.org/x/mod/semver"
13 )
14
15 // addSemverPrefix adds a 'v' prefix to s if it isn't already prefixed
16 // with 'v' or 'go'. This allows us to easily test go-style SEMVER
17 // strings against normal SEMVER strings.
18 func addSemverPrefix(s string) string {
19 if !strings.HasPrefix(s, "v") && !strings.HasPrefix(s, "go") {
20 return "v" + s
21 }
22 return s
23 }
24
25 // removeSemverPrefix removes the 'v' or 'go' prefixes from go-style
26 // SEMVER strings, for usage in the public vulnerability format.
27 func removeSemverPrefix(s string) string {
28 s = strings.TrimPrefix(s, "v")
29 s = strings.TrimPrefix(s, "go")
30 return s
31 }
32
33 // CanonicalizeSemverPrefix turns a SEMVER string into the canonical
34 // representation using the 'v' prefix, as used by the OSV format.
35 // Input may be a bare SEMVER ("1.2.3"), Go prefixed SEMVER ("go1.2.3"),
36 // or already canonical SEMVER ("v1.2.3").
37 func CanonicalizeSemverPrefix(s string) string {
38 return addSemverPrefix(removeSemverPrefix(s))
39 }
40
41 // Valid returns whether v is valid semver, allowing
42 // either a "v", "go" or no prefix.
43 func Valid(v string) bool {
44 return semver.IsValid(CanonicalizeSemverPrefix(v))
45 }