1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
package keybinds
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/AvengeMedia/DankMaterialShell/core/internal/utils"
)
type DiscoveryConfig struct {
SearchPaths []string
}
func DefaultDiscoveryConfig() *DiscoveryConfig {
var searchPaths []string
configDir, err := os.UserConfigDir()
if err == nil && configDir != "" {
searchPaths = append(searchPaths, filepath.Join(configDir, "DankMaterialShell", "cheatsheets"))
}
configDirs := os.Getenv("XDG_CONFIG_DIRS")
if configDirs != "" {
for dir := range strings.SplitSeq(configDirs, ":") {
if dir != "" {
searchPaths = append(searchPaths, filepath.Join(dir, "DankMaterialShell", "cheatsheets"))
}
}
}
return &DiscoveryConfig{
SearchPaths: searchPaths,
}
}
func (d *DiscoveryConfig) FindJSONFiles() ([]string, error) {
var files []string
for _, searchPath := range d.SearchPaths {
expandedPath, err := utils.ExpandPath(searchPath)
if err != nil {
continue
}
if _, err := os.Stat(expandedPath); os.IsNotExist(err) {
continue
}
entries, err := os.ReadDir(expandedPath)
if err != nil {
continue
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
if !strings.HasSuffix(entry.Name(), ".json") {
continue
}
fullPath := filepath.Join(expandedPath, entry.Name())
files = append(files, fullPath)
}
}
return files, nil
}
type JSONProviderFactory func(filePath string) (Provider, error)
var jsonProviderFactory JSONProviderFactory
func SetJSONProviderFactory(factory JSONProviderFactory) {
jsonProviderFactory = factory
}
func AutoDiscoverProviders(registry *Registry, config *DiscoveryConfig) error {
if config == nil {
config = DefaultDiscoveryConfig()
}
if jsonProviderFactory == nil {
return nil
}
files, err := config.FindJSONFiles()
if err != nil {
return fmt.Errorf("failed to discover JSON files: %w", err)
}
for _, file := range files {
provider, err := jsonProviderFactory(file)
if err != nil {
continue
}
if err := registry.Register(provider); err != nil {
continue
}
}
return nil
}
|