️ Do not save config changes to disk immediately

This commit is contained in:
2024-12-16 21:29:51 +01:00
parent 35681102b4
commit 5122791f85
3 changed files with 64 additions and 13 deletions

View File

@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"os"
"sync"
"github.com/pelletier/go-toml/v2"
)
@ -27,6 +28,11 @@ type Config struct {
var config Config
var shouldSaveConfigsMutex = new(sync.Mutex)
var shouldSaveConfigs = map[string]bool{
"ports": false,
}
// Copy default config if `{name}.toml` file does not exist
func createDefaultConfig(name string) {
dest_path := fmt.Sprintf("%s/%s.toml", CONFIG_DIR, name)
@ -59,6 +65,13 @@ func loadConfig(name string, dest interface{}) {
}
}
// Mark a config file as changed, so it gets saved to disk later
func markConfig(name string) {
shouldSaveConfigsMutex.Lock()
shouldSaveConfigs[name] = true
shouldSaveConfigsMutex.Unlock()
}
// Save struct as a `.toml` file
func saveConfig(name string, dest interface{}) {
bin, err := toml.Marshal(dest)
@ -70,3 +83,12 @@ func saveConfig(name string, dest interface{}) {
fmt.Println(err)
}
}
func saveConfigIfMarked(name string, dest interface{}) {
shouldSaveConfigsMutex.Lock()
if shouldSaveConfigs[name] {
shouldSaveConfigs[name] = false
saveConfig(name, dest)
}
shouldSaveConfigsMutex.Unlock()
}