Skip to content

[direnv] copy bash, fish, zsh shell code from direnv #1156

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
Jun 26, 2023
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
8 changes: 8 additions & 0 deletions internal/shenv/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Code in this directory was copy-pasted from the direnv codebase:
https://github.com/direnv/direnv/blob/master/internal/cmd/

We could not directly import this code because in the direnv
code it is inside an `internal` directory, and hence not
exported.

Full credit to the direnv authors.
181 changes: 181 additions & 0 deletions internal/shenv/shell_bash.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
package shenv

import "fmt"

type bash struct{}

// Bash shell instance
var Bash Shell = bash{}

const bashHook = `
_devbox_hook() {
local previous_exit_status=$?;
trap -- '' SIGINT;
eval "$(devbox shellenv --config {{ .ProjectDir }})";
trap - SIGINT;
return $previous_exit_status;
};
if ! [[ "${PROMPT_COMMAND:-}" =~ _devbox_hook ]]; then
PROMPT_COMMAND="_devbox_hook${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
fi
`

func (sh bash) Hook() (string, error) {
return bashHook, nil
}

func (sh bash) Export(e ShellExport) (out string) {
for key, value := range e {
if value == nil {
out += sh.unset(key)
} else {
out += sh.export(key, *value)
}
}
return out
}

func (sh bash) Dump(env Env) (out string) {
for key, value := range env {
out += sh.export(key, value)
}
return out
}

func (sh bash) export(key, value string) string {
return "export " + sh.escape(key) + "=" + sh.escape(value) + ";"
}

func (sh bash) unset(key string) string {
return "unset " + sh.escape(key) + ";"
}

func (sh bash) escape(str string) string {
return BashEscape(str)
}

/*
* Escaping
*/

// nolint
const (
ACK = 6
TAB = 9
LF = 10
CR = 13
US = 31
SPACE = 32
AMPERSTAND = 38
SINGLE_QUOTE = 39
PLUS = 43
NINE = 57
QUESTION = 63
UPPERCASE_Z = 90
OPEN_BRACKET = 91
BACKSLASH = 92
UNDERSCORE = 95
CLOSE_BRACKET = 93
BACKTICK = 96
LOWERCASE_Z = 122
TILDA = 126
DEL = 127
)

// https://github.com/solidsnack/shell-escape/blob/master/Text/ShellEscape/Bash.hs
/*
A Bash escaped string. The strings are wrapped in @$\'...\'@ if any
bytes within them must be escaped; otherwise, they are left as is.
Newlines and other control characters are represented as ANSI escape
sequences. High bytes are represented as hex codes. Thus Bash escaped
strings will always fit on one line and never contain non-ASCII bytes.
*/
func BashEscape(str string) string {
if str == "" {
return "''"
}
// var too short
//nolint:varnamelen
in := []byte(str)
out := ""
i := 0
// var too short
//nolint:varnamelen
l := len(in)
escape := false

hex := func(char byte) {
escape = true
out += fmt.Sprintf("\\x%02x", char)
}

backslash := func(char byte) {
escape = true
out += string([]byte{BACKSLASH, char})
}

escaped := func(str string) {
escape = true
out += str
}

quoted := func(char byte) {
escape = true
out += string([]byte{char})
}

literal := func(char byte) {
out += string([]byte{char})
}

for i < l {
char := in[i]
switch {
case char == ACK:
hex(char)
case char == TAB:
escaped(`\t`)
case char == LF:
escaped(`\n`)
case char == CR:
escaped(`\r`)
case char <= US:
hex(char)
case char <= AMPERSTAND:
quoted(char)
case char == SINGLE_QUOTE:
backslash(char)
case char <= PLUS:
quoted(char)
case char <= NINE:
literal(char)
case char <= QUESTION:
quoted(char)
case char <= UPPERCASE_Z:
literal(char)
case char == OPEN_BRACKET:
quoted(char)
case char == BACKSLASH:
backslash(char)
case char == UNDERSCORE:
literal(char)
case char <= CLOSE_BRACKET:
quoted(char)
case char <= BACKTICK:
quoted(char)
case char <= TILDA:
quoted(char)
case char == DEL:
hex(char)
default:
hex(char)
}
i++
}

if escape {
out = "$'" + out + "'"
}

return out
}
110 changes: 110 additions & 0 deletions internal/shenv/shell_fish.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package shenv

import (
"fmt"
"strings"
)

type fish struct{}

// Fish adds support for the fish shell as a host
var Fish Shell = fish{}

const fishHook = `
function __devbox_shellenv_eval --on-event fish_prompt;
devbox shellenv --config {{ .ProjectDir }} | source;
end;
`

func (sh fish) Hook() (string, error) {
return fishHook, nil
}

func (sh fish) Export(e ShellExport) (out string) {
for key, value := range e {
if value == nil {
out += sh.unset(key)
} else {
out += sh.export(key, *value)
}
}
return out
}

func (sh fish) Dump(env Env) (out string) {
for key, value := range env {
out += sh.export(key, value)
}
return out
}

func (sh fish) export(key, value string) string {
if key == "PATH" {
command := "set -x -g PATH"
for _, path := range strings.Split(value, ":") {
command += " " + sh.escape(path)
}
return command + ";"
}
return "set -x -g " + sh.escape(key) + " " + sh.escape(value) + ";"
}

func (sh fish) unset(key string) string {
return "set -e -g " + sh.escape(key) + ";"
}

func (sh fish) escape(str string) string {
// var too short
//nolint:varnamelen
in := []byte(str)
out := "'"
i := 0
// var too short
//nolint:varnamelen
l := len(in)

hex := func(char byte) {
out += fmt.Sprintf("'\\X%02x'", char)
}

backslash := func(char byte) {
out += string([]byte{BACKSLASH, char})
}

escaped := func(str string) {
out += "'" + str + "'"
}

literal := func(char byte) {
out += string([]byte{char})
}

for i < l {
char := in[i]
switch {
case char == TAB:
escaped(`\t`)
case char == LF:
escaped(`\n`)
case char == CR:
escaped(`\r`)
case char <= US:
hex(char)
case char == SINGLE_QUOTE:
backslash(char)
case char == BACKSLASH:
backslash(char)
case char <= TILDA:
literal(char)
case char == DEL:
hex(char)
default:
hex(char)
}
i++
}

out += "'"

return out
}
30 changes: 30 additions & 0 deletions internal/shenv/shell_ksh.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package shenv

type ksh struct{}

// Ksh adds support the korn shell
var Ksh Shell = ksh{}

// um, this is ChatGPT writing it. I need to verify and test
const kshHook = `
_devbox_hook() {
eval "$(devbox shellenv --config {{ .ProjectDir }})";
}
if [[ "$(typeset -f precmd)" != *"_devbox_hook"* ]]; then
function precmd {
devbox_hook
}
fi
`

func (sh ksh) Hook() (string, error) {
return kshHook, nil
}

func (sh ksh) Export(e ShellExport) (out string) {
panic("not implemented")
}

func (sh ksh) Dump(env Env) (out string) {
panic("not implemented")
}
34 changes: 34 additions & 0 deletions internal/shenv/shell_posix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package shenv

type posix struct{}

// Posix adds support for posix-compatible shells
// Specifically, in the context of devbox, this includes
// `dash`, `ash`, and `shell`
var Posix Shell = posix{}

// um, this is ChatGPT writing it. I need to verify and test
const posixHook = `
_devbox_hook() {
local previous_exit_status=$?
trap : INT
eval "$(devbox shellenv --config {{ .ProjectDir }})"
trap - INT
return $previous_exit_status
}
if [ -z "$PROMPT_COMMAND" ] || ! printf "%s" "$PROMPT_COMMAND" | grep -q "_devbox_hook"; then
PROMPT_COMMAND="_devbox_hook${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
fi
`

func (sh posix) Hook() (string, error) {
return posixHook, nil
}

func (sh posix) Export(e ShellExport) (out string) {
panic("not implemented")
}

func (sh posix) Dump(env Env) (out string) {
panic("not implemented")
}
24 changes: 24 additions & 0 deletions internal/shenv/shell_unknown.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package shenv

type unknown struct{}

// UnknownSh adds support the unknown shell. This serves
// as a fallback alternative to outright failure.
var UnknownSh Shell = unknown{}

const unknownHook = `
echo "Warning: this shell will not update its environment.
Please exit and re-enter shell after making any changes that may affect the devbox generated environment.\n"
`

func (sh unknown) Hook() (string, error) {
return unknownHook, nil
}

func (sh unknown) Export(e ShellExport) (out string) {
panic("not implemented")
}

func (sh unknown) Dump(env Env) (out string) {
panic("not implemented")
}
Loading