Trims whitespace from command arguments in RootCmd (#24218)

- Prevents commands from receiving potential whitespace characters
- Adds a new root test case ensuring various whitespace characters are removed

Co-authored-by: Nathan Geist <ngeist@spiria.com>
This commit is contained in:
Nathan 2023-08-17 02:19:09 -06:00 committed by GitHub
parent 7b164d4f82
commit 44f3482fee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 51 additions and 0 deletions

View File

@ -73,6 +73,9 @@ var RootCmd = &cobra.Command{
Long: `Mattermost offers workplace messaging across web, PC and phones with archiving, search and integration with your existing systems. Documentation available at https://docs.mattermost.com`,
DisableAutoGenTag: true,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
for i, arg := range args {
args[i] = strings.TrimSpace(arg)
}
format := viper.GetString("format")
if viper.GetBool("disable-pager") {
printer.OverrideEnablePager(false)

View File

@ -0,0 +1,48 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package commands
import (
"bytes"
"fmt"
"strings"
"github.com/spf13/cobra"
)
func executeRawCommand(root *cobra.Command, args string) (c *cobra.Command, output string, err error) {
actual := new(bytes.Buffer)
RootCmd.SetOut(actual)
RootCmd.SetErr(actual)
RootCmd.SetArgs(strings.Split(args, " "))
c, err = RootCmd.ExecuteC()
return c, actual.String(), err
}
func (s *MmctlUnitTestSuite) TestArgumentsHaveWhitespaceTrimmed() {
arguments := []string{"value_1", "value_2"}
lineEndings := []string{"\n", "\r", "\r\n"}
prettyNames := []string{"-n", "-r", "-r-n"}
commandCalled := false
for i, lineEnding := range lineEndings {
testName := fmt.Sprintf("Commands have their arguments stripped of whitespace[%s]", prettyNames[i])
s.Run(testName, func() {
commandCalled = false
commandFunction := func(command *cobra.Command, args []string) {
commandCalled = true
s.Equal(arguments, args, "Expected arguments to have their whitespace trimmed")
}
mockCommand := &cobra.Command{Use: "test", Run: commandFunction}
commandString := strings.Join([]string{"test", " ", arguments[0], lineEnding, " ", arguments[1], lineEnding}, "")
RootCmd.AddCommand(mockCommand)
executeRawCommand(RootCmd, commandString)
s.Require().True(commandCalled, "Expected mock command to be called")
})
}
}