Debian Codegraph @

internal/config/rtfiles.go

raw
1 package config
2
3 import (
4 "errors"
5 "log"
6 "os"
7 "path/filepath"
8 "regexp"
9 "strings"
10
11 rt "github.com/zyedidia/micro/v2/runtime"
12 )
13
14 const (
15 RTColorscheme = 0
16 RTSyntax = 1
17 RTHelp = 2
18 RTPlugin = 3
19 RTSyntaxHeader = 4
20 )
21
22 var (
23 NumTypes = 5 // How many filetypes are there
24 )
25
26 type RTFiletype int
27
28 // RuntimeFile allows the program to read runtime data like colorschemes or syntax files
29 type RuntimeFile interface {
30 // Name returns a name of the file without paths or extensions
31 Name() string
32 // Data returns the content of the file.
33 Data() ([]byte, error)
34 }
35
36 // allFiles contains all available files, mapped by filetype
37 var allFiles [][]RuntimeFile
38 var realFiles [][]RuntimeFile
39
40 func init() {
41 initRuntimeVars()
42 }
43
44 func initRuntimeVars() {
45 allFiles = make([][]RuntimeFile, NumTypes)
46 realFiles = make([][]RuntimeFile, NumTypes)
47 }
48
49 // NewRTFiletype creates a new RTFiletype
50 func NewRTFiletype() int {
51 NumTypes++
52 allFiles = append(allFiles, []RuntimeFile{})
53 realFiles = append(realFiles, []RuntimeFile{})
54 return NumTypes - 1
55 }
56
57 // some file on filesystem
58 type realFile string
59
60 // some asset file
61 type assetFile string
62
63 // a file with the data stored in memory
64 type memoryFile struct {
65 name string
66 data []byte
67 }
68
69 func (mf memoryFile) Name() string {
70 return mf.name
71 }
72 func (mf memoryFile) Data() ([]byte, error) {
73 return mf.data, nil
74 }
75
76 func (rf realFile) Name() string {
77 fn := filepath.Base(string(rf))
78 return fn[:len(fn)-len(filepath.Ext(fn))]
79 }
80
81 func (rf realFile) Data() ([]byte, error) {
82 return os.ReadFile(string(rf))
83 }
84
85 func (af assetFile) Name() string {
86 fn := filepath.Base(string(af))
87 return fn[:len(fn)-len(filepath.Ext(fn))]
88 }
89
90 func (af assetFile) Data() ([]byte, error) {
91 return rt.Asset(string(af))
92 }
93
94 // AddRuntimeFile registers a file for the given filetype
95 func AddRuntimeFile(fileType RTFiletype, file RuntimeFile) {
96 allFiles[fileType] = append(allFiles[fileType], file)
97 }
98
99 // AddRealRuntimeFile registers a file for the given filetype
100 func AddRealRuntimeFile(fileType RTFiletype, file RuntimeFile) {
101 allFiles[fileType] = append(allFiles[fileType], file)
102 realFiles[fileType] = append(realFiles[fileType], file)
103 }
104
105 // AddRuntimeFilesFromDirectory registers each file from the given directory for
106 // the filetype which matches the file-pattern
107 func AddRuntimeFilesFromDirectory(fileType RTFiletype, directory, pattern string) {
108 files, _ := os.ReadDir(directory)
109 for _, f := range files {
110 if ok, _ := filepath.Match(pattern, f.Name()); !f.IsDir() && ok {
111 fullPath := filepath.Join(directory, f.Name())
112 AddRealRuntimeFile(fileType, realFile(fullPath))
113 }
114 }
115 }
116
117 // AddRuntimeFilesFromAssets registers each file from the given asset-directory for
118 // the filetype which matches the file-pattern
119 func AddRuntimeFilesFromAssets(fileType RTFiletype, directory, pattern string) {
120 files, err := rt.AssetDir(directory)
121 if err != nil {
122 return
123 }
124
125 assetLoop:
126 for _, f := range files {
127 if ok, _ := filepath.Match(pattern, f); ok {
128 af := assetFile(filepath.Join(directory, f))
129 for _, rf := range realFiles[fileType] {
130 if af.Name() == rf.Name() {
131 continue assetLoop
132 }
133 }
134 AddRuntimeFile(fileType, af)
135 }
136 }
137 }
138
139 // FindRuntimeFile finds a runtime file of the given filetype and name
140 // will return nil if no file was found
141 func FindRuntimeFile(fileType RTFiletype, name string) RuntimeFile {
142 for _, f := range ListRuntimeFiles(fileType) {
143 if f.Name() == name {
144 return f
145 }
146 }
147 return nil
148 }
149
150 // ListRuntimeFiles lists all known runtime files for the given filetype
151 func ListRuntimeFiles(fileType RTFiletype) []RuntimeFile {
152 return allFiles[fileType]
153 }
154
155 // ListRealRuntimeFiles lists all real runtime files (on disk) for a filetype
156 // these runtime files will be ones defined by the user and loaded from the config directory
157 func ListRealRuntimeFiles(fileType RTFiletype) []RuntimeFile {
158 return realFiles[fileType]
159 }
160
161 // InitRuntimeFiles initializes all assets files and the config directory.
162 // If `user` is false, InitRuntimeFiles ignores the config directory and
163 // initializes asset files only.
164 func InitRuntimeFiles(user bool) {
165 add := func(fileType RTFiletype, dir, pattern string) {
166 if user {
167 AddRuntimeFilesFromDirectory(fileType, filepath.Join(ConfigDir, dir), pattern)
168 }
169 AddRuntimeFilesFromAssets(fileType, filepath.Join("runtime", dir), pattern)
170 }
171
172 initRuntimeVars()
173
174 add(RTColorscheme, "colorschemes", "*.micro")
175 add(RTSyntax, "syntax", "*.yaml")
176 add(RTSyntaxHeader, "syntax", "*.hdr")
177 add(RTHelp, "help", "*.md")
178 }
179
180 // InitPlugins initializes the plugins
181 func InitPlugins() {
182 Plugins = Plugins[:0]
183 initlua := filepath.Join(ConfigDir, "init.lua")
184
185 if _, err := os.Stat(initlua); !os.IsNotExist(err) {
186 p := new(Plugin)
187 p.Name = "initlua"
188 p.DirName = "initlua"
189 p.Srcs = append(p.Srcs, realFile(initlua))
190 p.Builtin = false
191 Plugins = append(Plugins, p)
192 }
193
194 // Search ConfigDir for plugin-scripts
195 plugdir := filepath.Join(ConfigDir, "plug")
196 files, _ := os.ReadDir(plugdir)
197
198 isID := regexp.MustCompile(`^[_A-Za-z0-9]+$`).MatchString
199
200 for _, d := range files {
201 plugpath := filepath.Join(plugdir, d.Name())
202 if stat, err := os.Stat(plugpath); err == nil && stat.IsDir() {
203 srcs, _ := os.ReadDir(plugpath)
204 p := new(Plugin)
205 p.Name = d.Name()
206 p.DirName = d.Name()
207 for _, f := range srcs {
208 if strings.HasSuffix(f.Name(), ".lua") {
209 p.Srcs = append(p.Srcs, realFile(filepath.Join(plugdir, d.Name(), f.Name())))
210 } else if strings.HasSuffix(f.Name(), ".json") {
211 data, err := os.ReadFile(filepath.Join(plugdir, d.Name(), f.Name()))
212 if err != nil {
213 continue
214 }
215 p.Info, err = NewPluginInfo(data)
216 if err != nil {
217 continue
218 }
219 p.Name = p.Info.Name
220 }
221 }
222
223 if !isID(p.Name) || len(p.Srcs) <= 0 {
224 log.Println(p.Name, "is not a plugin")
225 continue
226 }
227 Plugins = append(Plugins, p)
228 }
229 }
230
231 plugdir = filepath.Join("runtime", "plugins")
232 if files, err := rt.AssetDir(plugdir); err == nil {
233 outer:
234 for _, d := range files {
235 for _, p := range Plugins {
236 if p.Name == d {
237 log.Println(p.Name, "built-in plugin overridden by user-defined one")
238 continue outer
239 }
240 }
241
242 if srcs, err := rt.AssetDir(filepath.Join(plugdir, d)); err == nil {
243 p := new(Plugin)
244 p.Name = d
245 p.DirName = d
246 p.Builtin = true
247 for _, f := range srcs {
248 if strings.HasSuffix(f, ".lua") {
249 p.Srcs = append(p.Srcs, assetFile(filepath.Join(plugdir, d, f)))
250 } else if strings.HasSuffix(f, ".json") {
251 data, err := rt.Asset(filepath.Join(plugdir, d, f))
252 if err != nil {
253 continue
254 }
255 p.Info, err = NewPluginInfo(data)
256 if err != nil {
257 continue
258 }
259 p.Name = p.Info.Name
260 }
261 }
262 if !isID(p.Name) || len(p.Srcs) <= 0 {
263 log.Println(p.Name, "is not a plugin")
264 continue
265 }
266 Plugins = append(Plugins, p)
267 }
268 }
269 }
270 }
271
272 // PluginReadRuntimeFile allows plugin scripts to read the content of a runtime file
273 func PluginReadRuntimeFile(fileType RTFiletype, name string) string {
274 if file := FindRuntimeFile(fileType, name); file != nil {
275 if data, err := file.Data(); err == nil {
276 return string(data)
277 }
278 }
279 return ""
280 }
281
282 // PluginListRuntimeFiles allows plugins to lists all runtime files of the given type
283 func PluginListRuntimeFiles(fileType RTFiletype) []string {
284 files := ListRuntimeFiles(fileType)
285 result := make([]string, len(files))
286 for i, f := range files {
287 result[i] = f.Name()
288 }
289 return result
290 }
291
292 // PluginAddRuntimeFile adds a file to the runtime files for a plugin
293 func PluginAddRuntimeFile(plugin string, filetype RTFiletype, filePath string) error {
294 pl := FindPlugin(plugin)
295 if pl == nil {
296 return errors.New("Plugin " + plugin + " does not exist")
297 }
298 pldir := pl.DirName
299 fullpath := filepath.Join(ConfigDir, "plug", pldir, filePath)
300 if _, err := os.Stat(fullpath); err == nil {
301 AddRealRuntimeFile(filetype, realFile(fullpath))
302 } else {
303 fullpath = filepath.Join("runtime", "plugins", pldir, filePath)
304 AddRuntimeFile(filetype, assetFile(fullpath))
305 }
306 return nil
307 }
308
309 // PluginAddRuntimeFilesFromDirectory adds files from a directory to the runtime files for a plugin
310 func PluginAddRuntimeFilesFromDirectory(plugin string, filetype RTFiletype, directory, pattern string) error {
311 pl := FindPlugin(plugin)
312 if pl == nil {
313 return errors.New("Plugin " + plugin + " does not exist")
314 }
315 pldir := pl.DirName
316 fullpath := filepath.Join(ConfigDir, "plug", pldir, directory)
317 if _, err := os.Stat(fullpath); err == nil {
318 AddRuntimeFilesFromDirectory(filetype, fullpath, pattern)
319 } else {
320 fullpath = filepath.Join("runtime", "plugins", pldir, directory)
321 AddRuntimeFilesFromAssets(filetype, fullpath, pattern)
322 }
323 return nil
324 }
325
326 // PluginAddRuntimeFileFromMemory adds a file to the runtime files for a plugin from a given string
327 func PluginAddRuntimeFileFromMemory(filetype RTFiletype, filename, data string) {
328 AddRealRuntimeFile(filetype, memoryFile{filename, []byte(data)})
329 }