-
Notifications
You must be signed in to change notification settings - Fork 264
nix: allow users to set shell startup hooks #93
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
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,184 @@ | ||
// Copyright 2022 Jetpack Technologies Inc and contributors. All rights reserved. | ||
// Use of this source code is governed by the license in the LICENSE file. | ||
|
||
package nix | ||
|
||
import ( | ||
"bytes" | ||
_ "embed" | ||
"fmt" | ||
"os" | ||
"os/exec" | ||
"path/filepath" | ||
"strings" | ||
"text/template" | ||
|
||
"github.com/pkg/errors" | ||
"go.jetpack.io/devbox/debug" | ||
) | ||
|
||
//go:embed shellrc.tmpl | ||
var shellrcText string | ||
var shellrcTmpl = template.Must(template.New("shellrc").Parse(shellrcText)) | ||
|
||
type name string | ||
|
||
const ( | ||
shUnknown name = "" | ||
shBash name = "bash" | ||
shZsh name = "zsh" | ||
shKsh name = "ksh" | ||
shPosix name = "posix" | ||
) | ||
gcurtis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Shell configures a user's shell to run in Devbox. Its zero value is a | ||
// fallback shell that launches a regular Nix shell. | ||
type Shell struct { | ||
name name | ||
binPath string | ||
userShellrcPath string | ||
|
||
// UserInitHook contains commands that will run at shell startup. | ||
UserInitHook string | ||
} | ||
|
||
// DetectShell attempts to determine the user's default shell. | ||
func DetectShell() (*Shell, error) { | ||
path := os.Getenv("SHELL") | ||
if path == "" { | ||
return nil, errors.New("unable to detect the current shell") | ||
} | ||
|
||
sh := &Shell{binPath: filepath.Clean(path)} | ||
base := filepath.Base(path) | ||
// Login shell | ||
if base[0] == '-' { | ||
base = base[1:] | ||
} | ||
switch base { | ||
case "bash": | ||
sh.name = shBash | ||
sh.userShellrcPath = rcfilePath(".bashrc") | ||
case "zsh": | ||
sh.name = shZsh | ||
sh.userShellrcPath = rcfilePath(".zshrc") | ||
case "ksh": | ||
sh.name = shKsh | ||
sh.userShellrcPath = rcfilePath(".kshrc") | ||
case "dash", "ash", "sh": | ||
gcurtis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
sh.name = shPosix | ||
sh.userShellrcPath = os.Getenv("ENV") | ||
|
||
// Just make up a name if there isn't already an init file set | ||
// so we have somewhere to put a new one. | ||
if sh.userShellrcPath == "" { | ||
sh.userShellrcPath = ".shinit" | ||
} | ||
default: | ||
sh.name = shUnknown | ||
} | ||
debug.Log("Detected shell: %s", sh.binPath) | ||
debug.Log("Recognized shell as: %s", sh.binPath) | ||
debug.Log("Looking for user's shell init file at: %s", sh.userShellrcPath) | ||
return sh, nil | ||
} | ||
|
||
// rcfilePath returns the absolute path for an rcfile, which is usually in the | ||
// user's home directory. It doesn't guarantee that the file exists. | ||
func rcfilePath(basename string) string { | ||
home, err := os.UserHomeDir() | ||
if err != nil { | ||
return "" | ||
} | ||
return filepath.Join(home, basename) | ||
} | ||
|
||
func (s *Shell) Run(nixPath string) error { | ||
// Launch a fallback shell if we couldn't find the path to the user's | ||
// default shell. | ||
if s.binPath == "" { | ||
cmd := exec.Command("nix-shell", nixPath) | ||
cmd.Stdin = os.Stdin | ||
cmd.Stdout = os.Stdout | ||
cmd.Stderr = os.Stderr | ||
|
||
debug.Log("Unrecognized user shell, falling back to: %v", cmd.Args) | ||
gcurtis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return errors.WithStack(cmd.Run()) | ||
} | ||
|
||
cmd := exec.Command("nix-shell", nixPath) | ||
cmd.Args = append(cmd.Args, "--pure", "--command", s.execCommand()) | ||
cmd.Stdin = os.Stdin | ||
cmd.Stdout = os.Stdout | ||
cmd.Stderr = os.Stderr | ||
|
||
debug.Log("Executing nix-shell command: %v", cmd.Args) | ||
return errors.WithStack(cmd.Run()) | ||
} | ||
|
||
// execCommand is a command that replaces the current shell with s. | ||
func (s *Shell) execCommand() string { | ||
shellrc, err := writeDevboxShellrc(s.userShellrcPath, s.UserInitHook) | ||
if err != nil { | ||
debug.Log("Failed to write devbox shellrc: %v", err) | ||
return "exec " + s.binPath | ||
} | ||
|
||
switch s.name { | ||
case shBash: | ||
return fmt.Sprintf(`exec /usr/bin/env ORIGINAL_PATH="%s" %s --rcfile "%s"`, | ||
os.Getenv("PATH"), s.binPath, shellrc) | ||
case shZsh: | ||
return fmt.Sprintf(`exec /usr/bin/env ORIGINAL_PATH="%s" ZDOTDIR="%s" %s`, | ||
os.Getenv("PATH"), filepath.Dir(shellrc), s.binPath) | ||
case shKsh, shPosix: | ||
return fmt.Sprintf(`exec /usr/bin/env ORIGINAL_PATH="%s" ENV="%s" %s `, | ||
os.Getenv("PATH"), shellrc, s.binPath) | ||
default: | ||
return "exec " + s.binPath | ||
} | ||
} | ||
|
||
func writeDevboxShellrc(userShellrcPath string, userHook string) (path string, err error) { | ||
// We need a temp dir (as opposed to a temp file) because zsh uses | ||
// ZDOTDIR to point to a new directory containing the .zshrc. | ||
tmp, err := os.MkdirTemp("", "devbox") | ||
if err != nil { | ||
return "", fmt.Errorf("create temp dir for shell init file: %v", err) | ||
} | ||
|
||
// This is a best-effort to include the user's existing shellrc. If we | ||
// can't read it, then just omit it from the devbox shellrc. | ||
userShellrc, err := os.ReadFile(userShellrcPath) | ||
if err != nil { | ||
userShellrc = []byte{} | ||
} | ||
|
||
path = filepath.Join(tmp, filepath.Base(userShellrcPath)) | ||
shellrcf, err := os.Create(path) | ||
if err != nil { | ||
return "", fmt.Errorf("write to shell init file: %v", err) | ||
} | ||
defer func() { | ||
cerr := shellrcf.Close() | ||
if err == nil { | ||
err = cerr | ||
} | ||
}() | ||
|
||
err = shellrcTmpl.Execute(shellrcf, struct { | ||
OriginalInit string | ||
OriginalInitPath string | ||
UserHook string | ||
}{ | ||
OriginalInit: string(bytes.TrimSpace(userShellrc)), | ||
OriginalInitPath: filepath.Clean(userShellrcPath), | ||
UserHook: strings.TrimSpace(userHook), | ||
}) | ||
if err != nil { | ||
return "", fmt.Errorf("execute shellrc template: %v", err) | ||
} | ||
|
||
debug.Log("Wrote devbox shellrc to: %s", path) | ||
return path, nil | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
{{- /* | ||
|
||
// This template defines the shellrc file that the devbox shell will run at | ||
// startup. | ||
// | ||
// It includes the user's original shellrc, which varies depending on their | ||
// shell. It will either be ~/.bashrc, ~/.zshrc, a path set in ENV, or something | ||
// else. It also appends any user-defined shell hooks from devbox.json. | ||
// | ||
// Devbox also needs to ensure that the shell's PATH, prompt, and a few other | ||
// things are set correctly at startup. To do this, it must run some commands | ||
// before and after the user's shellrc. These commands are in the | ||
// "Devbox Pre/Post-init Hook" sections. | ||
// | ||
// The devbox pre/post-init hooks assume two environment variables are already | ||
// set: | ||
// | ||
// - ORIGINAL_PATH - embedded into the command built by Shell.execCommand. It | ||
// preserves the PATH at the time `devbox shell` is invoked. | ||
// - PURE_NIX_PATH - set by the shell hook in shell.nix.tmpl. It preserves the | ||
// PATH set by Nix's "pure" shell mode. | ||
|
||
*/ -}} | ||
|
||
# Begin Devbox Pre-init Hook | ||
|
||
# Update the $PATH so that the user's init script has access to all of their | ||
# non-devbox programs. | ||
export PATH="$PURE_NIX_PATH:$ORIGINAL_PATH" | ||
|
||
# End Devbox Pre-init Hook | ||
|
||
{{- if .OriginalInit }} | ||
|
||
# Begin {{ .OriginalInitPath }} | ||
|
||
{{ .OriginalInit }} | ||
|
||
# End {{ .OriginalInitPath }} | ||
|
||
{{- end }} | ||
|
||
# Begin Devbox Post-init Hook | ||
|
||
# Update the $PATH again so that the Nix packages take priority over the | ||
# programs outside of devbox. | ||
export PATH="$PURE_NIX_PATH:$ORIGINAL_PATH" | ||
|
||
# Prepend to the prompt to make it clear we're in a devbox shell. | ||
export PS1="(devbox) $PS1" | ||
|
||
# End Devbox Post-init Hook | ||
|
||
{{- if .UserHook }} | ||
|
||
# Begin Devbox User Hook | ||
|
||
{{ .UserHook }} | ||
|
||
# End Devbox User Hook | ||
|
||
{{- end }} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.