generated from dogmatiq/template-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
132 lines (108 loc) · 2.49 KB
/
command.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
package graph
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"github.com/dogmatiq/configkit"
"github.com/dogmatiq/configkit/static"
"github.com/dogmatiq/configkit/visualization/dot"
"github.com/dogmatiq/imbue"
"github.com/spf13/cobra"
"golang.org/x/tools/go/packages"
)
// Command returns the "visualize graph" command.
func Command(con *imbue.Container) *cobra.Command {
cmd := &cobra.Command{
Use: "graph [<package> ...]",
Short: "Generate a visualization of one or more Dogma applications in Graphviz DOT format",
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
if len(args) == 0 {
args = []string{"./..."}
}
cmd.SilenceUsage = true
apps, err := loadConfigsFromPackages(ctx, args)
if err != nil {
return err
}
if len(apps) == 0 {
return errors.New("no applications found")
}
g, err := dot.Generate(apps...)
if err != nil {
return err
}
out, err := cmd.Flags().GetString("output")
if err != nil {
return err
}
w := cmd.OutOrStdout()
if out != "-" {
f, err := os.Create(out)
if err != nil {
return err
}
defer f.Close()
w = f
}
_, err = io.WriteString(
w,
g.String(),
)
return err
},
}
cmd.Flags().StringP(
"output", "o",
"-",
"write output to the specified file",
)
return cmd
}
// loadConfigsFromPackages returns the configuration for all applications
// defined within the packages that match the given patterns.
func loadConfigsFromPackages(
ctx context.Context,
patterns []string,
) ([]configkit.Application, error) {
var applications []configkit.Application
for _, pattern := range patterns {
cfg := packages.Config{
Context: ctx,
Dir: pattern,
// TODO: Some of these modes can probably be omitted but without
// tests we're not sure which ones.
Mode: packages.NeedName |
packages.NeedFiles |
packages.NeedCompiledGoFiles |
packages.NeedImports |
packages.NeedTypes |
packages.NeedTypesSizes |
packages.NeedSyntax |
packages.NeedTypesInfo |
packages.NeedDeps,
}
if filepath.Base(pattern) == "..." {
cfg.Dir = filepath.Dir(pattern)
pattern = "./..."
} else {
pattern = "."
}
pkgs, err := packages.Load(&cfg, pattern)
if err != nil {
return nil, err
}
for _, pkg := range pkgs {
for _, err := range pkg.Errors {
return nil, err
}
}
applications = append(
applications,
static.FromPackages(pkgs)...,
)
}
return applications, nil
}