Skip to content

Commit

Permalink
feat: add environ format
Browse files Browse the repository at this point in the history
Adds a `direnv export environ` command that outputs the diff in
`<key>(=<value)?\0` format. It's a simple format that is quite close to
/proc/<pid>/environ on Linux. Each line is NUL-terminated. If the `=` is
not present on a line, consider that the <key> should be unset.

The idea was to find a format that could eventually replace the evals in
the hooks in the various shells.
  • Loading branch information
zimbatm committed Jul 26, 2022
1 parent ad34d39 commit 31e87f6
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
2 changes: 2 additions & 0 deletions internal/cmd/shell.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ func DetectShell(target string) Shell {
return Bash
case "elvish":
return Elvish
case "environ":
return Environ
case "fish":
return Fish
case "gha":
Expand Down
51 changes: 51 additions & 0 deletions internal/cmd/shell_environ.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package cmd

import (
"errors"
)

// environShell is not a real shell
type environShell struct{}

// Environ is a format exporter and not a shell. It implements a similar
// format as /proc/<pid>/environ in Linux.
var Environ Shell = environShell{}

func (sh environShell) Hook() (string, error) {
return "", errors.New("this feature is not supported")
}

// Exports emits a string composed of <key>(=<value>), separated by \0.
//
// It's the same as the Dump format with one additional case: if there is no =
// in the line, the environment variable should be unset.
func (sh environShell) 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
}

// Dump emits a string composed of <key>=<value, separated by \0. That
// format is the same as you would find in /prod/<pid>/environ and works with
// values that include special characters like \n.
func (sh environShell) Dump(env Env) (out string) {
for key, value := range env {
out += sh.export(key, value)
}
return out
}

// <key>=<value> , terminated by \0
func (sh environShell) export(key, value string) string {
return key + "=" + value + string([]byte{0})
}

// <key> , terminated by \0
func (sh environShell) unset(key string) string {
return key + string([]byte{0})
}

0 comments on commit 31e87f6

Please sign in to comment.