Skip to content
Snippets Groups Projects
Select Git revision
  • 8eaa7114d7e477af3cf6dcb8d90f30bce51e1a4a
  • master default protected
  • 1.31
  • 4.38.7
  • 4.38.6
  • 4.38.5
  • 4.38.4
  • 4.38.3
  • 4.38.2
  • 4.38.1
  • 4.38.0
  • 4.37.2
  • 4.37.1
  • 4.37.0
  • 4.36.0
  • 4.35.0
  • 4.34.1
  • 4.34.0
  • 4.33.1
  • 4.33.0
  • 4.32.2
  • 4.32.1
  • 4.32.0
23 results

monster.mjs

Blame
  • settings.go 1.46 KiB
    // Copyright 2022 schukai GmbH
    // SPDX-License-Identifier: AGPL-3.0
    
    package configuration
    
    import (
    	"github.com/fsnotify/fsnotify"
    	"reflect"
    	"strconv"
    	"sync"
    )
    
    type fileWatch struct {
    	sync.Mutex
    	watcher     *fsnotify.Watcher
    	watchList   map[string]bool
    	cancelWatch chan bool
    	onWatch     bool
    }
    
    // Settings is the main struct for the configuration
    type Settings[C any] struct {
    	files  fileBackend
    	stream streamBackend
    	config C
    	errors []error
    	sync.Mutex
    	mnemonic      string
    	importCounter int
    	hooks         struct {
    		change []ChangeHook
    		error  []ErrorHook
    	}
    
    	fileWatch fileWatch
    }
    
    func (s *Settings[C]) initDefaults() *Settings[C] {
    
    	errorCount := len(s.errors)
    	defer func() {
    		if len(s.errors) > errorCount {
    			s.notifyErrorHooks()
    		}
    	}()
    
    	err := runOnTags(&s.config, []string{"default"}, func(v string, field reflect.Value) {
    
    		if field.CanSet() {
    			switch field.Kind() {
    			case reflect.String:
    				field.SetString(v)
    			case reflect.Int:
    				intVar, err := strconv.Atoi(v)
    				if err != nil {
    					s.errors = append(s.errors, err)
    					return
    				}
    				field.SetInt(int64(intVar))
    			case reflect.Bool:
    				field.SetBool(v == "true")
    			default:
    				s.errors = append(s.errors, newUnsupportedTypeError(field.Type()))
    			}
    
    		}
    	})
    
    	if err != nil {
    		s.errors = append(s.errors, err)
    	}
    
    	return s
    }
    
    func validateConfig[C any](config C) error {
    	t := reflect.TypeOf(config)
    	if t.Kind() != reflect.Struct {
    		return newUnsupportedTypeError(t)
    	}
    	return nil
    }