summaryrefslogtreecommitdiff
path: root/go/internal/executable/executable.go
blob: 63f4c90127fb529bc6799447d363175698e953c8 (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
package executable

import (
	"os"
	"path/filepath"
)

const (
	GitlabShell               = "gitlab-shell"
	AuthorizedKeysCheck       = "gitlab-shell-authorized-keys-check"
	AuthorizedPrincipalsCheck = "gitlab-shell-authorized-principals-check"
)

type Executable struct {
	Name    string
	RootDir string
}

var (
	// osExecutable is overridden in tests
	osExecutable = os.Executable
)

func New() (*Executable, error) {
	path, err := osExecutable()
	if err != nil {
		return nil, err
	}

	rootDir, err := findRootDir(path)
	if err != nil {
		return nil, err
	}

	executable := &Executable{
		Name:    filepath.Base(path),
		RootDir: rootDir,
	}

	return executable, nil
}

func findRootDir(path string) (string, error) {
	// Start: /opt/.../gitlab-shell/bin/gitlab-shell
	// Ends:  /opt/.../gitlab-shell
	rootDir := filepath.Dir(filepath.Dir(path))
	pathFromEnv := os.Getenv("GITLAB_SHELL_DIR")

	if pathFromEnv != "" {
		if _, err := os.Stat(pathFromEnv); os.IsNotExist(err) {
			return "", err
		}

		rootDir = pathFromEnv
	}

	return rootDir, nil
}