Repository navigation
Expand file tree
/
Copy pathmisc.go
More file actions
82 lines (69 loc) · 1.92 KB
/
Copy pathmisc.go
File metadata and controls
82 lines (69 loc) · 1.92 KB
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
package utils
import (
"cmp"
"encoding/json"
"errors"
"fmt"
"hash/crc32"
"io/fs"
"math/rand/v2"
"os"
"slices"
"strings"
"time"
)
func Slash(text string) (string, string) {
before, after, _ := strings.Cut(text, "/")
return before, after
}
// A simple sum for naming fixture files in tests, e.g. based on an URL.
func Crc32(str string) string {
return fmt.Sprintf("%08x", crc32.ChecksumIEEE([]byte(str)))
}
// Generate a random string to append to emails, so that Gmail doesn't clump
// them into "conversations".
func RandEmail() string {
return fmt.Sprintf("%016x", rand.Uint64())
}
func Dump(path string, what any) error {
if b, err := json.MarshalIndent(what, "", "\t"); err != nil {
return Errorc(err)
} else if err := os.WriteFile(path, b, 0644); err != nil {
return Errorc(err)
}
return nil
}
// ReadDirByDate reads the directory and returns entries sorted by modification time (ascending: oldest first).
func ReadDirByDate(dirname string) ([]fs.DirEntry, error) {
entries, err := os.ReadDir(dirname)
if err != nil {
return nil, Errorc(err)
}
type entryWithTime struct {
entry fs.DirEntry
modTime time.Time
}
entryWrappers := make([]entryWithTime, 0, len(entries))
for _, entry := range entries {
info, err := entry.Info()
if errors.Is(err, fs.ErrNotExist) {
continue // file got deleted while we were working
} else if err != nil {
return nil, Errorc(err)
}
entryWrappers = append(entryWrappers, entryWithTime{entry: entry, modTime: info.ModTime()})
}
// Sort by modification time (ascending)
slices.SortFunc(entryWrappers, func(a, b entryWithTime) int {
return a.modTime.Compare(b.modTime)
})
// Extract sorted entries
sortedEntries := make([]fs.DirEntry, len(entryWrappers))
for i, wrapper := range entryWrappers {
sortedEntries[i] = wrapper.entry
}
return sortedEntries, nil
}
func Uniq[T cmp.Ordered](s []T) []T {
return slices.Compact(slices.Sorted(slices.Values(s)))
}