// Copyright (c) 2023 Open Anolis Community Distro SIG, all rights reserved. // // Author: Jacob Wang // Xiao Lun // Zhao Hang package file import ( "fmt" "io/ioutil" "os" "path/filepath" ) type File struct { path string } func New(path string) *File { return &File{ path: path, } } func (f *File) Write(path string, content []byte) error { w, err := os.OpenFile(filepath.Join(f.path, path), os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0o644) if err != nil { return fmt.Errorf("could not open file: %v", err) } _, err = w.Write(content) if err != nil { return fmt.Errorf("could not write file to file: %v", err) } // Close, just like writing a file. if err := w.Close(); err != nil { return fmt.Errorf("could not close file writer to source: %v", err) } return nil } func (f *File) Read(path string) ([]byte, error) { r, err := os.OpenFile(filepath.Join(f.path, path), os.O_RDONLY, 0o644) if err != nil { if os.IsNotExist(err) { return nil, nil } return nil, err } body, err := ioutil.ReadAll(r) if err != nil { return nil, err } return body, nil } func (f *File) Exists(path string) (bool, error) { _, err := os.Stat(filepath.Join(f.path, path)) if !os.IsNotExist(err) { if !os.IsExist(err) { return false, err } return true, nil } return false, nil }