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

     1  package validators
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/ismailbayram/bigpicture/internal/graph"
     6  	"strings"
     7  )
     8  
     9  type NoImportValidatorArgs struct {
    10  	From   string   `json:"from" validate:"required=true"`
    11  	To     string   `json:"to" validate:"required=true"`
    12  	Ignore []string `json:"ignore"`
    13  }
    14  
    15  type NoImportValidator struct {
    16  	args *NoImportValidatorArgs
    17  	tree *graph.Tree
    18  }
    19  
    20  func NewNoImportValidator(args map[string]any, tree *graph.Tree) (*NoImportValidator, error) {
    21  	validatorArgs := &NoImportValidatorArgs{}
    22  	if err := validateArgs(args, validatorArgs); err != nil {
    23  		return nil, err
    24  	}
    25  
    26  	from, err := validatePath(validatorArgs.From, tree)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  	validatorArgs.From = from
    31  
    32  	to, err := validatePath(validatorArgs.To, tree)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	validatorArgs.To = to
    37  
    38  	return &NoImportValidator{
    39  		args: validatorArgs,
    40  		tree: tree,
    41  	}, nil
    42  }
    43  
    44  func (v *NoImportValidator) Validate() error {
    45  	for _, link := range v.tree.Links {
    46  		if isIgnored(v.args.Ignore, link.From.Path) || isIgnored(v.args.Ignore, link.To.Path) {
    47  			continue
    48  		}
    49  
    50  		if strings.HasPrefix(link.From.Path, v.args.From) && strings.HasPrefix(link.To.Path, v.args.To) {
    51  			return fmt.Errorf("'%s' cannot import '%s'", link.From.Path, link.To.Path)
    52  		}
    53  		if v.args.From == "*" && strings.HasPrefix(link.To.Path, v.args.To) || v.args.To == "*" && strings.HasPrefix(link.From.Path, v.args.From) {
    54  			return fmt.Errorf("'%s' cannot import '%s'", link.From.Path, link.To.Path)
    55  		}
    56  	}
    57  
    58  	return nil
    59  }