-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.go
More file actions
122 lines (106 loc) · 2.1 KB
/
utils.go
File metadata and controls
122 lines (106 loc) · 2.1 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package dl
import (
"container/heap"
"context"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"golang.org/x/sync/errgroup"
)
// copyFile is an utility function to copy file.
func copyFile(ctx context.Context, dstFilePath string, srcFilePath string) error {
srcFile, err := os.Open(srcFilePath)
if err != nil {
return err
}
defer srcFile.Close()
dstFile, err := os.Create(dstFilePath)
if err != nil {
return err
}
defer dstFile.Close()
if _, err := io.Copy(dstFile, srcFile); err != nil {
return err
}
return nil
}
func walkDirWithValidation(ctx context.Context, baseDir string, fn func(ctx context.Context, path string, info fs.DirEntry) error) error {
eg, ctx := errgroup.WithContext(ctx)
err := filepath.WalkDir(baseDir, func(path string, info fs.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("failed to walkDir: %w", err)
}
if !strings.HasSuffix(path, ".go") {
return nil
}
eg.Go(func() error {
return fn(ctx, path, info)
})
return nil
})
if err != nil {
return err
}
if err := eg.Wait(); err != nil {
return err
}
return nil
}
// An intHeap is a min-heap of ints.
type intHeap struct {
s *[]int
mu *sync.Mutex
}
// newintHeap is a factory function for intHeap.
// heap.Init is done in this function.
func newintHeap(s []int) *intHeap {
if s == nil {
s = []int{}
}
h := &intHeap{
s: &s,
mu: new(sync.Mutex),
}
heap.Init(h)
return h
}
func (h intHeap) Len() int {
h.mu.Lock()
defer h.mu.Unlock()
s := h.s
return len(*s)
}
// greater order
func (h intHeap) Less(i, j int) bool {
h.mu.Lock()
defer h.mu.Unlock()
s := h.s
return (*s)[i] > (*s)[j]
}
func (h intHeap) Swap(i, j int) {
h.mu.Lock()
defer h.mu.Unlock()
s := h.s
(*s)[i], (*s)[j] = (*s)[j], (*s)[i]
}
func (h *intHeap) Push(x any) {
h.mu.Lock()
defer h.mu.Unlock()
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
s := h.s
*s = append(*s, x.(int))
}
func (h *intHeap) Pop() any {
h.mu.Lock()
defer h.mu.Unlock()
old := h.s
n := len(*old)
x := (*old)[n-1]
*old = (*old)[:n-1]
return x
}