github.com/blend/go-sdk@v1.20220411.3/fileutil/exists.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package fileutil 9 10 import ( 11 "os" 12 13 "github.com/blend/go-sdk/ex" 14 ) 15 16 // pathInfo encapsulates two of the more salient outputs of `os.Stat()` 17 // - Can we stat the file / path? (i.e. does it exist?) 18 // - Is the file mode a directory? 19 type pathInfo struct { 20 Exists bool 21 IsDir bool 22 } 23 24 func pathExists(path string) (*pathInfo, error) { 25 fi, err := os.Stat(path) 26 if err == nil { 27 return &pathInfo{Exists: true, IsDir: fi.Mode().IsDir()}, nil 28 } 29 30 if os.IsNotExist(err) { 31 return &pathInfo{Exists: false}, nil 32 } 33 34 return nil, ex.New(err) 35 } 36 37 // FileExists determines if a path exists and is a file (not a directory). 38 func FileExists(path string) (bool, error) { 39 pi, err := pathExists(path) 40 if err != nil { 41 return false, err 42 } 43 44 if pi.Exists && pi.IsDir { 45 return false, ex.New("Path exists but is a directory", ex.OptMessagef("Path: %q", path)) 46 } 47 48 return pi.Exists, nil 49 } 50 51 // DirExists determines if a path exists and is a directory (not a file). 52 func DirExists(path string) (bool, error) { 53 pi, err := pathExists(path) 54 if err != nil { 55 return false, err 56 } 57 58 if pi.Exists && !pi.IsDir { 59 return false, ex.New("Path exists but is not a directory", ex.OptMessagef("Path: %q", path)) 60 } 61 62 return pi.Exists, nil 63 }