github.com/ddev/ddev@v1.23.2-0.20240519125000-d824ffe36ff3/pkg/config/state/storage/yaml/yaml_storage.go (about) 1 package yaml 2 3 import ( 4 "os" 5 "path/filepath" 6 7 "github.com/ddev/ddev/pkg/config/state" 8 "github.com/ddev/ddev/pkg/config/state/types" 9 "gopkg.in/yaml.v3" 10 ) 11 12 // New returns a new StateStorage interface based on a YAML file. 13 // 14 // Parameter 'stateFilePath' is the path and file name to the storage file. 15 func New(stateFilePath string) types.StateStorage { 16 return &yamlStorage{ 17 filePath: stateFilePath, 18 } 19 } 20 21 // NewState returns a new State using a YAML storage. 22 func NewState(stateFilePath string) types.State { 23 return state.New(New(stateFilePath)) 24 } 25 26 // yamlStorage is the in-memory representation of the storage. 27 type yamlStorage struct { 28 filePath string 29 } 30 31 // Read see interface description. 32 func (s *yamlStorage) Read() (raw types.RawState, err error) { 33 content, err := os.ReadFile(s.filePath) 34 if os.IsNotExist(err) { 35 return make(types.RawState), nil 36 } else if err != nil { 37 return 38 } 39 40 err = yaml.Unmarshal(content, &raw) 41 42 return 43 } 44 45 // Write see interface description. 46 func (s *yamlStorage) Write(raw types.RawState) (err error) { 47 content, err := yaml.Marshal(&raw) 48 if err != nil { 49 return 50 } 51 52 err = os.MkdirAll(filepath.Dir(s.filePath), 0755) 53 if err != nil { 54 return 55 } 56 57 // Prefix content with YAML document start. 58 finalContent := []byte("---\n") 59 finalContent = append(finalContent, content...) 60 61 err = os.WriteFile(s.filePath, finalContent, 0600) 62 63 return 64 } 65 66 func (s *yamlStorage) TagName() string { 67 return "yaml" 68 }