101 lines
2.3 KiB
Go
101 lines
2.3 KiB
Go
package envconf
|
|
|
|
import (
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func parseInt(key string, str string, _ int) (ret cValue) {
|
|
val, err := strconv.ParseInt(str, 10, 64)
|
|
if err == nil {
|
|
ret.intval = val
|
|
} else {
|
|
ret.err = errors.New(fmt.Sprintf(`Environment variable "%s" is not of type int.`, key))
|
|
}
|
|
return
|
|
}
|
|
|
|
func parseMetric(key string, str string, _ int) (ret cValue) {
|
|
mod := int64(1)
|
|
str = strings.ToUpper(str)
|
|
if strings.HasSuffix(str, "K") {
|
|
mod = 1024
|
|
str = strings.TrimSuffix(str, "K")
|
|
} else if strings.HasSuffix(str, "M") {
|
|
mod = 1024 * 1024
|
|
str = strings.TrimSuffix(str, "M")
|
|
} else if strings.HasSuffix(str, "G") {
|
|
mod = 1024 * 1024 * 1024
|
|
str = strings.TrimSuffix(str, "G")
|
|
} else if strings.HasSuffix(str, "T") {
|
|
mod = 1024 * 1024 * 1024 * 1024
|
|
str = strings.TrimSuffix(str, "T")
|
|
}
|
|
val, err := strconv.ParseInt(str, 10, 64)
|
|
if err == nil {
|
|
ret.intval = mod * val
|
|
} else {
|
|
ret.err = errors.New(fmt.Sprintf(`Environment variable "%s" is not of type int.`, key))
|
|
}
|
|
return
|
|
}
|
|
|
|
func parseDuration(key string, str string, _ int) (ret cValue) {
|
|
val, err := time.ParseDuration(str)
|
|
if err == nil {
|
|
ret.durval = val
|
|
} else {
|
|
ret.err = errors.New(fmt.Sprintf(`Environment variable "%s" is not of type duration.`, key))
|
|
}
|
|
return
|
|
}
|
|
|
|
func parseBool(key string, str string, _ int) (ret cValue) {
|
|
val, err := strconv.ParseBool(str)
|
|
if err == nil {
|
|
ret.boolval = val
|
|
} else {
|
|
ret.err = errors.New(fmt.Sprintf(`Environment variable "%s" is not of type bool.`, key))
|
|
}
|
|
return
|
|
}
|
|
|
|
func parseHex(key string, str string, size int) (ret cValue) {
|
|
val, err := hex.DecodeString(str)
|
|
if err == nil && (size == 0 || size == len(val)) {
|
|
ret.binval = val
|
|
} else {
|
|
if size == 0 {
|
|
ret.err = errors.New(fmt.Sprintf(`Environment variable "%s" is not of type hex.`, key))
|
|
} else {
|
|
ret.err = errors.New(fmt.Sprintf(`Environment variable "%s" is not of type hex%d.`, key, size))
|
|
}
|
|
}
|
|
return
|
|
}
|
|
|
|
func parseDirectory(_ string, str string, _ int) (ret cValue) {
|
|
wd, err := os.Getwd()
|
|
if err == nil {
|
|
if path.IsAbs(str) {
|
|
ret.strval = path.Clean(str)
|
|
} else {
|
|
ret.strval = path.Join(wd, str)
|
|
}
|
|
} else {
|
|
ret.strval = path.Clean(str)
|
|
}
|
|
return
|
|
}
|
|
|
|
func parseString(_ string, str string, _ int) (ret cValue) {
|
|
ret.strval = str
|
|
return
|
|
}
|