github.com/abayer/test-infra@v0.0.5/mungegithub/mungers/matchers/comment/command.go (about)

     1  /*
     2  Copyright 2016 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 comment
    18  
    19  import (
    20  	"regexp"
    21  	"strings"
    22  )
    23  
    24  // Command is a way for human to interact with the bot
    25  type Command struct {
    26  	Name      string
    27  	Arguments string
    28  }
    29  
    30  var (
    31  	// Matches a command:
    32  	// - Line that starts with slash
    33  	// - followed by non-space characteres,
    34  	// - (optional) followed by space and arguments
    35  	commandRegex = regexp.MustCompile(`(?m)^/([^\s]+)[\t ]*([^\n\r]*)`)
    36  )
    37  
    38  // ParseCommands attempts to read a command from a comment
    39  // Returns nil if the comment doesn't contain a command
    40  func ParseCommands(comment *Comment) []*Command {
    41  	if comment == nil || comment.Body == nil {
    42  		return nil
    43  	}
    44  
    45  	commands := []*Command{}
    46  	matches := commandRegex.FindAllStringSubmatch(*comment.Body, -1)
    47  	for _, match := range matches {
    48  		commands = append(commands, &Command{
    49  			Name:      strings.ToUpper(match[1]),
    50  			Arguments: strings.TrimSpace(match[2]),
    51  		})
    52  	}
    53  
    54  	return commands
    55  }
    56  
    57  // String displays the command
    58  func (n *Command) String() string {
    59  	str := "/" + strings.ToUpper(n.Name)
    60  	args := strings.TrimSpace(n.Arguments)
    61  	if args != "" {
    62  		str += " " + args
    63  	}
    64  	return str
    65  }