1
// Copyright Istio Authors
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
7
// http://www.apache.org/licenses/LICENSE-2.0
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
22
"github.com/spf13/cobra"
25
func checkHelpForFlag(t *testing.T, gotHelpText, flag string, wantExists bool) {
28
if strings.Contains(gotHelpText, flag) != wantExists {
30
t.Errorf("%q flag was expected but not found in help text", flag)
32
t.Errorf("%q flag was found in help text but not expected", flag)
37
func TestHideInheritedFlags(t *testing.T) {
39
parentFlag0 = "parent-flag0"
40
parentFlag1 = "parent-flag1"
41
parentFlag2 = "parent-flag2"
42
childFlag2 = "child-flag2"
44
parent := &cobra.Command{Use: "parent"}
45
_ = parent.PersistentFlags().String(parentFlag0, "", parentFlag0)
46
_ = parent.PersistentFlags().String(parentFlag1, "", parentFlag1)
47
_ = parent.PersistentFlags().String(parentFlag2, "", parentFlag2)
52
child := &cobra.Command{
54
Run: func(c *cobra.Command, args []string) {},
56
_ = parent.PersistentFlags().String(childFlag2, "", childFlag2)
57
parent.AddCommand(child)
59
// verify both parent flags and the child flag are visible by default
60
parent.SetArgs([]string{"child", "--help"})
61
if err := parent.Execute(); err != nil {
66
checkHelpForFlag(t, got, parentFlag0, true)
67
checkHelpForFlag(t, got, parentFlag1, true)
68
checkHelpForFlag(t, got, parentFlag2, true)
69
checkHelpForFlag(t, got, childFlag2, true)
71
// verify the hidden parent flag is not visible in help text
72
hideInheritedFlags(child, parentFlag1, parentFlag2)
73
if err := parent.Execute(); err != nil {
78
checkHelpForFlag(t, got, parentFlag0, true)
79
checkHelpForFlag(t, got, parentFlag1, false)
80
checkHelpForFlag(t, got, parentFlag1, false)
81
checkHelpForFlag(t, got, childFlag2, true)