forked from mattermost/mattermost-plugin-github
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcommand.go
More file actions
831 lines (700 loc) · 26.8 KB
/
command.go
File metadata and controls
831 lines (700 loc) · 26.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
package plugin
import (
"context"
"fmt"
"strings"
"unicode"
"github.com/mattermost/mattermost-plugin-github/server/constants"
"github.com/mattermost/mattermost-plugin-github/server/serializer"
"github.com/mattermost/mattermost-plugin-api/experimental/command"
"github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mattermost-server/v6/plugin"
"github.com/pkg/errors"
)
const (
featureIssueCreation = "issue_creations"
featureIssues = "issues"
featurePulls = "pulls"
featurePullsMerged = "pulls_merged"
featurePushes = "pushes"
featureCreates = "creates"
featureDeletes = "deletes"
featureIssueComments = "issue_comments"
featurePullReviews = "pull_reviews"
featureStars = "stars"
)
var validFeatures = map[string]bool{
featureIssueCreation: true,
featureIssues: true,
featurePulls: true,
featurePullsMerged: true,
featurePushes: true,
featureCreates: true,
featureDeletes: true,
featureIssueComments: true,
featurePullReviews: true,
featureStars: true,
}
// validateFeatures returns false when 1 or more given features
// are invalid along with a list of the invalid features.
func validateFeatures(features []string) (bool, []string) {
valid := true
invalidFeatures := []string{}
hasLabel := false
for _, f := range features {
if _, ok := validFeatures[f]; ok {
continue
}
if strings.HasPrefix(f, "label") {
hasLabel = true
continue
}
invalidFeatures = append(invalidFeatures, f)
valid = false
}
if valid && hasLabel {
// must have "pulls" or "issues" in features when using a label
for _, f := range features {
if f == featurePulls || f == featureIssues {
return valid, invalidFeatures
}
}
valid = false
}
return valid, invalidFeatures
}
func (p *Plugin) getCommand(config *Configuration) (*model.Command, error) {
iconData, err := command.GetIconData(p.API, "assets/icon-bg.svg")
if err != nil {
return nil, errors.Wrap(err, "failed to get icon data")
}
return &model.Command{
Trigger: "github",
AutoComplete: true,
AutoCompleteDesc: "Available commands: connect, disconnect, todo, me, settings, subscribe, unsubscribe, mute, help, issue",
AutoCompleteHint: "[command]",
AutocompleteData: getAutocompleteData(config),
AutocompleteIconData: iconData,
}, nil
}
func (p *Plugin) postCommandResponse(args *model.CommandArgs, text string) {
post := &model.Post{
UserId: p.BotUserID,
ChannelId: args.ChannelId,
RootId: args.RootId,
Message: text,
}
_ = p.API.SendEphemeralPost(args.UserId, post)
}
func (p *Plugin) getMutedUsernames(userInfo *serializer.GitHubUserInfo) []string {
mutedUsernameBytes, err := p.API.KVGet(userInfo.UserID + "-muted-users")
if err != nil {
return nil
}
mutedUsernames := string(mutedUsernameBytes)
var mutedUsers []string
if len(mutedUsernames) == 0 {
return mutedUsers
}
mutedUsers = strings.Split(mutedUsernames, ",")
return mutedUsers
}
func (p *Plugin) handleMuteList(args *model.CommandArgs, userInfo *serializer.GitHubUserInfo) string {
mutedUsernames := p.getMutedUsernames(userInfo)
var mutedUsers string
for _, user := range mutedUsernames {
mutedUsers += fmt.Sprintf("- %v\n", user)
}
if len(mutedUsers) == 0 {
return "You have no muted users"
}
return "Your muted users:\n" + mutedUsers
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func (p *Plugin) handleMuteAdd(args *model.CommandArgs, username string, userInfo *serializer.GitHubUserInfo) string {
mutedUsernames := p.getMutedUsernames(userInfo)
if contains(mutedUsernames, username) {
return username + " is already muted"
}
if strings.Contains(username, ",") {
return "Invalid username provided"
}
var mutedUsers string
if len(mutedUsernames) > 0 {
// , is a character not allowed in github usernames so we can split on them
mutedUsers = strings.Join(mutedUsernames, ",") + "," + username
} else {
mutedUsers = username
}
if err := p.API.KVSet(userInfo.UserID+"-muted-users", []byte(mutedUsers)); err != nil {
return "Error occurred saving list of muted users"
}
return fmt.Sprintf("`%v`", username) + " is now muted. You'll no longer receive notifications for comments in your PRs and issues."
}
func (p *Plugin) handleUnmute(args *model.CommandArgs, username string, userInfo *serializer.GitHubUserInfo) string {
mutedUsernames := p.getMutedUsernames(userInfo)
userToMute := []string{username}
newMutedList := arrayDifference(mutedUsernames, userToMute)
if err := p.API.KVSet(userInfo.UserID+"-muted-users", []byte(strings.Join(newMutedList, ","))); err != nil {
return "Error occurred unmuting users"
}
return fmt.Sprintf("`%v`", username) + " is no longer muted"
}
func (p *Plugin) handleUnmuteAll(args *model.CommandArgs, userInfo *serializer.GitHubUserInfo) string {
if err := p.API.KVSet(userInfo.UserID+"-muted-users", []byte("")); err != nil {
return "Error occurred unmuting users"
}
return "Unmuted all users"
}
func (p *Plugin) handleMuteCommand(_ *plugin.Context, args *model.CommandArgs, parameters []string, userInfo *serializer.GitHubUserInfo) string {
if len(parameters) == 0 {
return "Invalid mute command. Available commands are 'list', 'add' and 'delete'."
}
command := parameters[0]
switch {
case command == "list":
return p.handleMuteList(args, userInfo)
case command == "add":
if len(parameters) != 2 {
return "Invalid number of parameters supplied to " + command
}
return p.handleMuteAdd(args, parameters[1], userInfo)
case command == "delete":
if len(parameters) != 2 {
return "Invalid number of parameters supplied to " + command
}
return p.handleUnmute(args, parameters[1], userInfo)
case command == "delete-all":
return p.handleUnmuteAll(args, userInfo)
default:
return fmt.Sprintf("Unknown subcommand %v", command)
}
}
// Returns the elements in a, that are not in b
func arrayDifference(a, b []string) []string {
mb := make(map[string]struct{}, len(b))
for _, x := range b {
mb[x] = struct{}{}
}
var diff []string
for _, x := range a {
if _, found := mb[x]; !found {
diff = append(diff, x)
}
}
return diff
}
func (p *Plugin) handleSubscribe(c *plugin.Context, args *model.CommandArgs, parameters []string, userInfo *serializer.GitHubUserInfo) string {
switch {
case len(parameters) == 0:
return "Please specify a repository or 'list' command."
case len(parameters) == 1 && parameters[0] == "list":
return p.handleSubscriptionsList(c, args, parameters[1:], userInfo)
default:
return p.handleSubscribesAdd(c, args, parameters, userInfo)
}
}
func (p *Plugin) handleSubscriptions(c *plugin.Context, args *model.CommandArgs, parameters []string, userInfo *serializer.GitHubUserInfo) string {
if len(parameters) == 0 {
return "Invalid subscribe command. Available commands are 'list', 'add' and 'delete'."
}
command := parameters[0]
parameters = parameters[1:]
switch {
case command == "list":
return p.handleSubscriptionsList(c, args, parameters, userInfo)
case command == "add":
return p.handleSubscribesAdd(c, args, parameters, userInfo)
case command == "delete":
return p.handleUnsubscribe(c, args, parameters, userInfo)
default:
return fmt.Sprintf("Unknown subcommand %v", command)
}
}
func (p *Plugin) handleSubscriptionsList(_ *plugin.Context, args *model.CommandArgs, parameters []string, _ *serializer.GitHubUserInfo) string {
txt := ""
subs, err := p.GetSubscriptionsByChannel(args.ChannelId)
if err != nil {
return err.Error()
}
if len(subs) == 0 {
txt = "Currently there are no subscriptions in this channel"
} else {
txt = "### Subscriptions in this channel\n"
}
for _, sub := range subs {
subFlags := sub.Flags.String()
txt += fmt.Sprintf("* `%s` - %s", strings.Trim(sub.Repository, "/"), sub.Features)
if subFlags != "" {
txt += fmt.Sprintf(" %s", subFlags)
}
txt += "\n"
}
return txt
}
func (p *Plugin) handleSubscribesAdd(_ *plugin.Context, args *model.CommandArgs, parameters []string, userInfo *serializer.GitHubUserInfo) string {
if len(parameters) == 0 {
return "Please specify a repository."
}
config := p.getConfiguration()
features := "pulls,issues,creates,deletes"
flags := SubscriptionFlags{}
if len(parameters) > 1 {
flagParams := parameters[1:]
if len(flagParams)%2 != 0 {
return "Please use the correct format for flags: --<name> <value>"
}
for i := 0; i < len(flagParams); i += 2 {
flag := flagParams[i]
value := flagParams[i+1]
if !isFlag(flag) {
return "Please use the correct format for flags: --<name> <value>"
}
parsedFlag := parseFlag(flag)
if parsedFlag == flagFeatures {
features = value
continue
}
if err := flags.AddFlag(parsedFlag, value); err != nil {
return fmt.Sprintf("Unsupported value for flag %s", flag)
}
}
fs := strings.Split(features, ",")
if SliceContainsString(fs, featureIssues) && SliceContainsString(fs, featureIssueCreation) {
return "Feature list cannot contain both issue and issue_creations"
}
if SliceContainsString(fs, featurePulls) && SliceContainsString(fs, featurePullsMerged) {
return "Feature list cannot contain both pulls and pulls_merged"
}
ok, ifs := validateFeatures(fs)
if !ok {
msg := fmt.Sprintf("Invalid feature(s) provided: %s", strings.Join(ifs, ","))
if len(ifs) == 0 {
msg = "Feature list must have \"pulls\" or \"issues\" when using a label."
}
return msg
}
}
ctx := context.Background()
githubClient := p.githubConnectUser(ctx, userInfo)
owner, repo := parseOwnerAndRepo(parameters[0], config.getBaseURL())
if repo == "" {
if err := p.SubscribeOrg(ctx, githubClient, args.UserId, owner, args.ChannelId, features, flags); err != nil {
return err.Error()
}
return fmt.Sprintf("Successfully subscribed to organization %s.", owner)
}
if err := p.Subscribe(ctx, githubClient, args.UserId, owner, repo, args.ChannelId, features, flags); err != nil {
return err.Error()
}
repoLink := config.getBaseURL() + owner + "/" + repo
msg := fmt.Sprintf("Successfully subscribed to [%s](%s).", repo, repoLink)
ghRepo, _, err := githubClient.Repositories.Get(ctx, owner, repo)
if err != nil {
p.API.LogWarn("Failed to fetch repository", "error", err.Error())
} else if ghRepo != nil && ghRepo.GetPrivate() {
msg += "\n\n**Warning:** You subscribed to a private repository. Anyone with access to this channel will be able to read the events getting posted here."
}
return msg
}
func (p *Plugin) handleUnsubscribe(_ *plugin.Context, args *model.CommandArgs, parameters []string, _ *serializer.GitHubUserInfo) string {
if len(parameters) == 0 {
return "Please specify a repository."
}
repo := parameters[0]
if err := p.Unsubscribe(args.ChannelId, repo); err != nil {
p.API.LogWarn("Failed to unsubscribe", "repo", repo, "error", err.Error())
return "Encountered an error trying to unsubscribe. Please try again."
}
return fmt.Sprintf("Successfully unsubscribed from %s.", repo)
}
func (p *Plugin) handleDisconnect(_ *plugin.Context, args *model.CommandArgs, _ []string, _ *serializer.GitHubUserInfo) string {
p.disconnectGitHubAccount(args.UserId)
return "Disconnected your GitHub account."
}
func (p *Plugin) handleTodo(_ *plugin.Context, _ *model.CommandArgs, _ []string, userInfo *serializer.GitHubUserInfo) string {
githubClient := p.githubConnectUser(context.Background(), userInfo)
text, err := p.GetToDo(context.Background(), userInfo.GitHubUsername, githubClient)
if err != nil {
p.API.LogWarn("Failed get get Todos", "error", err.Error())
return "Encountered an error getting your to do items."
}
return text
}
func (p *Plugin) handleMe(_ *plugin.Context, _ *model.CommandArgs, _ []string, userInfo *serializer.GitHubUserInfo) string {
githubClient := p.githubConnectUser(context.Background(), userInfo)
gitUser, _, err := githubClient.Users.Get(context.Background(), "")
if err != nil {
return "Encountered an error getting your GitHub profile."
}
text := fmt.Sprintf("You are connected to GitHub as:\n# [](%s) [%s](%s)", gitUser.GetAvatarURL(), gitUser.GetHTMLURL(), gitUser.GetLogin(), gitUser.GetHTMLURL())
return text
}
func (p *Plugin) handleHelp(_ *plugin.Context, _ *model.CommandArgs, _ []string, _ *serializer.GitHubUserInfo) string {
message, err := renderTemplate("helpText", p.getConfiguration())
if err != nil {
p.API.LogWarn("Failed to render help template", "error", err.Error())
return "Encountered an error posting help text."
}
return "###### Mattermost GitHub Plugin - Slash Command Help\n" + message
}
func (p *Plugin) handleSettings(_ *plugin.Context, _ *model.CommandArgs, parameters []string, userInfo *serializer.GitHubUserInfo) string {
if len(parameters) < 2 {
return "Please specify both a setting and value. Use `/github help` for more usage information."
}
setting := parameters[0]
settingValue := parameters[1]
switch setting {
case settingNotifications:
switch settingValue {
case settingOn:
userInfo.Settings.Notifications = true
case settingOff:
userInfo.Settings.Notifications = false
default:
return "Invalid value. Accepted values are: \"on\" or \"off\"."
}
case settingReminders:
switch settingValue {
case settingOn:
userInfo.Settings.DailyReminder = true
userInfo.Settings.DailyReminderOnChange = false
case settingOff:
userInfo.Settings.DailyReminder = false
userInfo.Settings.DailyReminderOnChange = false
case settingOnChange:
userInfo.Settings.DailyReminder = true
userInfo.Settings.DailyReminderOnChange = true
default:
return "Invalid value. Accepted values are: \"on\" or \"off\" or \"on-change\" ."
}
default:
return "Unknown setting " + setting
}
if setting == settingNotifications {
if userInfo.Settings.Notifications {
err := p.storeGitHubToUserIDMapping(userInfo.GitHubUsername, userInfo.UserID)
if err != nil {
p.API.LogWarn("Failed to store GitHub to userID mapping",
"userID", userInfo.UserID,
"GitHub username", userInfo.GitHubUsername,
"error", err.Error())
}
} else {
err := p.API.KVDelete(userInfo.GitHubUsername + githubUsernameKey)
if err != nil {
p.API.LogWarn("Failed to delete GitHub to userID mapping",
"userID", userInfo.UserID,
"GitHub username", userInfo.GitHubUsername,
"error", err.Error())
}
}
}
err := p.storeGitHubUserInfo(userInfo)
if err != nil {
p.API.LogWarn("Failed to store github user info", "error", err.Error())
return "Failed to store settings"
}
return "Settings updated."
}
func (p *Plugin) handleIssue(_ *plugin.Context, args *model.CommandArgs, parameters []string, userInfo *serializer.GitHubUserInfo) string {
if len(parameters) == 0 {
return "Invalid issue command. Available command is 'create'."
}
command := parameters[0]
parameters = parameters[1:]
switch {
case command == "create":
p.openIssueCreateModal(args.UserId, args.ChannelId, strings.Join(parameters, " "))
return ""
default:
return fmt.Sprintf("Unknown subcommand %v", command)
}
}
func (p *Plugin) handleSetup(c *plugin.Context, args *model.CommandArgs, parameters []string) string {
userID := args.UserId
isSysAdmin, err := p.isAuthorizedSysAdmin(userID)
if err != nil {
p.API.LogWarn("Failed to check if user is System Admin", "error", err.Error())
return "Error checking user's permissions"
}
if !isSysAdmin {
return "Only System Admins are allowed to set up the plugin."
}
if len(parameters) == 0 {
err = p.flowManager.StartSetupWizard(userID, "")
} else {
command := parameters[0]
switch {
case command == "oauth":
err = p.flowManager.StartOauthWizard(userID)
case command == "webhook":
err = p.flowManager.StartWebhookWizard(userID)
case command == "announcement":
err = p.flowManager.StartAnnouncementWizard(userID)
default:
return fmt.Sprintf("Unknown subcommand %v", command)
}
}
if err != nil {
return err.Error()
}
return ""
}
type CommandHandleFunc func(c *plugin.Context, args *model.CommandArgs, parameters []string, userInfo *serializer.GitHubUserInfo) string
func (p *Plugin) isAuthorizedSysAdmin(userID string) (bool, error) {
user, appErr := p.API.GetUser(userID)
if appErr != nil {
return false, appErr
}
if !strings.Contains(user.Roles, "system_admin") {
return false, nil
}
return true, nil
}
func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
command, action, parameters := parseCommand(args.Command)
if command != "/github" {
return &model.CommandResponse{}, nil
}
if action == "setup" {
message := p.handleSetup(c, args, parameters)
if message != "" {
p.postCommandResponse(args, message)
}
return &model.CommandResponse{}, nil
}
config := p.getConfiguration()
if validationErr := config.IsValid(); validationErr != nil {
isSysAdmin, err := p.isAuthorizedSysAdmin(args.UserId)
var text string
switch {
case err != nil:
text = "Error checking user's permissions"
p.API.LogWarn(text, "error", err.Error())
case isSysAdmin:
text = fmt.Sprintf("Before using this plugin, you'll need to configure it by running `/github setup`: %s", validationErr.Error())
default:
text = "Please contact your system administrator to correctly configure the GitHub plugin."
}
p.postCommandResponse(args, text)
return &model.CommandResponse{}, nil
}
if action == "connect" {
siteURL := p.API.GetConfig().ServiceSettings.SiteURL
if siteURL == nil {
p.postCommandResponse(args, "Encountered an error connecting to GitHub.")
return &model.CommandResponse{}, nil
}
privateAllowed := p.getConfiguration().ConnectToPrivateByDefault
if len(parameters) > 0 {
if privateAllowed {
p.postCommandResponse(args, fmt.Sprintf("Unknown command `%v`. Do you meant `/github connect`?", args.Command))
return &model.CommandResponse{}, nil
}
if len(parameters) != 1 || parameters[0] != "private" {
p.postCommandResponse(args, fmt.Sprintf("Unknown command `%v`. Do you meant `/github connect private`?", args.Command))
return &model.CommandResponse{}, nil
}
privateAllowed = true
}
qparams := ""
if privateAllowed {
if !p.getConfiguration().EnablePrivateRepo {
p.postCommandResponse(args, "Private repositories are disabled. Please ask a System Admin to enabled them.")
return &model.CommandResponse{}, nil
}
qparams = "?private=true"
}
msg := fmt.Sprintf("[Click here to link your GitHub account.](%s/plugins/%s/oauth/connect%s)", *siteURL, Manifest.Id, qparams)
p.postCommandResponse(args, msg)
return &model.CommandResponse{}, nil
}
info, apiErr := p.getGitHubUserInfo(args.UserId)
if apiErr != nil {
text := "Unknown error."
if apiErr.ID == constants.APIErrorIDNotConnected {
text = "You must connect your account to GitHub first. Either click on the GitHub logo in the bottom left of the screen or enter `/github connect`."
}
p.postCommandResponse(args, text)
return &model.CommandResponse{}, nil
}
if f, ok := p.CommandHandlers[action]; ok {
message := f(c, args, parameters, info)
if message != "" {
p.postCommandResponse(args, message)
}
return &model.CommandResponse{}, nil
}
p.postCommandResponse(args, fmt.Sprintf("Unknown action %v", action))
return &model.CommandResponse{}, nil
}
func getAutocompleteData(config *Configuration) *model.AutocompleteData {
if !config.IsOAuthConfigured() {
github := model.NewAutocompleteData("github", "[command]", "Available commands: setup")
setup := model.NewAutocompleteData("setup", "", "Set up the GitHub plugin")
setup.RoleID = model.SystemAdminRoleId
github.AddCommand(setup)
return github
}
github := model.NewAutocompleteData("github", "[command]", "Available commands: connect, disconnect, todo, subscribe, unsubscribe, me, settings")
connect := model.NewAutocompleteData("connect", "", "Connect your Mattermost account to your GitHub account")
if config.EnablePrivateRepo {
if config.ConnectToPrivateByDefault {
connect = model.NewAutocompleteData("connect", "", "Connect your Mattermost account to your GitHub account. Read access to your private repositories will be requested")
} else {
private := model.NewAutocompleteData("private", "(optional)", "If used, read access to your private repositories will be requested")
connect.AddCommand(private)
}
}
github.AddCommand(connect)
disconnect := model.NewAutocompleteData("disconnect", "", "Disconnect your Mattermost account from your GitHub account")
github.AddCommand(disconnect)
help := model.NewAutocompleteData("help", "", "Display Slash Command help text")
github.AddCommand(help)
todo := model.NewAutocompleteData("todo", "", "Get a list of unread messages and pull requests awaiting your review")
github.AddCommand(todo)
subscriptions := model.NewAutocompleteData("subscriptions", "[command]", "Available commands: list, add, delete")
subscribeList := model.NewAutocompleteData("list", "", "List the current channel subscriptions")
subscriptions.AddCommand(subscribeList)
subscriptionsAdd := model.NewAutocompleteData("add", "[owner/repo] [features] [flags]", "Subscribe the current channel to receive notifications about opened pull requests and issues for an organization or repository. [features] and [flags] are optional arguments")
subscriptionsAdd.AddTextArgument("Owner/repo to subscribe to", "[owner/repo]", "")
subscriptionsAdd.AddNamedTextArgument("features", "Comma-delimited list of one or more of: issues, pulls, pulls_merged, pushes, creates, deletes, issue_creations, issue_comments, pull_reviews, label:\"<labelname>\". Defaults to pulls,issues,creates,deletes", "", `/[^,-\s]+(,[^,-\s]+)*/`, false)
if config.GitHubOrg != "" {
subscriptionsAdd.AddNamedStaticListArgument("exclude-org-member", "Events triggered by organization members will not be delivered (the organization config should be set, otherwise this flag has not effect)", false, []model.AutocompleteListItem{
{
Item: "true",
HelpText: "Exclude posts from members of the configured organization",
},
{
Item: "false",
HelpText: "Include posts from members of the configured organization",
},
})
}
subscriptionsAdd.AddNamedStaticListArgument("render-style", "Determine the rendering style of various notifications.", false, []model.AutocompleteListItem{
{
Item: "default",
HelpText: "The default rendering style for all notifications (includes all information).",
},
{
Item: "skip-body",
HelpText: "Skips the body part of various long notifications that have a body (e.g. new PRs and new issues).",
},
{
Item: "collapsed",
HelpText: "Notifications come in a one-line format, without enlarged fonts or advanced layouts.",
},
})
subscriptions.AddCommand(subscriptionsAdd)
subscriptionsDelete := model.NewAutocompleteData("delete", "[owner/repo]", "Unsubscribe the current channel from an organization or repository")
subscriptionsDelete.AddTextArgument("Owner/repo to unsubscribe from", "[owner/repo]", "")
subscriptions.AddCommand(subscriptionsDelete)
github.AddCommand(subscriptions)
me := model.NewAutocompleteData("me", "", "Display the connected GitHub account")
github.AddCommand(me)
mute := model.NewAutocompleteData("mute", "[command]", "Available commands: list, add, delete, delete-all")
muteAdd := model.NewAutocompleteData("add", "[github username]", "Mute notifications from the provided GitHub user")
muteAdd.AddTextArgument("GitHub user to mute", "[username]", "")
mute.AddCommand(muteAdd)
muteDelete := model.NewAutocompleteData("delete", "[github username]", "Unmute notifications from the provided GitHub user")
muteDelete.AddTextArgument("GitHub user to unmute", "[username]", "")
mute.AddCommand(muteDelete)
github.AddCommand(mute)
muteDeleteAll := model.NewAutocompleteData("delete-all", "", "Unmute all muted GitHub users")
mute.AddCommand(muteDeleteAll)
muteList := model.NewAutocompleteData("list", "", "List muted GitHub users")
mute.AddCommand(muteList)
settings := model.NewAutocompleteData("settings", "[setting] [value]", "Update your user settings")
settingNotifications := model.NewAutocompleteData("notifications", "", "Turn notifications on/off")
settingValue := []model.AutocompleteListItem{{
HelpText: "Turn notifications on",
Item: "on",
}, {
HelpText: "Turn notifications off",
Item: "off",
}}
settingNotifications.AddStaticListArgument("", true, settingValue)
settings.AddCommand(settingNotifications)
remainderNotifications := model.NewAutocompleteData("reminders", "", "Turn notifications on/off")
settingValue = []model.AutocompleteListItem{{
HelpText: "Turn reminders on",
Item: "on",
}, {
HelpText: "Turn reminders off",
Item: "off",
}, {
HelpText: "Turn reminders on, but only get reminders if any changes have occurred since the previous day's reminder",
Item: settingOnChange,
}}
remainderNotifications.AddStaticListArgument("", true, settingValue)
settings.AddCommand(remainderNotifications)
github.AddCommand(settings)
issue := model.NewAutocompleteData("issue", "[command]", "Available commands: create")
issueCreate := model.NewAutocompleteData("create", "[title]", "Open a dialog to create a new issue in GitHub, using the title if provided")
issueCreate.AddTextArgument("Title for the GitHub issue", "[title]", "")
issue.AddCommand(issueCreate)
github.AddCommand(issue)
setup := model.NewAutocompleteData("setup", "[command]", "Available commands: oauth, webhook, announcement")
setup.RoleID = model.SystemAdminRoleId
setup.AddCommand(model.NewAutocompleteData("oauth", "", "Set up the OAuth2 Application in GitHub"))
setup.AddCommand(model.NewAutocompleteData("webhook", "", "Create a webhook from GitHub to Mattermost"))
setup.AddCommand(model.NewAutocompleteData("announcement", "", "Announce to your team that they can use GitHub integration"))
github.AddCommand(setup)
return github
}
// parseCommand parses the entire command input string and retrieves the command, action and parameters
func parseCommand(input string) (command, action string, parameters []string) {
split := make([]string, 0)
current := ""
inQuotes := false
for _, char := range input {
if unicode.IsSpace(char) {
// keep whitespaces that are inside double qoutes
if inQuotes {
current += " "
continue
}
// ignore successive whitespaces that are outside of double quotes
if len(current) == 0 && !inQuotes {
continue
}
// append the current word to the list & move on to the next word/expression
split = append(split, current)
current = ""
continue
}
// append the current character to the current word
current += string(char)
if char == '"' {
inQuotes = !inQuotes
}
}
// append the last word/expression to the list
if len(current) > 0 {
split = append(split, current)
}
command = split[0]
if len(split) > 1 {
action = split[1]
}
if len(split) > 2 {
parameters = split[2:]
}
return command, action, parameters
}
func SliceContainsString(a []string, x string) bool {
for _, n := range a {
if x == n {
return true
}
}
return false
}