Skip to content

Commit

Permalink
cfg: improve validation of app and task names
Browse files Browse the repository at this point in the history
Fail if an app or task name contains leading or trailing whitespaces or
non-printable characters.
Names containing these characters are error-prone and unnecessary.
Because app and task names are also used in multiple other commands as
arguments, these characters make the CLI harder to use.
  • Loading branch information
fho committed May 30, 2024
1 parent 5e9fdd6 commit e873ff2
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 16 deletions.
18 changes: 3 additions & 15 deletions internal/command/release_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import (
"io"
"os"
"strings"
"unicode"

"github.com/simplesurance/baur/v3/internal/command/term"
"github.com/simplesurance/baur/v3/internal/log"
"github.com/simplesurance/baur/v3/internal/validation"
"github.com/simplesurance/baur/v3/pkg/baur"
"github.com/simplesurance/baur/v3/pkg/storage"

Expand Down Expand Up @@ -98,24 +98,12 @@ func newReleaseCreateCmd() *releaseCreateCmd {
return &cmd
}

func mustValidateReleaseName(releaseName string) {
for pos, r := range releaseName {
if (pos == 0 || pos == len(releaseName)-1) && unicode.IsSpace(r) {
fatalf("release name must not contain leading or trailing whitespaces, got: %q\n",
releaseName)
}

if !unicode.IsPrint(r) {
fatalf("release name contains non-printable character: %q\n", r)
}
}
}

func (c *releaseCreateCmd) run(cmd *cobra.Command, args []string) {
ctx := cmd.Context()
releaseName := args[0]

mustValidateReleaseName(releaseName)
err := validation.StrID(releaseName)
exitOnErrf(err, "invalid release name: %q", releaseName)

stdout.Printf("creating release: %s\n", term.Highlight(releaseName))

Expand Down
23 changes: 23 additions & 0 deletions internal/validation/validation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package validation

import (
"errors"
"fmt"
"unicode"
)

// StrID ensures that id does not contain leading or trailing white spaces
// ([unicode.IsSpace] and only printable characters ([unicode.IsPrint].
func StrID(id string) error {
for pos, r := range id {
if (pos == 0 || pos == len(id)-1) && unicode.IsSpace(r) {
return errors.New("contains leading or trailing white spaces")
}

if !unicode.IsPrint(r) {
return fmt.Errorf("contains non-printable character: %x", r)
}
}

return nil
}
4 changes: 3 additions & 1 deletion pkg/cfg/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"errors"
"fmt"
"strings"

"github.com/simplesurance/baur/v3/internal/validation"
)

var forbiddenNameRunes = [...]rune{
Expand All @@ -23,5 +25,5 @@ func validateTaskOrAppName(name string) error {
}
}

return nil
return validation.StrID(name)
}

0 comments on commit e873ff2

Please sign in to comment.