-
Notifications
You must be signed in to change notification settings - Fork 0
/
clean.go
94 lines (74 loc) · 1.49 KB
/
clean.go
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
package main
import (
"errors"
"fmt"
"log"
"os"
"path"
"path/filepath"
"regexp"
"github.com/alecthomas/kong"
"github.com/c2h5oh/datasize"
)
type clean struct {
TmpDirs bool `help:"Clean temporary directories too." short:"t"`
}
func (c *clean) Run(ctx *kong.Context) error {
cacheDir := getCacheDir()
_, err := os.Stat(cacheDir)
var size int64 = 0
if !errors.Is(err, os.ErrNotExist) {
if err != nil {
log.Fatalln(err)
}
size, err = dirSize(cacheDir)
if err != nil {
log.Fatalln(err)
}
err = os.RemoveAll(cacheDir)
if err != nil {
log.Fatalln(err)
}
}
if c.TmpDirs {
tmp, err := os.Open("/tmp")
if err != nil {
log.Fatalln(err)
}
dirnames, err := tmp.Readdirnames(0)
if err != nil {
log.Fatalln(err)
}
tmpRe := regexp.MustCompile("^gh-foreach.*")
for _, item := range dirnames {
if tmpRe.MatchString(item) {
itemPath := path.Join("/tmp", item)
newSize, err := dirSize(itemPath)
if err != nil {
log.Fatalln(err)
}
size += newSize
err = os.RemoveAll(itemPath)
if err != nil {
log.Fatalln(err)
}
}
}
}
fmt.Printf("Freed %s\n", (datasize.ByteSize(size)).HumanReadable())
return nil
}
// source: https://stackoverflow.com/a/32482941
func dirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}