golang.org/x/tools/gopls@v0.15.3/internal/vulncheck/semver/semver.go (about)

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