-
Notifications
You must be signed in to change notification settings - Fork 0
/
regexp_utility.go
94 lines (74 loc) · 1.97 KB
/
regexp_utility.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
package main
import (
"flag"
"fmt"
"os"
"regexp_utility/cmd"
)
type stringArrayFlags []string
func (i *stringArrayFlags) Set(value string) error {
*i = append(*i, value)
return nil
}
// needed by flag
func (i *stringArrayFlags) String() string {
return ""
}
func mask(input *string, regexpList *[]string) {
result := cmd.Mask(input, regexpList)
fmt.Print(result)
}
func validate(regularExpression *string) {
isValid := cmd.Validate(regularExpression)
if !isValid {
fmt.Print("Invalid regular expression")
os.Exit(1)
}
}
func main() {
// mask command flags
maskCmd := flag.NewFlagSet("mask", flag.ExitOnError)
maskInput := maskCmd.String("input", "", "string to mask")
var regexpList stringArrayFlags
maskCmd.Var(®expList, "regexp", "Regular expression to match against, multiple --regexp flags are allowed")
// validate command flags
validateCmd := flag.NewFlagSet("validate", flag.ExitOnError)
validateRegexp := validateCmd.String("regexp", "", "Regular expression to validate")
unexpectedCommandError := "Usage: regexp_utility <subcommand> --help\n\tavailable subcommands: mask, validate"
if len(os.Args) < 2 {
fmt.Println(unexpectedCommandError)
os.Exit(1)
}
switch os.Args[1] {
case "mask":
err := maskCmd.Parse(os.Args[2:])
if err != nil {
fmt.Printf("Cannot parse command-line arguments: %s\n", err)
os.Exit(1)
}
regexpStringList := []string(regexpList)
if *maskInput == "" {
fmt.Println("Input cannot be empty")
os.Exit(1)
}
if len(regexpStringList) == 0 {
fmt.Println("At least one regular expression has to be specified")
os.Exit(1)
}
mask(maskInput, ®expStringList)
case "validate":
err := validateCmd.Parse(os.Args[2:])
if err != nil {
fmt.Printf("Cannot parse command-line arguments: %s\n", err)
os.Exit(1)
}
if *validateRegexp == "" {
fmt.Println("Regular expression cannot be empty")
os.Exit(1)
}
validate(validateRegexp)
default:
fmt.Println(unexpectedCommandError)
os.Exit(1)
}
}