cmd

package
v2.23.1-0...-8ac0e49 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 15, 2023 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DIRENV_CONFIG = "DIRENV_CONFIG"
	DIRENV_BASH   = "DIRENV_BASH"
	DIRENV_DEBUG  = "DIRENV_DEBUG"

	DIRENV_DIR     = "DIRENV_DIR"
	DIRENV_FILE    = "DIRENV_FILE"
	DIRENV_WATCHES = "DIRENV_WATCHES"
	DIRENV_DIFF    = "DIRENV_DIFF"

	DIRENV_DUMP_FILE_PATH = "DIRENV_DUMP_FILE_PATH"
)

nolint

View Source
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
)

nolint

Variables

View Source
var CmdAllow = &Cmd{
	Name:    "allow",
	Desc:    "Grants direnv permission to load the given .envrc or .env file.",
	Args:    []string{"[PATH_TO_RC]"},
	Aliases: []string{"permit", "grant"},
	Action:  actionWithConfig(cmdAllowAction),
}

CmdAllow is `direnv allow [PATH_TO_RC]`

View Source
var CmdApplyDump = &Cmd{
	Name:    "apply_dump",
	Desc:    "Accepts a filename containing `direnv dump` output and generates a series of bash export statements to apply the given env",
	Args:    []string{"FILE"},
	Private: true,
	Action:  actionSimple(cmdApplyDumpAction),
}

CmdApplyDump is `direnv apply_dump FILE`

View Source
var CmdCurrent = &Cmd{
	Name:    "current",
	Desc:    "Reports whether direnv's view of a file is current (or stale)",
	Args:    []string{"PATH"},
	Private: true,
	Action:  actionSimple(cmdCurrentAction),
}

CmdCurrent is `direnv current`

View Source
var CmdDeny = &Cmd{
	Name:    "block",
	Desc:    "Revokes the authorization of a given .envrc or .env file.",
	Args:    []string{"[PATH_TO_RC]"},
	Aliases: []string{"deny", "revoke"},
	Action:  actionWithConfig(cmdDenyAction),
}

CmdDeny is `direnv deny [PATH_TO_RC]`

View Source
var CmdDotEnv = &Cmd{
	Name:    "dotenv",
	Desc:    "Transforms a .env file to evaluatable `export KEY=PAIR` statements",
	Args:    []string{"[SHELL]", "[PATH_TO_DOTENV]"},
	Private: true,
	Action:  actionSimple(cmdDotEnvAction),
}

CmdDotEnv is `direnv dotenv [SHELL [PATH_TO_DOTENV]]` Transforms a .env file to evaluatable `export KEY=PAIR` statements.

See: https://github.com/bkeepers/dotenv and https://github.com/ddollar/foreman

View Source
var CmdDump = &Cmd{
	Name:    "dump",
	Desc:    "Used to export the inner bash state at the end of execution",
	Args:    []string{"[SHELL]", "[FILE]"},
	Private: true,
	Action:  actionSimple(cmdDumpAction),
}

CmdDump is `direnv dump`

View Source
var CmdEdit = &Cmd{
	Name: "edit",
	Desc: `Opens PATH_TO_RC or the current .envrc or .env into an $EDITOR and allow
  the file to be loaded afterwards.`,
	Args:   []string{"[PATH_TO_RC]"},
	Action: actionWithConfig(cmdEditAction),
}

CmdEdit is `direnv edit [PATH_TO_RC]`

View Source
var CmdExec = &Cmd{
	Name:   "exec",
	Desc:   "Executes a command after loading the first .envrc or .env found in DIR",
	Args:   []string{"DIR", "COMMAND", "[...ARGS]"},
	Action: actionWithConfig(cmdExecAction),
}

CmdExec is `direnv exec DIR <COMMAND> ...`

View Source
var CmdExport = &Cmd{
	Name:    "export",
	Desc:    "loads an .envrc or .env and prints the diff in terms of exports",
	Args:    []string{"SHELL"},
	Private: true,
	Action:  cmdWithWarnTimeout(actionWithConfig(exportCommand)),
}

CmdExport is `direnv export $0`

View Source
var CmdFetchURL = &Cmd{
	Name:   "fetchurl",
	Desc:   "Fetches a given URL into direnv's CAS",
	Args:   []string{"<url>", "[<integrity-hash>]"},
	Action: actionWithConfig(cmdFetchURL),
}

CmdFetchURL is `direnv fetchurl <url> [<integrity-hash>]`

View Source
var CmdHelp = &Cmd{
	Name:    "help",
	Desc:    "shows this help",
	Args:    []string{"[SHOW_PRIVATE]"},
	Aliases: []string{"--help"},
	Action: actionSimple(func(env Env, args []string) (err error) {
		var showPrivate = len(args) > 1
		fmt.Printf(`direnv v%s
Usage: direnv COMMAND [...ARGS]

Available commands
------------------
`, version)
		for _, cmd := range CmdList {
			var opts string
			if len(cmd.Args) > 0 {
				opts = " " + strings.Join(cmd.Args, " ")
			}
			if cmd.Private {
				if showPrivate {
					fmt.Printf("*%s%s:\n  %s\n", cmd.Name, opts, cmd.Desc)
				}
			} else {
				fmt.Printf("%s%s:\n", cmd.Name, opts)
				for _, alias := range cmd.Aliases {
					if alias[0:1] != "-" {
						fmt.Printf("%s%s:\n", alias, opts)
					}
				}
				fmt.Printf("  %s\n", cmd.Desc)
			}
		}

		if showPrivate {
			fmt.Println("* = private commands")
		}
		return
	}),
}

CmdHelp is `direnv help`

View Source
var CmdHook = &Cmd{
	Name:   "hook",
	Desc:   "Used to setup the shell hook",
	Args:   []string{"SHELL"},
	Action: actionSimple(cmdHookAction),
}

CmdHook is `direnv hook $0`

View Source
var CmdList []*Cmd

CmdList contains the list of all direnv sub-commands

View Source
var CmdPrune = &Cmd{
	Name:   "prune",
	Desc:   "removes old allowed files",
	Action: actionWithConfig(cmdPruneAction),
}

CmdPrune is `direnv prune`

View Source
var CmdReload = &Cmd{
	Name: "reload",
	Desc: "triggers an env reload",
	Action: actionWithConfig(func(env Env, args []string, config *Config) error {
		foundRC, err := config.FindRC()
		if err != nil {
			return err
		}
		if foundRC == nil {
			return fmt.Errorf(".envrc not found")
		}

		return foundRC.Touch()
	}),
}

CmdReload is `direnv reload`

View Source
var CmdShowDump = &Cmd{
	Name:    "show_dump",
	Desc:    "Show the data inside of a dump for debugging purposes",
	Args:    []string{"DUMP"},
	Private: true,
	Action:  actionSimple(cmdShowDumpAction),
}

CmdShowDump is `direnv show_dump`

View Source
var CmdStatus = &Cmd{
	Name: "status",
	Desc: "prints some debug status information",
	Action: actionWithConfig(func(env Env, args []string, config *Config) error {
		fmt.Println("direnv exec path", config.SelfPath)
		fmt.Println("DIRENV_CONFIG", config.ConfDir)

		fmt.Println("bash_path", config.BashPath)
		fmt.Println("disable_stdin", config.DisableStdin)
		fmt.Println("warn_timeout", config.WarnTimeout)
		fmt.Println("whitelist.prefix", config.WhitelistPrefix)
		fmt.Println("whitelist.exact", config.WhitelistExact)

		loadedRC := config.LoadedRC()
		foundRC, err := config.FindRC()
		if err != nil {
			return err
		}

		if loadedRC != nil {
			formatRC("Loaded", loadedRC)
		} else {
			fmt.Println("No .envrc or .env loaded")
		}

		if foundRC != nil {
			formatRC("Found", foundRC)
		} else {
			fmt.Println("No .envrc or .env found")
		}

		return nil
	}),
}

CmdStatus is `direnv status`

View Source
var CmdStdlib = &Cmd{
	Name: "stdlib",
	Desc: "Displays the stdlib available in the .envrc execution context",
	Action: actionWithConfig(func(env Env, args []string, config *Config) error {
		fmt.Println(getStdlib(config))
		return nil
	}),
}

CmdStdlib is `direnv stdlib`

View Source
var CmdVersion = &Cmd{
	Name:    "version",
	Desc:    "prints the version or checks that direnv is older than VERSION_AT_LEAST.",
	Args:    []string{"[VERSION_AT_LEAST]"},
	Aliases: []string{"--version"},
	Action: actionSimple(func(env Env, args []string) error {
		semVersion := ensureVPrefixed(version)
		if len(args) > 1 {
			atLeast := ensureVPrefixed(args[1])
			if !semver.IsValid(atLeast) {
				return fmt.Errorf("%s is not a valid semver version", atLeast)
			}
			cmp := semver.Compare(semVersion, atLeast)
			if cmp < 0 {
				return fmt.Errorf("current version %s is older than the desired version %s", semVersion, atLeast)
			}
		} else {
			fmt.Println(version)
		}
		return nil
	}),
}

CmdVersion is `direnv version`

View Source
var CmdWatch = &Cmd{
	Name:    "watch",
	Desc:    "Adds a path to the list that direnv watches for changes",
	Args:    []string{"SHELL", "PATH..."},
	Private: true,
	Action:  actionSimple(cmdWatchAction),
}

CmdWatch is `direnv watch SHELL [PATH...]`

View Source
var CmdWatchDir = &Cmd{
	Name:    "watch-dir",
	Desc:    "Recursively adds a directory to the list that direnv watches for changes",
	Args:    []string{"SHELL", "DIR"},
	Private: true,
	Action:  actionSimple(watchDirCommand),
}

CmdWatchDir is `direnv watch-dir SHELL PATH`

View Source
var CmdWatchList = &Cmd{
	Name:    "watch-list",
	Desc:    "Pipe pairs of `mtime path` to stdin to build a list of files to watch.",
	Args:    []string{"[SHELL]"},
	Private: true,
	Action:  actionSimple(watchListCommand),
}

CmdWatchList is `direnv watch-list`

View Source
var Editors = [][]string{
	{"subl", "-w"},
	{"mate", "-w"},
	{"open", "-t", "-W"},
	{"nano"},
	{"vim"},
	{"emacs"},
}

Editors contains a list of known editors and how to start them.

View Source
var IgnoredKeys = map[string]bool{

	"DIRENV_CONFIG": true,
	"DIRENV_BASH":   true,

	"DIRENV_IN_ENVRC": true,

	"COMP_WORDBREAKS": true,
	"PS1":             true,

	"OLDPWD":    true,
	"PWD":       true,
	"SHELL":     true,
	"SHELLOPTS": true,
	"SHLVL":     true,
	"_":         true,
}

IgnoredKeys is list of keys we don't want to deal with

Functions

func BashEscape

func BashEscape(str string) string

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 CommandsDispatch

func CommandsDispatch(env Env, args []string) error

CommandsDispatch is called by the main() function to dispatch to a sub-command

func IgnoredEnv

func IgnoredEnv(key string) bool

IgnoredEnv returns true if the key should be ignored in environment diffs.

func Main

func Main(env Env, args []string, modBashPath string, modStdlib string, modVersion string) error

Main is the main entrypoint to direnv

Types

type Cmd

type Cmd struct {
	Name    string
	Desc    string
	Args    []string
	Aliases []string
	Private bool
	Action  action
}

Cmd represents a direnv sub-command

type Config

type Config struct {
	Env             Env
	WorkDir         string // Current directory
	ConfDir         string
	CacheDir        string
	DataDir         string
	SelfPath        string
	BashPath        string
	RCFile          string
	TomlPath        string
	DisableStdin    bool
	StrictEnv       bool
	LoadDotenv      bool
	WarnTimeout     time.Duration
	WhitelistPrefix []string
	WhitelistExact  map[string]bool
}

Config represents the direnv configuration and state.

func LoadConfig

func LoadConfig(env Env) (config *Config, err error)

LoadConfig opens up the direnv configuration from the Env.

func (*Config) AllowDir

func (config *Config) AllowDir() string

AllowDir is the folder where all the "allow" files are stored.

func (*Config) EnvFromRC

func (config *Config) EnvFromRC(path string, previousEnv Env) (Env, error)

EnvFromRC loads an RC from a specified path and returns the new environment

func (*Config) FindRC

func (config *Config) FindRC() (*RC, error)

FindRC looks for a RC file in the config environment

func (*Config) LoadedRC

func (config *Config) LoadedRC() *RC

LoadedRC returns a RC file if any has been loaded

func (*Config) Revert

func (config *Config) Revert(env Env) (Env, error)

Revert undoes the recorded changes (if any) to the supplied environment, returning a new environment

type Env

type Env map[string]string

Env is a map representation of environment variables.

func GetEnv

func GetEnv() Env

GetEnv turns the classic unix environment variables into a map of key->values which is more handy to work with.

NOTE: We don't support having two variables with the same name. I've never seen it used in the wild but according to POSIX it's allowed.

func LoadEnv

func LoadEnv(gzenvStr string) (env Env, err error)

LoadEnv unmarshals the env back from a gzenv string

func LoadEnvJSON

func LoadEnvJSON(jsonBytes []byte) (env Env, err error)

LoadEnvJSON unmarshals the env back from a JSON string

func (Env) CleanContext

func (env Env) CleanContext()

CleanContext removes all the direnv-related environment variables. Call this after reverting the environment, otherwise direnv will just be amnesic about the previously-loaded environment.

func (Env) Copy

func (env Env) Copy() Env

Copy returns a fresh copy of the env. Because the env is a map under the hood, we want to get a copy whenever we mutate it and want to keep the original around.

func (Env) Diff

func (env Env) Diff(other Env) *EnvDiff

Diff returns the diff between the current env and the passed env

func (Env) Fetch

func (env Env) Fetch(key, def string) string

Fetch tries to get the value associated with the given 'key', or returns the provided default if none is set.

Note that empty environment variables are considered to be set.

func (Env) Serialize

func (env Env) Serialize() string

Serialize marshals the env into the gzenv format

func (Env) ToGoEnv

func (env Env) ToGoEnv() []string

ToGoEnv should really be named ToUnixEnv. It turns the env back into a list of "key=value" strings like returns by os.Environ().

func (Env) ToShell

func (env Env) ToShell(shell Shell) string

ToShell outputs the environment into an evaluatable string that is understood by the target shell

type EnvDiff

type EnvDiff struct {
	Prev map[string]string `json:"p"`
	Next map[string]string `json:"n"`
}

EnvDiff represents the diff between two environments

func BuildEnvDiff

func BuildEnvDiff(e1, e2 Env) *EnvDiff

BuildEnvDiff analyses the changes between 'e1' and 'e2' and builds an EnvDiff out of it.

func LoadEnvDiff

func LoadEnvDiff(gzenvStr string) (diff *EnvDiff, err error)

LoadEnvDiff unmarshalls a gzenv string back into an EnvDiff.

func NewEnvDiff

func NewEnvDiff() *EnvDiff

NewEnvDiff is an empty constructor for EnvDiff

func (*EnvDiff) Any

func (diff *EnvDiff) Any() bool

Any returns if the diff contains any changes.

func (*EnvDiff) Patch

func (diff *EnvDiff) Patch(env Env) (newEnv Env)

Patch applies the diff to the given env and returns a new env with the changes applied.

func (*EnvDiff) Reverse

func (diff *EnvDiff) Reverse() *EnvDiff

Reverse flips the diff so that it applies the other way around.

func (*EnvDiff) Serialize

func (diff *EnvDiff) Serialize() string

Serialize marshalls the environment diff to the gzenv format.

func (*EnvDiff) ToShell

func (diff *EnvDiff) ToShell(shell Shell) string

ToShell applies the env diff as a set of commands that are understood by the target `shell`. The outputted string is then meant to be evaluated in the target shell.

type FileTime

type FileTime struct {
	Path    string `json:"path"`
	Modtime int64  `json:"modtime"`
	Exists  bool   `json:"exists"`
}

FileTime represents a single recorded file status

func (FileTime) Check

func (times FileTime) Check() (err error)

Check verifies that the file is good and hasn't changed

func (*FileTime) Formatted

func (times *FileTime) Formatted(relDir string) string

Formatted shows the times in a user-friendly format.

type FileTimes

type FileTimes struct {
	// contains filtered or unexported fields
}

FileTimes represent a record of all the known files and times

func NewFileTimes

func NewFileTimes() (times FileTimes)

NewFileTimes creates a new empty FileTimes

func (*FileTimes) Check

func (times *FileTimes) Check() (err error)

Check validates all the recorded file times

func (*FileTimes) CheckOne

func (times *FileTimes) CheckOne(path string) (err error)

CheckOne compares notes between the given path and the recorded times

func (*FileTimes) Marshal

func (times *FileTimes) Marshal() string

Marshal dumps the times into gzenv format

func (*FileTimes) NewTime

func (times *FileTimes) NewTime(path string, modtime int64, exists bool) (err error)

NewTime add the file on path, with modtime and exists flag to the list of known files.

func (*FileTimes) Unmarshal

func (times *FileTimes) Unmarshal(from string) error

Unmarshal loads the watches back from gzenv

func (*FileTimes) Update

func (times *FileTimes) Update(path string) (err error)

Update gets the latest stats on the path and updates the record.

type HookContext

type HookContext struct {
	// SelfPath is the unescaped absolute path to direnv
	SelfPath string
}

HookContext are the variables available during hook template evaluation

type RC

type RC struct {
	// contains filtered or unexported fields
}

RC represents the .envrc or .env file

func FindRC

func FindRC(wd string, config *Config) (*RC, error)

FindRC looks for ".envrc" and ".env" files up in the file hierarchy.

func RCFromEnv

func RCFromEnv(path, marshalledTimes string, config *Config) *RC

RCFromEnv inits the RC from the environment

func RCFromPath

func RCFromPath(path string, config *Config) (*RC, error)

RCFromPath inits the RC from a given path

func (*RC) Allow

func (rc *RC) Allow() (err error)

Allow grants the RC as allowed to load

func (*RC) Allowed

func (rc *RC) Allowed() bool

Allowed checks if the RC file has been granted loading

func (*RC) Deny

func (rc *RC) Deny() error

Deny revokes the permission of the RC file to load

func (*RC) Load

func (rc *RC) Load(previousEnv Env) (newEnv Env, err error)

Load evaluates the RC file and returns the new Env or error.

This functions is key to the implementation of direnv.

func (*RC) Path

func (rc *RC) Path() string

Path returns the path to the RC file

func (*RC) Touch

func (rc *RC) Touch() error

Touch updates the mtime of the RC file. This is mainly used to trigger a reload in direnv.

type Shell

type Shell interface {
	// Hook is the string that gets evaluated into the host shell config and
	// setups direnv as a prompt hook.
	Hook() (string, error)

	// Export outputs the ShellExport as an evaluatable string on the host shell
	Export(e ShellExport) string

	// Dump outputs and evaluatable string that sets the env in the host shell
	Dump(env Env) string
}

Shell is the interface that represents the interaction with the host shell.

var Bash Shell = bash{}

Bash shell instance

var Elvish Shell = elvish{}

Elvish add support for the elvish shell

var Fish Shell = fish{}

Fish adds support for the fish shell as a host

var GitHubActions Shell = gha{}

GitHubActions shell instance

var GzEnv Shell = gzenvShell(0)

GzEnv is not a real shell. used for internal purposes.

var JSON Shell = jsonShell{}

JSON is not really a shell but it fits. Useful to add support to editor and other external tools that understand JSON as a format.

var Tcsh Shell = tcsh{}

Tcsh adds support for the tickle shell

var Vim Shell = vim{}

Vim adds support for vim. Not really a shell but it's handly.

var Zsh Shell = zsh{}

Zsh adds support for the venerable Z shell.

func DetectShell

func DetectShell(target string) Shell

DetectShell returns a Shell instance from the given target.

target is usually $0 and can also be prefixed by `-`

type ShellExport

type ShellExport map[string]*string

ShellExport represents environment variables to add and remove on the host shell.

func (ShellExport) Add

func (e ShellExport) Add(key, value string)

Add represents the addition of a new environment variable

func (ShellExport) Remove

func (e ShellExport) Remove(key string)

Remove represents the removal of a given `key` environment variable.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL