woodpecker/plugin/notify/slack.go

82 lines
2.3 KiB
Go
Raw Normal View History

2014-03-26 10:43:40 +00:00
package notify
import (
"encoding/json"
2014-04-06 09:05:30 +00:00
"fmt"
"github.com/drone/drone/shared/model"
2014-03-26 10:43:40 +00:00
)
const (
2014-04-06 20:04:13 +00:00
slackEndpoint = "https://%s.slack.com/services/hooks/incoming-webhook?token=%s"
2014-04-09 09:39:23 +00:00
slackStartedMessage = "*Building* %s, commit <%s|%s>, author %s"
slackSuccessMessage = "*Success* %s, commit <%s|%s>, author %s"
slackFailureMessage = "*Failed* %s, commit <%s|%s>, author %s"
2014-03-26 10:43:40 +00:00
)
type Slack struct {
Team string `yaml:"team,omitempty"`
Channel string `yaml:"channel,omitempty"`
Username string `yaml:"username,omitempty"`
Token string `yaml:"token,omitempty"`
Started bool `yaml:"on_started,omitempty"`
Success bool `yaml:"on_success,omitempty"`
Failure bool `yaml:"on_failure,omitempty"`
}
func (s *Slack) Send(context *model.Request) error {
2014-03-26 10:43:40 +00:00
switch {
case context.Commit.Status == "Started" && s.Started:
return s.sendStarted(context)
case context.Commit.Status == "Success" && s.Success:
return s.sendSuccess(context)
case context.Commit.Status == "Failure" && s.Failure:
return s.sendFailure(context)
}
return nil
}
func getBuildUrl(context *model.Request) string {
return fmt.Sprintf("%s/%s/%s/%s/%s/%s", context.Host, context.Repo.Host, context.Repo.Owner, context.Repo.Name, context.Commit.Branch, context.Commit.Sha)
2014-04-09 09:39:23 +00:00
}
func getMessage(context *model.Request, message string) string {
2014-04-09 09:39:23 +00:00
url := getBuildUrl(context)
2014-06-04 21:25:38 +00:00
return fmt.Sprintf(message, context.Repo.Name, url, context.Commit.ShaShort(), context.Commit.Author)
2014-04-09 09:39:23 +00:00
}
func (s *Slack) sendStarted(context *model.Request) error {
2014-04-09 09:39:23 +00:00
return s.send(getMessage(context, slackStartedMessage))
2014-03-26 10:43:40 +00:00
}
func (s *Slack) sendSuccess(context *model.Request) error {
2014-04-09 09:39:23 +00:00
return s.send(getMessage(context, slackSuccessMessage))
2014-03-26 10:43:40 +00:00
}
func (s *Slack) sendFailure(context *model.Request) error {
2014-04-09 09:39:23 +00:00
return s.send(getMessage(context, slackFailureMessage))
2014-03-26 10:43:40 +00:00
}
// helper function to send HTTP requests
func (s *Slack) send(msg string) error {
// data will get posted in this format
data := struct {
Channel string `json:"channel"`
Username string `json:"username"`
Text string `json:"text"`
}{s.Channel, s.Username, msg}
// data json encoded
payload, err := json.Marshal(data)
if err != nil {
return err
}
// send payload
2014-04-06 09:05:30 +00:00
url := fmt.Sprintf(slackEndpoint, s.Team, s.Token)
2014-03-26 10:43:40 +00:00
go sendJson(url, payload)
return nil
}