forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclean.go
123 lines (108 loc) · 2.27 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
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
123
package main
import (
"context"
"flag"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/gnolang/gno/gnovm/pkg/gnomod"
"github.com/gnolang/gno/tm2/pkg/commands"
)
type cleanCfg struct {
dryRun bool // clean -n flag
verbose bool // clean -x flag
modCache bool // clean -modcache flag
}
func newCleanCmd(io commands.IO) *commands.Command {
cfg := &cleanCfg{}
return commands.NewCommand(
commands.Metadata{
Name: "clean",
ShortUsage: "clean [flags]",
ShortHelp: "remove generated and cached data",
},
cfg,
func(ctx context.Context, args []string) error {
return execClean(cfg, args, io)
},
)
}
func (c *cleanCfg) RegisterFlags(fs *flag.FlagSet) {
fs.BoolVar(
&c.dryRun,
"n",
false,
"print remove commands it would execute, but not run them",
)
fs.BoolVar(
&c.verbose,
"x",
false,
"print remove commands as it executes them",
)
fs.BoolVar(
&c.modCache,
"modcache",
false,
"remove the entire module download cache and exit",
)
}
func execClean(cfg *cleanCfg, args []string, io commands.IO) error {
if len(args) > 0 {
return flag.ErrHelp
}
if cfg.modCache {
modCacheDir := gnomod.ModCachePath()
if !cfg.dryRun {
if err := os.RemoveAll(modCacheDir); err != nil {
return err
}
}
if cfg.dryRun || cfg.verbose {
io.Println("rm -rf", modCacheDir)
}
return nil
}
path, err := os.Getwd()
if err != nil {
return err
}
modDir, err := gnomod.FindRootDir(path)
if err != nil {
return fmt.Errorf("not a gno module: %w", err)
}
if path != modDir && (cfg.dryRun || cfg.verbose) {
io.Println("cd", modDir)
}
err = clean(modDir, cfg, io)
if err != nil {
return err
}
return nil
}
// clean removes generated files from a directory.
func clean(dir string, cfg *cleanCfg, io commands.IO) error {
return filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
// Ignore if not a generated file
if !strings.HasSuffix(path, ".gno.gen.go") && !strings.HasSuffix(path, ".gno.gen_test.go") {
return nil
}
if !cfg.dryRun {
if err := os.Remove(path); err != nil {
return err
}
}
if cfg.dryRun || cfg.verbose {
io.Println("rm", strings.TrimPrefix(path, dir+"/"))
}
return nil
})
}