Skip to content
This repository has been archived by the owner on Nov 22, 2022. It is now read-only.

Commit

Permalink
add function to validate key
Browse files Browse the repository at this point in the history
  • Loading branch information
profclems committed Jan 10, 2021
1 parent 86e57b6 commit 7e077d4
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions commands/variable/set/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"io/ioutil"
"regexp"
"strings"

"github.com/MakeNowJust/heredoc"
Expand Down Expand Up @@ -34,6 +35,8 @@ func NewVariableCmd(f *cmdutils.Factory, runE func(opts *SetOpts) error) *cobra.
IO: f.IO,
}

validKeyMsg := "A valid key must have no more than 255 characters; only A-Z, a-z, 0-9, and _ are allowed"

cmd := &cobra.Command{
Use: "set <key> <value>",
Short: "Create a new project or group variable",
Expand All @@ -55,6 +58,10 @@ func NewVariableCmd(f *cmdutils.Factory, runE func(opts *SetOpts) error) *cobra.

opts.Key = args[0]

if !isValidKey(opts.Key) {
return cmdutils.FlagError{Err: fmt.Errorf("invalid key provided.\n%s", validKeyMsg)}
}

if opts.Value != "" && len(args) == 2 {
if opts.Value != "" {
return cmdutils.FlagError{Err: errors.New("specify value either by second positional argument or --value flag")}
Expand Down Expand Up @@ -149,3 +156,15 @@ func setRun(opts *SetOpts) error {
fmt.Fprintf(opts.IO.StdOut, "%s Created variable %s for %s\n", utils.GreenCheck(), opts.Key, baseRepo.FullName())
return nil
}

// isValidKey checks if a key is valid if it follows the following criteria:
// must have no more than 255 characters;
// only A-Z, a-z, 0-9, and _ are allowed
func isValidKey(key string) bool {
// check if key falls within range of 1-255
if len(key) > 255 || len(key) < 1 {
return false
}
keyRE := regexp.MustCompile(`^[A-Za-z0-9_]+$`)
return keyRE.MatchString(key)
}

0 comments on commit 7e077d4

Please sign in to comment.