github.com/abayer/test-infra@v0.0.5/mungegithub/mungers/matchers/notification.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 matchers
    18  
    19  import (
    20  	"regexp"
    21  	"strings"
    22  
    23  	"github.com/google/go-github/github"
    24  	mgh "k8s.io/test-infra/mungegithub/github"
    25  )
    26  
    27  // Notification is a message sent by the bot. Easy to find and create.
    28  type Notification struct {
    29  	Name      string
    30  	Arguments string
    31  	Context   string
    32  }
    33  
    34  var (
    35  	// Matches a notification: [NOTIFNAME] Arguments
    36  	notificationRegex = regexp.MustCompile(`^\[([^\]\s]+)\] *?([^\n]*)`)
    37  )
    38  
    39  // ParseNotification attempts to read a notification from a comment
    40  // Returns nil if the comment doesn't contain a notification
    41  // Also note that Context is not parsed from the notification
    42  func ParseNotification(comment *github.IssueComment) *Notification {
    43  	if comment == nil || comment.Body == nil {
    44  		return nil
    45  	}
    46  
    47  	match := notificationRegex.FindStringSubmatch(*comment.Body)
    48  	if match == nil {
    49  		return nil
    50  	}
    51  
    52  	return &Notification{
    53  		Name:      strings.ToUpper(match[1]),
    54  		Arguments: strings.TrimSpace(match[2]),
    55  	}
    56  }
    57  
    58  // String converts the notification
    59  func (n *Notification) String() string {
    60  	str := "[" + strings.ToUpper(n.Name) + "]"
    61  
    62  	args := strings.TrimSpace(n.Arguments)
    63  	if args != "" {
    64  		str += " " + args
    65  	}
    66  
    67  	context := strings.TrimSpace(n.Context)
    68  	if context != "" {
    69  		str += "\n\n" + context
    70  	}
    71  
    72  	return str
    73  }
    74  
    75  // Post a new notification on Github
    76  func (n Notification) Post(obj *mgh.MungeObject) error {
    77  	return obj.WriteComment(n.String())
    78  }