|
1 | 1 | package plugin |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "database/sql/driver" |
4 | 5 | "encoding/json" |
5 | 6 | "errors" |
6 | 7 | "fmt" |
@@ -69,13 +70,23 @@ type ConfigOption struct { |
69 | 70 | Max types.Int `json:"max,omitempty"` |
70 | 71 | } |
71 | 72 |
|
| 73 | +// ConfigOptions describes all ConfigOption entries. |
| 74 | +// |
| 75 | +// This type became necessary to implement the database.sql.driver.Valuer to marshal it into JSON. |
| 76 | +type ConfigOptions []ConfigOption |
| 77 | + |
| 78 | +// Value implements database.sql's driver.Valuer to represent all ConfigOptions as a JSON array. |
| 79 | +func (c ConfigOptions) Value() (driver.Value, error) { |
| 80 | + return json.Marshal(c) |
| 81 | +} |
| 82 | + |
72 | 83 | // Info contains plugin information. |
73 | 84 | type Info struct { |
74 | | - Type string `db:"type" json:"-"` |
75 | | - Name string `db:"name" json:"name"` |
76 | | - Version string `db:"version" json:"version"` |
77 | | - Author string `db:"author" json:"author"` |
78 | | - ConfigAttributes json.RawMessage `db:"config_attrs" json:"config_attrs"` // ConfigOption(s) as json-encoded list |
| 85 | + Type string `db:"type" json:"-"` |
| 86 | + Name string `db:"name" json:"name"` |
| 87 | + Version string `db:"version" json:"version"` |
| 88 | + Author string `db:"author" json:"author"` |
| 89 | + ConfigAttributes ConfigOptions `db:"config_attrs" json:"config_attrs"` |
79 | 90 | } |
80 | 91 |
|
81 | 92 | // TableName implements the contracts.TableNamer interface. |
@@ -131,6 +142,25 @@ type Plugin interface { |
131 | 142 | SendNotification(req *NotificationRequest) error |
132 | 143 | } |
133 | 144 |
|
| 145 | +// PopulateDefaults sets the struct fields from Info.ConfigAttributes where ConfigOption.Default is set. |
| 146 | +// |
| 147 | +// It should be called from each channel plugin within its Plugin.SetConfig before doing any further configuration. |
| 148 | +func PopulateDefaults(typePtr Plugin) error { |
| 149 | + defaults := make(map[string]any) |
| 150 | + for _, confAttr := range typePtr.GetInfo().ConfigAttributes { |
| 151 | + if confAttr.Default != nil { |
| 152 | + defaults[confAttr.Name] = confAttr.Default |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + defaultConf, err := json.Marshal(defaults) |
| 157 | + if err != nil { |
| 158 | + return err |
| 159 | + } |
| 160 | + |
| 161 | + return json.Unmarshal(defaultConf, typePtr) |
| 162 | +} |
| 163 | + |
134 | 164 | // RunPlugin reads the incoming stdin requests, processes and writes the responses to stdout |
135 | 165 | func RunPlugin(plugin Plugin) { |
136 | 166 | encoder := json.NewEncoder(os.Stdout) |
|
0 commit comments