add onerror strategy
Some checks failed
Lint / golangci-lint (push) Has been cancelled
Declarative Tests / test (push) Has been cancelled
Declarative Tests / build-fedora (push) Has been cancelled
Declarative Tests / build-ubuntu-focal (push) Has been cancelled

This commit is contained in:
Matthew Rich 2024-09-15 17:16:00 +00:00
parent c3ea064bf0
commit 432a9472fe
2 changed files with 87 additions and 0 deletions

View File

@ -0,0 +1,66 @@
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package resource
import (
"errors"
"encoding/json"
"gopkg.in/yaml.v3"
)
var (
ErrInvalidOnErrorStrategy = errors.New("Invalid OnError strategy")
)
type OnError string
const (
OnErrorStop = "stop"
OnErrorFail = "fail"
OnErrorSkip = "skip"
)
func NewOnError() OnError {
return OnErrorFail
}
func (o OnError) Strategy() string {
switch o {
case OnErrorStop, OnErrorFail, OnErrorSkip:
return string(o)
}
return ""
}
func (o OnError) Validate() error {
switch o {
case OnErrorStop, OnErrorFail, OnErrorSkip:
return nil
default:
return ErrInvalidOnErrorStrategy
}
}
func (o *OnError) UnmarshalValue(value string) (err error) {
if err = OnError(value).Validate(); err == nil {
*o = OnError(value)
}
return
}
func (o *OnError) UnmarshalJSON(jsonData []byte) error {
var s string
if unmarshalErr := json.Unmarshal(jsonData, &s); unmarshalErr != nil {
return unmarshalErr
}
return o.UnmarshalValue(s)
}
func (o *OnError) UnmarshalYAML(value *yaml.Node) error {
var s string
if err := value.Decode(&s); err != nil {
return err
}
return o.UnmarshalValue(s)
}

View File

@ -0,0 +1,21 @@
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package resource
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestOnErrorStrategies(t *testing.T) {
for _, v := range []struct{ strategy OnError; expected OnError; validate error }{
{ strategy: OnErrorFail, expected: "fail", validate: nil },
{ strategy: OnErrorSkip, expected: "skip", validate: nil },
{ strategy: OnError("unknown"), expected: "", validate: ErrInvalidOnErrorStrategy },
}{
o := v.strategy
assert.Equal(t, v.expected, o.Strategy())
assert.ErrorIs(t, o.Validate(), v.validate)
}
}