diff --git a/internal/cloud/backend_saved_plan.go b/internal/cloud/backend_saved_plan.go new file mode 100644 index 0000000000..f780ee811b --- /dev/null +++ b/internal/cloud/backend_saved_plan.go @@ -0,0 +1,38 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package cloud + +import ( + "encoding/json" + "os" +) + +type SavedPlanBookmark struct { + RemotePlanFormat int `json:"remote_plan_format"` + RunID string `json:"run_id"` + Hostname string `json:"hostname"` +} + +func LoadSavedPlanBookmark(filepath string) (SavedPlanBookmark, error) { + bookmark := SavedPlanBookmark{} + data, err := os.ReadFile(filepath) + + if err != nil { + return bookmark, err + } + + err = json.Unmarshal([]byte(data), &bookmark) + return bookmark, err +} + +func (s *SavedPlanBookmark) Save(filepath string) error { + data, _ := json.Marshal(s) + + err := os.WriteFile(filepath, data, 0644) + if err != nil { + return err + } + + return nil +} diff --git a/internal/cloud/backend_saved_plan_test.go b/internal/cloud/backend_saved_plan_test.go new file mode 100644 index 0000000000..14a5d72c9a --- /dev/null +++ b/internal/cloud/backend_saved_plan_test.go @@ -0,0 +1,42 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package cloud + +import ( + "path/filepath" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/zclconf/go-cty/cty" +) + +func TestCloud_loadBasic(t *testing.T) { + bookmark := SavedPlanBookmark{ + RemotePlanFormat: 1, + RunID: "run-GXfuHMkbyHccAGUg", + Hostname: "app.terraform.io", + } + + result, err := LoadSavedPlanBookmark("./testdata/plan-bookmark/bookmark.json") + if err != nil { + t.Fatal(err) + } + + if diff := cmp.Diff(bookmark, result, cmp.Comparer(cty.Value.RawEquals)); diff != "" { + t.Errorf("wrong result\n%s", diff) + } +} + +func TestCloud_saveBasic(t *testing.T) { + tmp := t.TempDir() + bookmarkPath := filepath.Join(tmp, "saved-bookmark.json") + + b := &SavedPlanBookmark{ + RemotePlanFormat: 1, + RunID: "run-GXfuHMkbyHccAGUg", + Hostname: "app.terraform.io", + } + + b.Save(bookmarkPath) +} diff --git a/internal/cloud/testdata/plan-bookmark/bookmark.json b/internal/cloud/testdata/plan-bookmark/bookmark.json new file mode 100644 index 0000000000..0a1c73302a --- /dev/null +++ b/internal/cloud/testdata/plan-bookmark/bookmark.json @@ -0,0 +1,5 @@ +{ + "remote_plan_format": 1, + "run_id": "run-GXfuHMkbyHccAGUg", + "hostname": "app.terraform.io" +}