Source file src/cmd/go/internal/doc/mod.go

     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 doc
     6  
     7  import (
     8  	"context"
     9  	"debug/buildinfo"
    10  	"fmt"
    11  	"os/exec"
    12  
    13  	"cmd/go/internal/load"
    14  	"cmd/go/internal/modload"
    15  )
    16  
    17  // loadVersioned loads a package at a specific version.
    18  func loadVersioned(ctx context.Context, loader *modload.State, pkgPath, version string) (*load.Package, error) {
    19  	var opts load.PackageOpts
    20  	args := []string{
    21  		fmt.Sprintf("%s@%s", pkgPath, version),
    22  	}
    23  	pkgs, err := load.PackagesAndErrorsOutsideModule(loader, ctx, opts, args)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	if len(pkgs) != 1 {
    28  		return nil, fmt.Errorf("incorrect number of packages: want 1, got %d", len(pkgs))
    29  	}
    30  	return pkgs[0], nil
    31  }
    32  
    33  // inferVersion checks if the argument matches a command on $PATH and returns its module path and version.
    34  func inferVersion(arg string) (pkgPath, version string, ok bool) {
    35  	path, err := exec.LookPath(arg)
    36  	if err != nil {
    37  		return "", "", false
    38  	}
    39  	bi, err := buildinfo.ReadFile(path)
    40  	if err != nil {
    41  		return "", "", false
    42  	}
    43  	if bi.Main.Path == "" || bi.Main.Version == "" {
    44  		return "", "", false
    45  	}
    46  	// bi.Path is the package path for the main package.
    47  	return bi.Path, bi.Main.Version, true
    48  }
    49  

View as plain text