Source file src/cmd/go/internal/modcmd/download.go

     1  // Copyright 2018 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 modcmd
     6  
     7  import (
     8  	"context"
     9  	"encoding/json"
    10  	"errors"
    11  	"os"
    12  	"runtime"
    13  	"sync"
    14  
    15  	"cmd/go/internal/base"
    16  	"cmd/go/internal/cfg"
    17  	"cmd/go/internal/gover"
    18  	"cmd/go/internal/modfetch"
    19  	"cmd/go/internal/modfetch/codehost"
    20  	"cmd/go/internal/modload"
    21  	"cmd/go/internal/toolchain"
    22  
    23  	"golang.org/x/mod/module"
    24  )
    25  
    26  var cmdDownload = &base.Command{
    27  	UsageLine: "go mod download [-x] [-json] [-reuse=old.json] [modules]",
    28  	Short:     "download modules to local cache",
    29  	Long: `
    30  Download downloads the named modules, which can be module patterns selecting
    31  dependencies of the main module or module queries of the form path@version.
    32  
    33  With no arguments, download applies to the modules needed to build and test
    34  the packages in the main module: the modules explicitly required by the main
    35  module if it is at 'go 1.17' or higher, or all transitively-required modules
    36  if at 'go 1.16' or lower.
    37  
    38  The go command will automatically download modules as needed during ordinary
    39  execution. The "go mod download" command is useful mainly for pre-filling
    40  the local cache or to compute the answers for a Go module proxy.
    41  
    42  By default, download writes nothing to standard output. It may print progress
    43  messages and errors to standard error.
    44  
    45  The -json flag causes download to print a sequence of JSON objects
    46  to standard output, describing each downloaded module (or failure),
    47  corresponding to this Go struct:
    48  
    49      type Module struct {
    50          Path     string // module path
    51          Query    string // version query corresponding to this version
    52          Version  string // module version
    53          Error    string // error loading module
    54          Info     string // absolute path to cached .info file
    55          GoMod    string // absolute path to cached .mod file
    56          Zip      string // absolute path to cached .zip file
    57          Dir      string // absolute path to cached source root directory
    58          Sum      string // checksum for path, version (as in go.sum)
    59          GoModSum string // checksum for go.mod (as in go.sum)
    60          Origin   any    // provenance of module
    61          Reuse    bool   // reuse of old module info is safe
    62      }
    63  
    64  The -reuse flag accepts the name of file containing the JSON output of a
    65  previous 'go mod download -json' invocation. The go command may use this
    66  file to determine that a module is unchanged since the previous invocation
    67  and avoid redownloading it. Modules that are not redownloaded will be marked
    68  in the new output by setting the Reuse field to true. Normally the module
    69  cache provides this kind of reuse automatically; the -reuse flag can be
    70  useful on systems that do not preserve the module cache.
    71  
    72  The -x flag causes download to print the commands download executes.
    73  
    74  See https://golang.org/ref/mod#go-mod-download for more about 'go mod download'.
    75  
    76  See https://golang.org/ref/mod#version-queries for more about version queries.
    77  	`,
    78  }
    79  
    80  var (
    81  	downloadJSON  = cmdDownload.Flag.Bool("json", false, "")
    82  	downloadReuse = cmdDownload.Flag.String("reuse", "", "")
    83  )
    84  
    85  func init() {
    86  	cmdDownload.Run = runDownload // break init cycle
    87  
    88  	// TODO(jayconrod): https://golang.org/issue/35849 Apply -x to other 'go mod' commands.
    89  	cmdDownload.Flag.BoolVar(&cfg.BuildX, "x", false, "")
    90  	base.AddChdirFlag(&cmdDownload.Flag)
    91  	base.AddModCommonFlags(&cmdDownload.Flag)
    92  }
    93  
    94  // A ModuleJSON describes the result of go mod download.
    95  type ModuleJSON struct {
    96  	Path     string `json:",omitempty"`
    97  	Version  string `json:",omitempty"`
    98  	Query    string `json:",omitempty"`
    99  	Error    string `json:",omitempty"`
   100  	Info     string `json:",omitempty"`
   101  	GoMod    string `json:",omitempty"`
   102  	Zip      string `json:",omitempty"`
   103  	Dir      string `json:",omitempty"`
   104  	Sum      string `json:",omitempty"`
   105  	GoModSum string `json:",omitempty"`
   106  
   107  	Origin *codehost.Origin `json:",omitempty"`
   108  	Reuse  bool             `json:",omitempty"`
   109  }
   110  
   111  func runDownload(ctx context.Context, cmd *base.Command, args []string) {
   112  	moduleLoaderState := modload.NewState()
   113  	moduleLoaderState.InitWorkfile()
   114  
   115  	// Check whether modules are enabled and whether we're in a module.
   116  	moduleLoaderState.ForceUseModules = true
   117  	modload.ExplicitWriteGoMod = true
   118  	haveExplicitArgs := len(args) > 0
   119  
   120  	if moduleLoaderState.HasModRoot() || modload.WorkFilePath(moduleLoaderState) != "" {
   121  		modload.LoadModFile(moduleLoaderState, ctx) // to fill MainModules
   122  
   123  		if haveExplicitArgs {
   124  			for _, mainModule := range moduleLoaderState.MainModules.Versions() {
   125  				targetAtUpgrade := mainModule.Path + "@upgrade"
   126  				targetAtPatch := mainModule.Path + "@patch"
   127  				for _, arg := range args {
   128  					switch arg {
   129  					case mainModule.Path, targetAtUpgrade, targetAtPatch:
   130  						os.Stderr.WriteString("go: skipping download of " + arg + " that resolves to the main module\n")
   131  					}
   132  				}
   133  			}
   134  		} else if modload.WorkFilePath(moduleLoaderState) != "" {
   135  			// TODO(#44435): Think about what the correct query is to download the
   136  			// right set of modules. Also see code review comment at
   137  			// https://go-review.googlesource.com/c/go/+/359794/comments/ce946a80_6cf53992.
   138  			args = []string{"all"}
   139  		} else {
   140  			mainModule := moduleLoaderState.MainModules.Versions()[0]
   141  			modFile := moduleLoaderState.MainModules.ModFile(mainModule)
   142  			if modFile.Go == nil || gover.Compare(modFile.Go.Version, gover.ExplicitIndirectVersion) < 0 {
   143  				if len(modFile.Require) > 0 {
   144  					args = []string{"all"}
   145  				}
   146  			} else {
   147  				// As of Go 1.17, the go.mod file explicitly requires every module
   148  				// that provides any package imported by the main module.
   149  				// 'go mod download' is typically run before testing packages in the
   150  				// main module, so by default we shouldn't download the others
   151  				// (which are presumed irrelevant to the packages in the main module).
   152  				// See https://golang.org/issue/44435.
   153  				//
   154  				// However, we also need to load the full module graph, to ensure that
   155  				// we have downloaded enough of the module graph to run 'go list all',
   156  				// 'go mod graph', and similar commands.
   157  				_, err := modload.LoadModGraph(moduleLoaderState, ctx, "")
   158  				if err != nil {
   159  					// TODO(#64008): call base.Fatalf instead of toolchain.SwitchOrFatal
   160  					// here, since we can only reach this point with an outdated toolchain
   161  					// if the go.mod file is inconsistent.
   162  					toolchain.SwitchOrFatal(moduleLoaderState, ctx, err)
   163  				}
   164  
   165  				for _, m := range modFile.Require {
   166  					args = append(args, m.Mod.Path)
   167  				}
   168  			}
   169  		}
   170  	}
   171  
   172  	if len(args) == 0 {
   173  		if moduleLoaderState.HasModRoot() {
   174  			os.Stderr.WriteString("go: no module dependencies to download\n")
   175  		} else {
   176  			base.Errorf("go: no modules specified (see 'go help mod download')")
   177  		}
   178  		base.Exit()
   179  	}
   180  
   181  	if *downloadReuse != "" && moduleLoaderState.HasModRoot() {
   182  		base.Fatalf("go mod download -reuse cannot be used inside a module")
   183  	}
   184  
   185  	var mods []*ModuleJSON
   186  	type token struct{}
   187  	sem := make(chan token, runtime.GOMAXPROCS(0))
   188  	infos, infosErr := modload.ListModules(moduleLoaderState, ctx, args, 0, *downloadReuse)
   189  
   190  	// There is a bit of a chicken-and-egg problem here: ideally we need to know
   191  	// which Go version to switch to download the requested modules, but if we
   192  	// haven't downloaded the module's go.mod file yet the GoVersion field of its
   193  	// info struct is not yet populated.
   194  	//
   195  	// We also need to be careful to only print the info for each module once
   196  	// if the -json flag is set.
   197  	//
   198  	// In theory we could go through each module in the list, attempt to download
   199  	// its go.mod file, and record the maximum version (either from the file or
   200  	// from the resulting TooNewError), all before we try the actual full download
   201  	// of each module.
   202  	//
   203  	// For now, we go ahead and try all the downloads and collect the errors, and
   204  	// if any download failed due to a TooNewError, we switch toolchains and try
   205  	// again. Any downloads that already succeeded will still be in cache.
   206  	// That won't give optimal concurrency (we'll do two batches of concurrent
   207  	// downloads instead of all in one batch), and it might add a little overhead
   208  	// to look up the downloads from the first batch in the module cache when
   209  	// we see them again in the second batch. On the other hand, it's way simpler
   210  	// to implement, and not really any more expensive if the user is requesting
   211  	// no explicit arguments (their go.mod file should already list an appropriate
   212  	// toolchain version) or only one module (as is used by the Go Module Proxy).
   213  
   214  	if infosErr != nil {
   215  		sw := toolchain.NewSwitcher(moduleLoaderState)
   216  		sw.Error(infosErr)
   217  		if sw.NeedSwitch() {
   218  			sw.Switch(ctx)
   219  		}
   220  		// Otherwise, wait to report infosErr after we have downloaded
   221  		// when we can.
   222  	}
   223  
   224  	if !haveExplicitArgs && modload.WorkFilePath(moduleLoaderState) == "" {
   225  		// 'go mod download' is sometimes run without arguments to pre-populate the
   226  		// module cache. In modules that aren't at go 1.17 or higher, it may fetch
   227  		// modules that aren't needed to build packages in the main module. This is
   228  		// usually not intended, so don't save sums for downloaded modules
   229  		// (golang.org/issue/45332). We do still fix inconsistencies in go.mod
   230  		// though.
   231  		//
   232  		// TODO(#64008): In the future, report an error if go.mod or go.sum need to
   233  		// be updated after loading the build list. This may require setting
   234  		// the mode to "mod" or "readonly" depending on haveExplicitArgs.
   235  		if err := modload.WriteGoMod(moduleLoaderState, ctx, modload.WriteOpts{}); err != nil {
   236  			base.Fatal(err)
   237  		}
   238  	}
   239  
   240  	var downloadErrs sync.Map
   241  	for _, info := range infos {
   242  		if info.Replace != nil {
   243  			info = info.Replace
   244  		}
   245  		if info.Version == "" && info.Error == nil {
   246  			// main module or module replaced with file path.
   247  			// Nothing to download.
   248  			continue
   249  		}
   250  		m := &ModuleJSON{
   251  			Path:    info.Path,
   252  			Version: info.Version,
   253  			Query:   info.Query,
   254  			Reuse:   info.Reuse,
   255  			Origin:  info.Origin,
   256  		}
   257  		mods = append(mods, m)
   258  		if info.Error != nil {
   259  			m.Error = info.Error.Err
   260  			continue
   261  		}
   262  		if m.Reuse {
   263  			continue
   264  		}
   265  		sem <- token{}
   266  		go func() {
   267  			err := DownloadModule(ctx, moduleLoaderState.Fetcher(), m)
   268  			if err != nil {
   269  				downloadErrs.Store(m, err)
   270  				m.Error = err.Error()
   271  			}
   272  			<-sem
   273  		}()
   274  	}
   275  
   276  	// Fill semaphore channel to wait for goroutines to finish.
   277  	for n := cap(sem); n > 0; n-- {
   278  		sem <- token{}
   279  	}
   280  
   281  	// If there were explicit arguments
   282  	// (like 'go mod download golang.org/x/tools@latest'),
   283  	// check whether we need to upgrade the toolchain in order to download them.
   284  	//
   285  	// (If invoked without arguments, we expect the module graph to already
   286  	// be tidy and the go.mod file to declare a 'go' version that satisfies
   287  	// transitive requirements. If that invariant holds, then we should have
   288  	// already upgraded when we loaded the module graph, and should not need
   289  	// an additional check here. See https://go.dev/issue/45551.)
   290  	//
   291  	// We also allow upgrades if in a workspace because in workspace mode
   292  	// with no arguments we download the module pattern "all",
   293  	// which may include dependencies that are normally pruned out
   294  	// of the individual modules in the workspace.
   295  	if haveExplicitArgs || modload.WorkFilePath(moduleLoaderState) != "" {
   296  		sw := toolchain.NewSwitcher(moduleLoaderState)
   297  		// Add errors to the Switcher in deterministic order so that they will be
   298  		// logged deterministically.
   299  		for _, m := range mods {
   300  			if erri, ok := downloadErrs.Load(m); ok {
   301  				sw.Error(erri.(error))
   302  			}
   303  		}
   304  		// Only call sw.Switch if it will actually switch.
   305  		// Otherwise, we may want to write the errors as JSON
   306  		// (instead of using base.Error as sw.Switch would),
   307  		// and we may also have other errors to report from the
   308  		// initial infos returned by ListModules.
   309  		if sw.NeedSwitch() {
   310  			sw.Switch(ctx)
   311  		}
   312  	}
   313  
   314  	if *downloadJSON {
   315  		for _, m := range mods {
   316  			b, err := json.MarshalIndent(m, "", "\t")
   317  			if err != nil {
   318  				base.Fatal(err)
   319  			}
   320  			os.Stdout.Write(append(b, '\n'))
   321  			if m.Error != "" {
   322  				base.SetExitStatus(1)
   323  			}
   324  		}
   325  	} else {
   326  		for _, m := range mods {
   327  			if m.Error != "" {
   328  				base.Error(errors.New(m.Error))
   329  			}
   330  		}
   331  		base.ExitIfErrors()
   332  	}
   333  
   334  	// If there were explicit arguments, update go.mod and especially go.sum.
   335  	// 'go mod download mod@version' is a useful way to add a sum without using
   336  	// 'go get mod@version', which may have other side effects. We print this in
   337  	// some error message hints.
   338  	//
   339  	// If we're in workspace mode, update go.work.sum with checksums for all of
   340  	// the modules we downloaded that aren't already recorded. Since a requirement
   341  	// in one module may upgrade a dependency of another, we can't be sure that
   342  	// the import graph matches the import graph of any given module in isolation,
   343  	// so we may end up needing to load packages from modules that wouldn't
   344  	// otherwise be relevant.
   345  	//
   346  	// TODO(#44435): If we adjust the set of modules downloaded in workspace mode,
   347  	// we may also need to adjust the logic for saving checksums here.
   348  	//
   349  	// Don't save sums for 'go mod download' without arguments unless we're in
   350  	// workspace mode; see comment above.
   351  	if haveExplicitArgs || modload.WorkFilePath(moduleLoaderState) != "" {
   352  		if err := modload.WriteGoMod(moduleLoaderState, ctx, modload.WriteOpts{}); err != nil {
   353  			base.Error(err)
   354  		}
   355  	}
   356  
   357  	// If there was an error matching some of the requested packages, emit it now
   358  	// (after we've written the checksums for the modules that were downloaded
   359  	// successfully).
   360  	if infosErr != nil {
   361  		base.Error(infosErr)
   362  	}
   363  }
   364  
   365  // DownloadModule runs 'go mod download' for m.Path@m.Version,
   366  // leaving the results (including any error) in m itself.
   367  func DownloadModule(ctx context.Context, f *modfetch.Fetcher, m *ModuleJSON) error {
   368  	var err error
   369  	_, file, err := f.InfoFile(ctx, m.Path, m.Version)
   370  	if err != nil {
   371  		return err
   372  	}
   373  	m.Info = file
   374  	m.GoMod, err = f.GoModFile(ctx, m.Path, m.Version)
   375  	if err != nil {
   376  		return err
   377  	}
   378  	m.GoModSum, err = f.GoModSum(ctx, m.Path, m.Version)
   379  	if err != nil {
   380  		return err
   381  	}
   382  	mod := module.Version{Path: m.Path, Version: m.Version}
   383  	m.Zip, err = f.DownloadZip(ctx, mod)
   384  	if err != nil {
   385  		return err
   386  	}
   387  	m.Sum = modfetch.Sum(ctx, mod)
   388  	m.Dir, err = f.Download(ctx, mod)
   389  	return err
   390  }
   391  

View as plain text