forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.go
426 lines (371 loc) · 9.45 KB
/
mod.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package main
import (
"context"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/gnolang/gno/gnovm/cmd/gno/internal/pkgdownload"
"github.com/gnolang/gno/gnovm/cmd/gno/internal/pkgdownload/rpcpkgfetcher"
"github.com/gnolang/gno/gnovm/pkg/gnomod"
"github.com/gnolang/gno/gnovm/pkg/packages"
"github.com/gnolang/gno/tm2/pkg/commands"
"github.com/gnolang/gno/tm2/pkg/errors"
"go.uber.org/multierr"
)
// testPackageFetcher allows to override the package fetcher during tests.
var testPackageFetcher pkgdownload.PackageFetcher
func newModCmd(io commands.IO) *commands.Command {
cmd := commands.NewCommand(
commands.Metadata{
Name: "mod",
ShortUsage: "mod <command>",
ShortHelp: "module maintenance",
},
commands.NewEmptyConfig(),
commands.HelpExec,
)
cmd.AddSubCommands(
newModDownloadCmd(io),
// edit
newModGraphCmd(io),
newModInitCmd(),
newModTidy(io),
// vendor
// verify
newModWhy(io),
)
return cmd
}
func newModDownloadCmd(io commands.IO) *commands.Command {
cfg := &modDownloadCfg{}
return commands.NewCommand(
commands.Metadata{
Name: "download",
ShortUsage: "download [flags]",
ShortHelp: "download modules to local cache",
},
cfg,
func(_ context.Context, args []string) error {
return execModDownload(cfg, args, io)
},
)
}
func newModGraphCmd(io commands.IO) *commands.Command {
cfg := &modGraphCfg{}
return commands.NewCommand(
commands.Metadata{
Name: "graph",
ShortUsage: "graph [path]",
ShortHelp: "print module requirement graph",
},
cfg,
func(_ context.Context, args []string) error {
return execModGraph(cfg, args, io)
},
)
}
func newModInitCmd() *commands.Command {
return commands.NewCommand(
commands.Metadata{
Name: "init",
ShortUsage: "init [module-path]",
ShortHelp: "initialize gno.mod file in current directory",
},
commands.NewEmptyConfig(),
func(_ context.Context, args []string) error {
return execModInit(args)
},
)
}
func newModTidy(io commands.IO) *commands.Command {
cfg := &modTidyCfg{}
return commands.NewCommand(
commands.Metadata{
Name: "tidy",
ShortUsage: "tidy [flags]",
ShortHelp: "add missing and remove unused modules",
},
cfg,
func(_ context.Context, args []string) error {
return execModTidy(cfg, args, io)
},
)
}
func newModWhy(io commands.IO) *commands.Command {
return commands.NewCommand(
commands.Metadata{
Name: "why",
ShortUsage: "why <package> [<package>...]",
ShortHelp: "Explains why modules are needed",
LongHelp: `Explains why modules are needed.
gno mod why shows a list of files where specified packages or modules are
being used, explaining why those specified packages or modules are being
kept by gno mod tidy.
The output is a sequence of stanzas, one for each module/package name
specified, separated by blank lines. Each stanza begins with a
comment line "# module" giving the target module/package. Subsequent lines
show files that import the specified module/package, one filename per line.
If the package or module is not being used/needed/imported, the stanza
will display a single parenthesized note indicating that fact.
For example:
$ gno mod why gno.land/p/demo/avl gno.land/p/demo/users
# gno.land/p/demo/avl
[FILENAME_1.gno]
[FILENAME_2.gno]
# gno.land/p/demo/users
(module [MODULE_NAME] does not need package gno.land/p/demo/users)
$
`,
},
commands.NewEmptyConfig(),
func(_ context.Context, args []string) error {
return execModWhy(args, io)
},
)
}
type modDownloadCfg struct {
remoteOverrides string
}
const remoteOverridesArgName = "remote-overrides"
func (c *modDownloadCfg) RegisterFlags(fs *flag.FlagSet) {
fs.StringVar(
&c.remoteOverrides,
remoteOverridesArgName,
"",
"chain-domain=rpc-url comma-separated list",
)
}
type modGraphCfg struct{}
func (c *modGraphCfg) RegisterFlags(fs *flag.FlagSet) {
// /out std
// /out remote
// /out _test processing
// ...
}
func execModGraph(cfg *modGraphCfg, args []string, io commands.IO) error {
// default to current directory if no args provided
if len(args) == 0 {
args = []string{"."}
}
if len(args) > 1 {
return flag.ErrHelp
}
stdout := io.Out()
pkgs, err := gnomod.ListPkgs(args[0])
if err != nil {
return err
}
for _, pkg := range pkgs {
for _, dep := range pkg.Imports {
fmt.Fprintf(stdout, "%s %s\n", pkg.Name, dep)
}
}
return nil
}
func execModDownload(cfg *modDownloadCfg, args []string, io commands.IO) error {
if len(args) > 0 {
return flag.ErrHelp
}
fetcher := testPackageFetcher
if fetcher == nil {
remoteOverrides, err := parseRemoteOverrides(cfg.remoteOverrides)
if err != nil {
return fmt.Errorf("invalid %s flag: %w", remoteOverridesArgName, err)
}
fetcher = rpcpkgfetcher.New(remoteOverrides)
} else if len(cfg.remoteOverrides) != 0 {
return fmt.Errorf("can't use %s flag with a custom package fetcher", remoteOverridesArgName)
}
path, err := os.Getwd()
if err != nil {
return err
}
modPath := filepath.Join(path, "gno.mod")
if !isFileExist(modPath) {
return errors.New("gno.mod not found")
}
// read gno.mod
data, err := os.ReadFile(modPath)
if err != nil {
return fmt.Errorf("readfile %q: %w", modPath, err)
}
// parse gno.mod
gnoMod, err := gnomod.Parse(modPath, data)
if err != nil {
return fmt.Errorf("parse: %w", err)
}
// sanitize gno.mod
gnoMod.Sanitize()
// validate gno.mod
if err := gnoMod.Validate(); err != nil {
return fmt.Errorf("validate: %w", err)
}
if err := downloadDeps(io, path, gnoMod, fetcher); err != nil {
return err
}
return nil
}
func parseRemoteOverrides(arg string) (map[string]string, error) {
pairs := strings.Split(arg, ",")
res := make(map[string]string, len(pairs))
for _, pair := range pairs {
parts := strings.Split(pair, "=")
if len(parts) != 2 {
return nil, fmt.Errorf("expected 2 parts in chain-domain=rpc-url pair %q", arg)
}
domain := strings.TrimSpace(parts[0])
rpcURL := strings.TrimSpace(parts[1])
res[domain] = rpcURL
}
return res, nil
}
func execModInit(args []string) error {
if len(args) > 1 {
return flag.ErrHelp
}
var modPath string
if len(args) == 1 {
modPath = args[0]
}
dir, err := os.Getwd()
if err != nil {
return err
}
if err := gnomod.CreateGnoModFile(dir, modPath); err != nil {
return fmt.Errorf("create gno.mod file: %w", err)
}
return nil
}
type modTidyCfg struct {
verbose bool
recursive bool
}
func (c *modTidyCfg) RegisterFlags(fs *flag.FlagSet) {
fs.BoolVar(
&c.verbose,
"v",
false,
"verbose output when running",
)
fs.BoolVar(
&c.recursive,
"recursive",
false,
"walk subdirs for gno.mod files",
)
}
func execModTidy(cfg *modTidyCfg, args []string, io commands.IO) error {
if len(args) > 0 {
return flag.ErrHelp
}
wd, err := os.Getwd()
if err != nil {
return err
}
if cfg.recursive {
pkgs, err := gnomod.ListPkgs(wd)
if err != nil {
return err
}
var errs error
for _, pkg := range pkgs {
err := modTidyOnce(cfg, wd, pkg.Dir, io)
errs = multierr.Append(errs, err)
}
return errs
}
// XXX: recursively check parents if no $PWD/gno.mod
return modTidyOnce(cfg, wd, wd, io)
}
func modTidyOnce(cfg *modTidyCfg, wd, pkgdir string, io commands.IO) error {
fname := filepath.Join(pkgdir, "gno.mod")
relpath, err := filepath.Rel(wd, fname)
if err != nil {
return err
}
if cfg.verbose {
io.ErrPrintfln("%s", relpath)
}
gm, err := gnomod.ParseGnoMod(fname)
if err != nil {
return err
}
gm.Write(fname)
return nil
}
func execModWhy(args []string, io commands.IO) error {
if len(args) < 1 {
return flag.ErrHelp
}
wd, err := os.Getwd()
if err != nil {
return err
}
fname := filepath.Join(wd, "gno.mod")
gm, err := gnomod.ParseGnoMod(fname)
if err != nil {
return err
}
importToFilesMap, err := getImportToFilesMap(wd)
if err != nil {
return err
}
// Format and print `gno mod why` output stanzas
out := formatModWhyStanzas(gm.Module.Mod.Path, args, importToFilesMap)
io.Printf(out)
return nil
}
// formatModWhyStanzas returns a formatted output for the go mod why command.
// It takes three parameters:
// - modulePath (the path of the module)
// - args (input arguments)
// - importToFilesMap (a map of import to files).
func formatModWhyStanzas(modulePath string, args []string, importToFilesMap map[string][]string) (out string) {
for i, arg := range args {
out += fmt.Sprintf("# %s\n", arg)
files, ok := importToFilesMap[arg]
if !ok {
out += fmt.Sprintf("(module %s does not need package %s)\n", modulePath, arg)
} else {
for _, file := range files {
out += file + "\n"
}
}
if i < len(args)-1 { // Add a newline if it's not the last stanza
out += "\n"
}
}
return
}
// getImportToFilesMap returns a map where each key is an import path and its
// value is a list of files importing that package with the specified import path.
func getImportToFilesMap(pkgPath string) (map[string][]string, error) {
entries, err := os.ReadDir(pkgPath)
if err != nil {
return nil, err
}
m := make(map[string][]string) // import -> []file
for _, e := range entries {
filename := e.Name()
if ext := filepath.Ext(filename); ext != ".gno" {
continue
}
if strings.HasSuffix(filename, "_filetest.gno") {
continue
}
data, err := os.ReadFile(filepath.Join(pkgPath, filename))
if err != nil {
return nil, err
}
imports, err := packages.FileImports(filename, string(data), nil)
if err != nil {
return nil, err
}
for _, imp := range imports {
m[imp.PkgPath] = append(m[imp.PkgPath], filename)
}
}
return m, nil
}