parser.go raw

   1  package tri
   2  
   3  import (
   4  	"time"
   5  )
   6  
   7  // LoadAllDefaults walks a Tri and calls LoadDefaults on each one for the first step in composition of configuration
   8  func LoadAllDefaults(t *Tri) {
   9  	T := *t
  10  	var counter, varsfound int
  11  	for _, x := range T {
  12  		if v, ok := x.(Var); ok {
  13  			varsfound++
  14  			if LoadDefaults(&v) {
  15  				counter++
  16  			}
  17  		}
  18  		if v, ok := x.(Commands); ok {
  19  			for _, x := range v {
  20  				for _, y := range x {
  21  					if v, ok := y.(Var); ok {
  22  						varsfound++
  23  						if LoadDefaults(&v) {
  24  							counter++
  25  						}
  26  					}
  27  				}
  28  			}
  29  		}
  30  	}
  31  }
  32  
  33  // LoadDefaults reads the Default (if any) in a Var, and copies the value into the Slot, returns true if there was a Default and it was filled
  34  func LoadDefaults(v *Var) (found bool) {
  35  	// First find if there is a default
  36  	var def Default
  37  	V := *v
  38  	for _, x := range V {
  39  		if j, ok := x.(Default); ok {
  40  			def = j
  41  			found = true
  42  		}
  43  	}
  44  	if !found {
  45  		return false
  46  	}
  47  	found = false
  48  	var slot Slot
  49  	for _, x := range V {
  50  		if j, ok := x.(Slot); ok {
  51  			slot = j
  52  			found = true
  53  		}
  54  	}
  55  	if !found {
  56  		return false
  57  	}
  58  	for _, x := range slot {
  59  		switch S := x.(type) {
  60  		case *string:
  61  			s := def[0].(string)
  62  			*S = s
  63  		case *int:
  64  			s := def[0].(int)
  65  			*S = s
  66  		case *uint32:
  67  			s := def[0].(uint32)
  68  			*S = s
  69  		case *float64:
  70  			s := def[0].(float64)
  71  			*S = s
  72  		case *[]string:
  73  			s := def[0].([]string)
  74  			*S = s
  75  		case *time.Duration:
  76  			s := def[0].(time.Duration)
  77  			*S = s
  78  		default:
  79  			panic("unrecognised type found in slot")
  80  		}
  81  	}
  82  	return true
  83  }
  84