|
| 1 | +/******************************************************************************* |
| 2 | + * Copyright © 2018-2020 VMware, Inc. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
| 5 | + * in compliance with the License. You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software distributed under the License |
| 10 | + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
| 11 | + * or implied. See the License for the specific language governing permissions and limitations under |
| 12 | + * the License. |
| 13 | + * |
| 14 | + *******************************************************************************/ |
| 15 | + |
| 16 | +package configs |
| 17 | + |
| 18 | +import ( |
| 19 | + "os" |
| 20 | + "strings" |
| 21 | + "github.com/pelletier/go-toml" |
| 22 | + "reflect" |
| 23 | + "strconv" |
| 24 | +) |
| 25 | + |
| 26 | +type environment struct { |
| 27 | + env map[string]interface{} |
| 28 | +} |
| 29 | + |
| 30 | +func NewEnvironment() *environment { |
| 31 | + osEnv := os.Environ() |
| 32 | + e := &environment{ |
| 33 | + env: make(map[string]interface{}, len(osEnv)), |
| 34 | + } |
| 35 | + for _, e1 := range osEnv { |
| 36 | + kv := strings.Split(e1, "=") |
| 37 | + if len(kv) == 2 && len(kv[0]) > 0 && len(kv[1]) > 0 { |
| 38 | + e.env[kv[0]] = kv[1] |
| 39 | + } |
| 40 | + } |
| 41 | + return e |
| 42 | +} |
| 43 | + |
| 44 | +func (e *environment) OverrideFromEnvironment(tree *toml.Tree) (*toml.Tree, error) { |
| 45 | + for k, v := range e.env { |
| 46 | + k = strings.Replace(k, "_", ".", -1) |
| 47 | + if tree.Has(k) { |
| 48 | + // global key |
| 49 | + realType := reflect.TypeOf(tree.Get(k)).Kind() |
| 50 | + switch realType { |
| 51 | + case reflect.Int64: |
| 52 | + v, err := strconv.ParseInt(v.(string), 10, 64) |
| 53 | + if err != nil { |
| 54 | + return nil, err |
| 55 | + } |
| 56 | + tree.Set(k, v) |
| 57 | + break |
| 58 | + case reflect.Int: |
| 59 | + v, err := strconv.Atoi(v.(string)) |
| 60 | + if err != nil { |
| 61 | + return nil, err |
| 62 | + } |
| 63 | + tree.Set(k, v) |
| 64 | + break |
| 65 | + default: |
| 66 | + tree.Set(k, v) |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + return tree, nil |
| 71 | +} |
0 commit comments