github.com/aristanetworks/goarista@v0.0.0-20240514173732-cca2755bbd44/flag/helpers.go (about)

     1  // Copyright (c) 2019 Arista Networks, Inc.
     2  // Use of this source code is governed by the Apache License 2.0
     3  // that can be found in the COPYING file.
     4  
     5  package flag
     6  
     7  import (
     8  	"flag"
     9  	"fmt"
    10  	"io"
    11  	"sort"
    12  	"strings"
    13  )
    14  
    15  // FormatOptions writes a mapping of options to usage information
    16  // that looks like standard Go help information. The header should
    17  // end with a colon if options are provided.
    18  func FormatOptions(w io.Writer, header string, usageMap map[string]string) {
    19  	ops := []string{}
    20  	for k := range usageMap {
    21  		ops = append(ops, k)
    22  	}
    23  	sort.Strings(ops)
    24  	fmt.Fprintf(w, "%v\n", header)
    25  	for _, o := range ops {
    26  		fmt.Fprintf(w, "  %v\n\t%v\n", o, usageMap[o])
    27  	}
    28  }
    29  
    30  // AddHelp adds indented documentation to flag.Usage.
    31  func AddHelp(seperator, help string) {
    32  	result := []string{}
    33  	s := strings.Split(help, "\n")
    34  	for _, line := range s {
    35  		result = append(result, "  "+line)
    36  	}
    37  	old := flag.Usage
    38  	flag.Usage = func() {
    39  		old()
    40  		fmt.Println(seperator)
    41  		fmt.Print(strings.TrimRight(strings.Join(result, "\n"), " "))
    42  	}
    43  }