/
shell.go
81 lines (64 loc) · 1.64 KB
/
shell.go
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
//go:build !windows
// +build !windows
package shell
import (
"fmt"
"path/filepath"
"runtime"
"code.cloudfoundry.org/buildpackapplifecycle/credhub_flags"
"code.cloudfoundry.org/buildpackapplifecycle/env"
"code.cloudfoundry.org/goshims/osshim"
)
type exec interface {
Exec(dir, launcher, args, command string, environ []string)
}
func Run(os osshim.Os, exec exec, shellArgs []string) error {
var dir string
var commands []string
if len(shellArgs) >= 2 {
dir = shellArgs[1]
if _, err := os.Stat(dir); err != nil {
return fmt.Errorf("Provided app direcory does not exist")
}
} else {
dir = filepath.Join(os.Getenv("HOME"), "app")
if _, err := os.Stat(dir); err != nil {
return fmt.Errorf("Could not infer app directory, please provide one")
}
}
if absDir, err := filepath.Abs(dir); err == nil {
dir = absDir
}
argsToParseForFlags := []string{}
if len(shellArgs) >= 3 {
commands = shellArgs[2:]
argsToParseForFlags = shellArgs[3:]
} else {
commands = []string{"bash"}
}
credhubFlags := credhub_flags.NewCredhubFlags("shell")
credhubFlags.Parse(argsToParseForFlags)
attempts := credhubFlags.ConnectAttempts()
delay := credhubFlags.RetryDelay()
if err := env.CalcEnv(os, dir, attempts, delay); err != nil {
return err
}
runtime.GOMAXPROCS(1)
exec.Exec(dir, launcher, shellArgs[0], commands[0], os.Environ())
return nil
}
const launcher = `
cd "$1"
if [ -n "$(ls ../profile.d/* 2> /dev/null)" ]; then
for env_file in ../profile.d/*; do
source $env_file
done
fi
if [ -n "$(ls .profile.d/* 2> /dev/null)" ]; then
for env_file in .profile.d/*; do
source $env_file
done
fi
shift
exec bash -c "$@"
`