From 0e16366f95b1cccac6e2533ce192ae9bda38040f Mon Sep 17 00:00:00 2001 From: liushun-ing <67847279+liushun-ing@users.noreply.github.com> Date: Tue, 10 Dec 2024 10:38:27 +0800 Subject: [PATCH] feat: add filex (#9) * feat: add filex * feat: add filex --- filex/filex.go | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 filex/filex.go diff --git a/filex/filex.go b/filex/filex.go new file mode 100644 index 0000000..bacaf0a --- /dev/null +++ b/filex/filex.go @@ -0,0 +1,39 @@ +package filex + +import ( + "fmt" + "os" + "path/filepath" + "strings" +) + +// FileExists check file exist +func FileExists(path string) bool { + info, err := os.Stat(path) + if os.IsNotExist(err) { + return false + } + return !info.IsDir() +} + +// IsYamlFile check YAML file +func IsYamlFile(path string) bool { + ext := strings.ToLower(filepath.Ext(path)) + return ext == ".yaml" || ext == ".yml" +} + +// EnsureDirExists create dir with check +func EnsureDirExists(dirPath string) error { + info, err := os.Stat(dirPath) + if os.IsNotExist(err) { + err = os.MkdirAll(dirPath, 0o755) + if err != nil { + return fmt.Errorf("failed to create directory: %w", err) + } + } else if err != nil { + return fmt.Errorf("failed to check directory: %w", err) + } else if !info.IsDir() { + return fmt.Errorf("path exists but is not a directory: %s", dirPath) + } + return nil +}