/
cmd.go
79 lines (66 loc) · 1.78 KB
/
cmd.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
package list
import (
"context"
"flag"
"fmt"
"io"
"os"
"text/tabwriter"
"github.com/google/subcommands"
"github.com/loov/goda/internal/pkggraph"
"github.com/loov/goda/internal/pkgset"
"github.com/loov/goda/internal/templates"
)
type Command struct {
printStandard bool
noAlign bool
format string
}
func (*Command) Name() string { return "list" }
func (*Command) Synopsis() string { return "List packages" }
func (*Command) Usage() string {
return `list <expr>:
List packages using an expression.
See "help expr" for further information about expressions.
See "help format" for further information about formatting.
`
}
func (cmd *Command) SetFlags(f *flag.FlagSet) {
f.BoolVar(&cmd.printStandard, "std", false, "print std packages")
f.BoolVar(&cmd.noAlign, "noalign", false, "disable aligning tabs")
f.StringVar(&cmd.format, "f", "{{.ID}}", "formatting")
}
func (cmd *Command) Execute(ctx context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
t, err := templates.Parse(cmd.format)
if err != nil {
fmt.Fprintf(os.Stderr, "invalid format string: %v\n", err)
return subcommands.ExitFailure
}
if !cmd.printStandard {
go pkgset.LoadStd()
}
result, err := pkgset.Calc(ctx, f.Args())
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
return subcommands.ExitFailure
}
if !cmd.printStandard {
result = pkgset.Subtract(result, pkgset.Std())
}
graph := pkggraph.From(result)
var w io.Writer = os.Stdout
if !cmd.noAlign {
w = tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
}
for _, p := range graph.Sorted {
err := t.Execute(w, p)
fmt.Fprintln(w)
if err != nil {
fmt.Fprintf(os.Stderr, "template error: %v\n", err)
}
}
if w, ok := w.(interface{ Flush() error }); ok {
w.Flush()
}
return subcommands.ExitSuccess
}