common: use Readdirnames to check if dir is empty

This commit is contained in:
jsvisa 2025-10-27 23:44:15 +08:00
parent 33dbd64a23
commit 4bfad2651d
2 changed files with 13 additions and 11 deletions

View file

@ -37,3 +37,14 @@ func AbsolutePath(datadir string, filename string) string {
}
return filepath.Join(datadir, filename)
}
// IsNonEmptyDir checks if a directory exists and is non-empty.
func IsNonEmptyDir(dir string) bool {
f, err := os.Open(dir)
if err != nil {
return false
}
defer f.Close()
names, _ := f.Readdirnames(1)
return len(names) > 0
}

View file

@ -22,6 +22,7 @@ import (
"path/filepath"
"runtime"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/nat"
"github.com/ethereum/go-ethereum/rpc"
@ -90,7 +91,7 @@ func DefaultDataDir() string {
// is non-empty, use it, otherwise DTRT and check %LOCALAPPDATA%.
fallback := filepath.Join(home, "AppData", "Roaming", "Ethereum")
appdata := windowsAppData()
if appdata == "" || isNonEmptyDir(fallback) {
if appdata == "" || common.IsNonEmptyDir(fallback) {
return fallback
}
return filepath.Join(appdata, "Ethereum")
@ -113,16 +114,6 @@ func windowsAppData() string {
return v
}
func isNonEmptyDir(dir string) bool {
f, err := os.Open(dir)
if err != nil {
return false
}
names, _ := f.Readdir(1)
f.Close()
return len(names) > 0
}
func homeDir() string {
if home := os.Getenv("HOME"); home != "" {
return home