libgo: update to Go 1.11
[official-gcc.git] / libgo / go / cmd / go / internal / modcmd / tidy.go
blobf2063a9ea601c976d596c9581aed7144db2f605d
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.
5 // go mod tidy
7 package modcmd
9 import (
10 "fmt"
11 "os"
13 "cmd/go/internal/base"
14 "cmd/go/internal/cfg"
15 "cmd/go/internal/modfetch"
16 "cmd/go/internal/modload"
17 "cmd/go/internal/module"
20 var cmdTidy = &base.Command{
21 UsageLine: "go mod tidy [-v]",
22 Short: "add missing and remove unused modules",
23 Long: `
24 Tidy makes sure go.mod matches the source code in the module.
25 It adds any missing modules necessary to build the current module's
26 packages and dependencies, and it removes unused modules that
27 don't provide any relevant packages. It also adds any missing entries
28 to go.sum and removes any unnecessary ones.
30 The -v flag causes tidy to print information about removed modules
31 to standard error.
35 func init() {
36 cmdTidy.Run = runTidy // break init cycle
37 cmdTidy.Flag.BoolVar(&cfg.BuildV, "v", false, "")
40 func runTidy(cmd *base.Command, args []string) {
41 if len(args) > 0 {
42 base.Fatalf("go mod tidy: no arguments allowed")
45 // LoadALL adds missing modules.
46 // Remove unused modules.
47 used := make(map[module.Version]bool)
48 for _, pkg := range modload.LoadALL() {
49 used[modload.PackageModule(pkg)] = true
51 used[modload.Target] = true // note: LoadALL initializes Target
53 inGoMod := make(map[string]bool)
54 for _, r := range modload.ModFile().Require {
55 inGoMod[r.Mod.Path] = true
58 var keep []module.Version
59 for _, m := range modload.BuildList() {
60 if used[m] {
61 keep = append(keep, m)
62 } else if cfg.BuildV && inGoMod[m.Path] {
63 fmt.Fprintf(os.Stderr, "unused %s\n", m.Path)
66 modload.SetBuildList(keep)
67 modTidyGoSum() // updates memory copy; WriteGoMod on next line flushes it out
68 modload.WriteGoMod()
71 // modTidyGoSum resets the go.sum file content
72 // to be exactly what's needed for the current go.mod.
73 func modTidyGoSum() {
74 // Assuming go.sum already has at least enough from the successful load,
75 // we only have to tell modfetch what needs keeping.
76 reqs := modload.Reqs()
77 keep := make(map[module.Version]bool)
78 var walk func(module.Version)
79 walk = func(m module.Version) {
80 keep[m] = true
81 list, _ := reqs.Required(m)
82 for _, r := range list {
83 if !keep[r] {
84 walk(r)
88 walk(modload.Target)
89 modfetch.TrimGoSum(keep)