Skip to content

Commit

Permalink
more validation work
Browse files Browse the repository at this point in the history
  • Loading branch information
jippi committed Feb 10, 2024
1 parent 1accfa7 commit f559abf
Show file tree
Hide file tree
Showing 8 changed files with 91 additions and 29 deletions.
8 changes: 8 additions & 0 deletions cmd/set/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,14 @@ func Command() *cobra.Command {
return fmt.Errorf("failed to upsert the key/value pair [%s]", key)
}

if validationErrors := validation.ValidateSignleAssignment(env, assignment.Name, nil, nil); len(validationErrors) > 0 {

Check failure on line 78 in cmd/set/set.go

View workflow job for this annotation

GitHub Actions / lint

undefined: validation.ValidateSignleAssignment (typecheck)

Check failure on line 78 in cmd/set/set.go

View workflow job for this annotation

GitHub Actions / lint

undefined: validation.ValidateSignleAssignment) (typecheck)

Check failure on line 78 in cmd/set/set.go

View workflow job for this annotation

GitHub Actions / goreleaser

undefined: validation.ValidateSignleAssignment

Check failure on line 78 in cmd/set/set.go

View workflow job for this annotation

GitHub Actions / test

undefined: validation.ValidateSignleAssignment

Check failure on line 78 in cmd/set/set.go

View workflow job for this annotation

GitHub Actions / govulncheck / scan

undefined: validation.ValidateSignleAssignment

Check failure on line 78 in cmd/set/set.go

View workflow job for this annotation

GitHub Actions / ruleguard / scan

undefined: validation.ValidateSignleAssignment

Check failure on line 78 in cmd/set/set.go

View workflow job for this annotation

GitHub Actions / ruleguard / scan

undefined: validation.ValidateSignleAssignment

Check failure on line 78 in cmd/set/set.go

View workflow job for this annotation

GitHub Actions / lint

undefined: validation.ValidateSignleAssignment (typecheck)

Check failure on line 78 in cmd/set/set.go

View workflow job for this annotation

GitHub Actions / lint

undefined: validation.ValidateSignleAssignment) (typecheck)

Check failure on line 78 in cmd/set/set.go

View workflow job for this annotation

GitHub Actions / goreleaser

undefined: validation.ValidateSignleAssignment
for _, errIsh := range validationErrors {
fmt.Fprintln(os.Stderr, validation.Explain(env, errIsh, false, false))
}

return errors.New("validation failed")
}

tui.Theme.Success.StderrPrinter().Printfln("Key [%s] was successfully upserted", key)
}

Expand Down
41 changes: 38 additions & 3 deletions cmd/update/update.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package update

import (
"errors"
"fmt"
"io"
"os"
"strings"

"github.com/hashicorp/go-getter"
"github.com/jippi/dottie/pkg"
"github.com/jippi/dottie/pkg/ast"
"github.com/jippi/dottie/pkg/tui"
"github.com/jippi/dottie/pkg/validation"
"github.com/spf13/cobra"
)

Expand All @@ -35,6 +38,7 @@ func runE(cmd *cobra.Command, args []string) error {
dark := tui.Theme.Dark.StdoutPrinter()
info := tui.Theme.Info.StdoutPrinter()
danger := tui.Theme.Danger.StdoutPrinter()
dangerEmphasis := tui.Theme.Danger.StdoutPrinter(tui.WithEmphasis(true))
success := tui.Theme.Success.StdoutPrinter()
primary := tui.Theme.Primary.StdoutPrinter()

Expand Down Expand Up @@ -102,6 +106,9 @@ func runE(cmd *cobra.Command, args []string) error {
dark.Println("Updating upstream with key/value pairs from", primary.Sprint(filename))
dark.Println()

sawError := false
lastWasError := false

for _, stmt := range env.Assignments() {
if !stmt.Active {
continue
Expand All @@ -114,15 +121,43 @@ func runE(cmd *cobra.Command, args []string) error {
continue
}

if errors := validation.ValidateSingleAssignment(env, stmt.Name, nil, []string{"file", "dir"}); len(errors) > 0 {
sawError = true
lastWasError = true

dark.Println()
dark.Print(" ")
dangerEmphasis.Print(stmt.Name)
dark.Print(" could not be set to ")
primary.Print(stmt.Literal)
dark.Println(" due to validation error:")

for _, errIsh := range errors {
danger.Println(" ", strings.Repeat(" ", len(stmt.Name)), strings.TrimSpace(validation.Explain(env, errIsh, false, false)))
}

continue
}

if changed != nil {
success.Print(" OK! ")
primary.Print(stmt.Name)
success.Print(" was successfully set to ")
if lastWasError {
danger.Println()
}

lastWasError = false

success.Print(" ", stmt.Name)
dark.Print(" was successfully set to ")
primary.Println(stmt.Literal)
}
}

dark.Println()

if sawError {
return errors.New("some fields failed validation, aborting ...")
}

dark.Print("Backing up ")
primary.Print(filename)
dark.Print(" to ")
Expand Down
12 changes: 0 additions & 12 deletions pkg/ast/assignment.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@ package ast

import (
"bytes"
"errors"
"reflect"
"strings"

"github.com/go-playground/validator/v10"
"github.com/jippi/dottie/pkg/token"
)

Expand Down Expand Up @@ -108,16 +106,6 @@ func (a *Assignment) IsHidden() bool {
return false
}

func (a *Assignment) IsValid() error {
if !a.Quote.Valid() {
return errors.New("invalid quote-style")
}

return validator.
New(validator.WithRequiredStructEnabled()).
Var(a.Interpolated, a.ValidationRules())
}

func (a *Assignment) Disable() {
a.Active = false
}
Expand Down
15 changes: 15 additions & 0 deletions pkg/ast/assignment_selectors.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ast

import (
"slices"
"strings"
)

Expand Down Expand Up @@ -55,6 +56,20 @@ func RetainKeyPrefix(prefix string) Selector {
}
}

// RetainExactKey will *RETAIN* Assignments with the exact name
func RetainExactKey(key ...string) Selector {
return func(input Statement) SelectorResult {
switch statement := input.(type) {
case *Assignment:
if !slices.Contains(key, statement.Name) {
return Exclude
}
}

return Keep
}
}

// ExcludeKeyPrefix will *EXCLUDE* Assignments with the provided prefix
func ExcludeKeyPrefix(prefix string) Selector {
return func(input Statement) SelectorResult {
Expand Down
4 changes: 0 additions & 4 deletions pkg/ast/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,10 +222,6 @@ func (doc *Document) Upsert(input *Assignment, options UpsertOptions) (*Assignme
return existing, nil
}

if err := existing.IsValid(); err != nil {
return existing, err
}

return existing, nil
}

Expand Down
7 changes: 4 additions & 3 deletions pkg/render/handler_filters.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ var (
ExcludeHiddenViaAnnotation = newSelectorHandler(ast.ExcludeHiddenViaAnnotation)
)

func RetainGroup(value string) Handler { return newSelectorHandler(ast.RetainGroup(value)) }
func ExcludeKeyPrefix(value string) Handler { return newSelectorHandler(ast.ExcludeKeyPrefix(value)) }
func RetainKeyPrefix(value string) Handler { return newSelectorHandler(ast.RetainKeyPrefix(value)) }
func RetainGroup(value string) Handler { return newSelectorHandler(ast.RetainGroup(value)) }
func ExcludeKeyPrefix(value string) Handler { return newSelectorHandler(ast.ExcludeKeyPrefix(value)) }
func RetainKeyPrefix(value string) Handler { return newSelectorHandler(ast.RetainKeyPrefix(value)) }
func RetainExactKey(value ...string) Handler { return newSelectorHandler(ast.RetainExactKey(value...)) }

func newSelectorHandler(selector ast.Selector) Handler {
return func(input *HandlerInput) HandlerSignal {
Expand Down
19 changes: 12 additions & 7 deletions pkg/validation/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
"github.com/jippi/dottie/pkg/tui"
)

func Explain(doc *ast.Document, keyErr ValidationError, fix, showField bool) string {
func Explain(doc *ast.Document, keyErr ValidationError, applyFixer, showField bool) string {
var buff bytes.Buffer

dark := tui.Theme.Dark.BuffPrinter(&buff)
Expand All @@ -39,7 +39,7 @@ func Explain(doc *ast.Document, keyErr ValidationError, fix, showField bool) str
}

for _, rule := range err {
askToFix := fix
askToFix := applyFixer

if showField {
primary.Print(" * ")
Expand Down Expand Up @@ -68,17 +68,17 @@ func Explain(doc *ast.Document, keyErr ValidationError, fix, showField bool) str
bold.Print(keyErr.Assignment.Interpolated)
light.Print("] is not one of [")
bold.Print(rule.Param())
light.Println("]")
light.Println("].")

case "number":
light.Print("(number) The value [")
bold.Print(keyErr.Assignment.Interpolated)
light.Println("] is not a valid number")
light.Println("] is not a valid number.")

case "email":
light.Print("(email) The value [")
bold.Print(keyErr.Assignment.Interpolated)
light.Println("] is not a valid e-mail")
light.Println("] is not a valid e-mail.")

case "required":
light.Println("(required) This value must not be empty/blank.")
Expand All @@ -97,8 +97,13 @@ func Explain(doc *ast.Document, keyErr ValidationError, fix, showField bool) str
light.Print("(ne) The value [")
bold.Print(keyErr.Assignment.Interpolated)
light.Print("] must NOT be equal to [")
bold.Print(rule.Param())
light.Println("], please change it.")

case "boolean":
light.Print("(boolean) The value [")
bold.Print(keyErr.Assignment.Interpolated)
light.Println("], please change it")
light.Print("] is not a valid boolean.")

case "http_url":
light.Print("(http_url) The value [")
Expand All @@ -108,7 +113,7 @@ func Explain(doc *ast.Document, keyErr ValidationError, fix, showField bool) str
default:
light.Printf("(%s) The value [", rule.ActualTag())
bold.Print(keyErr.Assignment.Interpolated)
light.Println("] failed validation")
light.Println("] failed validation.")
}

if askToFix {
Expand Down
14 changes: 14 additions & 0 deletions pkg/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,17 @@ NEXT_FIELD:

return result
}

func ValidateSingleAssignment(doc *ast.Document, name string, handlers []render.Handler, ignoreErrors []string) []ValidationError {
return Validate(
doc,
append(
[]render.Handler{
render.ExcludeDisabledAssignments,
render.RetainExactKey(name),
},
handlers...,
),
ignoreErrors,
)
}

0 comments on commit f559abf

Please sign in to comment.