mirror of
https://github.com/spf13/cobra
synced 2025-05-03 11:57:21 +00:00
Generated Documentation
This commit is contained in:
parent
db21c59299
commit
dc9a1310c2
3 changed files with 103 additions and 14 deletions
|
@ -20,6 +20,8 @@ import (
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// TestBashCompletionV2WithActiveHelp tests the generation of bash completion V2 with active help enabled.
|
||||||
|
// It creates a command, generates bash completion, and asserts that active help is not being disabled.
|
||||||
func TestBashCompletionV2WithActiveHelp(t *testing.T) {
|
func TestBashCompletionV2WithActiveHelp(t *testing.T) {
|
||||||
c := &Command{Use: "c", Run: emptyRun}
|
c := &Command{Use: "c", Run: emptyRun}
|
||||||
|
|
||||||
|
|
|
@ -24,18 +24,31 @@ import (
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// checkOmit checks if the 'unexpected' substring is present in 'found'.
|
||||||
|
// If it is, it logs an error using t.Errorf indicating that the 'unexpected'
|
||||||
|
// value was found. This function is typically used in tests to ensure that
|
||||||
|
// certain substrings are omitted from a string being tested.
|
||||||
|
//
|
||||||
|
// Parameters:
|
||||||
|
// - t: A testing.T instance for reporting errors.
|
||||||
|
// - found: The string to search within.
|
||||||
|
// - unexpected: The substring that should not be present in 'found'.
|
||||||
func checkOmit(t *testing.T, found, unexpected string) {
|
func checkOmit(t *testing.T, found, unexpected string) {
|
||||||
if strings.Contains(found, unexpected) {
|
if strings.Contains(found, unexpected) {
|
||||||
t.Errorf("Got: %q\nBut should not have!\n", unexpected)
|
t.Errorf("Got: %q\nBut should not have!\n", unexpected)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// check asserts that the `found` string contains the `expected` substring.
|
||||||
|
// If not, it logs an error with the expected and actual values.
|
||||||
|
// This function is typically used in testing to validate substrings within larger strings.
|
||||||
func check(t *testing.T, found, expected string) {
|
func check(t *testing.T, found, expected string) {
|
||||||
if !strings.Contains(found, expected) {
|
if !strings.Contains(found, expected) {
|
||||||
t.Errorf("Expecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
t.Errorf("Expecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// checkNumOccurrences checks if the string `found` contains the substring `expected` exactly `expectedOccurrences` times. If not, it fails the test with an error message indicating the expected and actual occurrences.
|
||||||
func checkNumOccurrences(t *testing.T, found, expected string, expectedOccurrences int) {
|
func checkNumOccurrences(t *testing.T, found, expected string, expectedOccurrences int) {
|
||||||
numOccurrences := strings.Count(found, expected)
|
numOccurrences := strings.Count(found, expected)
|
||||||
if numOccurrences != expectedOccurrences {
|
if numOccurrences != expectedOccurrences {
|
||||||
|
@ -43,6 +56,9 @@ func checkNumOccurrences(t *testing.T, found, expected string, expectedOccurrenc
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// checkRegex checks if the `found` string matches the `pattern` using regular expressions.
|
||||||
|
// If an error occurs during the matching process, it logs the error and fails the test.
|
||||||
|
// It asserts that the `found` string should match the `pattern`, otherwise failing the test with a detailed message.
|
||||||
func checkRegex(t *testing.T, found, pattern string) {
|
func checkRegex(t *testing.T, found, pattern string) {
|
||||||
matched, err := regexp.MatchString(pattern, found)
|
matched, err := regexp.MatchString(pattern, found)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -53,6 +69,10 @@ func checkRegex(t *testing.T, found, pattern string) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// runShellCheck runs shellcheck on the provided string with specific options and error codes.
|
||||||
|
// It executes shellcheck with the bash syntax, sending the input from the string through stdin.
|
||||||
|
// The function redirects the standard output and error of the command to os.Stdout and os.Stderr respectively.
|
||||||
|
// Returns an error if the execution of shellcheck fails or if there's an issue with setting up the command input.
|
||||||
func runShellCheck(s string) error {
|
func runShellCheck(s string) error {
|
||||||
cmd := exec.Command("shellcheck", "-s", "bash", "-", "-e",
|
cmd := exec.Command("shellcheck", "-s", "bash", "-", "-e",
|
||||||
"SC2034", // PREFIX appears unused. Verify it or export it.
|
"SC2034", // PREFIX appears unused. Verify it or export it.
|
||||||
|
@ -80,6 +100,7 @@ const bashCompletionFunc = `__root_custom_func() {
|
||||||
}
|
}
|
||||||
`
|
`
|
||||||
|
|
||||||
|
// TestBashCompletions tests the generation of bash completion functions for a root command.
|
||||||
func TestBashCompletions(t *testing.T) {
|
func TestBashCompletions(t *testing.T) {
|
||||||
rootCmd := &Command{
|
rootCmd := &Command{
|
||||||
Use: "root",
|
Use: "root",
|
||||||
|
@ -226,6 +247,9 @@ func TestBashCompletions(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestBashCompletionHiddenFlag tests that a hidden flag is not included in the Bash completion output.
|
||||||
|
// It creates a command with a hidden flag and asserts that after generating the Bash completion script,
|
||||||
|
// the hidden flag is not present in the output.
|
||||||
func TestBashCompletionHiddenFlag(t *testing.T) {
|
func TestBashCompletionHiddenFlag(t *testing.T) {
|
||||||
c := &Command{Use: "c", Run: emptyRun}
|
c := &Command{Use: "c", Run: emptyRun}
|
||||||
|
|
||||||
|
@ -242,6 +266,9 @@ func TestBashCompletionHiddenFlag(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestBashCompletionDeprecatedFlag tests the generation of bash completion script for a command with a deprecated flag.
|
||||||
|
// It ensures that the deprecated flag is not included in the generated completion script.
|
||||||
|
// The function takes a testing.T pointer as an argument to perform assertions and checks.
|
||||||
func TestBashCompletionDeprecatedFlag(t *testing.T) {
|
func TestBashCompletionDeprecatedFlag(t *testing.T) {
|
||||||
c := &Command{Use: "c", Run: emptyRun}
|
c := &Command{Use: "c", Run: emptyRun}
|
||||||
|
|
||||||
|
@ -258,6 +285,8 @@ func TestBashCompletionDeprecatedFlag(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestBashCompletionTraverseChildren tests the bash completion generation for commands with TraverseChildren set to true.
|
||||||
|
// It checks that local non-persistent flags are not included in the generated completion script.
|
||||||
func TestBashCompletionTraverseChildren(t *testing.T) {
|
func TestBashCompletionTraverseChildren(t *testing.T) {
|
||||||
c := &Command{Use: "c", Run: emptyRun, TraverseChildren: true}
|
c := &Command{Use: "c", Run: emptyRun, TraverseChildren: true}
|
||||||
|
|
||||||
|
@ -276,6 +305,13 @@ func TestBashCompletionTraverseChildren(t *testing.T) {
|
||||||
checkOmit(t, output, `local_nonpersistent_flags+=("-b")`)
|
checkOmit(t, output, `local_nonpersistent_flags+=("-b")`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestBashCompletionNoActiveHelp tests the generation of bash completion without active help.
|
||||||
|
//
|
||||||
|
// Parameters:
|
||||||
|
// - t: A testing.T instance for assertions and logging test failures.
|
||||||
|
//
|
||||||
|
// This function creates a Command instance, generates bash completion with disabled active help,
|
||||||
|
// and checks if the output contains the correct environment variable setting to disable active help.
|
||||||
func TestBashCompletionNoActiveHelp(t *testing.T) {
|
func TestBashCompletionNoActiveHelp(t *testing.T) {
|
||||||
c := &Command{Use: "c", Run: emptyRun}
|
c := &Command{Use: "c", Run: emptyRun}
|
||||||
|
|
||||||
|
|
79
cobra.go
79
cobra.go
|
@ -80,37 +80,48 @@ You need to open cmd.exe and run it from there.
|
||||||
// Works only on Microsoft Windows.
|
// Works only on Microsoft Windows.
|
||||||
var MousetrapDisplayDuration = 5 * time.Second
|
var MousetrapDisplayDuration = 5 * time.Second
|
||||||
|
|
||||||
// AddTemplateFunc adds a template function that's available to Usage and Help
|
// AddTemplateFunc registers a new template function with the given name, making it available for use in the Usage and Help templates.
|
||||||
// template generation.
|
|
||||||
func AddTemplateFunc(name string, tmplFunc interface{}) {
|
func AddTemplateFunc(name string, tmplFunc interface{}) {
|
||||||
templateFuncs[name] = tmplFunc
|
templateFuncs[name] = tmplFunc
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddTemplateFuncs adds multiple template functions that are available to Usage and
|
// AddTemplateFuncs adds multiple template functions that are available to Usage and
|
||||||
// Help template generation.
|
// Help template generation. It takes a map of template function names to their implementations
|
||||||
|
// and merges them into the global template function map, allowing these functions to be used
|
||||||
|
// in usage and help text templates.
|
||||||
func AddTemplateFuncs(tmplFuncs template.FuncMap) {
|
func AddTemplateFuncs(tmplFuncs template.FuncMap) {
|
||||||
for k, v := range tmplFuncs {
|
for k, v := range tmplFuncs {
|
||||||
templateFuncs[k] = v
|
templateFuncs[k] = v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// OnInitialize sets the passed functions to be run when each command's
|
// OnInitialize registers functions that will be executed whenever a command's
|
||||||
// Execute method is called.
|
// Execute method is invoked. These functions are typically used for setup or initialization tasks.
|
||||||
func OnInitialize(y ...func()) {
|
func OnInitialize(y ...func()) {
|
||||||
initializers = append(initializers, y...)
|
initializers = append(initializers, y...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// OnFinalize sets the passed functions to be run when each command's
|
// OnFinalize sets the provided functions to be executed when each command's
|
||||||
// Execute method is terminated.
|
// Execute method is completed. The functions are called in the order they are provided.
|
||||||
func OnFinalize(y ...func()) {
|
func OnFinalize(y ...func()) {
|
||||||
finalizers = append(finalizers, y...)
|
finalizers = append(finalizers, y...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
||||||
|
|
||||||
// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
// Gt compares two types and returns true if the first type is greater than the second. For arrays, channels,
|
||||||
// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
|
// maps, and slices, it compares their lengths. Ints are compared directly, while strings are first converted to ints
|
||||||
// ints and then compared.
|
// before comparison. If either conversion fails (e.g., string is not a valid integer), Gt will return false.
|
||||||
|
//
|
||||||
|
// Parameters:
|
||||||
|
// a - the first value to compare.
|
||||||
|
// b - the second value to compare.
|
||||||
|
//
|
||||||
|
// Returns:
|
||||||
|
// true if a is greater than b, false otherwise.
|
||||||
|
//
|
||||||
|
// Errors:
|
||||||
|
// None. The function handles invalid string conversions internally and returns false in such cases.
|
||||||
func Gt(a interface{}, b interface{}) bool {
|
func Gt(a interface{}, b interface{}) bool {
|
||||||
var left, right int64
|
var left, right int64
|
||||||
av := reflect.ValueOf(a)
|
av := reflect.ValueOf(a)
|
||||||
|
@ -141,6 +152,13 @@ func Gt(a interface{}, b interface{}) bool {
|
||||||
// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
||||||
|
|
||||||
// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
|
// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
|
||||||
|
// Parameters:
|
||||||
|
// a - the first value to compare
|
||||||
|
// b - the second value to compare
|
||||||
|
// Returns:
|
||||||
|
// true if a and b are equal, false otherwise
|
||||||
|
// Panics:
|
||||||
|
// if a or b is of an unsupported type (array, chan, map, slice)
|
||||||
func Eq(a interface{}, b interface{}) bool {
|
func Eq(a interface{}, b interface{}) bool {
|
||||||
av := reflect.ValueOf(a)
|
av := reflect.ValueOf(a)
|
||||||
bv := reflect.ValueOf(b)
|
bv := reflect.ValueOf(b)
|
||||||
|
@ -156,13 +174,21 @@ func Eq(a interface{}, b interface{}) bool {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TrimRightSpace returns a copy of the input string with trailing white space removed.
|
||||||
func trimRightSpace(s string) string {
|
func trimRightSpace(s string) string {
|
||||||
return strings.TrimRightFunc(s, unicode.IsSpace)
|
return strings.TrimRightFunc(s, unicode.IsSpace)
|
||||||
}
|
}
|
||||||
|
|
||||||
// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
||||||
|
|
||||||
// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.
|
// AppendIfNotPresent appends a string to the end of the slice if it's not already present.
|
||||||
|
//
|
||||||
|
// Parameters:
|
||||||
|
// - s: The slice to append to.
|
||||||
|
// - stringToAppend: The string to be appended.
|
||||||
|
//
|
||||||
|
// Returns:
|
||||||
|
// The updated slice with the string appended, or the original slice unchanged if the string was already present.
|
||||||
func appendIfNotPresent(s, stringToAppend string) string {
|
func appendIfNotPresent(s, stringToAppend string) string {
|
||||||
if strings.Contains(s, stringToAppend) {
|
if strings.Contains(s, stringToAppend) {
|
||||||
return s
|
return s
|
||||||
|
@ -171,11 +197,19 @@ func appendIfNotPresent(s, stringToAppend string) string {
|
||||||
}
|
}
|
||||||
|
|
||||||
// rpad adds padding to the right of a string.
|
// rpad adds padding to the right of a string.
|
||||||
|
//
|
||||||
|
// Parameters:
|
||||||
|
// - s: The input string to pad.
|
||||||
|
// - padding: The number of spaces to add as padding on the right.
|
||||||
|
//
|
||||||
|
// Returns:
|
||||||
|
// - The formatted string with right-padding applied.
|
||||||
func rpad(s string, padding int) string {
|
func rpad(s string, padding int) string {
|
||||||
formattedString := fmt.Sprintf("%%-%ds", padding)
|
formattedString := fmt.Sprintf("%%-%ds", padding)
|
||||||
return fmt.Sprintf(formattedString, s)
|
return fmt.Sprintf(formattedString, s)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// tmpl returns a new tmplFunc instance with the provided text.
|
||||||
func tmpl(text string) *tmplFunc {
|
func tmpl(text string) *tmplFunc {
|
||||||
return &tmplFunc{
|
return &tmplFunc{
|
||||||
tmpl: text,
|
tmpl: text,
|
||||||
|
@ -188,7 +222,14 @@ func tmpl(text string) *tmplFunc {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ld compares two strings and returns the levenshtein distance between them.
|
// ld calculates the Levenshtein distance between two strings, optionally ignoring case.
|
||||||
|
// It returns the minimum number of single-character edits required to change one word into the other.
|
||||||
|
// Parameters:
|
||||||
|
// s - the first string
|
||||||
|
// t - the second string
|
||||||
|
// ignoreCase - if true, the comparison is case-insensitive
|
||||||
|
// Returns:
|
||||||
|
// The Levenshtein distance between the two strings.
|
||||||
func ld(s, t string, ignoreCase bool) int {
|
func ld(s, t string, ignoreCase bool) int {
|
||||||
if ignoreCase {
|
if ignoreCase {
|
||||||
s = strings.ToLower(s)
|
s = strings.ToLower(s)
|
||||||
|
@ -222,6 +263,14 @@ func ld(s, t string, ignoreCase bool) int {
|
||||||
return d[len(s)][len(t)]
|
return d[len(s)][len(t)]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// stringInSlice checks if a string is present in the given slice of strings.
|
||||||
|
//
|
||||||
|
// Parameters:
|
||||||
|
// - a: The string to search for.
|
||||||
|
// - list: The slice of strings to search within.
|
||||||
|
//
|
||||||
|
// Returns:
|
||||||
|
// - true if the string is found in the slice, false otherwise.
|
||||||
func stringInSlice(a string, list []string) bool {
|
func stringInSlice(a string, list []string) bool {
|
||||||
for _, b := range list {
|
for _, b := range list {
|
||||||
if b == a {
|
if b == a {
|
||||||
|
@ -231,7 +280,7 @@ func stringInSlice(a string, list []string) bool {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing.
|
// CheckErr prints the provided message with the prefix 'Error:' and exits with an error code of 1. If the message is `nil`, it does nothing.
|
||||||
func CheckErr(msg interface{}) {
|
func CheckErr(msg interface{}) {
|
||||||
if msg != nil {
|
if msg != nil {
|
||||||
fmt.Fprintln(os.Stderr, "Error:", msg)
|
fmt.Fprintln(os.Stderr, "Error:", msg)
|
||||||
|
@ -239,7 +288,9 @@ func CheckErr(msg interface{}) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil.
|
// WriteStringAndCheck writes a string into a buffer and checks if the error is not nil.
|
||||||
|
// It takes an io.StringWriter `b` and a string `s`, writes the string to the writer,
|
||||||
|
// and calls CheckErr with the resulting error, handling any errors that occur during the write operation.
|
||||||
func WriteStringAndCheck(b io.StringWriter, s string) {
|
func WriteStringAndCheck(b io.StringWriter, s string) {
|
||||||
_, err := b.WriteString(s)
|
_, err := b.WriteString(s)
|
||||||
CheckErr(err)
|
CheckErr(err)
|
||||||
|
|
Loading…
Add table
Reference in a new issue