github.com/segakazzz/buffalo@v0.16.22-0.20210119082501-1f52048d3feb/plugins/plugdeps/plugins.go (about) 1 package plugdeps 2 3 import ( 4 "io" 5 "sort" 6 "sync" 7 8 "github.com/BurntSushi/toml" 9 ) 10 11 // Plugins manages the config/buffalo-plugins.toml file 12 // as well as the plugins available from the file. 13 type Plugins struct { 14 plugins map[string]Plugin 15 moot *sync.RWMutex 16 } 17 18 // Encode the list of plugins, in TOML format, to the reader 19 func (plugs *Plugins) Encode(w io.Writer) error { 20 tp := tomlPlugins{ 21 Plugins: plugs.List(), 22 } 23 24 if err := toml.NewEncoder(w).Encode(tp); err != nil { 25 return err 26 } 27 return nil 28 } 29 30 // Decode the list of plugins, in TOML format, from the reader 31 func (plugs *Plugins) Decode(r io.Reader) error { 32 tp := &tomlPlugins{ 33 Plugins: []Plugin{}, 34 } 35 if _, err := toml.DecodeReader(r, tp); err != nil { 36 return err 37 } 38 for _, p := range tp.Plugins { 39 plugs.Add(p) 40 } 41 return nil 42 } 43 44 // List of dependent plugins listed in order of Plugin.String() 45 func (plugs *Plugins) List() []Plugin { 46 m := map[string]Plugin{} 47 plugs.moot.RLock() 48 for _, p := range plugs.plugins { 49 m[p.key()] = p 50 } 51 plugs.moot.RUnlock() 52 var pp []Plugin 53 for _, v := range m { 54 pp = append(pp, v) 55 } 56 sort.Slice(pp, func(a, b int) bool { 57 return pp[a].Binary < pp[b].Binary 58 }) 59 return pp 60 } 61 62 // Add plugin(s) to the list of dependencies 63 func (plugs *Plugins) Add(pp ...Plugin) { 64 plugs.moot.Lock() 65 for _, p := range pp { 66 plugs.plugins[p.key()] = p 67 } 68 plugs.moot.Unlock() 69 } 70 71 // Remove plugin(s) from the list of dependencies 72 func (plugs *Plugins) Remove(pp ...Plugin) { 73 plugs.moot.Lock() 74 for _, p := range pp { 75 delete(plugs.plugins, p.key()) 76 } 77 plugs.moot.Unlock() 78 } 79 80 // New returns a configured *Plugins value 81 func New() *Plugins { 82 plugs := &Plugins{ 83 plugins: map[string]Plugin{}, 84 moot: &sync.RWMutex{}, 85 } 86 return plugs 87 } 88 89 type tomlPlugins struct { 90 Plugins []Plugin `toml:"plugin"` 91 }