github.com/elek/golangci-lint@v1.42.2-0.20211208090441-c05b7fcb3a9a/pkg/commands/cache.go (about)

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/spf13/cobra"
     9  
    10  	"github.com/elek/golangci-lint/internal/cache"
    11  	"github.com/elek/golangci-lint/pkg/fsutils"
    12  	"github.com/elek/golangci-lint/pkg/logutils"
    13  )
    14  
    15  func (e *Executor) initCache() {
    16  	cacheCmd := &cobra.Command{
    17  		Use:   "cache",
    18  		Short: "Cache control and information",
    19  		Run: func(cmd *cobra.Command, args []string) {
    20  			if len(args) != 0 {
    21  				e.log.Fatalf("Usage: golangci-lint cache")
    22  			}
    23  			if err := cmd.Help(); err != nil {
    24  				e.log.Fatalf("Can't run cache: %s", err)
    25  			}
    26  		},
    27  	}
    28  	e.rootCmd.AddCommand(cacheCmd)
    29  
    30  	cacheCmd.AddCommand(&cobra.Command{
    31  		Use:   "clean",
    32  		Short: "Clean cache",
    33  		Run:   e.executeCleanCache,
    34  	})
    35  	cacheCmd.AddCommand(&cobra.Command{
    36  		Use:   "status",
    37  		Short: "Show cache status",
    38  		Run:   e.executeCacheStatus,
    39  	})
    40  
    41  	// TODO: add trim command?
    42  }
    43  
    44  func (e *Executor) executeCleanCache(_ *cobra.Command, args []string) {
    45  	if len(args) != 0 {
    46  		e.log.Fatalf("Usage: golangci-lint cache clean")
    47  	}
    48  
    49  	cacheDir := cache.DefaultDir()
    50  	if err := os.RemoveAll(cacheDir); err != nil {
    51  		e.log.Fatalf("Failed to remove dir %s: %s", cacheDir, err)
    52  	}
    53  
    54  	os.Exit(0)
    55  }
    56  
    57  func (e *Executor) executeCacheStatus(_ *cobra.Command, args []string) {
    58  	if len(args) != 0 {
    59  		e.log.Fatalf("Usage: golangci-lint cache status")
    60  	}
    61  
    62  	cacheDir := cache.DefaultDir()
    63  	fmt.Fprintf(logutils.StdOut, "Dir: %s\n", cacheDir)
    64  	cacheSizeBytes, err := dirSizeBytes(cacheDir)
    65  	if err == nil {
    66  		fmt.Fprintf(logutils.StdOut, "Size: %s\n", fsutils.PrettifyBytesCount(cacheSizeBytes))
    67  	}
    68  
    69  	os.Exit(0)
    70  }
    71  
    72  func dirSizeBytes(path string) (int64, error) {
    73  	var size int64
    74  	err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
    75  		if err != nil {
    76  			return err
    77  		}
    78  		if !info.IsDir() {
    79  			size += info.Size()
    80  		}
    81  		return err
    82  	})
    83  	return size, err
    84  }