github.com/orteth01/up@v0.2.0/internal/validate/validate.go (about)

     1  // Package validate provides config validation functions.
     2  package validate
     3  
     4  import (
     5  	"regexp"
     6  	"strings"
     7  
     8  	"github.com/pkg/errors"
     9  )
    10  
    11  // RequiredString validation.
    12  func RequiredString(s string) error {
    13  	if strings.TrimSpace(s) == "" {
    14  		return errors.New("is required")
    15  	}
    16  
    17  	return nil
    18  }
    19  
    20  // RequiredStrings validation.
    21  func RequiredStrings(s []string) error {
    22  	for i, v := range s {
    23  		if err := RequiredString(v); err != nil {
    24  			return errors.Wrapf(err, "at index %d", i)
    25  		}
    26  	}
    27  
    28  	return nil
    29  }
    30  
    31  // MinStrings validation.
    32  func MinStrings(s []string, n int) error {
    33  	if len(s) < n {
    34  		if n == 1 {
    35  			return errors.Errorf("must have at least %d value", n)
    36  		}
    37  
    38  		return errors.Errorf("must have at least %d values", n)
    39  	}
    40  
    41  	return nil
    42  }
    43  
    44  // name regexp.
    45  var name = regexp.MustCompile(`^[a-zA-Z][-a-zA-Z0-9]*$`)
    46  
    47  // Name validation.
    48  func Name(s string) error {
    49  	if !name.MatchString(s) {
    50  		return errors.Errorf("must contain only alphanumeric characters and '-'")
    51  	}
    52  
    53  	return nil
    54  }
    55  
    56  // List validation.
    57  func List(s string, list []string) error {
    58  	for _, v := range list {
    59  		if s == v {
    60  			return nil
    61  		}
    62  	}
    63  
    64  	return errors.Errorf("%q is invalid, must be one of:\n\n  • %s", s, strings.Join(list, "\n  • "))
    65  }
    66  
    67  // Lists validation.
    68  func Lists(vals, list []string) error {
    69  	for _, v := range vals {
    70  		if err := List(v, list); err != nil {
    71  			return err
    72  		}
    73  	}
    74  
    75  	return nil
    76  }
    77  
    78  // Stage validation.
    79  func Stage(stage string) error {
    80  	if err := List(stage, []string{"development", "staging", "production"}); err != nil {
    81  		return errors.Wrap(err, "stage")
    82  	}
    83  
    84  	return nil
    85  }