github.com/dop251/modtools@v0.0.0-20220314120634-3b2fc95d1790/cmd/check.go (about)

     1  package cmd
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  
     7  	"github.com/muesli/coral"
     8  	"golang.org/x/mod/semver"
     9  )
    10  
    11  func init() {
    12  	rootCmd.AddCommand(&coral.Command{
    13  		Use:   "check",
    14  		Short: "Check for out-of-date dependencies",
    15  		Long:  "Scans through direct and indirect dependencies to check if a newer version is available. Exceptions can be set by 'modtools freeze'",
    16  		RunE: func(cmd *coral.Command, args []string) error {
    17  			res, err := checkDeps(getDirectOnly(cmd))
    18  			if err != nil {
    19  				return err
    20  			}
    21  			if len(res) > 0 {
    22  				fmt.Printf("Some dependencies are out-of-date. Please upgrade by running 'modtools update' or the following commands:\n\n")
    23  				for _, item := range res {
    24  					fmt.Printf("go get %s@%s\n", item.Path, item.Version)
    25  				}
    26  				fmt.Println()
    27  				return errors.New("check has failed")
    28  			}
    29  			return nil
    30  		},
    31  	})
    32  }
    33  
    34  func checkDeps(directOnly bool) (updates []Update, err error) {
    35  	e, err := loadExceptions()
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  	list, err := readDeps(true, directOnly)
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  	for _, item := range list {
    44  		if ex := e.Get(item.Path); ex != nil {
    45  			if semver.Compare(item.Version, ex.MinVersion) < 0 {
    46  				updates = append(updates, Update{Path: item.Path, Version: ex.MinVersion})
    47  				fmt.Printf("Frozen module %q should be at least version %q\n", item.Path, ex.MinVersion)
    48  			}
    49  			continue
    50  		}
    51  		if item.Update.Version != "" {
    52  			updates = append(updates, item.Update)
    53  		}
    54  	}
    55  	return
    56  }