-
Notifications
You must be signed in to change notification settings - Fork 104
/
namespace_flags.go
75 lines (57 loc) · 1.58 KB
/
namespace_flags.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
package core
import (
"fmt"
"os"
"github.com/cppforlife/cobrautil"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
type NamespaceFlags struct {
Name string
}
func (s *NamespaceFlags) Set(cmd *cobra.Command, flagsFactory FlagsFactory) {
name := flagsFactory.NewNamespaceNameFlag(&s.Name)
cmd.Flags().VarP(name, "namespace", "n", "Specified namespace ($KAPP_NAMESPACE or default from kubeconfig)")
}
type NamespaceNameFlag struct {
value *string
configFactory ConfigFactory
}
var _ pflag.Value = &NamespaceNameFlag{}
var _ cobrautil.ResolvableFlag = &NamespaceNameFlag{}
func NewNamespaceNameFlag(value *string, configFactory ConfigFactory) *NamespaceNameFlag {
return &NamespaceNameFlag{value, configFactory}
}
func (s *NamespaceNameFlag) Set(val string) error {
*s.value = val
return nil
}
func (s *NamespaceNameFlag) Type() string { return "string" }
func (s *NamespaceNameFlag) String() string { return "" } // default for usage
func (s *NamespaceNameFlag) Resolve() error {
value, err := s.resolveValue()
if err != nil {
return err
}
*s.value = value
return nil
}
func (s *NamespaceNameFlag) resolveValue() (string, error) {
if s.value != nil && len(*s.value) > 0 {
return *s.value, nil
}
envVal := os.Getenv("KAPP_NAMESPACE")
if len(envVal) > 0 {
return envVal, nil
}
configVal, err := s.configFactory.DefaultNamespace()
if err != nil {
return configVal, nil
}
if len(configVal) > 0 {
return configVal, nil
}
return "", fmt.Errorf("Expected to non-empty namespace name")
}