summaryrefslogtreecommitdiff
path: root/internal/recordsdir/recordsdir.go
blob: 94f7f0ea4ff49251ad72bef19d0c295963a07e24 (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
package recordsdir

import (
	"io/fs"
	"os"
	"path"
	"path/filepath"
	"strings"
)

type Entry struct {
	Path string
	Host string
}

func HostFromFileName(name string) string {
	host := strings.TrimSuffix(name, filepath.Ext(name))
	if idx := strings.Index(host, "."); idx > 0 {
		host = host[:idx]
	}
	return host
}

func listRecordsFileNames(fsys fs.FS, root string) ([]string, error) {
	entries, err := fs.ReadDir(fsys, root)
	if err != nil {
		return nil, err
	}
	var names []string
	for _, e := range entries {
		if e.IsDir() || !strings.HasSuffix(e.Name(), ".records") {
			continue
		}
		rel := path.Join(root, e.Name())
		info, err := fs.Stat(fsys, rel)
		if err != nil || info.Size() == 0 {
			continue
		}
		names = append(names, e.Name())
	}
	return names, nil
}

// ListNonEmptyFilesFS returns non-empty .records files under root within fsys.
func ListNonEmptyFilesFS(fsys fs.FS, root string) ([]Entry, error) {
	names, err := listRecordsFileNames(fsys, root)
	if err != nil {
		return nil, err
	}
	var out []Entry
	for _, name := range names {
		out = append(out, Entry{
			Path: path.Join(root, name),
			Host: HostFromFileName(name),
		})
	}
	return out, nil
}

func ListNonEmptyFiles(dir string) ([]Entry, error) {
	names, err := listRecordsFileNames(os.DirFS(dir), ".")
	if err != nil {
		return nil, err
	}
	var out []Entry
	for _, name := range names {
		out = append(out, Entry{
			Path: filepath.Join(dir, name),
			Host: HostFromFileName(name),
		})
	}
	return out, nil
}