func IsDir(path string, fs afero.Fs) (bool, error) { fi, err := fs.Stat(path) if err != nil { return false, err } return fi.IsDir(), nil }
// FindArchetype takes a given kind/archetype of content and returns an output // path for that archetype. If no archetype is found, an empty string is // returned. func FindArchetype(fs afero.Fs, kind string) (outpath string) { search := []string{helpers.AbsPathify(viper.GetString("archetypeDir"))} if viper.GetString("theme") != "" { themeDir := filepath.Join(helpers.AbsPathify(viper.GetString("themesDir")+"/"+viper.GetString("theme")), "/archetypes/") if _, err := fs.Stat(themeDir); os.IsNotExist(err) { jww.ERROR.Printf("Unable to find archetypes directory for theme %q at %q", viper.GetString("theme"), themeDir) } else { search = append(search, themeDir) } } for _, x := range search { // If the new content isn't in a subdirectory, kind == "". // Therefore it should be excluded otherwise `is a directory` // error will occur. github.com/spf13/hugo/issues/411 var pathsToCheck []string if kind == "" { pathsToCheck = []string{"default.md", "default"} } else { pathsToCheck = []string{kind + ".md", kind, "default.md", "default"} } for _, p := range pathsToCheck { curpath := filepath.Join(x, p) jww.DEBUG.Println("checking", curpath, "for archetypes") if exists, _ := helpers.Exists(curpath, fs); exists { jww.INFO.Println("curpath: " + curpath) return curpath } } } return "" }
// Code copied from Afero's path.go // if the filesystem is OsFs use Lstat, else use fs.Stat func lstatIfOs(fs afero.Fs, path string) (info os.FileInfo, err error) { _, ok := fs.(*afero.OsFs) if ok { info, err = os.Lstat(path) } else { info, err = fs.Stat(path) } return }
// Check if Exists && is Directory func DirExists(path string, fs afero.Fs) (bool, error) { fi, err := fs.Stat(path) if err == nil && fi.IsDir() { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err }
// Check if File / Directory Exists func Exists(path string, fs afero.Fs) (bool, error) { _, err := fs.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err }
func IsEmpty(path string, fs afero.Fs) (bool, error) { if b, _ := Exists(path, fs); !b { return false, fmt.Errorf("%q path does not exist", path) } fi, err := fs.Stat(path) if err != nil { return false, err } if fi.IsDir() { f, err := os.Open(path) // FIX: Resource leak - f.close() should be called here by defer or is missed // if the err != nil branch is taken. defer f.Close() if err != nil { return false, err } list, err := f.Readdir(-1) // f.Close() - see bug fix above return len(list) == 0, nil } else { return fi.Size() == 0, nil } }