summaryrefslogtreecommitdiff
path: root/go/internal/command/commandargs/command_args.go
blob: 9e679d3e51d1bb0d3b3739140822cf0a0ce9a6c3 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package commandargs

import (
	"errors"
	"os"
	"regexp"
)

type CommandType string

const (
	Discover CommandType = "discover"
)

var (
	whoKeyRegex      = regexp.MustCompile(`\bkey-(?P<keyid>\d+)\b`)
	whoUsernameRegex = regexp.MustCompile(`\busername-(?P<username>\S+)\b`)
)

type CommandArgs struct {
	GitlabUsername string
	GitlabKeyId    string
	SshCommand     string
	CommandType    CommandType
}

func Parse(arguments []string) (*CommandArgs, error) {
	if sshConnection := os.Getenv("SSH_CONNECTION"); sshConnection == "" {
		return nil, errors.New("Only ssh allowed")
	}

	info := &CommandArgs{}

	info.parseWho(arguments)
	info.parseCommand(os.Getenv("SSH_ORIGINAL_COMMAND"))

	return info, nil
}

func (c *CommandArgs) parseWho(arguments []string) {
	for _, argument := range arguments {
		if keyId := tryParseKeyId(argument); keyId != "" {
			c.GitlabKeyId = keyId
			break
		}

		if username := tryParseUsername(argument); username != "" {
			c.GitlabUsername = username
			break
		}
	}
}

func tryParseKeyId(argument string) string {
	matchInfo := whoKeyRegex.FindStringSubmatch(argument)
	if len(matchInfo) == 2 {
		// The first element is the full matched string
		// The second element is the named `keyid`
		return matchInfo[1]
	}

	return ""
}

func tryParseUsername(argument string) string {
	matchInfo := whoUsernameRegex.FindStringSubmatch(argument)
	if len(matchInfo) == 2 {
		// The first element is the full matched string
		// The second element is the named `username`
		return matchInfo[1]
	}

	return ""
}

func (c *CommandArgs) parseCommand(commandString string) {
	c.SshCommand = commandString

	if commandString == "" {
		c.CommandType = Discover
	}
}