Source file src/cmd/go/internal/clean/clean.go

     1  // Copyright 2012 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 clean implements the “go clean” command.
     6  package clean
     7  
     8  import (
     9  	"context"
    10  	"errors"
    11  	"fmt"
    12  	"io"
    13  	"io/fs"
    14  	"os"
    15  	"path/filepath"
    16  	"runtime"
    17  	"strconv"
    18  	"strings"
    19  	"time"
    20  
    21  	"cmd/go/internal/base"
    22  	"cmd/go/internal/cache"
    23  	"cmd/go/internal/cfg"
    24  	"cmd/go/internal/load"
    25  	"cmd/go/internal/lockedfile"
    26  	"cmd/go/internal/modfetch"
    27  	"cmd/go/internal/modload"
    28  	"cmd/go/internal/str"
    29  	"cmd/go/internal/work"
    30  )
    31  
    32  var CmdClean = &base.Command{
    33  	UsageLine: "go clean [-i] [-r] [-cache] [-testcache] [-modcache] [-fuzzcache] [build flags] [packages]",
    34  	Short:     "remove object files and cached files",
    35  	Long: `
    36  Clean removes object files from package source directories.
    37  The go command builds most objects in a temporary directory,
    38  so go clean is mainly concerned with object files left by other
    39  tools or by manual invocations of go build.
    40  
    41  If a package argument is given or the -i or -r flag is set,
    42  clean removes the following files from each of the
    43  source directories corresponding to the import paths:
    44  
    45  	_obj/            old object directory, left from Makefiles
    46  	_test/           old test directory, left from Makefiles
    47  	_testmain.go     old gotest file, left from Makefiles
    48  	test.out         old test log, left from Makefiles
    49  	build.out        old test log, left from Makefiles
    50  	*.[568ao]        object files, left from Makefiles
    51  
    52  	DIR(.exe)        from go build
    53  	DIR.test(.exe)   from go test -c
    54  	MAINFILE(.exe)   from go build MAINFILE.go
    55  	*.so             from SWIG
    56  
    57  In the list, DIR represents the final path element of the
    58  directory, and MAINFILE is the base name of any Go source
    59  file in the directory that is not included when building
    60  the package.
    61  
    62  The -i flag causes clean to remove the corresponding installed
    63  archive or binary (what 'go install' would create).
    64  
    65  The -n flag causes clean to print the remove commands it would execute,
    66  but not run them.
    67  
    68  The -r flag causes clean to be applied recursively to all the
    69  dependencies of the packages named by the import paths.
    70  
    71  The -x flag causes clean to print remove commands as it executes them.
    72  
    73  The -cache flag causes clean to remove the entire go build cache.
    74  
    75  The -testcache flag causes clean to expire all test results in the
    76  go build cache.
    77  
    78  The -modcache flag causes clean to remove the entire module
    79  download cache, including unpacked source code of versioned
    80  dependencies.
    81  
    82  The -fuzzcache flag causes clean to remove files stored in the Go build
    83  cache for fuzz testing. The fuzzing engine caches files that expand
    84  code coverage, so removing them may make fuzzing less effective until
    85  new inputs are found that provide the same coverage. These files are
    86  distinct from those stored in testdata directory; clean does not remove
    87  those files.
    88  
    89  For more about build flags, see 'go help build'.
    90  
    91  For more about specifying packages, see 'go help packages'.
    92  	`,
    93  }
    94  
    95  var (
    96  	cleanI         bool // clean -i flag
    97  	cleanR         bool // clean -r flag
    98  	cleanCache     bool // clean -cache flag
    99  	cleanFuzzcache bool // clean -fuzzcache flag
   100  	cleanModcache  bool // clean -modcache flag
   101  	cleanTestcache bool // clean -testcache flag
   102  )
   103  
   104  func init() {
   105  	// break init cycle
   106  	CmdClean.Run = runClean
   107  
   108  	CmdClean.Flag.BoolVar(&cleanI, "i", false, "remove the corresponding installed archive or binary (what 'go install' would create)")
   109  	CmdClean.Flag.BoolVar(&cleanR, "r", false, "apply clean recursively to all the dependencies of the packages named by the import paths")
   110  	CmdClean.Flag.BoolVar(&cleanCache, "cache", false, "remove the entire go build cache")
   111  	CmdClean.Flag.BoolVar(&cleanFuzzcache, "fuzzcache", false, "remove all cached fuzzing values")
   112  	CmdClean.Flag.BoolVar(&cleanModcache, "modcache", false, "remove the entire module download cache, including unpacked source code of versioned dependencies")
   113  	CmdClean.Flag.BoolVar(&cleanTestcache, "testcache", false, "expire all test results in the go build cache")
   114  
   115  	// -n and -x are important enough to be
   116  	// mentioned explicitly in the docs but they
   117  	// are part of the build flags.
   118  
   119  	work.AddBuildFlags(CmdClean, work.OmitBuildOnlyFlags)
   120  }
   121  
   122  func runClean(ctx context.Context, cmd *base.Command, args []string) {
   123  	moduleLoader := modload.NewLoader()
   124  	moduleLoader.InitWorkfile()
   125  	if len(args) > 0 {
   126  		cacheFlag := ""
   127  		switch {
   128  		case cleanCache:
   129  			cacheFlag = "-cache"
   130  		case cleanTestcache:
   131  			cacheFlag = "-testcache"
   132  		case cleanFuzzcache:
   133  			cacheFlag = "-fuzzcache"
   134  		case cleanModcache:
   135  			cacheFlag = "-modcache"
   136  		}
   137  		if cacheFlag != "" {
   138  			base.Fatalf("go: clean %s cannot be used with package arguments", cacheFlag)
   139  		}
   140  	}
   141  
   142  	// golang.org/issue/29925: only load packages before cleaning if
   143  	// either the flags and arguments explicitly imply a package,
   144  	// or no other target (such as a cache) was requested to be cleaned.
   145  	cleanPkg := len(args) > 0 || cleanI || cleanR
   146  	if (!moduleLoader.Enabled() || moduleLoader.HasModRoot()) &&
   147  		!cleanCache && !cleanModcache && !cleanTestcache && !cleanFuzzcache {
   148  		cleanPkg = true
   149  	}
   150  
   151  	if cleanPkg {
   152  		for _, pkg := range load.PackagesAndErrors(moduleLoader, ctx, load.PackageOpts{}, args) {
   153  			clean(pkg)
   154  		}
   155  	}
   156  
   157  	sh := work.NewShell("", &load.TextPrinter{Writer: os.Stdout})
   158  
   159  	if cleanCache {
   160  		dir, _, err := cache.DefaultDir()
   161  		if err != nil {
   162  			base.Fatal(err)
   163  		}
   164  		if dir != "off" {
   165  			// Remove the cache subdirectories but not the top cache directory.
   166  			// The top cache directory may have been created with special permissions
   167  			// and not something that we want to remove. Also, preserve trim.txt and
   168  			// size.txt (reset by cache.CleanCache below) as well as cache.log,
   169  			// cache.1.log, and cache.2.log, which record trim history across cleans.
   170  			subdirs, _ := filepath.Glob(filepath.Join(str.QuoteGlob(dir), "[0-9a-f][0-9a-f]"))
   171  			printedErrors := false
   172  			if len(subdirs) > 0 {
   173  				if err := sh.RemoveAll(subdirs...); err != nil && !printedErrors {
   174  					printedErrors = true
   175  					base.Error(err)
   176  				}
   177  			}
   178  
   179  			logFile := filepath.Join(dir, "log.txt")
   180  			if err := sh.RemoveAll(logFile); err != nil && !printedErrors {
   181  				printedErrors = true
   182  				base.Error(err)
   183  			}
   184  
   185  			if !cfg.BuildN && cfg.Experiment != nil && cfg.Experiment.TrimBuildCache {
   186  				cache.CleanCache(dir)
   187  			}
   188  		}
   189  	}
   190  
   191  	if cleanTestcache && !cleanCache {
   192  		// Instead of walking through the entire cache looking for test results,
   193  		// we write a file to the cache indicating that all test results from before
   194  		// right now are to be ignored.
   195  		dir, _, err := cache.DefaultDir()
   196  		if err != nil {
   197  			base.Fatal(err)
   198  		}
   199  		if dir != "off" {
   200  			f, err := lockedfile.Edit(filepath.Join(dir, "testexpire.txt"))
   201  			if err == nil {
   202  				now := time.Now().UnixNano()
   203  				buf, _ := io.ReadAll(f)
   204  				prev, _ := strconv.ParseInt(strings.TrimSpace(string(buf)), 10, 64)
   205  				if now > prev {
   206  					if err = f.Truncate(0); err == nil {
   207  						if _, err = f.Seek(0, 0); err == nil {
   208  							_, err = fmt.Fprintf(f, "%d\n", now)
   209  						}
   210  					}
   211  				}
   212  				if closeErr := f.Close(); err == nil {
   213  					err = closeErr
   214  				}
   215  			}
   216  			if err != nil {
   217  				if _, statErr := os.Stat(dir); !os.IsNotExist(statErr) {
   218  					base.Error(err)
   219  				}
   220  			}
   221  		}
   222  	}
   223  
   224  	if cleanModcache {
   225  		if cfg.GOMODCACHE == "" {
   226  			base.Fatalf("go: cannot clean -modcache without a module cache")
   227  		}
   228  		if cfg.BuildN || cfg.BuildX {
   229  			sh.ShowCmd("", "rm -rf %s", cfg.GOMODCACHE)
   230  		}
   231  		if !cfg.BuildN {
   232  			if err := modfetch.RemoveAll(cfg.GOMODCACHE); err != nil {
   233  				base.Error(err)
   234  
   235  				// Add extra logging for the purposes of debugging #68087.
   236  				// We're getting ENOTEMPTY errors on openbsd from RemoveAll.
   237  				// Check for os.ErrExist, which can match syscall.ENOTEMPTY
   238  				// and syscall.EEXIST, because syscall.ENOTEMPTY is not defined
   239  				// on all platforms.
   240  				if runtime.GOOS == "openbsd" && errors.Is(err, fs.ErrExist) {
   241  					logFilesInGOMODCACHE()
   242  				}
   243  			}
   244  		}
   245  	}
   246  
   247  	if cleanFuzzcache {
   248  		fuzzDir := cache.Default().FuzzDir()
   249  		if err := sh.RemoveAll(fuzzDir); err != nil {
   250  			base.Error(err)
   251  		}
   252  	}
   253  }
   254  
   255  // logFilesInGOMODCACHE reports the file names and modes for the files in GOMODCACHE using base.Error.
   256  func logFilesInGOMODCACHE() {
   257  	var found []string
   258  	werr := filepath.WalkDir(cfg.GOMODCACHE, func(path string, d fs.DirEntry, err error) error {
   259  		if err != nil {
   260  			return err
   261  		}
   262  		var mode string
   263  		info, err := d.Info()
   264  		if err == nil {
   265  			mode = info.Mode().String()
   266  		} else {
   267  			mode = fmt.Sprintf("<err: %s>", info.Mode())
   268  		}
   269  		found = append(found, fmt.Sprintf("%s (mode: %s)", path, mode))
   270  		return nil
   271  	})
   272  	if werr != nil {
   273  		base.Errorf("walking files in GOMODCACHE (for debugging go.dev/issue/68087): %v", werr)
   274  	}
   275  	base.Errorf("files in GOMODCACHE (for debugging go.dev/issue/68087):\n%s", strings.Join(found, "\n"))
   276  }
   277  
   278  var cleaned = map[*load.Package]bool{}
   279  
   280  var cleanFile = map[string]bool{
   281  	"_testmain.go": true,
   282  	"test.out":     true,
   283  	"build.out":    true,
   284  	"a.out":        true,
   285  }
   286  
   287  var cleanExt = map[string]bool{
   288  	".5":  true,
   289  	".6":  true,
   290  	".8":  true,
   291  	".a":  true,
   292  	".o":  true,
   293  	".so": true,
   294  }
   295  
   296  func clean(p *load.Package) {
   297  	if cleaned[p] {
   298  		return
   299  	}
   300  	cleaned[p] = true
   301  
   302  	if p.Dir == "" {
   303  		base.Errorf("%v", p.Error)
   304  		return
   305  	}
   306  	dirs, err := os.ReadDir(p.Dir)
   307  	if err != nil {
   308  		base.Errorf("go: %s: %v", p.Dir, err)
   309  		return
   310  	}
   311  
   312  	sh := work.NewShell("", &load.TextPrinter{Writer: os.Stdout})
   313  
   314  	packageFile := map[string]bool{}
   315  	if p.Name != "main" {
   316  		// Record which files are not in package main.
   317  		// The others are.
   318  		keep := func(list []string) {
   319  			for _, f := range list {
   320  				packageFile[f] = true
   321  			}
   322  		}
   323  		keep(p.GoFiles)
   324  		keep(p.CgoFiles)
   325  		keep(p.TestGoFiles)
   326  		keep(p.XTestGoFiles)
   327  	}
   328  
   329  	_, elem := filepath.Split(p.Dir)
   330  	toRemove := map[string]bool{}
   331  
   332  	// Remove dir-named executable only if this is package main.
   333  	if p.Name == "main" {
   334  		toRemove[elem] = true
   335  		toRemove[elem+".exe"] = true
   336  		toRemove[p.DefaultExecName()] = true
   337  		toRemove[p.DefaultExecName()+".exe"] = true
   338  	}
   339  
   340  	// Remove package test executables.
   341  	toRemove[elem+".test"] = true
   342  	toRemove[elem+".test.exe"] = true
   343  	toRemove[p.DefaultExecName()+".test"] = true
   344  	toRemove[p.DefaultExecName()+".test.exe"] = true
   345  
   346  	// Remove a potential executable, test executable for each .go file in the directory that
   347  	// is not part of the directory's package.
   348  	for _, dir := range dirs {
   349  		name := dir.Name()
   350  		if packageFile[name] {
   351  			continue
   352  		}
   353  
   354  		if dir.IsDir() {
   355  			continue
   356  		}
   357  
   358  		if base, found := strings.CutSuffix(name, "_test.go"); found {
   359  			toRemove[base+".test"] = true
   360  			toRemove[base+".test.exe"] = true
   361  		}
   362  
   363  		if base, found := strings.CutSuffix(name, ".go"); found {
   364  			// TODO(adg,rsc): check that this .go file is actually
   365  			// in "package main", and therefore capable of building
   366  			// to an executable file.
   367  			toRemove[base] = true
   368  			toRemove[base+".exe"] = true
   369  		}
   370  	}
   371  
   372  	for _, dir := range dirs {
   373  		name := dir.Name()
   374  		if dir.IsDir() {
   375  			// Clean the .dSYM directory for split DWARF.
   376  			if exe, ok := strings.CutSuffix(name, ".dSYM"); ok && (cleanFile[exe] || toRemove[exe]) {
   377  				if err := sh.RemoveAll(filepath.Join(p.Dir, name)); err != nil {
   378  					base.Error(err)
   379  				}
   380  			}
   381  			continue
   382  		}
   383  		if cleanFile[name] || cleanExt[filepath.Ext(name)] || toRemove[name] {
   384  			removeFile(sh, filepath.Join(p.Dir, name))
   385  		}
   386  	}
   387  
   388  	if cleanI && p.Target != "" {
   389  		removeFile(sh, p.Target)
   390  	}
   391  
   392  	if cleanR {
   393  		for _, p1 := range p.Internal.Imports {
   394  			clean(p1)
   395  		}
   396  	}
   397  }
   398  
   399  // removeFile tries to remove file f, if error other than file doesn't exist
   400  // occurs, it will report the error.
   401  func removeFile(sh *work.Shell, f string) {
   402  	if cfg.BuildN || cfg.BuildX {
   403  		sh.ShowCmd("", "rm -f %s", f)
   404  	}
   405  	if cfg.BuildN {
   406  		return
   407  	}
   408  	err := os.Remove(f)
   409  	if err == nil || os.IsNotExist(err) {
   410  		return
   411  	}
   412  	// Windows does not allow deletion of a binary file while it is executing.
   413  	if runtime.GOOS == "windows" {
   414  		// Remove lingering ~ file from last attempt.
   415  		if _, err2 := os.Stat(f + "~"); err2 == nil {
   416  			os.Remove(f + "~")
   417  		}
   418  		// Try to move it out of the way. If the move fails,
   419  		// which is likely, we'll try again the
   420  		// next time we do an install of this binary.
   421  		if err2 := os.Rename(f, f+"~"); err2 == nil {
   422  			os.Remove(f + "~")
   423  			return
   424  		}
   425  	}
   426  	base.Error(err)
   427  }
   428  

View as plain text