...
1 package manager
2
3 import (
4 "encoding/json"
5 "path/filepath"
6 "regexp"
7 "strings"
8
9 "github.com/pkg/errors"
10 "github.com/spf13/cobra"
11 )
12
13 var pluginNameRe = regexp.MustCompile("^[a-z][a-z0-9]*$")
14
15
16 type Plugin struct {
17 Metadata
18
19 Name string `json:",omitempty"`
20 Path string `json:",omitempty"`
21
22
23 Err error `json:",omitempty"`
24
25
26 ShadowedPaths []string `json:",omitempty"`
27 }
28
29
30
31
32
33
34 func newPlugin(c Candidate, cmds []*cobra.Command) (Plugin, error) {
35 path := c.Path()
36 if path == "" {
37 return Plugin{}, errors.New("plugin candidate path cannot be empty")
38 }
39
40
41
42 fullname := filepath.Base(path)
43 if fullname == "." {
44 return Plugin{}, errors.Errorf("unable to determine basename of plugin candidate %q", path)
45 }
46 var err error
47 if fullname, err = trimExeSuffix(fullname); err != nil {
48 return Plugin{}, errors.Wrapf(err, "plugin candidate %q", path)
49 }
50 if !strings.HasPrefix(fullname, NamePrefix) {
51 return Plugin{}, errors.Errorf("plugin candidate %q: does not have %q prefix", path, NamePrefix)
52 }
53
54 p := Plugin{
55 Name: strings.TrimPrefix(fullname, NamePrefix),
56 Path: path,
57 }
58
59
60 if !pluginNameRe.MatchString(p.Name) {
61 p.Err = NewPluginError("plugin candidate %q did not match %q", p.Name, pluginNameRe.String())
62 return p, nil
63 }
64
65 for _, cmd := range cmds {
66
67
68
69 if IsPluginCommand(cmd) {
70 continue
71 }
72 if cmd.Name() == p.Name {
73 p.Err = NewPluginError("plugin %q duplicates builtin command", p.Name)
74 return p, nil
75 }
76 if cmd.HasAlias(p.Name) {
77 p.Err = NewPluginError("plugin %q duplicates an alias of builtin command %q", p.Name, cmd.Name())
78 return p, nil
79 }
80 }
81
82
83 meta, err := c.Metadata()
84 if err != nil {
85 p.Err = wrapAsPluginError(err, "failed to fetch metadata")
86 return p, nil
87 }
88
89 if err := json.Unmarshal(meta, &p.Metadata); err != nil {
90 p.Err = wrapAsPluginError(err, "invalid metadata")
91 return p, nil
92 }
93 if p.Metadata.SchemaVersion != "0.1.0" {
94 p.Err = NewPluginError("plugin SchemaVersion %q is not valid, must be 0.1.0", p.Metadata.SchemaVersion)
95 return p, nil
96 }
97 if p.Metadata.Vendor == "" {
98 p.Err = NewPluginError("plugin metadata does not define a vendor")
99 return p, nil
100 }
101 return p, nil
102 }
103
View as plain text