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

     1  package cmd
     2  
     3  import (
     4  	"github.com/muesli/coral"
     5  	"golang.org/x/mod/semver"
     6  )
     7  
     8  func init() {
     9  	rootCmd.AddCommand(&coral.Command{
    10  		Use:   "update",
    11  		Short: "Update dependencies to the latest version",
    12  		Long:  "Updates all direct dependencies to a newer version if available so that 'modtools check' passes",
    13  		RunE: func(cmd *coral.Command, args []string) error {
    14  			return updateDeps(getDirectOnly(cmd))
    15  		},
    16  	})
    17  }
    18  
    19  func updateDeps(directOnly bool) error {
    20  	e, err := loadExceptions()
    21  	if err != nil {
    22  		return err
    23  	}
    24  	list, err := readDeps(true, directOnly)
    25  	if err != nil {
    26  		return err
    27  	}
    28  	for _, item := range list {
    29  		if item.Update.Version != "" {
    30  			if ex := e.Get(item.Path); ex != nil {
    31  				if semver.Compare(item.Version, ex.MinVersion) >= 0 {
    32  					continue
    33  				}
    34  			}
    35  			_, err = runCommand("go", "get", "-d", item.Path+"@"+item.Update.Version)
    36  			if err != nil {
    37  				break
    38  			}
    39  		}
    40  	}
    41  	if err == nil {
    42  		err = e.Save()
    43  	}
    44  	return err
    45  }