github.com/sandwich-go/boost@v1.3.29/xdebug/dependency.go (about)

     1  package xdebug
     2  
     3  import (
     4  	"github.com/coreos/go-semver/semver"
     5  	"github.com/sandwich-go/boost"
     6  	"runtime/debug"
     7  )
     8  
     9  type dependency interface {
    10  	GetPath() string
    11  	GetRequireVersion() string
    12  	WarnString() string
    13  }
    14  
    15  // dependencies 依赖的包
    16  var dependencies = make([]dependency, 0)
    17  
    18  func registerDependency(d dependency) {
    19  	dependencies = append(dependencies, d)
    20  }
    21  
    22  func getDependenciesFromBuildInfo() (map[string]semver.Version, bool) {
    23  	bi, ok := debug.ReadBuildInfo()
    24  	if !ok {
    25  		// read fail, don't check require dependencies
    26  		return nil, false
    27  	}
    28  	if bi == nil {
    29  		return nil, true
    30  	}
    31  	var out = make(map[string]semver.Version)
    32  	for _, dep := range bi.Deps {
    33  		if v, _ := semver.NewVersion(dep.Version); v != nil {
    34  			out[dep.Path] = *v
    35  		} else {
    36  			out[dep.Path] = semver.Version{}
    37  		}
    38  	}
    39  	return out, true
    40  }
    41  
    42  func checkRequireDependency(deps map[string]semver.Version, requireDependency dependency) bool {
    43  	// has require dependency?
    44  	depSemVer, ok := deps[requireDependency.GetPath()]
    45  	if !ok {
    46  		return false
    47  	}
    48  	// compare dependency version
    49  	requireVer := requireDependency.GetRequireVersion()
    50  	if len(requireVer) == 0 {
    51  		return true
    52  	}
    53  	requireSemVer, _ := semver.NewVersion(requireVer)
    54  	if requireSemVer == nil {
    55  		return true
    56  	}
    57  	return requireSemVer.LessThan(depSemVer) || requireSemVer.Equal(depSemVer)
    58  }
    59  
    60  // CheckRequireDependencies 检查依赖
    61  func CheckRequireDependencies() {
    62  	deps, ok := getDependenciesFromBuildInfo()
    63  	if !ok {
    64  		return
    65  	}
    66  	for _, v := range dependencies {
    67  		if checkRequireDependency(deps, v) {
    68  			continue
    69  		}
    70  		boost.LogWarn(v.WarnString())
    71  	}
    72  }