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

     1  package validators
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/ismailbayram/bigpicture/internal/graph"
     6  	"regexp"
     7  	"strings"
     8  )
     9  
    10  type FileNameValidatorArgs struct {
    11  	Module    string   `json:"module" validate:"required=true"`
    12  	MaxLength int      `json:"max_length" validate:"required=true,gte=1"`
    13  	Regexp    string   `json:"regexp"`
    14  	Ignore    []string `json:"ignore"`
    15  }
    16  
    17  type FileNameValidator struct {
    18  	args *FileNameValidatorArgs
    19  	tree *graph.Tree
    20  }
    21  
    22  func NewFileNameValidator(args map[string]any, tree *graph.Tree) (*FileNameValidator, error) {
    23  	validatorArgs := &FileNameValidatorArgs{}
    24  	if err := validateArgs(args, validatorArgs); err != nil {
    25  		return nil, err
    26  	}
    27  
    28  	module, err := validatePath(validatorArgs.Module, tree)
    29  	if err != nil {
    30  		return nil, err
    31  	}
    32  	validatorArgs.Module = module
    33  
    34  	return &FileNameValidator{
    35  		args: validatorArgs,
    36  		tree: tree,
    37  	}, nil
    38  }
    39  
    40  func (v *FileNameValidator) Validate() error {
    41  	for _, node := range v.tree.Nodes {
    42  		if isIgnored(v.args.Ignore, node.Path) {
    43  			continue
    44  		}
    45  		if !strings.HasPrefix(node.Path, v.args.Module) {
    46  			continue
    47  		}
    48  
    49  		if len(node.FileName()) > v.args.MaxLength {
    50  			return fmt.Errorf("File name of '%s' is longer than %d", node.Path, v.args.MaxLength)
    51  		}
    52  
    53  		if v.args.Regexp != "" {
    54  			re := regexp.MustCompile(v.args.Regexp)
    55  			if !re.MatchString(node.FileName()) {
    56  				return fmt.Errorf("File name of '%s' does not match '%s'", node.Path, v.args.Regexp)
    57  			}
    58  		}
    59  	}
    60  
    61  	return nil
    62  }