Skip to content

Commit

Permalink
Add "check" command to validate UUIDs (#12)
Browse files Browse the repository at this point in the history
* introduce the new check command
  • Loading branch information
norbinsh authored Oct 5, 2020
1 parent 22d9644 commit 27eb0ee
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ Run the following command

### Commands:
- uuid v4
- uuid check

39 changes: 39 additions & 0 deletions cmd/check.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package cmd

import (
"fmt"
"regexp"

"github.com/spf13/cobra"
)

// check represents a command validating whether the provided input is a valid UUID
var check = &cobra.Command{
Use: "check",
Short: "Checks whether each of the provided arguments is a valid UUID",
Long: `Checks whether each of the provided arguments is a valid UUID,
while using regular expression pattern matching.
you can pass one or more UUIDs to be checked:
example usage:
uuid check d50cddd9-71f3-47f0-a407-1bf7581874fc`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
for _, arg := range args {
if Check(arg) {
fmt.Printf("%s is a valid UUID\n", arg)
} else {
fmt.Printf("%s is not a valid UUID\n", arg)
}
}
},
}

func Check(uuid string) bool {
uuidPattern := "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
re := regexp.MustCompile(uuidPattern)
if re.MatchString(uuid) {
return true
}
return false
}
25 changes: 25 additions & 0 deletions cmd/check_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package cmd

import "testing"

func TestCheck(t *testing.T) {

t.Run("should return true", func(t *testing.T) {
input := "c923d13a-cee4-4182-af57-438f8b032fb6" // valid UUID
got := Check(input)
expect := true
if got != expect {
t.Errorf("expected %s to be %t but got %t", input, expect, got)
}
})

t.Run("should return false", func(t *testing.T) {
input := "c93a-cee4-4182-af57-438f2fb6" // not a valid UUID
got := Check(input)
expect := false
if got != expect {
t.Errorf("expected %s to be %t but got %t", input, expect, got)
}
})

}
1 change: 1 addition & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ func init() {

rootCmd.AddCommand(v4Cmd)
rootCmd.AddCommand(empty)
rootCmd.AddCommand(check)

cobra.OnInitialize(initConfig)

Expand Down

0 comments on commit 27eb0ee

Please sign in to comment.