17 "github.com/blang/semver"
18 "github.com/yosuke-furukawa/json5/encoding/json5"
19 "github.com/yuin/gopher-lua"
23 pluginChannels PluginChannels = PluginChannels{
24 PluginChannel("https://www.boombuler.de/channel.json"),
27 allPluginPackages PluginPackages = nil
30 // CorePluginName is a plugin dependency name for the micro core.
31 const CorePluginName = "micro"
33 // PluginChannel contains an url to a json list of PluginRepository
34 type PluginChannel string
36 // PluginChannels is a slice of PluginChannel
37 type PluginChannels []PluginChannel
39 // PluginRepository contains an url to json file containing PluginPackages
40 type PluginRepository string
42 // PluginPackage contains the meta-data of a plugin and all available versions
43 type PluginPackage struct {
48 Versions PluginVersions
51 // PluginPackages is a list of PluginPackage instances.
52 type PluginPackages []*PluginPackage
54 // PluginVersion descripes a version of a PluginPackage. Containing a version, download url and also dependencies.
55 type PluginVersion struct {
57 Version semver.Version
59 Require PluginDependencies
62 // PluginVersions is a slice of PluginVersion
63 type PluginVersions []*PluginVersion
65 // PluginDenendency descripes a dependency to another plugin or micro itself.
66 type PluginDependency struct {
71 // PluginDependencies is a slice of PluginDependency
72 type PluginDependencies []*PluginDependency
74 func (pp *PluginPackage) String() string {
75 buf := new(bytes.Buffer)
76 buf.WriteString("Plugin: ")
77 buf.WriteString(pp.Name)
80 buf.WriteString("Author: ")
81 buf.WriteString(pp.Author)
84 if pp.Description != "" {
85 buf.WriteString(pp.Description)
90 func fetchAllSources(count int, fetcher func(i int) PluginPackages) PluginPackages {
91 wgQuery := new(sync.WaitGroup)
94 results := make(chan PluginPackages)
96 wgDone := new(sync.WaitGroup)
98 var packages PluginPackages
99 for i := 0; i < count; i++ {
101 results <- fetcher(i)
106 packages = make(PluginPackages, 0)
107 for res := range results {
108 packages = append(packages, res...)
118 // Fetch retrieves all available PluginPackages from the given channels
119 func (pc PluginChannels) Fetch() PluginPackages {
120 return fetchAllSources(len(pc), func(i int) PluginPackages {
125 // Fetch retrieves all available PluginPackages from the given channel
126 func (pc PluginChannel) Fetch() PluginPackages {
127 resp, err := http.Get(string(pc))
129 TermMessage("Failed to query plugin channel:\n", err)
130 return PluginPackages{}
132 defer resp.Body.Close()
133 decoder := json5.NewDecoder(resp.Body)
135 var repositories []PluginRepository
136 if err := decoder.Decode(&repositories); err != nil {
137 TermMessage("Failed to decode channel data:\n", err)
138 return PluginPackages{}
140 return fetchAllSources(len(repositories), func(i int) PluginPackages {
141 return repositories[i].Fetch()
145 // Fetch retrieves all available PluginPackages from the given repository
146 func (pr PluginRepository) Fetch() PluginPackages {
147 resp, err := http.Get(string(pr))
149 TermMessage("Failed to query plugin repository:\n", err)
150 return PluginPackages{}
152 defer resp.Body.Close()
153 decoder := json5.NewDecoder(resp.Body)
155 var plugins PluginPackages
156 if err := decoder.Decode(&plugins); err != nil {
157 TermMessage("Failed to decode repository data:\n", err)
158 return PluginPackages{}
163 // UnmarshalJSON unmarshals raw json to a PluginVersion
164 func (pv *PluginVersion) UnmarshalJSON(data []byte) error {
166 Version semver.Version
168 Require map[string]string
171 if err := json5.Unmarshal(data, &values); err != nil {
174 pv.Version = values.Version
176 pv.Require = make(PluginDependencies, 0)
178 for k, v := range values.Require {
179 if vRange, err := semver.ParseRange(v); err == nil {
180 pv.Require = append(pv.Require, &PluginDependency{k, vRange})
186 // UnmarshalJSON unmarshals raw json to a PluginPackage
187 func (pp *PluginPackage) UnmarshalJSON(data []byte) error {
193 Versions PluginVersions
195 if err := json5.Unmarshal(data, &values); err != nil {
198 pp.Name = values.Name
199 pp.Description = values.Description
200 pp.Author = values.Author
201 pp.Tags = values.Tags
202 pp.Versions = values.Versions
203 for _, v := range pp.Versions {
209 // GetAllPluginPackages gets all PluginPackages which may be available.
210 func GetAllPluginPackages() PluginPackages {
211 if allPluginPackages == nil {
212 allPluginPackages = pluginChannels.Fetch()
214 return allPluginPackages
217 func (pv PluginVersions) find(ppName string) *PluginVersion {
218 for _, v := range pv {
219 if v.pack.Name == ppName {
226 // Len returns the number of pluginversions in this slice
227 func (pv PluginVersions) Len() int {
231 // Swap two entries of the slice
232 func (pv PluginVersions) Swap(i, j int) {
233 pv[i], pv[j] = pv[j], pv[i]
236 // Less returns true if the version at position i is greater then the version at position j (used for sorting)
237 func (s PluginVersions) Less(i, j int) bool {
238 return s[i].Version.GT(s[j].Version)
241 // Match returns true if the package matches a given search text
242 func (pp PluginPackage) Match(text string) bool {
243 // ToDo: improve matching.
245 if r, err := regexp.Compile(text); err == nil {
246 return r.MatchString(pp.Name)
251 // IsInstallable returns true if the package can be installed.
252 func (pp PluginPackage) IsInstallable() bool {
253 _, err := GetAllPluginPackages().Resolve(GetInstalledVersions(), PluginDependencies{
256 Range: semver.Range(func(v semver.Version) bool { return true }),
261 // SearchPlugin retrieves a list of all PluginPackages which match the given search text and
262 // could be or are already installed
263 func SearchPlugin(text string) (plugins PluginPackages) {
264 plugins = make(PluginPackages, 0)
265 for _, pp := range GetAllPluginPackages() {
266 if pp.Match(text) && pp.IsInstallable() {
267 plugins = append(plugins, pp)
273 func newStaticPluginVersion(name, version string) *PluginVersion {
274 vers, err := semver.ParseTolerant(version)
277 if vers, err = semver.ParseTolerant("0.0.0-" + version); err != nil {
278 vers = semver.MustParse("0.0.0-unknown")
281 pl := &PluginPackage{
284 pv := &PluginVersion{
288 pl.Versions = PluginVersions{pv}
292 // GetInstalledVersions returns a list of all currently installed plugins including an entry for
293 // micro itself. This can be used to resolve dependencies.
294 func GetInstalledVersions() PluginVersions {
295 result := PluginVersions{
296 newStaticPluginVersion(CorePluginName, Version),
299 for _, name := range loadedPlugins {
300 version := GetInstalledPluginVersion(name)
301 if pv := newStaticPluginVersion(name, version); pv != nil {
302 result = append(result, pv)
309 // GetInstalledPluginVersion returns the string of the exported VERSION variable of a loaded plugin
310 func GetInstalledPluginVersion(name string) string {
311 plugin := L.GetGlobal(name)
312 if plugin != lua.LNil {
313 version := L.GetField(plugin, "VERSION")
314 if str, ok := version.(lua.LString); ok {
322 func (pv *PluginVersion) DownloadAndInstall() error {
323 resp, err := http.Get(pv.Url)
327 defer resp.Body.Close()
328 data, err := ioutil.ReadAll(resp.Body)
332 zipbuf := bytes.NewReader(data)
333 z, err := zip.NewReader(zipbuf, zipbuf.Size())
337 targetDir := filepath.Join(configDir, "plugins", pv.pack.Name)
338 dirPerm := os.FileMode(0755)
339 if err = os.MkdirAll(targetDir, dirPerm); err != nil {
342 for _, f := range z.File {
343 targetName := filepath.Join(targetDir, filepath.Join(strings.Split(f.Name, "/")...))
344 if f.FileInfo().IsDir() {
345 if err := os.MkdirAll(targetName, dirPerm); err != nil {
349 content, err := f.Open()
353 defer content.Close()
354 if target, err := os.Create(targetName); err != nil {
358 if _, err = io.Copy(target, content); err != nil {
367 func (pl PluginPackages) Get(name string) *PluginPackage {
368 for _, p := range pl {
376 func (pl PluginPackages) GetAllVersions(name string) PluginVersions {
377 result := make(PluginVersions, 0)
380 for _, v := range p.Versions {
381 result = append(result, v)
387 func (req PluginDependencies) Join(other PluginDependencies) PluginDependencies {
388 m := make(map[string]*PluginDependency)
389 for _, r := range req {
392 for _, o := range other {
395 m[o.Name] = &PluginDependency{
397 o.Range.AND(cur.Range),
403 result := make(PluginDependencies, 0, len(m))
404 for _, v := range m {
405 result = append(result, v)
410 func (all PluginPackages) Resolve(selectedVersions PluginVersions, open PluginDependencies) (PluginVersions, error) {
412 return selectedVersions, nil
414 currentRequirement, stillOpen := open[0], open[1:]
415 if currentRequirement != nil {
416 if selVersion := selectedVersions.find(currentRequirement.Name); selVersion != nil {
417 if currentRequirement.Range(selVersion.Version) {
418 return all.Resolve(selectedVersions, stillOpen)
420 return nil, fmt.Errorf("unable to find a matching version for \"%s\"", currentRequirement.Name)
422 availableVersions := all.GetAllVersions(currentRequirement.Name)
423 sort.Sort(availableVersions)
425 for _, version := range availableVersions {
426 if currentRequirement.Range(version.Version) {
427 resolved, err := all.Resolve(append(selectedVersions, version), stillOpen.Join(version.Require))
434 return nil, fmt.Errorf("unable to find a matching version for \"%s\"", currentRequirement.Name)
437 return selectedVersions, nil
441 func (versions PluginVersions) install() {
442 anyInstalled := false
443 for _, sel := range versions {
444 if sel.pack.Name != CorePluginName {
445 installed := GetInstalledPluginVersion(sel.pack.Name)
446 if v, err := semver.ParseTolerant(installed); err != nil || v.NE(sel.Version) {
447 UninstallPlugin(sel.pack.Name)
449 if err := sel.DownloadAndInstall(); err != nil {
457 messenger.Message("One or more plugins installed. Please restart micro.")
461 // UninstallPlugin deletes the plugin folder of the given plugin
462 func UninstallPlugin(name string) {
463 if err := os.RemoveAll(filepath.Join(configDir, "plugins", name)); err != nil {
468 func (pl PluginPackage) Install() {
469 selected, err := GetAllPluginPackages().Resolve(GetInstalledVersions(), PluginDependencies{
472 Range: semver.Range(func(v semver.Version) bool { return true }),
481 func UpdatePlugins() {
482 microVersion := PluginVersions{
483 newStaticPluginVersion(CorePluginName, Version),
486 var updates = make(PluginDependencies, 0)
487 for _, name := range loadedPlugins {
488 pv := GetInstalledPluginVersion(name)
489 r, err := semver.ParseRange(">=" + pv) // Try to get newer versions.
491 updates = append(updates, &PluginDependency{
498 selected, err := GetAllPluginPackages().Resolve(microVersion, updates)