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