-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconfig.go
249 lines (215 loc) · 7.08 KB
/
config.go
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"github.com/goccy/go-yaml"
)
type Config struct {
RepoURLs []string `yaml:"RepoURLs" env:"DBIN_REPO_URLS"`
InstallDir string `yaml:"InstallDir" env:"DBIN_INSTALL_DIR XDG_BIN_HOME"`
CacheDir string `yaml:"CacheDir" env:"DBIN_CACHEDIR"`
Limit uint `yaml:"SearchResultsLimit"`
ProgressbarStyle int `yaml:"PbarStyle,omitempty"`
DisableTruncation bool `yaml:"Truncation" env:"DBIN_NOTRUNCATION"`
RetakeOwnership bool `yaml:"RetakeOwnership" env:"DBIN_REOWN"`
UseIntegrationHooks bool `yaml:"IntegrationHooks" env:"DBIN_USEHOOKS"`
Hooks Hooks `yaml:"Hooks,omitempty"`
}
type Hooks struct {
Commands map[string]HookCommands `yaml:"commands"`
}
type HookCommands struct {
IntegrationCommands []string `yaml:"integration_commands"`
DeintegrationCommands []string `yaml:"deintegration_commands"`
IntegrationErrorMsg string `yaml:"integration_error_msg"`
DeintegrationErrorMsg string `yaml:"deintegration_error_msg"`
UseRunFromCache bool `yaml:"use_run_from_cache"`
NoOp bool `yaml:"nop"`
}
func executeHookCommand(config *Config, cmdTemplate, bEntryPath, extension string, isIntegration bool, verbosityLevel Verbosity, uRepoIndex []binaryEntry) error {
hookCommands, exists := config.Hooks.Commands[extension]
if !exists {
return fmt.Errorf("no commands found for extension: %s", extension)
}
if hookCommands.NoOp {
return nil
}
cmd := strings.ReplaceAll(cmdTemplate, "{{binary}}", bEntryPath)
commandParts := strings.Fields(cmd)
if len(commandParts) == 0 {
return nil
}
command := commandParts[0]
args := commandParts[1:]
if hookCommands.UseRunFromCache {
return runFromCache(config, stringToBinaryEntry(command), args, true, verbosityLevel, uRepoIndex)
}
cmdExec := exec.Command(command, args...)
cmdExec.Stdout = os.Stdout
cmdExec.Stderr = os.Stderr
if err := cmdExec.Run(); err != nil {
var errorMsg string
if isIntegration {
errorMsg = hookCommands.IntegrationErrorMsg
} else {
errorMsg = hookCommands.DeintegrationErrorMsg
}
return fmt.Errorf(errorMsg, bEntryPath, err)
}
return nil
}
func loadConfig() (*Config, error) {
cfg := Config{}
if noConfig, _ := strconv.ParseBool(os.Getenv("DBIN_NOCONFIG")); noConfig {
setDefaultValues(&cfg)
return &cfg, nil
}
configFilePath := os.Getenv("DBIN_CONFIG_FILE")
if configFilePath == "" {
userConfigDir, err := os.UserConfigDir()
if err != nil {
return nil, fmt.Errorf("failed to get user config directory: %v", err)
}
configFilePath = filepath.Join(userConfigDir, "dbin.yaml")
}
if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
if err := createDefaultConfig(); err != nil {
return nil, fmt.Errorf("failed to create default config file: %v", err)
}
}
if err := loadYAML(configFilePath, &cfg); err != nil {
return nil, fmt.Errorf("failed to load YAML file: %v", err)
}
overrideWithEnv(&cfg)
return &cfg, nil
}
func loadYAML(filePath string, cfg *Config) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
return yaml.NewDecoder(file).Decode(cfg)
}
func overrideWithEnv(cfg *Config) {
v := reflect.ValueOf(cfg).Elem()
t := v.Type()
setFieldFromEnv := func(field reflect.Value, envVar string) bool {
if value, exists := os.LookupEnv(envVar); exists {
switch field.Kind() {
case reflect.String:
field.SetString(value)
case reflect.Slice:
field.Set(reflect.ValueOf(strings.Split(value, ",")))
case reflect.Bool:
if val, err := strconv.ParseBool(value); err == nil {
field.SetBool(val)
}
case reflect.Int:
if val, err := strconv.Atoi(value); err == nil {
field.SetInt(int64(val))
}
}
return true
}
return false
}
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
envTags := strings.Split(t.Field(i).Tag.Get("env"), " ")
if len(envTags) > 0 && setFieldFromEnv(field, envTags[0]) {
continue
}
if field.IsZero() {
for _, envVar := range envTags[1:] {
if setFieldFromEnv(field, envVar) {
break
}
}
}
}
}
func setDefaultValues(config *Config) {
homeDir, err := os.UserHomeDir()
if err != nil {
fmt.Printf("failed to get user's Home directory: %v\n", err)
return
}
config.InstallDir = filepath.Join(homeDir, ".local/bin")
tempDir, err := os.UserCacheDir()
if err != nil {
fmt.Printf("failed to get user's Cache directory: %v\n", err)
return
}
if config.CacheDir == "" {
config.CacheDir = filepath.Join(tempDir, "dbin_cache")
}
arch := runtime.GOARCH + "_" + runtime.GOOS
config.RepoURLs = []string{
"https://github.com/xplshn/dbin-metadata/raw/refs/heads/master/misc/cmd/modMetadata/METADATA_" + arch + ".lite.cbor.zst",
}
config.DisableTruncation = false
config.Limit = 90
config.UseIntegrationHooks = true
config.RetakeOwnership = false
config.ProgressbarStyle = 1
}
func createDefaultConfig() error {
cfg := Config{}
setDefaultValues(&cfg)
cfg.Hooks = Hooks{
Commands: map[string]HookCommands{
".AppBundle": {
IntegrationCommands: []string{"pelfd --integrate {{binary}}"},
DeintegrationCommands: []string{"pelfd --deintegrate {{binary}}"},
IntegrationErrorMsg: "[%s] Could not integrate with the system via pelfd; Error: %v",
DeintegrationErrorMsg: "[%s] Could not deintegrate from the system via pelfd; Error: %v",
UseRunFromCache: true,
},
".AppImage": {
IntegrationCommands: []string{"pelfd --integrate {{binary}}"},
DeintegrationCommands: []string{"pelfd --deintegrate {{binary}}"},
IntegrationErrorMsg: "[%s] Could not integrate with the system via pelfd; Error: %v",
DeintegrationErrorMsg: "[%s] Could not deintegrate from the system via pelfd; Error: %v",
UseRunFromCache: true,
},
".NixAppImage": {
IntegrationCommands: []string{"pelfd --integrate {{binary}}"},
DeintegrationCommands: []string{"pelfd --deintegrate {{binary}}"},
IntegrationErrorMsg: "[%s] Could not integrate with the system via pelfd; Error: %v",
DeintegrationErrorMsg: "[%s] Could not deintegrate from the system via pelfd; Error: %v",
UseRunFromCache: true,
},
"": {
IntegrationCommands: []string{"upx {{binary}}"},
DeintegrationCommands: []string{""},
IntegrationErrorMsg: "[%s] Could not be UPXed; Error: %v",
UseRunFromCache: true,
NoOp: true,
},
},
}
userConfigDir, err := os.UserConfigDir()
if err != nil {
return fmt.Errorf("failed to get user config directory: %v", err)
}
configFilePath := filepath.Join(userConfigDir, "dbin.yaml")
if err := os.MkdirAll(userConfigDir, 0755); err != nil {
return fmt.Errorf("failed to create config directory: %v", err)
}
configYAML, err := yaml.Marshal(cfg)
if err != nil {
return fmt.Errorf("failed to marshal config to YAML: %v", err)
}
if err := os.WriteFile(configFilePath, configYAML, 0644); err != nil {
return fmt.Errorf("failed to write config file: %v", err)
}
fmt.Printf("Default config file created at: %s\n", configFilePath)
return nil
}