...

Source file src/k8s.io/kubectl/pkg/util/templates/help_flags_printer.go

Documentation: k8s.io/kubectl/pkg/util/templates

     1  /*
     2  Copyright 2022 The Kubernetes 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 templates
    18  
    19  import (
    20  	"bytes"
    21  	"fmt"
    22  	"io"
    23  	"strings"
    24  
    25  	"github.com/mitchellh/go-wordwrap"
    26  	flag "github.com/spf13/pflag"
    27  )
    28  
    29  const offset = 10
    30  
    31  // HelpFlagPrinter is a printer that
    32  // processes the help flag and print
    33  // it to i/o writer
    34  type HelpFlagPrinter struct {
    35  	wrapLimit uint
    36  	out       io.Writer
    37  }
    38  
    39  // NewHelpFlagPrinter will initialize a HelpFlagPrinter given the
    40  // i/o writer
    41  func NewHelpFlagPrinter(out io.Writer, wrapLimit uint) *HelpFlagPrinter {
    42  	return &HelpFlagPrinter{
    43  		wrapLimit: wrapLimit,
    44  		out:       out,
    45  	}
    46  }
    47  
    48  // PrintHelpFlag will beautify the help flags and print it out to p.out
    49  func (p *HelpFlagPrinter) PrintHelpFlag(flag *flag.Flag) {
    50  	formatBuf := new(bytes.Buffer)
    51  	writeFlag(formatBuf, flag)
    52  
    53  	wrappedStr := formatBuf.String()
    54  	flagAndUsage := strings.Split(formatBuf.String(), "\n")
    55  	flagStr := flagAndUsage[0]
    56  
    57  	// if the flag usage is longer than one line, wrap it again
    58  	if len(flagAndUsage) > 1 {
    59  		nextLines := strings.Join(flagAndUsage[1:], " ")
    60  		wrappedUsages := wordwrap.WrapString(nextLines, p.wrapLimit-offset)
    61  		wrappedStr = flagStr + "\n" + wrappedUsages
    62  	}
    63  	appendTabStr := strings.ReplaceAll(wrappedStr, "\n", "\n\t")
    64  
    65  	fmt.Fprintf(p.out, appendTabStr+"\n\n")
    66  }
    67  
    68  // writeFlag will output the help flag based
    69  // on the format provided by getFlagFormat to i/o writer
    70  func writeFlag(out io.Writer, f *flag.Flag) {
    71  	deprecated := ""
    72  	if f.Deprecated != "" {
    73  		deprecated = fmt.Sprintf(" (DEPRECATED: %s)", f.Deprecated)
    74  	}
    75  	fmt.Fprintf(out, getFlagFormat(f), f.Shorthand, f.Name, f.DefValue, f.Usage, deprecated)
    76  }
    77  

View as plain text