From 432a9472fefbb71bec8e5661608d5c3a690b334c Mon Sep 17 00:00:00 2001 From: Matthew Rich Date: Sun, 15 Sep 2024 17:16:00 +0000 Subject: [PATCH] add onerror strategy --- internal/resource/onerror.go | 66 +++++++++++++++++++++++++++++++ internal/resource/onerror_test.go | 21 ++++++++++ 2 files changed, 87 insertions(+) create mode 100644 internal/resource/onerror.go create mode 100644 internal/resource/onerror_test.go diff --git a/internal/resource/onerror.go b/internal/resource/onerror.go new file mode 100644 index 0000000..8941f1d --- /dev/null +++ b/internal/resource/onerror.go @@ -0,0 +1,66 @@ +// Copyright 2024 Matthew Rich . 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) +} diff --git a/internal/resource/onerror_test.go b/internal/resource/onerror_test.go new file mode 100644 index 0000000..b18194a --- /dev/null +++ b/internal/resource/onerror_test.go @@ -0,0 +1,21 @@ +// Copyright 2024 Matthew Rich . 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) + } + +}