/
validation.go
101 lines (82 loc) · 2.51 KB
/
validation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package utils
import (
"fmt"
"os"
"regexp"
"github.com/AlecAivazis/survey/v2"
"github.com/pluralsh/plural-cli/pkg/utils/errors"
)
const (
dnsRegex = "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])"
)
func ValidateSingleLevelDeep(val, subdomain string) error {
reg, err := regexp.Compile(fmt.Sprintf("\\w+.%s", subdomain))
if err != nil {
return err
}
submatch := reg.FindStringSubmatch(val)
if len(submatch) == 1 {
if submatch[0] == val {
return nil
}
}
return fmt.Errorf("use single level deep domain: <domainName>.%s", subdomain)
}
func ValidateRegex(val, regex, message string) error {
reg, err := regexp.Compile(fmt.Sprintf("^%s$", regex))
if err != nil {
return err
}
if reg.MatchString(val) {
return nil
}
return errors.ErrorWrap(fmt.Errorf(message), "Validation Failure")
}
func RegexValidator(regex, message string) survey.Validator {
return func(val interface{}) error {
str, ok := val.(string)
if !ok {
return fmt.Errorf("Result is not a string")
}
return ValidateRegex(str, regex, message)
}
}
// ValidateStorageAccountName validates Azure storage account names.
var ValidateStorageAccountName = survey.ComposeValidators(
survey.Required,
RegexValidator("[a-z][a-z0-9]{2,23}", "Must be between 3 and 24 characters in length, start with lowercase letter and may contain numbers and lowercase letters only"),
)
// ValidateResourceGroupName validates Azure resource group names.
var ValidateResourceGroupName = survey.ComposeValidators(
survey.Required,
RegexValidator("[a-z][a-z0-9]{2,62}", "Must be between 3 and 63 characters in length, start with lowercase letter and may contain numbers and lowercase letters only"),
)
var ValidateAlphaNumeric = survey.ComposeValidators(
survey.Required,
RegexValidator("[a-z][0-9\\-a-z]+", "Must be an alphanumeric string"),
)
func ValidateDns(val string) error {
return ValidateRegex(val, dnsRegex, "String must be a dns compliant hostname")
}
func Confirm(msg string) bool {
res := true
prompt := &survey.Confirm{Message: msg, Default: true}
if err := survey.AskOne(prompt, &res, survey.WithValidator(survey.Required)); err != nil {
return false
}
return res
}
func FileExists(val interface{}) error {
path, ok := val.(string)
if !ok {
return fmt.Errorf("value is not a string: %v", val)
}
info, err := os.Stat(path)
if os.IsNotExist(err) {
return err
}
if info.IsDir() {
return fmt.Errorf("provided path points to a directory, not a file: %s", path)
}
return nil
}