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

import (
	"os"
	"path/filepath"
)

const (
	BinDir                    = "bin"
	Healthcheck               = "check"
	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(name string) (*Executable, error) {
	path, err := osExecutable()
	if err != nil {
		return nil, err
	}

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

	executable := &Executable{
		Name:    name,
		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
}