| 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 versions |
| 6 |
|
| 7 |
import ( |
| 8 |
"go/ast" |
| 9 |
"go/types" |
| 10 |
) |
| 11 |
|
| 12 |
// FileVersion returns a file's Go version. |
| 13 |
// The reported version is an unknown Future version if a |
| 14 |
// version cannot be determined. |
| 15 |
func FileVersion(info *types.Info, file *ast.File) string { |
| 16 |
// In tools built with Go >= 1.22, the Go version of a file |
| 17 |
// follow a cascades of sources: |
| 18 |
// 1) types.Info.FileVersion, which follows the cascade: |
| 19 |
// 1.a) file version (ast.File.GoVersion), |
| 20 |
// 1.b) the package version (types.Config.GoVersion), or |
| 21 |
// 2) is some unknown Future version. |
| 22 |
// |
| 23 |
// File versions require a valid package version to be provided to types |
| 24 |
// in Config.GoVersion. Config.GoVersion is either from the package's module |
| 25 |
// or the toolchain (go run). This value should be provided by go/packages |
| 26 |
// or unitchecker.Config.GoVersion. |
| 27 |
if v := info.FileVersions[file]; IsValid(v) { |
| 28 |
return v |
| 29 |
} |
| 30 |
// Note: we could instead return runtime.Version() [if valid]. |
| 31 |
// This would act as a max version on what a tool can support. |
| 32 |
return Future |
| 33 |
} |