crossplane

Форк
0
82 строки · 2.1 Кб
1
/*
2
Copyright 2023 The Crossplane Authors.
3

4
Licensed under the Apache License, Version 2.0 (the "License");
5
you may not use this file except in compliance with the License.
6
You may obtain a copy of the License at
7

8
    http://www.apache.org/licenses/LICENSE-2.0
9

10
Unless required by applicable law or agreed to in writing, software
11
distributed under the License is distributed on an "AS IS" BASIS,
12
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
See the License for the specific language governing permissions and
14
limitations under the License.
15
*/
16

17
package upbound
18

19
import (
20
	"encoding/json"
21
	"io"
22
	"strings"
23

24
	"github.com/alecthomas/kong"
25
)
26

27
// JSON returns a Resolver that retrieves values from a JSON source.
28
// Based slightly off of https://github.com/alecthomas/kong/blob/f48da244f54370c0cb63e22b0e500e5459a491bf/resolver.go#L33-L60
29
// Hyphens in flag names are replaced with underscores.
30
func JSON(base, overlay io.Reader) (kong.Resolver, error) {
31
	baseValues := map[string]interface{}{}
32
	overlayValues := map[string]interface{}{}
33
	err := json.NewDecoder(base).Decode(&baseValues)
34
	if err != nil {
35
		return nil, err
36
	}
37
	err = json.NewDecoder(overlay).Decode(&overlayValues)
38
	if err != nil {
39
		return nil, err
40
	}
41

42
	var f kong.ResolverFunc = func(_ *kong.Context, _ *kong.Path, flag *kong.Flag) (interface{}, error) {
43
		name := strings.ReplaceAll(flag.Name, "-", "_")
44
		bRaw, bOk := resolveValue(name, flag.Envs, baseValues)
45
		oRaw, oOk := resolveValue(name, flag.Envs, overlayValues)
46

47
		// if found in base and in overlay AND is not the defaultValue for overlay
48
		if bOk && oOk && flag.Default != oRaw {
49
			return oRaw, nil
50
		}
51

52
		if bOk {
53
			return bRaw, nil
54
		}
55

56
		if oOk {
57
			return oRaw, nil
58
		}
59

60
		return nil, nil
61
	}
62

63
	return f, nil
64
}
65

66
func resolveValue(fieldName string, envVarsName []string, vals map[string]interface{}) (interface{}, bool) {
67
	// attempt to lookup by field name first
68
	raw, ok := vals[fieldName]
69
	if !ok {
70
		// fall back to env var name
71
		for _, envVarName := range envVarsName {
72
			raw, ok = vals[envVarName]
73
			if ok {
74
				break
75
			}
76
		}
77
		if !ok {
78
			return nil, false
79
		}
80
	}
81
	return raw, true
82
}
83

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.