-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.go
More file actions
92 lines (84 loc) · 1.67 KB
/
Copy pathutil.go
File metadata and controls
92 lines (84 loc) · 1.67 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
package main
import (
"bytes"
"context"
"fmt"
"io"
"os"
"log/slog"
"sync"
"time"
)
func CountLines(path string) int64 {
fp, err := os.Open(path)
if err != nil {
slog.Error("Failed to open file", "path", path, "err", err)
return 0
}
defer fp.Close()
buf := make([]byte, 32 * 1024)
newline := []byte{'\n'}
res := int64(0)
for {
size, err := fp.Read(buf)
res += int64(bytes.Count(buf[:size], newline))
switch {
case err == io.EOF:
return res
case err != nil:
slog.Error("Failed to read file", "path", path, "err", err)
return 0
}
}
}
func Drain[T any](ch <-chan T, timeout time.Duration) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
for {
select {
case <-ctx.Done():
return
case _, ok := <-ch:
if !ok {
return
}
}
}
}
func ShowProgress[T any](
progress int64,
count int64,
in <-chan T,
out chan<- T,
wg *sync.WaitGroup,
) {
var value T
prevProgress := progress
prevTime := time.Now()
line := "\033[2K\r%v | %d/%d | %d it/s | %s"
for value = range in {
progress++
if progress % 100 == 0 {
t := time.Now()
elapsed := t.Sub(prevTime).Seconds()
if elapsed > 1.0 {
speed := float64(progress - prevProgress) / elapsed
timeRemaining := time.Second * time.Duration(
int64(float64(count - progress) / speed),
)
fmt.Printf(
line,
value, progress, count, int(speed), timeRemaining.String(),
)
prevProgress = progress
prevTime = t
}
}
out <- value
}
elapsed := time.Now().Sub(prevTime).Seconds()
speed := int(float64(progress - prevProgress) / elapsed)
fmt.Printf(line, value, progress, count, speed, "done\n")
close(out)
wg.Done()
}