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.
13 "cmd/go/internal/base"
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",
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
36 cmdTidy
.Run
= runTidy
// break init cycle
37 cmdTidy
.Flag
.BoolVar(&cfg
.BuildV
, "v", false, "")
40 func runTidy(cmd
*base
.Command
, args
[]string) {
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() {
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
71 // modTidyGoSum resets the go.sum file content
72 // to be exactly what's needed for the current go.mod.
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
) {
81 list
, _
:= reqs
.Required(m
)
82 for _
, r
:= range list
{
89 modfetch
.TrimGoSum(keep
)