From 71b3046c78cd6de977052a870fb5d27d6a0f3fcd Mon Sep 17 00:00:00 2001 From: Anna Lushnikova Date: Tue, 5 Nov 2024 14:09:21 -0500 Subject: [PATCH] add internal droplets package to parse a policy --- internal/droplets/droplets.go | 58 ++++++++++++++++++++++++++++++ internal/droplets/droplets_test.go | 1 + 2 files changed, 59 insertions(+) create mode 100644 internal/droplets/droplets.go create mode 100644 internal/droplets/droplets_test.go diff --git a/internal/droplets/droplets.go b/internal/droplets/droplets.go new file mode 100644 index 000000000..cb5cea6ae --- /dev/null +++ b/internal/droplets/droplets.go @@ -0,0 +1,58 @@ +package droplets + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "os" + + "github.com/digitalocean/godo" + "sigs.k8s.io/yaml" +) + +func ReadDropletBackupPolicy(stdin io.Reader, path string) (*godo.DropletBackupPolicyRequest, error) { + var policy io.Reader + if path == "-" && stdin != nil { + policy = stdin + } else { + specFile, err := os.Open(path) // guardrails-disable-line + if err != nil { + if os.IsNotExist(err) { + return nil, fmt.Errorf("opening droplet backup policy: %s does not exist", path) + } + return nil, fmt.Errorf("opening droplet backup policy: %w", err) + } + defer specFile.Close() + policy = specFile + } + + byt, err := io.ReadAll(policy) + if err != nil { + return nil, fmt.Errorf("reading droplet backup policy: %w", err) + } + + s, err := ParseDropletBackupPolicy(byt) + if err != nil { + return nil, fmt.Errorf("parsing droplet backup policy: %w", err) + } + + return s, nil +} + +func ParseDropletBackupPolicy(spec []byte) (*godo.DropletBackupPolicyRequest, error) { + jsonSpec, err := yaml.YAMLToJSON(spec) + if err != nil { + return nil, err + } + + dec := json.NewDecoder(bytes.NewReader(jsonSpec)) + dec.DisallowUnknownFields() + + var policy godo.DropletBackupPolicyRequest + if err := dec.Decode(&policy); err != nil { + return nil, err + } + + return &policy, nil +} diff --git a/internal/droplets/droplets_test.go b/internal/droplets/droplets_test.go new file mode 100644 index 000000000..2eadb6532 --- /dev/null +++ b/internal/droplets/droplets_test.go @@ -0,0 +1 @@ +package droplets