Skip to content

[init-hooks] Prevent init hook recursion #1709

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions internal/devbox/devbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ func (d *Devbox) EnvVars(ctx context.Context) ([]string, error) {

func (d *Devbox) shellEnvHashKey() string {
// Don't make this a const so we don't use it by itself accidentally
return "__DEVBOX_SHELLENV_HASH_" + d.projectDirHash()
return "__DEVBOX_SHELLENV_HASH_" + d.ProjectDirHash()
}

func (d *Devbox) Info(ctx context.Context, pkg string, markdown bool) (string, error) {
Expand Down Expand Up @@ -949,7 +949,7 @@ func (d *Devbox) computeEnv(ctx context.Context, usePrintDevEnvCache bool) (map[
devboxEnvPath = envpath.JoinPathLists(devboxEnvPath, runXPaths)

pathStack := envpath.Stack(env, originalEnv)
pathStack.Push(env, d.projectDirHash(), devboxEnvPath, d.preservePathStack)
pathStack.Push(env, d.ProjectDirHash(), devboxEnvPath, d.preservePathStack)
env["PATH"] = pathStack.Path(env)
debug.Log("New path stack is: %s", pathStack)

Expand Down Expand Up @@ -1170,7 +1170,7 @@ func (d *Devbox) setCommonHelperEnvVars(env map[string]string) {
env["LIBRARY_PATH"] = envpath.JoinPathLists(profileLibDir, env["LIBRARY_PATH"])
}

func (d *Devbox) projectDirHash() string {
func (d *Devbox) ProjectDirHash() string {
h, _ := cachehash.Bytes([]byte(d.projectDir))
return h
}
Expand Down
4 changes: 2 additions & 2 deletions internal/devbox/devbox_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func TestComputeDevboxPathIsIdempotent(t *testing.T) {
t.Setenv("PATH", path)
t.Setenv(envpath.InitPathEnv, env[envpath.InitPathEnv])
t.Setenv(envpath.PathStackEnv, env[envpath.PathStackEnv])
t.Setenv(envpath.Key(devbox.projectDirHash()), env[envpath.Key(devbox.projectDirHash())])
t.Setenv(envpath.Key(devbox.ProjectDirHash()), env[envpath.Key(devbox.ProjectDirHash())])

env, err = devbox.computeEnv(ctx, false /*use cache*/)
require.NoError(t, err, "computeEnv should not fail")
Expand All @@ -110,7 +110,7 @@ func TestComputeDevboxPathWhenRemoving(t *testing.T) {
t.Setenv("PATH", path)
t.Setenv(envpath.InitPathEnv, env[envpath.InitPathEnv])
t.Setenv(envpath.PathStackEnv, env[envpath.PathStackEnv])
t.Setenv(envpath.Key(devbox.projectDirHash()), env[envpath.Key(devbox.projectDirHash())])
t.Setenv(envpath.Key(devbox.ProjectDirHash()), env[envpath.Key(devbox.ProjectDirHash())])

devbox.nix.(*testNix).path = ""
env, err = devbox.computeEnv(ctx, false /*use cache*/)
Expand Down
2 changes: 1 addition & 1 deletion internal/devbox/envvars.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,5 +76,5 @@ func (d *Devbox) IsEnvEnabled() bool {
fakeEnv := map[string]string{}
// the Stack is initialized in the fakeEnv, from the state in the real os.Environ
pathStack := envpath.Stack(fakeEnv, envir.PairsToMap(os.Environ()))
return pathStack.Has(d.projectDirHash())
return pathStack.Has(d.ProjectDirHash())
}
2 changes: 1 addition & 1 deletion internal/devbox/refresh.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func (d *Devbox) isRefreshAliasSet() bool {
}

func (d *Devbox) refreshAliasEnvVar() string {
return "DEVBOX_REFRESH_ALIAS_" + d.projectDirHash()
return "DEVBOX_REFRESH_ALIAS_" + d.ProjectDirHash()
}

func (d *Devbox) isGlobal() bool {
Expand Down
25 changes: 21 additions & 4 deletions internal/shellgen/scripts.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import (
"os"
"path/filepath"
"strings"
"text/template"

_ "embed"

"github.com/pkg/errors"
"go.jetpack.io/devbox/internal/boxcli/featureflag"
Expand All @@ -15,6 +18,9 @@ import (
"go.jetpack.io/devbox/internal/plugin"
)

//go:embed tmpl/init-hook.tmpl
var initHookTmpl string

const scriptsDir = ".devbox/gen/scripts"

// HooksFilename is the name of the file that contains the project's init-hooks and plugin hooks
Expand All @@ -27,6 +33,7 @@ type devboxer interface {
InstallablePackages() []*devpkg.Package
PluginManager() *plugin.Manager
ProjectDir() string
ProjectDirHash() string
}

// WriteScriptsToFiles writes scripts defined in devbox.json into files inside .devbox/gen/scripts.
Expand Down Expand Up @@ -55,7 +62,7 @@ func WriteScriptsToFiles(devbox devboxer) error {
}
hooks := strings.Join(append(pluginHooks, devbox.Config().InitHook().String()), "\n\n")
// always write it, even if there are no hooks, because scripts will source it.
err = writeHookFile(devbox, hooks)
err = writeInitHookFile(devbox, hooks)
if err != nil {
return errors.WithStack(err)
}
Expand Down Expand Up @@ -84,15 +91,25 @@ func WriteScriptsToFiles(devbox devboxer) error {
return nil
}

func writeHookFile(devbox devboxer, body string) (err error) {
func writeInitHookFile(devbox devboxer, body string) (err error) {
script, err := createScriptFile(devbox, HooksFilename)
if err != nil {
return errors.WithStack(err)
}
defer script.Close() // best effort: close file

_, err = script.WriteString(body)
return errors.WithStack(err)
t, err := template.New("init-hook-template").Parse(initHookTmpl)
if err != nil {
return errors.WithStack(err)
}

return t.Execute(script, map[string]any{
"Body": body,
"InitHookHash": "__DEVBOX_INIT_HOOK_" + devbox.ProjectDirHash(),
// TODO put IsFish() in common place so we can call here and in devbox package
// without adding more stuff to interface
"IsFish": filepath.Base(os.Getenv("SHELL")) == "fish",
})
}

func WriteScriptFile(devbox devboxer, name, body string) (err error) {
Expand Down
15 changes: 15 additions & 0 deletions internal/shellgen/tmpl/init-hook.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

{{/* if hash is set, we're in recursive loop, just exit */ -}}
if [ -n "${{ .InitHookHash }}" ]; then
return
fi

export {{ .InitHookHash }}=true

{{ .Body }}

{{ if .IsFish }}
set -e {{ .InitHookHash }}
{{ else }}
unset {{ .InitHookHash }}
{{ end }}