modules are now represented by a struct that holds import-function, module description and importa status.

It is also available the new function IterateModules() to explore all modules.
This commit is contained in:
2024-04-28 05:41:13 +02:00
parent 6dd8283308
commit bf8f1a175f
5 changed files with 41 additions and 14 deletions
+37 -10
View File
@@ -5,33 +5,49 @@
package expr
import (
"fmt"
"path/filepath"
)
var moduleRegister map[string]func(ExprContext)
type module struct {
importFunc func(ExprContext)
description string
imported bool
}
func registerImport(name string, importFunc func(ExprContext)) {
func newModule(importFunc func(ExprContext), description string) *module {
return &module{importFunc, description, false}
}
var moduleRegister map[string]*module
func registerImport(name string, importFunc func(ExprContext), description string) {
if moduleRegister == nil {
moduleRegister = make(map[string]func(ExprContext))
moduleRegister = make(map[string]*module)
}
moduleRegister[name] = importFunc
if _, exists := moduleRegister[name]; exists {
panic(fmt.Errorf("module %q already registered", name))
}
moduleRegister[name] = newModule(importFunc, description)
}
func ImportInContext(ctx ExprContext, name string) (exists bool) {
var importFunc func(ExprContext)
if importFunc, exists = moduleRegister[name]; exists {
importFunc(ctx)
var mod *module
if mod, exists = moduleRegister[name]; exists {
mod.importFunc(ctx)
mod.imported = true
}
return
}
func ImportInContextByGlobPattern(ctx ExprContext, pattern string) (count int, err error) {
var matched bool
for name, importFunc := range moduleRegister {
for name, mod := range moduleRegister {
if matched, err = filepath.Match(pattern, name); err == nil {
if matched {
count++
importFunc(ctx)
mod.importFunc(ctx)
mod.imported = true
}
} else {
break
@@ -40,8 +56,19 @@ func ImportInContextByGlobPattern(ctx ExprContext, pattern string) (count int, e
return
}
func IterateModules(op func(name, description string, imported bool) bool) {
if op != nil {
for name, mod := range moduleRegister {
if !op(name, mod.description, mod.imported) {
break
}
}
}
}
// ----
func init() {
if moduleRegister == nil {
moduleRegister = make(map[string]func(ExprContext))
moduleRegister = make(map[string]*module)
}
}