summaryrefslogtreecommitdiff
path: root/vendor/codeberg.org/gruf/go-store/util/fs.go
blob: fa6a9d2c4156277fccec601526cd48863ca250de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package util

import (
	"io/fs"
	"os"
	"strings"
	"syscall"

	"codeberg.org/gruf/go-fastpath"
)

var dotdot = "../"

// CountDotdots returns the number of "dot-dots" (../) in a cleaned filesystem path
func CountDotdots(path string) int {
	if !strings.HasSuffix(path, dotdot) {
		return 0
	}
	return strings.Count(path, dotdot)
}

// WalkDir traverses the dir tree of the supplied path, performing the supplied walkFn on each entry
func WalkDir(pb *fastpath.Builder, path string, walkFn func(string, fs.DirEntry)) error {
	// Read supplied dir path
	dirEntries, err := os.ReadDir(path)
	if err != nil {
		return err
	}

	// Iter entries
	for _, entry := range dirEntries {
		// Pass to walk fn
		walkFn(path, entry)

		// Recurse dir entries
		if entry.IsDir() {
			err = WalkDir(pb, pb.Join(path, entry.Name()), walkFn)
			if err != nil {
				return err
			}
		}
	}

	return nil
}

// CleanDirs traverses the dir tree of the supplied path, removing any folders with zero children
func CleanDirs(path string) error {
	// Acquire builder
	pb := GetPathBuilder()
	defer PutPathBuilder(pb)

	// Get dir entries
	entries, err := os.ReadDir(path)
	if err != nil {
		return err
	}

	// Recurse dirs
	for _, entry := range entries {
		if entry.IsDir() {
			err := cleanDirs(pb, pb.Join(path, entry.Name()))
			if err != nil {
				return err
			}
		}
	}
	return nil
}

// cleanDirs performs the actual dir cleaning logic for the exported version
func cleanDirs(pb *fastpath.Builder, path string) error {
	// Get dir entries
	entries, err := os.ReadDir(path)
	if err != nil {
		return err
	}

	// If no entries, delete
	if len(entries) < 1 {
		return os.Remove(path)
	}

	// Recurse dirs
	for _, entry := range entries {
		if entry.IsDir() {
			err := cleanDirs(pb, pb.Join(path, entry.Name()))
			if err != nil {
				return err
			}
		}
	}
	return nil
}

// RetryOnEINTR is a low-level filesystem function for retrying syscalls on O_EINTR received
func RetryOnEINTR(do func() error) error {
	for {
		err := do()
		if err == syscall.EINTR {
			continue
		}
		return err
	}
}