GitRoot
craft your forge, build your project, grow your community freely
1// SPDX-FileCopyrightText: 2025 Romain Maneschi <romain@gitroot.dev>
2//
3// SPDX-License-Identifier: EUPL-1.2
4
5package plugin
6
7import (
8 "io/fs"
9 "os"
10
11 "github.com/goccy/go-yaml"
12 "github.com/samber/oops"
13)
14
15// Sync add/remove wasm package in global forge directory
16func (m *Manager) Sync(fileContent []byte) error {
17 errorHandler := oops.With("pluginsDataDir", m.conf.PathDataPlugin()).With("file", fileContent)
18 needReloadPlugins := false
19
20 plugins := make([]Plugin, 0)
21 if err := yaml.Unmarshal(fileContent, &plugins); err != nil {
22 return errorHandler.Wrapf(err, "can't unmarshal yaml")
23 }
24 entries, err := os.ReadDir(m.conf.PathDataPlugin())
25 if err != nil {
26 if os.IsNotExist(err) {
27 if err := os.MkdirAll(m.conf.PathDataPlugin(), os.ModePerm); err != nil {
28 return errorHandler.Wrapf(err, "can't create plugin directory")
29 }
30 entries = make([]fs.DirEntry, 0)
31 } else {
32 return errorHandler.Wrapf(err, "can't read directory")
33 }
34 }
35 for _, plugin := range plugins {
36 found := false
37 for _, e := range entries {
38 if e.Name() == plugin.Name {
39 found = true
40 break
41 }
42 }
43 if !found {
44 if err := m.add(plugin); err != nil {
45 return errorHandler.Wrap(err)
46 }
47 needReloadPlugins = true
48 }
49 }
50
51 for _, e := range entries {
52 found := false
53 for _, plugin := range plugins {
54 if e.Name() == plugin.Name {
55 found = true
56 break
57 }
58 }
59 if !found {
60 if err := os.Remove(m.conf.GetDirPathDataPlugin(e.Name())); err != nil {
61 return errorHandler.With("plugin", e.Name()).Wrapf(err, "can't delete plugin")
62 }
63 needReloadPlugins = true
64 }
65 }
66
67 if needReloadPlugins {
68 m.reloadPlugins()
69 }
70
71 return nil
72}
73
74func (m *Manager) add(plugin Plugin) error {
75 if plugin.Name == "" {
76 plugin = plugin.DetermineNameFromUrl()
77 }
78 if err := os.MkdirAll(m.conf.GetDirPathDataPlugin(plugin.Name), os.ModePerm); err != nil {
79 return oops.With("plugin", plugin.Name).Wrapf(err, "can't MkdirAll")
80 }
81 if err := m.Install(plugin); err != nil {
82 return oops.With("plugin", plugin.Url).Wrapf(err, "can't copy plugin")
83 }
84 return nil
85}