code.vegaprotocol.io/vega@v0.79.0/libs/fs/fs.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package fs 17 18 import ( 19 "errors" 20 "fmt" 21 "io/fs" 22 "os" 23 "path/filepath" 24 ) 25 26 var ErrIsADirectory = errors.New("is a directory") 27 28 // EnsureDir will make sure a directory exists or is created at the given path. 29 func EnsureDir(path string) error { 30 _, err := os.Stat(path) 31 if err != nil { 32 if os.IsNotExist(err) { 33 return os.MkdirAll(path, os.ModeDir|0o700) 34 } 35 return err 36 } 37 return nil 38 } 39 40 // PathExists returns whether a link exists at the given path. 41 func PathExists(path string) (bool, error) { 42 _, err := os.Stat(path) 43 if err == nil { 44 return true, nil 45 } 46 if os.IsNotExist(err) { 47 return false, nil 48 } 49 return false, err 50 } 51 52 // FileExists similar to PathExists, but ensures the path is to a file, not a 53 // directory. 54 func FileExists(path string) (bool, error) { 55 fileInfo, err := os.Stat(path) 56 if err == nil { 57 if fileInfo.IsDir() { 58 return false, ErrIsADirectory 59 } 60 return true, nil 61 } 62 if os.IsNotExist(err) { 63 return false, nil 64 } 65 return false, err 66 } 67 68 func ReadFile(path string) ([]byte, error) { 69 dir, fileName := filepath.Split(path) 70 if len(dir) == 0 { 71 dir = "." 72 } 73 74 buf, err := fs.ReadFile(os.DirFS(dir), fileName) 75 if err != nil { 76 return nil, fmt.Errorf("couldn't read file: %w", err) 77 } 78 79 return buf, nil 80 } 81 82 func WriteFile(path string, content []byte) error { 83 f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) 84 if err != nil { 85 return fmt.Errorf("couldn't create file: %w", err) 86 } 87 defer f.Close() 88 89 _, err = f.Write(content) 90 if err != nil { 91 return fmt.Errorf("couldn't write file: %w", err) 92 } 93 94 return nil 95 }