github.com/ismailbayram/bigpicture@v0.0.0-20231225173155-e4b21f5efcff/internal/validators/instability.go (about)

     1  package validators
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/ismailbayram/bigpicture/internal/graph"
     6  )
     7  
     8  type InstabilityValidatorArgs struct {
     9  	Module string  `json:"module" validate:"required=true"`
    10  	Max    float64 `json:"max" validate:"required=true,min=0,max=1"`
    11  }
    12  
    13  type InstabilityValidator struct {
    14  	args *InstabilityValidatorArgs
    15  	tree *graph.Tree
    16  }
    17  
    18  func NewInstabilityValidator(args map[string]any, tree *graph.Tree) (*InstabilityValidator, error) {
    19  	validatorArgs := &InstabilityValidatorArgs{}
    20  	if err := validateArgs(args, validatorArgs); err != nil {
    21  		return nil, err
    22  	}
    23  
    24  	module, err := validatePath(validatorArgs.Module, tree)
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  	validatorArgs.Module = module
    29  
    30  	return &InstabilityValidator{
    31  		args: validatorArgs,
    32  		tree: tree,
    33  	}, nil
    34  }
    35  
    36  func (v *InstabilityValidator) Validate() error {
    37  	node := v.tree.Nodes[v.args.Module]
    38  
    39  	if node.Instability != nil && *node.Instability > v.args.Max {
    40  		return fmt.Errorf(
    41  			"instability of %s is %.2f, but should be less than %.2f",
    42  			node.Path,
    43  			*node.Instability,
    44  			v.args.Max,
    45  		)
    46  	}
    47  	return nil
    48  }