Skip to content

Commit

Permalink
Extract function
Browse files Browse the repository at this point in the history
  • Loading branch information
ebc-2in2crc committed Sep 21, 2023
1 parent 3d62fa8 commit 28c6032
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 9 deletions.
25 changes: 16 additions & 9 deletions cmd/slack-notify/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"strings"
"time"

"google.golang.org/api/calendar/v3"

"golang.org/x/net/context"
)

Expand Down Expand Up @@ -67,15 +69,7 @@ func main() {
}

// Slack に投稿するメッセージを作成する
a := make([]string, len(events))
for i := range events {
a[i] = fmt.Sprintf("• %s", events[i].Summary)
}
desc := opt.message
if len(events) == 0 && opt.alternativeMessage != "" {
desc = opt.alternativeMessage
}
msg := fmt.Sprintf("%s\n\n%s", desc, strings.Join(a, "\n"))
msg := createSlackMessage(events, opt.message, opt.alternativeMessage)

// Slack に投稿する
if err := c.poster.post(ctx, opt.slackChannelID, msg); err != nil {
Expand Down Expand Up @@ -156,3 +150,16 @@ func newClient(opt *opt) (*client, error) {

return &client{fetcher: ef, poster: sp}, nil
}

func createSlackMessage(events []*calendar.Event, msg, alt string) string {
if len(events) == 0 && alt != "" {
return alt
}

a := make([]string, len(events))
for i := range events {
a[i] = fmt.Sprintf("• %s", events[i].Summary)
}
s := fmt.Sprintf("%s\n\n%s", msg, strings.Join(a, "\n"))
return s
}
42 changes: 42 additions & 0 deletions cmd/slack-notify/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import (
"testing"

"google.golang.org/api/calendar/v3"
)

func TestCreateSlackMessage(t *testing.T) {
var tests = []struct {
name string
events []*calendar.Event
msg string
alt string
want string
}{
{
name: "normal",
events: []*calendar.Event{
{Summary: "Summary1"},
{Summary: "Summary2"},
},
msg: "Test Message",
alt: "Alternative Message",
want: "Test Message\n\n• Summary1\n• Summary2",
},
{
name: "empty events",
events: []*calendar.Event{},
msg: "Test Message",
alt: "Alternative Message",
want: "Alternative Message",
},
}

for _, tt := range tests {
got := createSlackMessage(tt.events, tt.msg, tt.alt)
if got != tt.want {
t.Errorf("Want '%s', but got '%s'", tt.want, got)
}
}
}

0 comments on commit 28c6032

Please sign in to comment.