summaryrefslogtreecommitdiffstats
path: root/cmd/commands/commandargs.go
blob: 702f01c9a64c0e1cd7d8f8de0828a26742f89981 (plain)
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
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

package commands

import (
	"fmt"
	"strings"

	"github.com/mattermost/mattermost-server/app"
	"github.com/mattermost/mattermost-server/model"
)

const COMMAND_ARGS_SEPARATOR = ":"

func getCommandsFromCommandArgs(a *app.App, commandArgs []string) []*model.Command {
	commands := make([]*model.Command, 0, len(commandArgs))

	for _, commandArg := range commandArgs {
		command := getCommandFromCommandArg(a, commandArg)
		commands = append(commands, command)
	}

	return commands
}

func parseCommandArg(commandArg string) (string, string) {
	result := strings.SplitN(commandArg, COMMAND_ARGS_SEPARATOR, 2)

	if len(result) == 1 {
		return "", commandArg
	}

	return result[0], result[1]
}

func getCommandFromCommandArg(a *app.App, commandArg string) *model.Command {
	teamArg, commandPart := parseCommandArg(commandArg)
	if teamArg == "" && commandPart == "" {
		return nil
	}

	var command *model.Command
	if teamArg != "" {
		team := getTeamFromTeamArg(a, teamArg)
		if team == nil {
			return nil
		}

		if result := <-a.Srv.Store.Command().GetByTrigger(team.Id, commandPart); result.Err == nil {
			command = result.Data.(*model.Command)
		} else {
			fmt.Println(result.Err.Error())
		}
	}

	if command == nil {
		if result := <-a.Srv.Store.Command().Get(commandPart); result.Err == nil {
			command = result.Data.(*model.Command)
		}
	}

	return command
}