| 1 |
// Copyright 2024 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 telemetry |
| 6 |
|
| 7 |
import ( |
| 8 |
"go/version" |
| 9 |
"os" |
| 10 |
"path/filepath" |
| 11 |
"runtime/debug" |
| 12 |
"strings" |
| 13 |
) |
| 14 |
|
| 15 |
// IsToolchainProgram reports whether a program with the given path is a Go |
| 16 |
// toolchain program. |
| 17 |
func IsToolchainProgram(progPath string) bool { |
| 18 |
return strings.HasPrefix(progPath, "cmd/") |
| 19 |
} |
| 20 |
|
| 21 |
// ProgramInfo extracts the go version, program package path, and program |
| 22 |
// version to use for counter files. |
| 23 |
// |
| 24 |
// For programs in the Go toolchain, the program version will be the same as |
| 25 |
// the Go version, and will typically be of the form "go1.2.3", not a semantic |
| 26 |
// version of the form "v1.2.3". Go versions may also include spaces and |
| 27 |
// special characters. |
| 28 |
func ProgramInfo(info *debug.BuildInfo) (goVers, progPath, progVers string) { |
| 29 |
goVers = info.GoVersion |
| 30 |
if strings.Contains(goVers, "devel") || strings.Contains(goVers, "-") || !version.IsValid(goVers) { |
| 31 |
goVers = "devel" |
| 32 |
} |
| 33 |
|
| 34 |
progPath = info.Path |
| 35 |
if progPath == "" { |
| 36 |
progPath = strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe") |
| 37 |
} |
| 38 |
|
| 39 |
// Main module version information is not populated for the cmd module, but |
| 40 |
// we can re-use the Go version here. |
| 41 |
if IsToolchainProgram(progPath) { |
| 42 |
progVers = goVers |
| 43 |
} else { |
| 44 |
progVers = info.Main.Version |
| 45 |
if strings.Contains(progVers, "devel") || strings.Count(progVers, "-") > 1 { |
| 46 |
// Heuristically mark all pseudo-version-like version strings as "devel" |
| 47 |
// to avoid creating too many counter files. |
| 48 |
// We should not use regexp that pulls in large dependencies. |
| 49 |
// Pseudo-versions have at least three parts (https://go.dev/ref/mod#pseudo-versions). |
| 50 |
// This heuristic still allows use to track prerelease |
| 51 |
// versions (e.g. [email protected], [email protected]). |
| 52 |
progVers = "devel" |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
return goVers, progPath, progVers |
| 57 |
} |