util: refactor checking if path exists

This commit is contained in:
David Allen 2024-10-15 15:25:03 -06:00
parent e1d49e17a1
commit 036a5d3ab7
Signed by: towk
GPG key ID: 793B2924A49B3A3F

View file

@ -2,6 +2,7 @@ package util
import ( import (
"fmt" "fmt"
"io/fs"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -13,15 +14,9 @@ import (
// //
// Returns whether the path exists and no error if successful, // Returns whether the path exists and no error if successful,
// otherwise, it returns false with an error. // otherwise, it returns false with an error.
func PathExists(path string) (bool, error) { func PathExists(path string) (fs.FileInfo, bool) {
_, err := os.Stat(path) fi, err := os.Stat(path)
if err == nil { return fi, !os.IsNotExist(err)
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
} }
// SplitPathForViper() is an utility function to split a path into 3 parts: // SplitPathForViper() is an utility function to split a path into 3 parts:
@ -51,17 +46,14 @@ func MakeOutputDirectory(path string, overwrite bool) (string, error) {
final := path + "/" + dirname final := path + "/" + dirname
// check if path is valid and directory // check if path is valid and directory
pathExists, err := PathExists(final) _, pathExists := PathExists(final)
if err != nil {
return "", fmt.Errorf("failed to check for existing path: %v", err)
}
if pathExists && !overwrite { if pathExists && !overwrite {
// make sure it is directory with 0o644 permissions // make sure it is directory with 0o644 permissions
return "", fmt.Errorf("found existing path: %v", final) return "", fmt.Errorf("found existing path: %v", final)
} }
// create directory with data + time // create directory with data + time
err = os.MkdirAll(final, 0766) err := os.MkdirAll(final, 0766)
if err != nil { if err != nil {
return "", fmt.Errorf("failed to make directory: %v", err) return "", fmt.Errorf("failed to make directory: %v", err)
} }