pax_global_header00006660000000000000000000000064132441047470014520gustar00rootroot0000000000000052 comment=6de2eafa575296b37dbf6a2d2126e3aa0cf72c10 direnv-2.15.0/000077500000000000000000000000001324410474700130745ustar00rootroot00000000000000direnv-2.15.0/.github/000077500000000000000000000000001324410474700144345ustar00rootroot00000000000000direnv-2.15.0/.github/ISSUE_TEMPLATE.md000066400000000000000000000003011324410474700171330ustar00rootroot00000000000000## Issue description ### Steps to reproduce ## Technical details * `direnv version`: * OS release: (eg: Ubuntu 16.04) direnv-2.15.0/.gitignore000066400000000000000000000001251324410474700150620ustar00rootroot00000000000000.direnv /direnv /direnv.test /dist /site /test/allow /test/config/direnv/allow *.sw? direnv-2.15.0/.nojekyll000066400000000000000000000000001324410474700147120ustar00rootroot00000000000000direnv-2.15.0/.travis.yml000066400000000000000000000016311324410474700152060ustar00rootroot00000000000000language: go go: - 1.5.x - 1.6.x - 1.7.x - 1.8.x sudo: false script: make test branches: except: - gh-pages before_deploy: - PATH="$HOME/gopath/bin:$PATH" make dist deploy: provider: releases api_key: secure: aIw9Rt8yY8hQu+KFqgESP1v228sX709zTjWIA+mWW1NG5O6m99pjB8UDhar1SBtwZ8ovf/pYfvox4MFEzTsP3cJ9YKrK2HlodZZy46l7qaCpplhd+GIY7JOJlWgeUK5smgaVq60ITvTGoJtcLLX+TedkfaKfQsehIg6Sob4WhQ8= file: - dist/direnv.darwin-386 - dist/direnv.darwin-amd64 - dist/direnv.freebsd-386 - dist/direnv.freebsd-amd64 - dist/direnv.freebsd-arm - dist/direnv.linux-386 - dist/direnv.linux-amd64 - dist/direnv.linux-arm - dist/direnv.netbsd-386 - dist/direnv.netbsd-amd64 - dist/direnv.netbsd-arm - dist/direnv.openbsd-386 - dist/direnv.openbsd-amd64 - dist/direnv.windows-386.exe - dist/direnv.windows-amd64.exe skip_cleanup: true on: tags: true condition: $TRAVIS_GO_VERSION =~ ^1\.8\..*$ direnv-2.15.0/CHANGELOG.md000066400000000000000000000211441324410474700147070ustar00rootroot00000000000000 2.15.0 / 2018-02-23 ================== * NEW: TOML configuration file! (#332, #337) * NEW: support for allow folder whitelist (#332) * NEW: add anaconda support (#312) * CHANGE: use_nix: unset IN_NIX_SHELL 2.14.0 / 2017-12-13 ================== * NEW: Add support for Pipenv layout (#314) * CHANGE: direnv version: make public * FIX: direnv edit: run the command through bash * FIX: website: update ditto to v0.15 2.13.3 / 2017-11-30 ================== * FIX: fixes dotenv loading issue on macOS `''=''` 2.13.2 / 2017-11-28 ================== * FIX: direnv edit: fix path escaping * FIX: stdlib: fix find_up * FIX: stdlib: use absolute path in source_up * FIX: remove ruby as a build dependency * FIX: go-dotenv: update to latest master to fix a parsing error 2.13.1 / 2017-09-27 ================== * FIX: stdlib: make direnv_layout_dir lazy (#298) 2.13.0 / 2017-09-24 ================== * NEW: stdlib: configurable direnv_layout_dir * CHANGE: stdlib: source the direnvrc directly * FIX: permit empty NODE_VERSION_PREFIX variable * FIX: pwd: Don't use -P to remove symlinks (#295) * FIX: also reload when mtime goes back in time * FIX: Prevent `$HOME` path from being striked (#287) * BUILD: use the new `dep` tool to manage dependencies * BUILD: dotenv: move to vendor folder 2.12.2 / 2017-07-05 ================== * stdlib layout_python: fixes on no arg 2.12.1 / 2017-07-01 ================== * FIX: stdlib path_add(), see #278 * FIX: install from source instructions 2.12.0 / 2017-06-30 ================== * NEW: support multiple items in path_add and PATH_add (#276) * NEW: add a configurable DIRENV_WARN_TIMEOUT option (#273) * CHANGE: rewrite the dotenv parsing, now supports commented lines * CHANGE: pass additional args to virtualenv (#261) * FIX: stdlib watch_file(): escaping fix * FIX: only output color if $TERM is not dumb (#264) * FIX: the watch_file documentation 2.11.3 / 2017-03-02 ================== * FIX: node version sorting (#255) 2.11.2 / 2017-03-01 ================== * FIX: Typo in MANPATH_add always generates "PATH missing" error. (#256) 2.11.1 / 2017-02-20 ================== * FIX: only deploy the go 1.8 version 2.11.0 / 2017-02-20 ================== * NEW: stdlib.sh: introduce MANPATH_add (#248) * NEW: provide packages using the equinox service * CHANGE: test direnv with go 1.8 (#254) * FIX: Add warning about source_env/up * FIX: go-md2man install instruction 2.10.0 / 2016-12-10 ================== * NEW: `use guix` (#242) * CHANGE: use go-md2man to generate the man pages * FIX: tcsh escaping (#241) * FIX: doc typos and rewords (#226) 2.9.0 / 2016-07-03 ================== * NEW: use_nix() is now watching default.nix and shell.nix * NEW: Allow to fix the bash path at built time * FIX: Panic on `direnv current` with no argument * FIX: Permit empty NODE_VERSION_PREFIX variable * FIX: layout_python: fail properly when python is not found 2.8.1 / 2016-04-04 ================== * FIX: travis dist release 2.8.0 / 2016-03-27 ================== * NEW: `direnv export json` to facilitate IDE integration * NEW: watch functionality thanks to @avnik Now direnv also reload on associate .env and .envrc changes. * NEW: stdlib `watch_file` function thanks to @avnik Allows to monitor more files for change. * NEW: stdlib `use node` function thanks to @wilmoore * NEW: `direnv prune` to remove old allowed files thanks to @punitagrawal Only works with newly-generated files since we're not storing the path inside of them. 2.7.0 / 2015-08-08 ================== * NEW: use_nix() helper to stdlib. Thanks @gfxmonk * FIX: Added SHELLOPTS to ignored vars. Thanks @fernandomora * FIX: Removed shellcheck offenses in the stdlib, better escaping * FIX: typos. Thanks @camelpunch, @oppegard 2.6.1 / 2015-06-23 ================== * FIX: source_env handles missing .envrc gracefully. Thanks @gerhard * FIX: Empty variable as unloading in Vim. Thanks @p0deje * FIX: Corrected spelling mistake in deny command. Thanks @neanias 2.6.0 / 2015-02-15 ================== * NEW: tcsh is now supported ! Thanks @bbense * CHANGE: `direnv dump` now ignores `BASH_FUNC_` exports. Thanks @gfxmonk * CHANGE: Interactive input during load is now possible. Thanks @toao * FIX: allow workaround for tmux users: `alias tmux='direnv exec / tmux'` * FIX: hardened fish shell escaping thanks to @gfxmonk Thanks @bbense @vially and @dadooda for corrections in the docs 2.5.0 / 2014-11-04 ================== * NEW: Use a different virtualenv per python versions for easier version switching. Eg: ./.direnv/python-${python_version} * NEW: Makes `layout python3` a shortcut for `layout python python3`. Thanks @ghickman ! * NEW: Allows to specify which executable of python to use in `layout_python` * CHANGE: `layout python` now unsets $PYTHONHOME to better mimic virtualenv * CHANGE: Don't make virtualenvs relocatable. Fixes #137 * OTHER: Use Travis to push release builds to github 2.4.0 / 2014-06-15 ================== * NEW: Try to detect an editor in the PATH if EDITOR is not set. * NEW: Preliminary support for vim * NEW: New site: put the doc inside the project so it stays in sync * NEW: Support for Cygwin - Thanks @CMCDragonkai ! * NEW: Allow to disable logging by setting an empty `DIRENV_LOG_FORMAT` * NEW: stdlib `layout perl`. Thanks @halkeye ! * CHANGE: layout ruby: share the gem home starting from rubygems v2.2.0 * CHANGE: Allow arbitrary number of args in `log_status` * CHANGE: Bump command timeout to 5 seconds * FIX: Adds selected bash executable in `direnv status` * FIX: man changes, replaced abandonned ronn by md2man * FIX: `make install` was creating a ./bin directory * FIX: issue #114 - work for blank envs. Thanks @pwaller ! * FIX: man pages warning. Thanks @punitagrawal ! * FIX: Multi-arg EDITOR was broken #108 * FIX: typos in doc. Thanks @HeroicEric and @lmarlow ! * FIX: If two paths don't have a common ancestors, don't make them relative. * FIX: missing doc on layered .envrc. Thanks @take ! 2.3.0 / 2014-02-06 ================== * NEW: DIRENV_LOG_FORMAT environment variable can be used tocontrol log formatting * NEW: `direnv exec [DIR] ` to execute programs with an .envrc context * CHANGE: layout_python now tries to make your virtualenv relocatable * CHANGE: the export diff is not from the old env, not the current env * CHANGE: layout_go now also adds $PWD/bin in the PATH * FIX: Hides the DIRENV_ variables in the output diff. Fixes #94 * FIX: Makes sure the path used in the allow hash is absolute. See #95 * FIX: Set the executable bit on direnv on install * FIX: Some bash installs had a parse error in the hook. 2.2.1 / 2014-01-12 ================== The last release was heavily broken. Ooops ! * FIX: Refactored the whole export and diff mechanism. Fixes #92 regression. * CHANGE: DIRENV_BACKUP has been renamed to DIRENV_DIFF 2.2.0 / 2014-01-11 ================== Restart your shells on upgrade, the format of DIRENV_BACKUP has changed and is incompatible with previous versions. * NEW: `direnv_load ` stdlib function * CHANGE: Only backup the diff of environments. Fixes #82 * CHANGE: Renames `$DIRENV_PATH` to `$direnv` in the stdlib. * CHANGE: Allow/Deny mechanism now includes the path to make it more secure. * CHANGE: `direnv --help` is an alias to `direnv help` * CHANGE: more consistent log outputs and error messages * CHANGE: `direnv edit` only auto-allows the .envrc if it's mtime has changed. * CHANGE: Fixes old bash (OSX) segfault in some cases. See #81 * CHANGE: The stdlib `dotenv` now supports more .env syntax * FIX: Restore the environment properly after loading errors. 2.1.0 / 2013-11-10 ================== * Added support for the fish shell. See README.md for install instructions. * Stop recommending using $0 to detect the shell. Fixes #64. * Makes the zsh hook resistant to double-hooking. * Makes the bash hook resistant to double-hooking. * More precise direnv allow error message. Fixes #72 2.0.1 / 2013-07-27 ================== * Fixes shell detection corner case 2.0.0 / 2013-06-16 ================== When upgrading from direnv 1.x make sure to restart your shell. The rest is relatively backward-compatible. * changed the execution model. Everything is in a single static executable * most of the logic has been rewritten in Go * robust shell escaping (supports UTF-8 in env vars) * robust eval/export loop, avoids retrys on every prompt if there is an error * stdlib: added the `dotenv [PATH]` command to load .env files * command: added `direnv reload` to force-reload your environment direnv-2.15.0/CNAME000066400000000000000000000000131324410474700136340ustar00rootroot00000000000000direnv.net direnv-2.15.0/Gopkg.lock000066400000000000000000000011061324410474700150130ustar00rootroot00000000000000# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. [[projects]] name = "github.com/BurntSushi/toml" packages = ["."] revision = "b26d9c308763d68093482582cea63d69be07a0f0" version = "v0.3.0" [[projects]] branch = "master" name = "github.com/direnv/go-dotenv" packages = ["."] revision = "4738ec4932d7ea82d158b6900f0c7a12f116e5e5" [solve-meta] analyzer-name = "dep" analyzer-version = 1 inputs-digest = "e82f451544754a32dfc841dc03a43f341b78356b29888b2a57385294ddf920e3" solver-name = "gps-cdcl" solver-version = 1 direnv-2.15.0/Gopkg.toml000066400000000000000000000011421324410474700150360ustar00rootroot00000000000000 # Gopkg.toml example # # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md # for detailed Gopkg.toml documentation. # # required = ["github.com/user/thing/cmd/thing"] # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] # # [[constraint]] # name = "github.com/user/project" # version = "1.0.0" # # [[constraint]] # name = "github.com/user/project2" # branch = "dev" # source = "github.com/myfork/project2" # # [[override]] # name = "github.com/x/y" # version = "2.4.0" [[constraint]] branch = "master" name = "github.com/direnv/go-dotenv" direnv-2.15.0/LICENSE.md000066400000000000000000000021671324410474700145060ustar00rootroot00000000000000(The MIT License) Copyright (c) 2014 zimbatm and [contributors](https://github.com/direnv/direnv/graphs/contributors) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. direnv-2.15.0/Makefile000066400000000000000000000023311324410474700145330ustar00rootroot00000000000000DESTDIR ?= /usr/local MAN_MD = $(wildcard man/*.md) ROFFS = $(MAN_MD:.md=) GO_LDFLAGS = export GO15VENDOREXPERIMENT=1 ifeq ($(shell uname), Darwin) # Fixes DYLD_INSERT_LIBRARIES issues # See https://github.com/direnv/direnv/issues/194 GO_LDFLAGS += -linkmode=external endif ifdef BASH_PATH GO_LDFLAGS += -X main.bashPath=$(BASH_PATH) endif ifdef GO_LDFLAGS GO_FLAGS += -ldflags '$(GO_LDFLAGS)' endif .PHONY: all man html test install dist #all: build man test all: build man build: direnv stdlib.go: stdlib.sh cat $< | ./script/str2go main STDLIB $< > $@ version.go: version.txt echo package main > $@ echo 'const VERSION = "$(shell cat $<)";' >> $@ direnv: stdlib.go *.go go fmt go build $(GO_FLAGS) -o direnv clean: rm -f direnv %.1: %.1.md @which go-md2man >/dev/null || (echo "Could not generate man page because go-md2man is missing. Run: go get -u github.com/cpuguy83/go-md2man"; false) go-md2man -in $< -out $@ man: $(ROFFS) test: build go test ./test/direnv-test.sh install: all install -d $(DESTDIR)/bin install -d $(DESTDIR)/share/man/man1 install direnv $(DESTDIR)/bin cp -R man/*.1 $(DESTDIR)/share/man/man1 dist: go get github.com/mitchellh/gox gox -output "dist/direnv.{{.OS}}-{{.Arch}}" direnv-2.15.0/README.md000066400000000000000000000164431324410474700143630ustar00rootroot00000000000000direnv -- Unclutter your .profile ================================= `direnv` is an environment switcher for the shell. It knows how to hook into bash, zsh, tcsh and fish shell to load or unload environment variables depending on the current directory. This allows project-specific environment variables without cluttering the `~/.profile` file. Before each prompt, direnv checks for the existence of a ".envrc" file in the current and parent directories. If the file exists (and is authorized), it is loaded into a **bash** sub-shell and all exported variables are then captured by direnv and then made available to the current shell. Because direnv is compiled into a single static executable, it is fast enough to be unnoticeable on each prompt. It is also language-agnostic and can be used to build solutions similar to rbenv, pyenv and phpenv. ## Example ``` $ cd ~/my_project $ echo ${FOO-nope} nope $ echo export FOO=foo > .envrc .envrc is not allowed $ direnv allow . direnv: reloading direnv: loading .envrc direnv export: +FOO $ echo ${FOO-nope} foo $ cd .. direnv: unloading direnv export: ~PATH $ echo ${FOO-nope} nope ``` ## Install ### From source Dependencies: make, golang ```bash git clone https://github.com/direnv/direnv cd direnv make install # or symlink ./direnv into the $PATH ``` ### From system packages direnv is packaged for a variety of systems: * [Fedora](https://apps.fedoraproject.org/packages/direnv) * [Arch AUR](https://aur.archlinux.org/packages/direnv/) * [Debian](https://packages.debian.org/search?keywords=direnv&searchon=names&suite=all§ion=all) * [Gentoo go-overlay](https://github.com/Dr-Terrible/go-overlay) * [NetBSD pkgsrc-wip](http://www.pkgsrc.org/wip/) * [NixOS](https://nixos.org/nixos/packages.html) * [OSX Homebrew](http://brew.sh/) * [MacPorts](https://www.macports.org/) * [Ubuntu](https://packages.ubuntu.com/search?keywords=direnv&searchon=names&suite=all§ion=all) * [GNU Guix](https://www.gnu.org/software/guix/) Non-official builds for Debian and Fedora are also available at https://dl.equinox.io/zimbatm/direnv/stable ### From binary builds Binary builds for a variety of architectures are also available for [each release](https://github.com/direnv/direnv/releases). Fetch the binary, `chmod +x direnv` and put it somewhere in your PATH. ## Setup For direnv to work properly it needs to be hooked into the shell. Each shell has its own extension mechanism: ### BASH Add the following line at the end of the `~/.bashrc` file: ```sh eval "$(direnv hook bash)" ``` Make sure it appears even after rvm, git-prompt and other shell extensions that manipulate the prompt. ### ZSH Add the following line at the end of the `~/.zshrc` file: ```sh eval "$(direnv hook zsh)" ``` ### FISH Add the following line at the end of the `~/.config/fish/config.fish` file: ```fish eval (direnv hook fish) ``` ### TCSH Add the following line at the end of the `~/.cshrc` file: ```sh eval `direnv hook tcsh` ``` ## Usage In some target folder, create a ".envrc" file and add some export(1) directives in it. Note that the contents of the `.envrc` file must be valid bash syntax, regardless of the shell you are using. This is because direnv always executes the `.envrc` with bash (a sort of lowest common denominator of UNIX shells) so that direnv can work across shells. If you try to use some syntax that doesn't work in bash (like zsh's nested expansions), you will [run into trouble](https://github.com/direnv/direnv/issues/199). On the next prompt you will notice that direnv complains about the ".envrc" being blocked. This is the security mechanism to avoid loading new files automatically. Otherwise any git repo that you pull, or tar archive that you unpack, would be able to wipe your hard drive once you `cd` into it. So here we are pretty sure that it won't do anything bad. Type `direnv allow .` and watch direnv loading your new environment. Note that `direnv edit .` is a handy shortcut that opens the file in your $EDITOR and automatically allows it if the file's modification time has changed. Now that the environment is loaded, you will notice that once you `cd` out of the directory it automatically gets unloaded. If you `cd` back into it, it's loaded again. That's the basis of the mechanism that allows you to build cool things. ### The stdlib Exporting variables by hand is a bit repetitive so direnv provides a set of utility functions that are made available in the context of the ".envrc" file. As an example, the `PATH_add` function is used to expand and prepend a path to the $PATH environment variable. Instead of `export $PATH=$PWD/bin:$PATH` you can write `PATH_add bin`. It's shorter and avoids a common mistake where `$PATH=bin`. To find the documentation for all available functions check the direnv-stdlib(1) man page. It's also possible to create your own extensions by creating a bash file at `~/.config/direnv/direnvrc` or `~/.direnvrc`. This file is loaded before your ".envrc" and thus allows you to make your own extensions to direnv. #### Loading layered .envrc Let's say you have the following structure: - "/a/.envrc" - "/a/b/.envrc" If you add the following line in "/a/b/.envrc", you can load both of the ".envrc" files when you are in `/a/b`: ```sh source_env .. ``` ## Common things people don't know Based on GitHub issues interractions, here are the top things that have been confusing for users: 1. direnv has a standard library of functions, a collection of utilities that I found useful to have and accumulated over the years. If you know how to read bash, you can find it here: https://github.com/direnv/direnv/blob/master/stdlib.sh 2. It's possible to override the stdlib with your own set of function by adding a bash file to either `~/.config/direnv/direnvrc` or `~/.direnvrc`. These will become available to all your `.envrc` files. 3. direnv is actually creating a new bash process to load the stdlib, direnvrc and `.envrc`, and only exports the environment diff back to the original shell. This allows direnv to record the environment changes accurately and also work with all sorts of shells. It also means that aliases and functions are not exportable right now. ## Similar projects * [Environment Modules](http://modules.sourceforge.net/) - one of the oldest (in a good way) environment-loading systems * [autoenv](https://github.com/kennethreitz/autoenv) - lightweight; doesn't support unloads * [zsh-autoenv](https://github.com/Tarrasch/zsh-autoenv) - a feature-rich mixture of autoenv and [smartcd](https://github.com/cxreg/smartcd): enter/leave events, nesting, stashing (Zsh-only). ## Contribute Bug reports, contributions and forks are welcome. All bugs or other forms of discussion happen on . There is a wiki available where you can share your usage patterns or other tips and tricks For longer form discussions you can also write to Or drop by on [IRC (#direnv on freenode)](irc://irc.freenode.net/#direnv) to have a chat. If you ask a question make sure to stay around as not everyone is active all day. [![Build Status](https://api.travis-ci.org/direnv/direnv.png?branch=master)](http://travis-ci.org/direnv/direnv) ## COPYRIGHT Copyright (C) 2014 shared by all [contributors](https://github.com/direnv/direnv/graphs/contributors) under the MIT licence. direnv-2.15.0/cmd_allow.go000066400000000000000000000011101324410474700153550ustar00rootroot00000000000000package main import ( "fmt" "os" ) // `direnv allow [PATH_TO_RC]` var CmdAllow = &Cmd{ Name: "allow", Desc: "Grants direnv to load the given .envrc", Args: []string{"[PATH_TO_RC]"}, Fn: func(env Env, args []string) (err error) { var rcPath string var config *Config if len(args) > 1 { rcPath = args[1] } else { if rcPath, err = os.Getwd(); err != nil { return } } if config, err = LoadConfig(env); err != nil { return } rc := FindRC(rcPath, config) if rc == nil { return fmt.Errorf(".envrc file not found") } return rc.Allow() }, } direnv-2.15.0/cmd_apply_dump.go000066400000000000000000000014661324410474700164270ustar00rootroot00000000000000package main import ( "fmt" "io/ioutil" ) // `direnv apply_dump FILE` 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, Fn: func(env Env, args []string) (err error) { if len(args) < 2 { return fmt.Errorf("Not enough arguments") } if len(args) > 2 { return fmt.Errorf("Too many arguments") } filename := args[1] dumped, err := ioutil.ReadFile(filename) if err != nil { return err } dumpedEnv, err := LoadEnv(string(dumped)) if err != nil { return err } diff := env.Diff(dumpedEnv) exports := diff.ToShell(BASH) _, err = fmt.Println(exports) if err != nil { return err } return }, } direnv-2.15.0/cmd_current.go000066400000000000000000000010321324410474700157240ustar00rootroot00000000000000package main import ( "errors" ) var CmdCurrent = &Cmd{ Name: "current", Desc: "Reports whether direnv's view of a file is current (or stale)", Args: []string{"PATH"}, Private: true, Fn: currentCommandFn, } func currentCommandFn(env Env, args []string) (err error) { if len(args) < 2 { err = errors.New("Missing PATH argument") return } path := args[1] watches := NewFileTimes() watchString, ok := env[DIRENV_WATCHES] if ok { watches.Unmarshal(watchString) } err = watches.CheckOne(path) return } direnv-2.15.0/cmd_deny.go000066400000000000000000000011121324410474700152000ustar00rootroot00000000000000package main import ( "fmt" "os" ) // `direnv deny [PATH_TO_RC]` var CmdDeny = &Cmd{ Name: "deny", Desc: "Revokes the authorization of a given .envrc", Args: []string{"[PATH_TO_RC]"}, Fn: func(env Env, args []string) (err error) { var rcPath string var config *Config if len(args) > 1 { rcPath = args[1] } else { if rcPath, err = os.Getwd(); err != nil { return } } if config, err = LoadConfig(env); err != nil { return } rc := FindRC(rcPath, config) if rc == nil { return fmt.Errorf(".envrc file not found") } return rc.Deny() }, } direnv-2.15.0/cmd_dotenv.go000066400000000000000000000017121324410474700155460ustar00rootroot00000000000000package main import ( "fmt" "io/ioutil" "github.com/direnv/go-dotenv" ) // `direnv private 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 var CmdDotEnv = &Cmd{ Name: "dotenv", Desc: "Transforms a .env file to evaluatable `export KEY=PAIR` statements", Args: []string{"[SHELL]", "[PATH_TO_DOTENV]"}, Private: true, Fn: func(env Env, args []string) (err error) { var shell Shell var target string if len(args) > 1 { shell = DetectShell(args[1]) } else { shell = BASH } if len(args) > 2 { target = args[2] } if target == "" { target = ".env" } var data []byte if data, err = ioutil.ReadFile(target); err != nil { return } env, err = dotenv.Parse(string(data)) if err != nil { return err } str := env.ToShell(shell) fmt.Println(str) return }, } direnv-2.15.0/cmd_dump.go000066400000000000000000000004121324410474700152100ustar00rootroot00000000000000package main import "fmt" // `direnv dump` var CmdDump = &Cmd{ Name: "dump", Desc: "Used to export the inner bash state at the end of execution", Private: true, Fn: func(env Env, args []string) (err error) { fmt.Println(env.Serialize()) return }, } direnv-2.15.0/cmd_edit.go000066400000000000000000000040751324410474700152010ustar00rootroot00000000000000package main import ( "fmt" "log" "os" "os/exec" "path/filepath" "strings" ) // `direnv edit [PATH_TO_RC]` var CmdEdit = &Cmd{ Name: "edit", Desc: `Opens PATH_TO_RC or the current .envrc into an $EDITOR and allow the file to be loaded afterwards.`, Args: []string{"[PATH_TO_RC]"}, NoWait: true, Fn: func(env Env, args []string) (err error) { var config *Config var rcPath string var times *FileTimes var foundRC *RC defer log.SetPrefix(log.Prefix()) log.SetPrefix(log.Prefix() + "cmd_edit: ") if config, err = LoadConfig(env); err != nil { return } foundRC = config.FindRC() if foundRC != nil { times = &foundRC.times } if len(args) > 1 { rcPath = args[1] fi, _ := os.Stat(rcPath) if fi != nil && fi.IsDir() { rcPath = filepath.Join(rcPath, ".envrc") } } else { if foundRC == nil { return fmt.Errorf(".envrc not found. Use `direnv edit .` to create a new envrc in the current directory.") } rcPath = foundRC.path } editor := env["EDITOR"] if editor == "" { log_error("$EDITOR not found.") editor = detectEditor(env["PATH"]) if editor == "" { err = fmt.Errorf("Could not find a default editor in the PATH") return } } run := fmt.Sprintf("%s %s", editor, BashEscape(rcPath)) cmd := exec.Command(config.BashPath, "-c", run) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err = cmd.Run(); err != nil { return } foundRC = FindRC(rcPath, config) log_debug("foundRC: %#v", foundRC) log_debug("times: %#v", times) if times != nil { log_debug("times.Check(): %#v", times.Check()) } if foundRC != nil && (times == nil || times.Check() != nil) { foundRC.Allow() } return }, } // Utils var EDITORS = [][]string{ {"subl", "-w"}, {"mate", "-w"}, {"open", "-t", "-W"}, // Opens with the default text editor on mac {"nano"}, {"vim"}, {"emacs"}, } func detectEditor(pathenv string) string { for _, editor := range EDITORS { if _, err := lookPath(editor[0], pathenv); err == nil { return strings.Join(editor, " ") } } return "" } direnv-2.15.0/cmd_exec.go000066400000000000000000000025411324410474700151740ustar00rootroot00000000000000package main import ( "fmt" "os" "path/filepath" "syscall" ) // `direnv exec [DIR] ...` var CmdExec = &Cmd{ Name: "exec", Desc: "Executes a command after loading the first .envrc found in DIR", Args: []string{"[DIR]", "COMMAND", "[...ARGS]"}, Fn: func(env Env, args []string) (err error) { var ( backupDiff *EnvDiff config *Config newEnv Env rcPath string command string ) if len(args) < 2 { return fmt.Errorf("missing DIR and COMMAND arguments") } rcPath = filepath.Clean(args[1]) fi, err := os.Stat(rcPath) if err != nil { return } if fi.IsDir() { if len(args) < 3 { return fmt.Errorf("missing COMMAND argument") } command = args[2] args = args[2:] } else { command = rcPath rcPath = filepath.Dir(rcPath) args = args[1:] } if config, err = LoadConfig(env); err != nil { return } rc := FindRC(rcPath, config) // Restore pristine environment if needed if backupDiff, err = config.EnvDiff(); err == nil { backupDiff.Reverse().Patch(env) } env.CleanContext() // Load the rc if rc != nil { if newEnv, err = rc.Load(config, env); err != nil { return } } else { newEnv = env } command, err = lookPath(command, newEnv["PATH"]) if err != nil { return } err = syscall.Exec(command, args, newEnv.ToGoEnv()) return }, } direnv-2.15.0/cmd_expand_path.go000066400000000000000000000016631324410474700165470ustar00rootroot00000000000000package main import ( "flag" "fmt" "os" "path/filepath" ) func expandPath(path, relTo string) string { if filepath.IsAbs(path) { return path } return filepath.Clean(filepath.Join(relTo, path)) } // `direnv expand_path PATH [REL_TO]` var CmdExpandPath = &Cmd{ Name: "expand_path", Desc: "Transforms a PATH to an absolute path to REL_TO or $PWD", Args: []string{"PATH", "[REL_TO]"}, Private: true, Fn: func(env Env, args []string) (err error) { var path string flagset := flag.NewFlagSet(args[0], flag.ExitOnError) flagset.Parse(args[1:]) path = flagset.Arg(0) if path == "" { return fmt.Errorf("PATH missing") } if !filepath.IsAbs(path) { wd, err := os.Getwd() if err != nil { return err } relTo := flagset.Arg(1) if relTo == "" { relTo = wd } else { relTo = expandPath(relTo, wd) } path = expandPath(path, relTo) } _, err = fmt.Println(path) return }, } direnv-2.15.0/cmd_export.go000066400000000000000000000072721324410474700155770ustar00rootroot00000000000000package main import ( "fmt" "log" "sort" "strings" ) type ExportContext struct { config *Config foundRC *RC loadedRC *RC env Env oldEnv Env newEnv Env } func (self *ExportContext) loadConfig() (err error) { self.config, err = LoadConfig(self.env) return } func (self *ExportContext) getRCs() { self.loadedRC = self.config.LoadedRC() self.foundRC = self.config.FindRC() } func (self *ExportContext) hasRC() bool { return self.foundRC != nil || self.loadedRC != nil } func (self *ExportContext) updateRC() (err error) { defer log.SetPrefix(log.Prefix()) log.SetPrefix(log.Prefix() + "update:") self.oldEnv = self.env.Copy() var backupDiff *EnvDiff if backupDiff, err = self.config.EnvDiff(); err != nil { err = fmt.Errorf("EnvDiff() failed: %q", err) return } self.oldEnv = backupDiff.Reverse().Patch(self.env) log_debug("Determining action:") log_debug("foundRC: %#v", self.foundRC) log_debug("loadedRC: %#v", self.loadedRC) switch { case self.foundRC == nil: log_debug("no RC found, unloading") err = self.unloadEnv() case self.loadedRC == nil: log_debug("no RC (implies no DIRENV_DIFF),loading") err = self.loadRC() case self.loadedRC.path != self.foundRC.path: log_debug("new RC, loading") err = self.loadRC() case self.loadedRC.times.Check() != nil: log_debug("file changed, reloading") err = self.loadRC() default: log_debug("no update needed") } return } func (self *ExportContext) loadRC() (err error) { self.newEnv, err = self.foundRC.Load(self.config, self.oldEnv) return } func (self *ExportContext) unloadEnv() (err error) { log_status(self.env, "unloading") self.newEnv = self.oldEnv.Copy() cleanEnv(self.newEnv) return } func (self *ExportContext) resetEnv() { self.newEnv = self.oldEnv.Copy() cleanEnv(self.oldEnv) if self.foundRC != nil { delete(self.newEnv, DIRENV_DIFF) self.foundRC.RecordState(self.oldEnv, self.newEnv) } } func cleanEnv(env Env) { env.CleanContext() } func (self *ExportContext) diffString(shell Shell) string { oldDiff := self.oldEnv.Diff(self.newEnv) if oldDiff.Any() { var out []string for key := range oldDiff.Prev { _, ok := oldDiff.Next[key] if !ok && !direnvKey(key) { out = append(out, "-"+key) } } for key := range oldDiff.Next { _, ok := oldDiff.Prev[key] if direnvKey(key) { continue } if ok { out = append(out, "~"+key) } else { out = append(out, "+"+key) } } sort.Strings(out) if len(out) > 0 { log_status(self.env, "export %s", strings.Join(out, " ")) } } diff := self.env.Diff(self.newEnv) return diff.ToShell(shell) } func exportCommand(env Env, args []string) (err error) { defer log.SetPrefix(log.Prefix()) log.SetPrefix(log.Prefix() + "export:") log_debug("start") context := ExportContext{env: env} var target string if len(args) > 1 { target = args[1] } shell := DetectShell(target) if shell == nil { return fmt.Errorf("Unknown target shell '%s'", target) } log_debug("load config") if err = context.loadConfig(); err != nil { return } log_debug("loading RCs") if context.getRCs(); !context.hasRC() { return nil } log_debug("updating RC") if err = context.updateRC(); err != nil { log_debug("err: %v", err) context.resetEnv() } if context.newEnv == nil { log_debug("newEnv nil, exiting") return nil } diffString := context.diffString(shell) log_debug("env diff %s", diffString) fmt.Print(diffString) return } // `direnv export $0` var CmdExport = &Cmd{ Name: "export", Desc: "loads an .envrc and prints the diff in terms of exports", Args: []string{"SHELL"}, Private: true, Fn: exportCommand, } func direnvKey(key string) bool { return strings.HasPrefix(key, "DIRENV_") } direnv-2.15.0/cmd_help.go000066400000000000000000000014111324410474700151730ustar00rootroot00000000000000package main import ( "fmt" "strings" ) // `direnv help` var CmdHelp = &Cmd{ Name: "help", Desc: "shows this help", Args: []string{"[SHOW_PRIVATE]"}, Aliases: []string{"--help"}, Fn: 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 %s\n", cmd.Name, opts, cmd.Desc) } } if showPrivate { fmt.Println("* = private commands") } return }, } direnv-2.15.0/cmd_hook.go000066400000000000000000000007351324410474700152130ustar00rootroot00000000000000package main import ( "fmt" ) // `direnv hook $0` var CmdHook = &Cmd{ Name: "hook", Desc: "Used to setup the shell hook", Args: []string{"SHELL"}, Fn: func(env Env, args []string) (err error) { var target string if len(args) > 1 { target = args[1] } shell := DetectShell(target) if shell == nil { return fmt.Errorf("Unknown target shell '%s'", target) } h, err := shell.Hook() if err != nil { return err } fmt.Println(h) return }, } direnv-2.15.0/cmd_prune.go000066400000000000000000000020021324410474700153710ustar00rootroot00000000000000package main import ( "io/ioutil" "os" "path" "strings" ) var CmdPrune = &Cmd{ Name: "prune", Desc: "removes old allowed files", Fn: func(env Env, args []string) (err error) { var config *Config var dir *os.File var fi os.FileInfo var dir_list []string var envrc []byte if config, err = LoadConfig(env); err != nil { return err } allowed := config.AllowDir() if dir, err = os.Open(allowed); err != nil { return err } defer dir.Close() if dir_list, err = dir.Readdirnames(0); err != nil { return err } for _, hash := range dir_list { filename := path.Join(allowed, hash) if fi, err = os.Stat(filename); err != nil { return err } if !fi.IsDir() { if envrc, err = ioutil.ReadFile(filename); err != nil { return err } envrc_str := strings.TrimSpace(string(envrc)) // skip old files, w/o path inside if envrc_str == "" { continue } if !fileExists(envrc_str) { _ = os.Remove(filename) } } } return nil }, } direnv-2.15.0/cmd_reload.go000066400000000000000000000005311324410474700155130ustar00rootroot00000000000000package main import ( "fmt" ) var CmdReload = &Cmd{ Name: "reload", Desc: "triggers an env reload", Fn: func(env Env, args []string) error { config, err := LoadConfig(env) if err != nil { return err } foundRC := config.FindRC() if foundRC == nil { return fmt.Errorf(".envrc not found") } return foundRC.Touch() }, } direnv-2.15.0/cmd_status.go000066400000000000000000000017541324410474700156000ustar00rootroot00000000000000package main import ( "fmt" "path/filepath" ) var CmdStatus = &Cmd{ Name: "status", Desc: "prints some debug status information", Fn: func(env Env, args []string) error { config, err := LoadConfig(env) if err != nil { return err } fmt.Println("direnv exec path", config.SelfPath) fmt.Println("DIRENV_CONFIG", config.ConfDir) fmt.Println("DIRENV_BASH", config.BashPath) loadedRC := config.LoadedRC() foundRC := config.FindRC() if loadedRC != nil { formatRC("Loaded", loadedRC) } else { fmt.Println("No .envrc loaded") } if foundRC != nil { formatRC("Found", foundRC) } else { fmt.Println("No .envrc found") } return nil }, } func formatRC(desc string, rc *RC) { workDir := filepath.Dir(rc.path) fmt.Println(desc, "RC path", rc.path) for idx := range *(rc.times.list) { fmt.Println(desc, "watch:", (*rc.times.list)[idx].Formatted(workDir)) } fmt.Println(desc, "RC allowed", rc.Allowed()) fmt.Println(desc, "RC allowPath", rc.allowPath) } direnv-2.15.0/cmd_stdlib.go000066400000000000000000000005351324410474700155320ustar00rootroot00000000000000package main import ( "fmt" ) // `direnv stdlib` var CmdStdlib = &Cmd{ Name: "stdlib", Desc: "Displays the stdlib available in the .envrc execution context", Fn: func(env Env, args []string) (err error) { var config *Config if config, err = LoadConfig(env); err != nil { return } fmt.Printf(STDLIB, config.SelfPath) return }, } direnv-2.15.0/cmd_version.go000066400000000000000000000002731324410474700157350ustar00rootroot00000000000000package main import ( "fmt" ) var CmdVersion = &Cmd{ Name: "version", Desc: "prints the version", Fn: func(env Env, args []string) error { fmt.Println(VERSION) return nil }, } direnv-2.15.0/cmd_watch.go000066400000000000000000000015721324410474700153610ustar00rootroot00000000000000package main import "fmt" var CmdWatch = &Cmd{ Name: "watch", Desc: "Adds a path to the list that direnv watches for changes", Args: []string{"[SHELL]", "PATH"}, Private: false, Fn: watchCommand, } func watchCommand(env Env, args []string) (err error) { var path, shellName string args = args[1:] if len(args) < 1 { return fmt.Errorf("A path is required to add to the list of watches") } if len(args) >= 2 { shellName = args[0] args = args[1:] } else { shellName = "bash" } shell := DetectShell(shellName) if shell == nil { return fmt.Errorf("Unknown target shell '%s'", shellName) } path = args[0] watches := NewFileTimes() watchString, ok := env[DIRENV_WATCHES] if ok { watches.Unmarshal(watchString) } watches.Update(path) e := make(ShellExport) e.Add(DIRENV_WATCHES, watches.Marshal()) fmt.Printf(shell.Export(e)) return } direnv-2.15.0/commands.go000066400000000000000000000032271324410474700152300ustar00rootroot00000000000000package main import ( "fmt" "strings" "time" ) type Cmd struct { Name string Desc string Args []string Aliases []string NoWait bool Private bool Fn func(env Env, args []string) error } var CmdList []*Cmd func init() { CmdList = []*Cmd{ CmdAllow, CmdApplyDump, CmdDeny, CmdDotEnv, CmdDump, CmdEdit, CmdExec, CmdExpandPath, CmdExport, CmdHelp, CmdHook, CmdPrune, CmdReload, CmdStatus, CmdStdlib, CmdVersion, CmdWatch, CmdCurrent, } } func CommandsDispatch(env Env, args []string) error { var command *Cmd var commandName string var commandPrefix string var commandArgs []string if len(args) < 2 { commandName = "help" commandPrefix = args[0] commandArgs = []string{} } else { commandName = args[1] commandPrefix = strings.Join(args[0:2], " ") commandArgs = append([]string{commandPrefix}, args[2:]...) } for _, cmd := range CmdList { if cmd.Name == commandName { command = cmd break } if cmd.Aliases != nil { for _, alias := range cmd.Aliases { if alias == commandName { command = cmd } } } } if command == nil { return fmt.Errorf("Command \"%s\" not found", commandPrefix) } done := make(chan bool, 1) if !command.NoWait { timeout, err := time.ParseDuration(env.Fetch("DIRENV_WARN_TIMEOUT", "5s")) if err != nil { log_error("invalid DIRENV_WARN_TIMEOUT: " + err.Error()) timeout = 5 * time.Second } go func() { select { case <-done: return case <-time.After(timeout): log_error("(%v) is taking a while to execute. Use CTRL-C to give up.", args) } }() } err := command.Fn(env, commandArgs) done <- true return err } direnv-2.15.0/config.go000066400000000000000000000063021324410474700146710ustar00rootroot00000000000000package main import ( "fmt" "os" "os/exec" "path/filepath" "strings" toml "github.com/BurntSushi/toml" ) type Config struct { Env Env WorkDir string // Current directory ConfDir string SelfPath string BashPath string RCDir string TomlPath string WhitelistPrefix []string WhitelistExact map[string]bool } type tomlConfig struct { Whitelist whitelist `toml:"whitelist"` BashPath string `toml:"bash_path"` } type whitelist struct { Prefix []string Exact []string } func LoadConfig(env Env) (config *Config, err error) { config = &Config{ Env: env, } config.ConfDir = env[DIRENV_CONFIG] if config.ConfDir == "" { config.ConfDir = XdgConfigDir(env, "direnv") } if config.ConfDir == "" { err = fmt.Errorf("Couldn't find a configuration directory for direnv") return } var exePath string if exePath, err = exec.LookPath(os.Args[0]); err != nil { err = fmt.Errorf("LoadConfig() Lookpath failed: %q", err) return } if exePath, err = filepath.EvalSymlinks(exePath); err != nil { err = fmt.Errorf("LoadConfig() symlink resolution: %q", err) return } exePath = strings.Replace(exePath, "\\", "/", -1) config.SelfPath = exePath if config.WorkDir, err = os.Getwd(); err != nil { err = fmt.Errorf("LoadConfig() Getwd failed: %q", err) return } config.RCDir = env[DIRENV_DIR] if len(config.RCDir) > 0 && config.RCDir[0:1] == "-" { config.RCDir = config.RCDir[1:] } config.WhitelistPrefix = make([]string, 0) config.WhitelistExact = make(map[string]bool) // Load the config.toml config.TomlPath = filepath.Join(config.ConfDir, "config.toml") if _, statErr := os.Stat(config.TomlPath); statErr == nil { var tomlConf tomlConfig if _, err = toml.DecodeFile(config.TomlPath, &tomlConf); err != nil { err = fmt.Errorf("LoadConfig() failed to parse config.toml: %q", err) return } for _, prefix := range tomlConf.Whitelist.Prefix { config.WhitelistPrefix = append(config.WhitelistPrefix, prefix) } for _, path := range tomlConf.Whitelist.Exact { if !strings.HasSuffix(path, "/.envrc") { path = filepath.Join(path, ".envrc") } config.WhitelistExact[path] = true } config.BashPath = tomlConf.BashPath } if config.BashPath == "" { if env[DIRENV_BASH] != "" { config.BashPath = env[DIRENV_BASH] } else if bashPath != "" { config.BashPath = bashPath } else if config.BashPath, err = exec.LookPath("bash"); err != nil { err = fmt.Errorf("Can't find bash: %q", err) return } } return } func (self *Config) AllowDir() string { return filepath.Join(self.ConfDir, "allow") } func (self *Config) LoadedRC() *RC { if self.RCDir == "" { log_debug("RCDir is blank - loadedRC is nil") return nil } rcPath := filepath.Join(self.RCDir, ".envrc") times_string := self.Env[DIRENV_WATCHES] return RCFromEnv(rcPath, times_string, self) } func (self *Config) FindRC() *RC { return FindRC(self.WorkDir, self) } func (self *Config) EnvDiff() (*EnvDiff, error) { if self.Env[DIRENV_DIFF] == "" { if self.Env[DIRENV_WATCHES] == "" { return self.Env.Diff(self.Env), nil } else { return nil, fmt.Errorf("DIRENV_DIFF is empty") } } return LoadEnvDiff(self.Env[DIRENV_DIFF]) } direnv-2.15.0/const.go000066400000000000000000000003331324410474700145500ustar00rootroot00000000000000package main const ( DIRENV_CONFIG = "DIRENV_CONFIG" DIRENV_BASH = "DIRENV_BASH" DIRENV_DEBUG = "DIRENV_DEBUG" DIRENV_DIR = "DIRENV_DIR" DIRENV_WATCHES = "DIRENV_WATCHES" DIRENV_DIFF = "DIRENV_DIFF" ) direnv-2.15.0/default.nix000066400000000000000000000014051324410474700152400ustar00rootroot00000000000000with import {}; let rstrip = s: let inherit (builtins) substring; len = builtins.stringLength s; suffix = substring (len - 1) 1 s; ws = [ " " "\r" "\n" "\t" ]; in if len > 0 && builtins.any (char: char == suffix) ws then rstrip (substring 0 (len - 1) s) else s; readVersion = f: rstrip (builtins.readFile f); in buildGoPackage rec { version = readVersion ./version.txt; name = "direnv-${version}"; goPackagePath = "github.com/zimbatm/direnv"; src = ./.; meta = with stdenv.lib; { homepage = http://direnv.net; description = "path-dependent environments"; maintainers = with maintainers; [ zimbatm ]; license = licenses.mit; platforms = go.meta.platforms; }; } direnv-2.15.0/docs/000077500000000000000000000000001324410474700140245ustar00rootroot00000000000000direnv-2.15.0/docs/ruby.md000066400000000000000000000066731324410474700153430ustar00rootroot00000000000000# Manage your rubies with direnv and ruby-install direnv is just a shell extension that manages your environment variables depending on the folder you live in. In this article we will explore how it can be used in combination with [ruby-install](https://github.com/postmodern/ruby-install) to manage and select the version of ruby that you want to use in a project. ## The setup First install direnv. This is the quick version on OSX + Bash: ```bash brew install direnv echo 'eval $(direnv hook bash)' >> .bashrc exec $0 ``` Then use [ruby-install](https://github.com/postmodern/ruby-install) to install a couple of ruby versions. We're also creating a couple of aliases for convenience. ``` brew install ruby-install ruby-install ruby 1.9 ruby-install ruby 2.0 cd ~/.rubies ln -s 1.9.3-p448 1.9.3 ln -s 1.9.3-p448 1.9 ln -s 2.0.0-p247 2.0.0 ln -s 2.0.0-p247 2.0 ``` The end goal is that each project will have an ".envrc" file that contains a descriptive syntax like `use ruby 1.9.3` to selects the right ruby version for the project. For that regard we are going to use a couple of commands available in the [direnv stdlib](/stdlib.html) and expand it a bit in the ~/.direnvrc file. Add this to the ~/.direnvrc file (you have to create it if it doesn't exist): ```bash # Usage: use ruby # # Loads the specified ruby version into the environent # use_ruby() { local ruby_dir=$HOME/.rubies/$1 load_prefix $ruby_dir layout ruby } ``` That's it. Now in any project you can run `direnv edit .` and add `use ruby 1.9.3` or `use ruby 2.0` in the file like you want and direnv will select the right ruby version when you enter the project's folder. ## A bit of explanation The last part probably needs a bit more explanation. We make use of a couple of commands that are part of the [stdlib](/stdlib.html) which is availabe in the execution context of an envrc. `use` is a command dispatch that's just there to build the `use something something` dsl so that `use ruby ` will translate into `use_ruby `. `load_prefix` will add a couple of things into the environment, notably add `/bin` into the PATH. This is what makes the specified ruby available. And finally `layout ruby` who like `use` translates into the `layout_ruby` function call. It's used to decribe common project layouts. In the stdlib, the ruby layout will configure rubygems (with the `GEM_HOME` environment variable) to install all the gems into the .direnv/ruby/RUBY_VERSION folder under the project root. This is a bit similar to rvm's gemsets except that they live inside your project's folder. It also configures bundler to install wrapper shims into the .direnv/bin folder which allows you to invoke the commands directly instead of prefixing your ruby programs with `bundle exec` all the time. ## Conclusion As you see this approach is not restricted to ruby. You could have various versions of python installed under ~/.pythons and a `use_python` defined in your ~/.direnvrc. Or perl, php, ... This is the good thing about direnv, it's not restricted to a single language. Actually, wouldn't it be great to have all your project's dependencies available when you enter the project folder ? Not only your ruby version but also the exact redis or mysql or ... version that you want to use, without having to start a VM. I think that's definitely possible using something like the [Nix package manager](http://nixos.org/nix/), something that still needs to be explored in a future post. direnv-2.15.0/docs/screencasts.md000066400000000000000000000014301324410474700166610ustar00rootroot00000000000000# direnv screencasts Here's a couple of screencasts that I recorded a while ago and didn't took the time to share until now. Enjoy ! ## direnv installation on OS X with Homebrew Showing how to install direnv and checking that it works afterwards. ## The direnv security model Explains how the .envrc files are protected from unwanted loading. ## Handling ruby versions with direnv This shows how direnv can be used to build something akin to rvm, rbenv and friends. direnv-2.15.0/docs/sidebar.md000066400000000000000000000011701324410474700157560ustar00rootroot00000000000000# direnv [ditto:searchbar] - [Home]() - [CHANGELOG](#/CHANGELOG) - [LICENSE (MIT)](#/LICENSE) ## Github - [Repo](https://github.com/direnv/direnv) - [Issues](https://github.com/direnv/direnv/issues) - [Releases](https://github.com/direnv/direnv/releases) - [Wiki](https://github.com/direnv/direnv/wiki) ## Guides - [Screencasts](#/docs/screencasts) - [Ruby](#/docs/ruby) - [Emacs integration](https://github.com/wbolster/emacs-direnv) - [Vim integration](https://github.com/direnv/direnv.vim) ## Man pages - [man 1 direnv](#man/direnv.1) - [man 1 direnv-stdlib](#man/direnv-stdlib.1) - [man 1 direnv.toml](#man/direnv.toml.1) direnv-2.15.0/env.go000066400000000000000000000025121324410474700142130ustar00rootroot00000000000000package main import ( "os" "strings" ) type Env map[string]string // NOTE: We don't support having two variables with the same name. // I've never seen it used in the wild but accoding to POSIX // it's allowed. func GetEnv() Env { env := make(Env) for _, kv := range os.Environ() { kv2 := strings.SplitN(kv, "=", 2) key := kv2[0] value := kv2[1] env[key] = value } return env } func (env Env) CleanContext() { delete(env, DIRENV_DIR) delete(env, DIRENV_WATCHES) delete(env, DIRENV_DIFF) } func LoadEnv(base64env string) (env Env, err error) { env = make(Env) err = unmarshal(base64env, &env) return } func (env Env) Copy() Env { newEnv := make(Env) for key, value := range env { newEnv[key] = value } return newEnv } func (env Env) ToGoEnv() []string { goEnv := make([]string, len(env)) index := 0 for key, value := range env { goEnv[index] = strings.Join([]string{key, value}, "=") index += 1 } return goEnv } func (env Env) ToShell(shell Shell) string { e := make(ShellExport) for key, value := range env { e.Add(key, value) } return shell.Export(e) } func (env Env) Serialize() string { return marshal(env) } func (e1 Env) Diff(e2 Env) *EnvDiff { return BuildEnvDiff(e1, e2) } func (e Env) Fetch(key, def string) string { v, ok := e[key] if !ok { v = def } return v } direnv-2.15.0/env_diff.go000066400000000000000000000042271324410474700152100ustar00rootroot00000000000000package main import ( "strings" ) // A list of keys we don't want to deal with var IGNORED_KEYS = map[string]bool{ // direnv env config "DIRENV_CONFIG": true, "DIRENV_BASH": true, "COMP_WORDBREAKS": true, // Avoids segfaults in bash "PS1": true, // PS1 should not be exported, fixes problem in bash // variables that should change freely "OLDPWD": true, "PWD": true, "SHELL": true, "SHELLOPTS": true, "SHLVL": true, "_": true, } type EnvDiff struct { Prev map[string]string `json:"p"` Next map[string]string `json:"n"` } func NewEnvDiff() *EnvDiff { return &EnvDiff{make(map[string]string), make(map[string]string)} } func BuildEnvDiff(e1, e2 Env) *EnvDiff { diff := NewEnvDiff() in := func(key string, e Env) bool { _, ok := e[key] return ok } for key := range e1 { if IgnoredEnv(key) { continue } if e2[key] != e1[key] || !in(key, e2) { diff.Prev[key] = e1[key] } } for key := range e2 { if IgnoredEnv(key) { continue } if e2[key] != e1[key] || !in(key, e1) { diff.Next[key] = e2[key] } } return diff } func LoadEnvDiff(base64env string) (diff *EnvDiff, err error) { diff = new(EnvDiff) err = unmarshal(base64env, diff) return } func (self *EnvDiff) Any() bool { return len(self.Prev) > 0 || len(self.Next) > 0 } func (self *EnvDiff) ToShell(shell Shell) string { e := make(ShellExport) for key := range self.Prev { _, ok := self.Next[key] if !ok { e.Remove(key) } } for key, value := range self.Next { e.Add(key, value) } return shell.Export(e) } func (self *EnvDiff) Patch(env Env) (newEnv Env) { newEnv = make(Env) for k, v := range env { newEnv[k] = v } for key := range self.Prev { delete(newEnv, key) } for key, value := range self.Next { newEnv[key] = value } return newEnv } func (self *EnvDiff) Reverse() *EnvDiff { return &EnvDiff{self.Next, self.Prev} } func (self *EnvDiff) Serialize() string { return marshal(self) } //// Utils func IgnoredEnv(key string) bool { if strings.HasPrefix(key, "__fish") { return true } if strings.HasPrefix(key, "BASH_FUNC_") { return true } _, found := IGNORED_KEYS[key] return found } direnv-2.15.0/env_diff_test.go000066400000000000000000000020151324410474700162400ustar00rootroot00000000000000package main import ( "reflect" "testing" ) func TestEnvDiff(t *testing.T) { diff := &EnvDiff{map[string]string{"FOO": "bar"}, map[string]string{"BAR": "baz"}} out := diff.Serialize() diff2, err := LoadEnvDiff(out) if err != nil { t.Error("parse error", err) } if len(diff2.Prev) != 1 { t.Error("len(diff2.prev) != 1", len(diff2.Prev)) } if len(diff2.Next) != 1 { t.Error("len(diff2.next) != 0", len(diff2.Next)) } } // Issue #114 // Check that empty environment variables correctly appear in the diff func TestEnvDiffEmptyValue(t *testing.T) { before := Env{} after := Env{"FOO": ""} diff := BuildEnvDiff(before, after) if !reflect.DeepEqual(diff.Next, map[string]string(after)) { t.Errorf("diff.Next != after (%#+v != %#+v)", diff.Next, after) } } func TestIgnoredEnv(t *testing.T) { if !IgnoredEnv(DIRENV_BASH) { t.Fail() } if IgnoredEnv(DIRENV_DIFF) { t.Fail() } if !IgnoredEnv("_") { t.Fail() } if !IgnoredEnv("__fish_foo") { t.Fail() } if !IgnoredEnv("__fishx") { t.Fail() } } direnv-2.15.0/env_test.go000066400000000000000000000005031324410474700152500ustar00rootroot00000000000000package main import ( "testing" ) func TestEnv(t *testing.T) { env := Env{"FOO": "bar"} out := env.Serialize() env2, err := LoadEnv(out) if err != nil { t.Error("parse error", err) } if env2["FOO"] != "bar" { t.Error("FOO != bar", env2["FOO"]) } if len(env2) != 1 { t.Error("len != 1", len(env2)) } } direnv-2.15.0/file_times.go000066400000000000000000000055621324410474700155530ustar00rootroot00000000000000package main import ( "fmt" "os" "path/filepath" "time" ) type FileTime struct { Path string Modtime int64 Exists bool } type FileTimes struct { list *[]FileTime } func NewFileTimes() (times FileTimes) { list := make([]FileTime, 0) times.list = &list return } func (times *FileTimes) Update(path string) (err error) { var modtime int64 var exists bool stat, err := os.Stat(path) if os.IsNotExist(err) { exists = false } else { exists = true if err != nil { return } modtime = stat.ModTime().Unix() } err = times.NewTime(path, modtime, exists) return } func (times *FileTimes) NewTime(path string, modtime int64, exists bool) (err error) { var time *FileTime path, err = filepath.Abs(path) if err != nil { return } path = filepath.Clean(path) for idx := range *(times.list) { if (*times.list)[idx].Path == path { time = &(*times.list)[idx] break } } if time == nil { newTimes := append(*times.list, FileTime{Path: path}) times.list = &newTimes time = &((*times.list)[len(*times.list)-1]) } time.Modtime = modtime time.Exists = exists return } type checkFailed struct { message string } func (err checkFailed) Error() string { return err.message } func (times *FileTimes) Check() (err error) { if len(*times.list) == 0 { return checkFailed{"Times list is empty"} } for idx := range *times.list { err = (*times.list)[idx].Check() if err != nil { return } } return } func (times *FileTimes) CheckOne(path string) (err error) { path, err = filepath.Abs(path) if err != nil { return } for idx := range *times.list { if time := (*times.list)[idx]; time.Path == path { err = time.Check() return } } return checkFailed{fmt.Sprintf("File %q is unknown", path)} } func (time FileTime) Check() (err error) { stat, err := os.Stat(time.Path) switch { case os.IsNotExist(err): if time.Exists { log_debug("Check: %s: gone", time.Path) return checkFailed{fmt.Sprintf("File %q is missing", time.Path)} } case err != nil: log_debug("Check: %s: ERR: %v", time.Path, err) return err case !time.Exists: log_debug("Check: %s: appeared", time.Path) return checkFailed{fmt.Sprintf("File %q newly created", time.Path)} case stat.ModTime().Unix() != time.Modtime: log_debug("Check: %s: stale", time.Path) return checkFailed{fmt.Sprintf("File %q has changed", time.Path)} } log_debug("Check: %s: up to date", time.Path) return nil } func (self *FileTime) Formatted(relDir string) string { timeBytes, err := time.Unix(self.Modtime, 0).MarshalText() if err != nil { timeBytes = []byte("<>") } path, err := filepath.Rel(relDir, self.Path) if err != nil { path = self.Path } return fmt.Sprintf("%q - %s", path, timeBytes) } func (times *FileTimes) Marshal() string { return marshal(*times.list) } func (times *FileTimes) Unmarshal(from string) error { return unmarshal(from, times.list) } direnv-2.15.0/file_times_test.go000066400000000000000000000043641324410474700166110ustar00rootroot00000000000000package main import ( "bytes" "encoding/json" "testing" "time" ) func TestUpdate(t *testing.T) { times := NewFileTimes() times.Update("file_times.go") if len(*times.list) != 1 { t.Error("Length of updated list not 1") } if !(*times.list)[0].Exists { t.Error("Existing file marked not existing") } } func TestFTJsons(t *testing.T) { ft := FileTime{"something.txt", time.Now().Unix(), true} marshalled, err := json.Marshal(ft) if err != nil { t.Error("Filetime failed to marshal:", err) } if bytes.NewBuffer(marshalled).String() == "{}" { t.Error(ft, "marshals as empty object") } } func TestRoundTrip(t *testing.T) { watches := NewFileTimes() watches.Update("file_times.go") rt_chk := NewFileTimes() rt_chk.Unmarshal(watches.Marshal()) compareFTs(t, watches, rt_chk, "length", func(ft FileTimes) interface{} { return len(*ft.list) }) compareFTs(t, watches, rt_chk, "first path", func(ft FileTimes) interface{} { return (*ft.list)[0].Path }) } func compareFTs(t *testing.T, left, right FileTimes, desc string, compare func(ft FileTimes) (res interface{})) { lc, rc := compare(left), compare(right) if lc != rc { t.Error("Filetimes didn't round trip.", "Original", desc, "was:", lc, "RT", desc, "was:", rc) } } func TestCanonicalAdds(t *testing.T) { fts := NewFileTimes() fts.NewTime("docs/../file_times.go", 0, true) fts.NewTime("file_times.go", 0, true) if len(*fts.list) > 1 { t.Error("Double add of the same file") } } func TestCheckPasses(t *testing.T) { fts := NewFileTimes() fts.Update("file_times.go") err := fts.Check() if err != nil { t.Error("Check that should pass fails with:", err) } } func TestCheckStale(t *testing.T) { fts := NewFileTimes() fts.NewTime("file_times.go", 0, true) err := fts.Check() if err == nil { t.Error("Check that should fail because stale passes") } } func TestCheckAppeared(t *testing.T) { fts := NewFileTimes() fts.NewTime("file_times.go", 0, false) err := fts.Check() if err == nil { t.Error("Check that should fail because appeared passes") } } func TestCheckGone(t *testing.T) { fts := NewFileTimes() fts.NewTime("nosuchfileevarright.go", time.Now().Unix()+1000, true) err := fts.Check() if err == nil { t.Error("Check that should fail because gone passes") } } direnv-2.15.0/index.html000066400000000000000000000041611324410474700150730ustar00rootroot00000000000000 direnv - unclutter your .profile
top
edit
Loading ...
direnv-2.15.0/log.go000066400000000000000000000024011324410474700142010ustar00rootroot00000000000000package main import ( "fmt" "log" "os" ) const ( debugLogFormat = "DBG-direnv: %s" defaultLogFormat = "direnv: %s" errorLogFormat = defaultLogFormat errorLogFormatWithColor = "\033[31mdirenv: %s\033[0m" ) var debugging bool var noColor = os.Getenv("TERM") == "dumb" func setupLogging(env Env) { log.SetFlags(0) log.SetPrefix("") if val, ok := env[DIRENV_DEBUG]; ok == true && val == "1" { debugging = true log.SetFlags(log.Ltime) log.SetPrefix("direnv: ") } } func log_error(msg string, a ...interface{}) { if noColor { logMsg(errorLogFormat, msg, a...) } else { logMsg(errorLogFormatWithColor, msg, a...) } } func log_status(env Env, msg string, a ...interface{}) { format, ok := env["DIRENV_LOG_FORMAT"] if !ok { format = defaultLogFormat } if format != "" { logMsg(format, msg, a...) } } func log_debug(msg string, a ...interface{}) { if !debugging { return } defer log.SetFlags(log.Flags()) log.SetFlags(log.Flags() | log.Lshortfile) msg = fmt.Sprintf(msg, a...) log.Output(2, msg) } func logMsg(format, msg string, a ...interface{}) { defer log.SetFlags(log.Flags()) defer log.SetPrefix(log.Prefix()) log.SetFlags(0) log.SetPrefix("") msg = fmt.Sprintf(format+"\n", msg) log.Printf(msg, a...) } direnv-2.15.0/look_path.go000066400000000000000000000017001324410474700154010ustar00rootroot00000000000000package main import ( "errors" "os" "strings" ) // Similar to os/exec.LookPath except we pass in the PATH func lookPath(file string, pathenv string) (string, error) { if strings.Contains(file, "/") { err := findExecutable(file) if err == nil { return file, nil } return "", err } if pathenv == "" { return "", errNotFound } for _, dir := range strings.Split(pathenv, ":") { if dir == "" { // Unix shell semantics: path element "" means "." dir = "." } path := dir + "/" + file if err := findExecutable(path); err == nil { return path, nil } } return "", errNotFound } // ErrNotFound is the error resulting if a path search failed to find an executable file. var errNotFound = errors.New("executable file not found in $PATH") func findExecutable(file string) error { d, err := os.Stat(file) if err != nil { return err } if m := d.Mode(); !m.IsDir() && m&0111 != 0 { return nil } return os.ErrPermission } direnv-2.15.0/main.go000066400000000000000000000004021324410474700143430ustar00rootroot00000000000000package main import ( "os" ) // Configured at compile time var bashPath string func main() { var env = GetEnv() var args = os.Args setupLogging(env) err := CommandsDispatch(env, args) if err != nil { log_error("error %v", err) os.Exit(1) } } direnv-2.15.0/man/000077500000000000000000000000001324410474700136475ustar00rootroot00000000000000direnv-2.15.0/man/direnv-stdlib.1000066400000000000000000000162561324410474700165110ustar00rootroot00000000000000.TH DIRENV\-STDLIB 1 "APRIL 2014" direnv "User Manuals" .SH NAME .PP direnv\_stdlib \- the ".envrc" stdlib .SH SYNOPSIS .PP \fB\fCdirenv stdlib\fR .SH DESCRIPTION .PP Outputs a bash script called the \fIstdlib\fP\&. The following commands are included in that script and loaded in the context of an ".envrc". In addition, it also loads the file in "\~\&/.direnvrc" if it exists. .SH STDLIB.IP \(bu 2 \fB\fChas\fR \fIcommand\fP: Returns 0 if the \fIcommand\fP is available. Returns 1 otherwise. It can be a binary in the PATH or a shell function. .PP Example: .PP .RS .nf if has curl; then echo "Yes we do" fi .fi .RE .IP \(bu 2 \fB\fCexpand\_path\fR \fIrel\_path\fP [\fIrelative\_to\fP]: Outputs the absolute path of \fIrel\_path\fP relative to \fIrelative\_to\fP or the current directory. .PP Example: .PP .RS .nf cd /usr/local/games expand\_path ../foo # output: /usr/local/foo .fi .RE .IP \(bu 2 .PP \fB\fCdotenv\fR [\fIdotenv\_path\fP]: Loads a ".env" file into the current environment .IP \(bu 2 .PP \fB\fCuser\_rel\_path\fR \fIabs\_path\fP: Transforms an absolute path \fIabs\_path\fP into a user\-relative path if possible. .PP Example: .PP .RS .nf echo $HOME # output: /home/user user\_rel\_path /home/user/my/project # output: \~/my/project user\_rel\_path /usr/local/lib # output: /usr/local/lib .fi .RE .IP \(bu 2 \fB\fCfind\_up\fR \fIfilename\fP: Outputs the path of \fIfilename\fP when searched from the current directory up to /. Returns 1 if the file has not been found. .PP Example: .PP .RS .nf cd /usr/local/my mkdir \-p project/foo touch bar cd project/foo find\_up bar # output: /usr/local/my/bar .fi .RE .IP \(bu 2 .PP \fB\fCsource\_env\fR \fIfile\_or\_dir\_path\fP: Loads another ".envrc" either by specifying its path or filename. .PP NOTE: the other ".envrc" is not checked by the security framework. .IP \(bu 2 .PP \fB\fCsource\_up\fR [\fIfilename\fP]: Loads another ".envrc" if found with the \fB\fCfind\_up\fR command. .PP NOTE: the other ".envrc" is not checked by the security framework. .IP \(bu 2 .PP \fB\fCdirenv\_load\fR [\fIcommand\-generating\-dump\-output\fP] Applies the environment generated by running \fIargv\fP as a command. This is useful for adopting the environment of a child process \- cause that process to run "direnv dump" and then wrap the results with direnv\_load. .PP Example: .PP .RS .nf direnv\_load opam\-env exec \-\- direnv dump .fi .RE .IP \(bu 2 \fB\fCPATH\_add\fR \fIpath\fP: Prepends the expanded \fIpath\fP to the PATH environment variable. It prevents a common mistake where PATH is replaced by only the new \fIpath\fP\&. .PP Example: .PP .RS .nf pwd # output: /home/user/my/project PATH\_add bin echo $PATH # output: /home/user/my/project/bin:/usr/bin:/bin .fi .RE .IP \(bu 2 .PP \fB\fCMANPATH\_add\fR \fIpath\fP: Prepends the expanded \fIpath\fP to the MANPATH environment variable. It takes care of man\-specific heuritic. .IP \(bu 2 .PP \fB\fCpath\_add\fR \fIvarname\fP \fIpath\fP: Works like \fB\fCPATH\_add\fR except that it's for an arbitrary \fIvarname\fP\&. .IP \(bu 2 .PP \fB\fCload\_prefix\fR \fIprefix\_path\fP: Expands some common path variables for the given \fIprefix\_path\fP prefix. This is useful if you installed something in the \fIprefix\_path\fP using \fB\fC\&./configure \-\&\-\&prefix=$prefix\_\&path \&\&\&\& make install\fR and want to use it in the project. .PP Variables set: .PP .RS .nf CPATH LD\_LIBRARY\_PATH LIBRARY\_PATH MANPATH PATH PKG\_CONFIG\_PATH .fi .RE .PP Example: .PP .RS .nf \&./configure \-\&\-\&prefix=$HOME/rubies/ruby\-\&1.9.3 make \&\&\&\& make install # Then in the .envrc load\_\&prefix \~\&/rubies/ruby\-\&1.9.3 .fi .RE .IP \(bu 2 .PP \fB\fClayout\fR \fItype\fP: A semantic dispatch used to describe common project layouts. .IP \(bu 2 .PP \fB\fClayout go\fR: Sets the GOPATH environment variable to the current directory. .IP \(bu 2 .PP \fB\fClayout node\fR: Adds "$PWD/node\_modules/.bin" to the PATH environment variable. .IP \(bu 2 .PP \fB\fClayout perl\fR: Setup environment variables required by perl's local::lib See \[la]http://search.cpan.org/dist/local-lib/lib/local/lib.pm\[ra] for more details .IP \(bu 2 .PP \fB\fClayout python\fR [\fIpython\_exe\fP]: Creates and loads a virtualenv environment under \fB\fC$PWD/.direnv/python\-$python\_version\fR\&. This forces the installation of any egg into the project's sub\-\&folder. .PP It's possible to specify the python executable if you want to use different versions of python (eg: \fB\fClayout python python3\fR). .PP Note that previously virtualenv was located under \fB\fC$PWD/.direnv/virtualenv\fR and will be re\-used by direnv if it exists. .IP \(bu 2 .PP \fB\fClayout python3\fR: A shortcut for \fB\fClayout python python3\fR .IP \(bu 2 .PP \fB\fClayout ruby\fR: Sets the GEM\_HOME environment variable to \fB\fC$PWD/.direnv/ruby/RUBY\_VERSION\fR\&. This forces the installation of any gems into the project's sub\-\&folder. If you're using bundler it will create wrapper programs that can be invoked directly instead of using the \fB\fCbundle exec\fR prefix. .IP \(bu 2 .PP \fB\fCuse\fR \fIprogram\_name\fP [\fIversion\fP]: A semantic command dispatch intended for loading external dependencies into the environment. .PP Example: .PP .RS .nf use\_ruby() { echo "Ruby $1" } use ruby 1.9.3 # output: Ruby 1.9.3 .fi .RE .IP \(bu 2 \fB\fCuse rbenv\fR: Loads rbenv which add the ruby wrappers available on the PATH. .IP \(bu 2 .PP \fB\fCuse nix [...]\fR: Load environment variables from \fB\fCnix\-shell\fR\&. .PP If you have a \fB\fCdefault.nix\fR or \fB\fCshell.nix\fR these will be used by default, but you can also specify packages directly (e.g \fB\fCuse nix \-p ocaml\fR). .PP See \[la]http://nixos.org/nix/manual/#sec-nix-shell\[ra] .IP \(bu 2 .PP \fB\fCuse guix [...]\fR: Load environment variables from \fB\fCguix environment\fR\&. .PP Any arguments given will be passed to guix environment. For example, \fB\fCuse guix hello\fR would setup an environment with the dependencies of the hello package. To create an environment including hello, the \fB\fC\-\-ad\-hoc\fR flag is used \fB\fCuse guix \-\-ad\-hoc hello\fR\&. Other options include \fB\fC\-\-load\fR which allows loading an environment from a file. .PP See \[la]https://www.gnu.org/software/guix/manual/html_node/Invoking-guix-environment.html\[ra] .IP \(bu 2 .PP \fB\fCrvm\fR ...: Should work just like in the shell if you have rvm installed. .IP \(bu 2 .PP \fB\fCuse node\fR: Loads NodeJS version from a \fB\fC\&.node\-\&version\fR or \fB\fC\&.nvmrc\fR file. .PP If you specify a partial NodeJS version (i.e. \fB\fC4.2\fR), a fuzzy match is performed and the highest matching version installed is selected. .PP Example (.envrc): .PP .RS .nf set \-e use node .fi .RE .PP Example (.node\-version): .PP .RS .nf 4.2 .fi .RE .IP \(bu 2 \fB\fCuse node\fR version: Loads specified NodeJS version. .PP Example (.envrc): .PP .RS .nf set \-e use node 4.2.2 .fi .RE .IP \(bu 2 \fB\fCwatch\_file\fR path: Adds a file to direnv's watch\-list. If the file changes direnv will reload the environment on the next prompt. .PP Example (.envrc): .PP .RS .nf watch\_file Gemfile .fi .RE .SH COPYRIGHT .PP Copyright (C) 2014 zimbatm \[la]http://zimbatm.com\[ra] and contributors under the MIT licence. .SH SEE ALSO .PP direnv(1) direnv-2.15.0/man/direnv-stdlib.1.md000066400000000000000000000144351324410474700171050ustar00rootroot00000000000000DIRENV-STDLIB 1 "APRIL 2014" direnv "User Manuals" ================================================== NAME ---- direnv_stdlib - the ".envrc" stdlib SYNOPSIS -------- `direnv stdlib` DESCRIPTION ----------- Outputs a bash script called the *stdlib*. The following commands are included in that script and loaded in the context of an ".envrc". In addition, it also loads the file in "~/.direnvrc" if it exists. STDLIB ------ * `has` *command*: Returns 0 if the *command* is available. Returns 1 otherwise. It can be a binary in the PATH or a shell function. Example: if has curl; then echo "Yes we do" fi * `expand_path` *rel_path* [*relative_to*]: Outputs the absolute path of *rel_path* relative to *relative_to* or the current directory. Example: cd /usr/local/games expand_path ../foo # output: /usr/local/foo * `dotenv` [*dotenv_path*]: Loads a ".env" file into the current environment * `user_rel_path` *abs_path*: Transforms an absolute path *abs_path* into a user-relative path if possible. Example: echo $HOME # output: /home/user user_rel_path /home/user/my/project # output: ~/my/project user_rel_path /usr/local/lib # output: /usr/local/lib * `find_up` *filename*: Outputs the path of *filename* when searched from the current directory up to /. Returns 1 if the file has not been found. Example: cd /usr/local/my mkdir -p project/foo touch bar cd project/foo find_up bar # output: /usr/local/my/bar * `source_env` *file_or_dir_path*: Loads another ".envrc" either by specifying its path or filename. NOTE: the other ".envrc" is not checked by the security framework. * `source_up` [*filename*]: Loads another ".envrc" if found with the `find_up` command. NOTE: the other ".envrc" is not checked by the security framework. * `direnv_load` [*command-generating-dump-output*] Applies the environment generated by running *argv* as a command. This is useful for adopting the environment of a child process - cause that process to run "direnv dump" and then wrap the results with direnv_load. Example: direnv_load opam-env exec -- direnv dump * `PATH_add` *path*: Prepends the expanded *path* to the PATH environment variable. It prevents a common mistake where PATH is replaced by only the new *path*. Example: pwd # output: /home/user/my/project PATH_add bin echo $PATH # output: /home/user/my/project/bin:/usr/bin:/bin * `MANPATH_add` *path*: Prepends the expanded *path* to the MANPATH environment variable. It takes care of man-specific heuritic. * `path_add` *varname* *path*: Works like `PATH_add` except that it's for an arbitrary *varname*. * `load_prefix` *prefix_path*: Expands some common path variables for the given *prefix_path* prefix. This is useful if you installed something in the *prefix_path* using `./configure --prefix=$prefix_path && make install` and want to use it in the project. Variables set: CPATH LD_LIBRARY_PATH LIBRARY_PATH MANPATH PATH PKG_CONFIG_PATH Example: ./configure --prefix=$HOME/rubies/ruby-1.9.3 make && make install # Then in the .envrc load_prefix ~/rubies/ruby-1.9.3 * `layout` *type*: A semantic dispatch used to describe common project layouts. * `layout go`: Sets the GOPATH environment variable to the current directory. * `layout node`: Adds "$PWD/node_modules/.bin" to the PATH environment variable. * `layout perl`: Setup environment variables required by perl's local::lib See http://search.cpan.org/dist/local-lib/lib/local/lib.pm for more details * `layout python` [*python_exe*]: Creates and loads a virtualenv environment under `$PWD/.direnv/python-$python_version`. This forces the installation of any egg into the project's sub-folder. It's possible to specify the python executable if you want to use different versions of python (eg: `layout python python3`). Note that previously virtualenv was located under `$PWD/.direnv/virtualenv` and will be re-used by direnv if it exists. * `layout python3`: A shortcut for `layout python python3` * `layout ruby`: Sets the GEM_HOME environment variable to `$PWD/.direnv/ruby/RUBY_VERSION`. This forces the installation of any gems into the project's sub-folder. If you're using bundler it will create wrapper programs that can be invoked directly instead of using the `bundle exec` prefix. * `use` *program_name* [*version*]: A semantic command dispatch intended for loading external dependencies into the environment. Example: use_ruby() { echo "Ruby $1" } use ruby 1.9.3 # output: Ruby 1.9.3 * `use rbenv`: Loads rbenv which add the ruby wrappers available on the PATH. * `use nix [...]`: Load environment variables from `nix-shell`. If you have a `default.nix` or `shell.nix` these will be used by default, but you can also specify packages directly (e.g `use nix -p ocaml`). See http://nixos.org/nix/manual/#sec-nix-shell * `use guix [...]`: Load environment variables from `guix environment`. Any arguments given will be passed to guix environment. For example, `use guix hello` would setup an environment with the dependencies of the hello package. To create an environment including hello, the `--ad-hoc` flag is used `use guix --ad-hoc hello`. Other options include `--load` which allows loading an environment from a file. See https://www.gnu.org/software/guix/manual/html_node/Invoking-guix-environment.html * `rvm` ...: Should work just like in the shell if you have rvm installed. * `use node`: Loads NodeJS version from a `.node-version` or `.nvmrc` file. If you specify a partial NodeJS version (i.e. `4.2`), a fuzzy match is performed and the highest matching version installed is selected. Example (.envrc): set -e use node Example (.node-version): 4.2 * `use node` version: Loads specified NodeJS version. Example (.envrc): set -e use node 4.2.2 * `watch_file` path: Adds a file to direnv's watch-list. If the file changes direnv will reload the environment on the next prompt. Example (.envrc): watch_file Gemfile COPYRIGHT --------- Copyright (C) 2014 zimbatm and contributors under the MIT licence. SEE ALSO -------- direnv(1) direnv-2.15.0/man/direnv.1000066400000000000000000000073251324410474700152270ustar00rootroot00000000000000.TH DIRENV 1 "APRIL 2014" direnv "User Manuals" .SH NAME .PP direnv \- unclutter your .profile .SH SYNOPSIS .PP \fB\fCdirenv\fR \fIcommand\fP ... .SH DESCRIPTION .PP \fB\fCdirenv\fR is an environment variable manager for your shell. It knows how to hook into bash, zsh and fish shell to load or unload environment variables depending on your current directory. This allows you to have project\-specific environment variables and not clutter the "\~/.profile" file. .PP Before each prompt it checks for the existence of an ".envrc" file in the current and parent directories. If the file exists, it is loaded into a bash sub\-shell and all exported variables are then captured by direnv and then made available to your current shell. .PP Because direnv is compiled into a single static executable it is fast enough to be unnoticeable on each prompt. It is also language agnostic and can be used to build solutions similar to rbenv, pyenv, phpenv, ... .SH EXAMPLE .PP .RS .nf $ cd \~/my\_project $ echo ${FOO\-nope} nope $ echo export FOO=foo > .envrc .envrc is not allowed $ direnv allow . direnv: reloading direnv: loading .envrc direnv export: +FOO $ echo ${FOO\-nope} foo $ cd .. direnv: unloading direnv export: \~PATH $ echo ${FOO\-nope} nope .fi .RE .SH SETUP .PP For direnv to work properly it needs to be hooked into the shell. Each shell has it's own extension mechanism: .SS BASH .PP Add the following line at the end of your "\~/.bashrc" file: .PP \fB\fCeval "$(direnv hook bash)"\fR .PP Make sure it appears even after rvm, git\-prompt and other shell extensions that manipulate your prompt. .SS ZSH .PP Add the following line at the end of your "\~/.zshrc" file: .PP \fB\fCeval "$(direnv hook zsh)"\fR .SS FISH .PP Add the following line at the end of your "\~/.config/fish/config.fish" file: .PP \fB\fCeval (direnv hook fish)\fR .SS TCSH .PP Add the following line at the end of your "\~/.cshrc" file: .PP .RS .nf eval `direnv hook tcsh` .fi .RE .SH USAGE .PP In some target folder, create an ".envrc" file and add some export(1) directives in it. .PP On the next prompt you will notice that direnv complains about the ".envrc" being blocked. This is the security mechanism to avoid loading new files automatically. Otherwise any git repo that you pull, or tar archive that you unpack, would be able to wipe your hard drive once you \fB\fCcd\fR into it. .PP So here we are pretty sure that it won't do anything bad. Type \fB\fCdirenv allow .\fR and watch direnv loading your new environment. Note that \fB\fCdirenv edit .\fR is a handy shortcut that open the file in your $EDITOR and automatically allows it if the file's modification time has changed. .PP Now that the environment is loaded you can notice that once you \fB\fCcd\fR out of the directory it automatically gets unloaded. If you \fB\fCcd\fR back into it it's loaded again. That's the base of the mechanism that allows you to build cool things. .PP Exporting variables by hand is a bit repetitive so direnv provides a set of utility functions that are made available in the context of the ".envrc" file. Check the direnv\-stdlib(1) man page for more details. You can also define your own extensions inside a "\~/.direnvrc" file. .PP Hopefully this is enough to get you started. .SH CONTRIBUTE .PP Bug reports, contributions and forks are welcome. .PP All bugs or other forms of discussion happen on \[la]http://github.com/direnv/direnv/issues\[ra] .PP There is also a wiki available where you can share your usage patterns or other tips and tricks \[la]https://github.com/direnv/direnv/wiki\[ra] .PP Or drop by on the \[la]irc://#direnv@FreeNode\[ra] to have a chat. .SH COPYRIGHT .PP Copyright (C) 2014 zimbatm and contributors under the MIT licence. .SH SEE ALSO .PP direnv\-stdlib(1) direnv-2.15.0/man/direnv.1.md000066400000000000000000000071231324410474700156220ustar00rootroot00000000000000DIRENV 1 "APRIL 2014" direnv "User Manuals" =========================================== NAME ---- direnv - unclutter your .profile SYNOPSIS -------- `direnv` *command* ... DESCRIPTION ----------- `direnv` is an environment variable manager for your shell. It knows how to hook into bash, zsh and fish shell to load or unload environment variables depending on your current directory. This allows you to have project-specific environment variables and not clutter the "~/.profile" file. Before each prompt it checks for the existence of an ".envrc" file in the current and parent directories. If the file exists, it is loaded into a bash sub-shell and all exported variables are then captured by direnv and then made available to your current shell. Because direnv is compiled into a single static executable it is fast enough to be unnoticeable on each prompt. It is also language agnostic and can be used to build solutions similar to rbenv, pyenv, phpenv, ... EXAMPLE ------- ``` $ cd ~/my_project $ echo ${FOO-nope} nope $ echo export FOO=foo > .envrc .envrc is not allowed $ direnv allow . direnv: reloading direnv: loading .envrc direnv export: +FOO $ echo ${FOO-nope} foo $ cd .. direnv: unloading direnv export: ~PATH $ echo ${FOO-nope} nope ``` SETUP ----- For direnv to work properly it needs to be hooked into the shell. Each shell has it's own extension mechanism: ### BASH Add the following line at the end of your "~/.bashrc" file: `eval "$(direnv hook bash)"` Make sure it appears even after rvm, git-prompt and other shell extensions that manipulate your prompt. ### ZSH Add the following line at the end of your "~/.zshrc" file: `eval "$(direnv hook zsh)"` ### FISH Add the following line at the end of your "~/.config/fish/config.fish" file: `eval (direnv hook fish)` ### TCSH Add the following line at the end of your "~/.cshrc" file: eval `direnv hook tcsh` USAGE ----- In some target folder, create an ".envrc" file and add some export(1) directives in it. On the next prompt you will notice that direnv complains about the ".envrc" being blocked. This is the security mechanism to avoid loading new files automatically. Otherwise any git repo that you pull, or tar archive that you unpack, would be able to wipe your hard drive once you `cd` into it. So here we are pretty sure that it won't do anything bad. Type `direnv allow .` and watch direnv loading your new environment. Note that `direnv edit .` is a handy shortcut that open the file in your $EDITOR and automatically allows it if the file's modification time has changed. Now that the environment is loaded you can notice that once you `cd` out of the directory it automatically gets unloaded. If you `cd` back into it it's loaded again. That's the base of the mechanism that allows you to build cool things. Exporting variables by hand is a bit repetitive so direnv provides a set of utility functions that are made available in the context of the ".envrc" file. Check the direnv-stdlib(1) man page for more details. You can also define your own extensions inside a "~/.direnvrc" file. Hopefully this is enough to get you started. CONTRIBUTE ---------- Bug reports, contributions and forks are welcome. All bugs or other forms of discussion happen on There is also a wiki available where you can share your usage patterns or other tips and tricks Or drop by on the [#direnv channel on FreeNode](irc://#direnv@FreeNode) to have a chat. COPYRIGHT --------- Copyright (C) 2014 zimbatm and contributors under the MIT licence. SEE ALSO -------- direnv-stdlib(1) direnv-2.15.0/man/direnv.toml.1000066400000000000000000000070171324410474700161770ustar00rootroot00000000000000.TH DIRENV.TOML "FEBRUARY 2018" direnv "User Manuals" .SH NAME .PP direnv.toml \- the direnv configuration file .SH DESCRIPTION .PP A configuration file in TOML \[la]https://github.com/toml-lang/toml\[ra] format to specify a variety of configuration options for direnv. Resides at CONFIGURATION\_DIR/config.toml. For many users, this will be located at $HOME/.config/direnv/config.toml. .SH FORMAT .PP See the TOML GitHub Repository \[la]https://github.com/toml-lang/toml\[ra] for details about the syntax of the configuration file. .SH CONFIG .PP The configuration is specified in sections which each have their own top\-level tables \[la]https://github.com/toml-lang/toml#table\[ra], with key/value pairs specified in each section. .PP Example: .PP .RS .nf [section] key = "value" .fi .RE .PP The following sections are supported: .SH \fB\fCwhitelist\fR .PP Specifying whitelist directives marks specific directory hierarchies or specific directories as "trusted" \-\- direnv will evaluate any matching .envrc files regardless of whether they have been specifically allowed. \fBThis feature should be used with great care\fP, as anyone with the ability to write files to that directory (including collaborators on VCS repositories) will be able to execute arbitrary code on your computer. .PP There are two types of whitelist directives supported: .SS \fB\fCprefix\fR .PP Accepts an array of strings. If any of the strings in this list are a prefix of an .envrc file's absolute path, that file will be implicitly allowed, regardless of contents or past usage of \fB\fCdirenv allow\fR or \fB\fCdirenv deny\fR\&. .PP Example: .PP .RS .nf [whitelist] prefix = [ "/home/user/code/project\-a" ] .fi .RE .PP In this example, the following .envrc files will be implicitly allowed: .IP \(bu 2 \fB\fC/home/user/code/project\-a/.envrc\fR .IP \(bu 2 \fB\fC/home/user/code/project\-a/subdir/.envrc\fR .IP \(bu 2 and so on .PP In this example, the following .envrc files will not be implicitly allowed (although they can be explicitly allowed by running \fB\fCdirenv allow\fR): .IP \(bu 2 \fB\fC/home/user/project\-b/.envrc\fR .IP \(bu 2 \fB\fC/opt/random/.envrc\fR .SS \fB\fCexact\fR .PP Accepts an array of strings. Each string can be a directory name or the full path to an .envrc file. If a directory name is passed, it will be treated as if it had been passed as itself with \fB\fC/.envrc\fR appended. After resolving the filename, each string will be checked for being an exact match with an .envrc file's absolute path. If they match exactly, that .envrc file will be implicitly allowed, regardless of contents or past usage of \fB\fCdirenv allow\fR or \fB\fCdirenv deny\fR\&. .PP Example: .PP .RS .nf [whitelist] exact = [ "/home/user/project\-b/.envrc", "/home/user/project\-b/subdir\-a" ] .fi .RE .PP In this example, the following .envrc files will be implicitly allowed, and no others: .IP \(bu 2 \fB\fC/home/user/code/project\-b/.envrc\fR .IP \(bu 2 \fB\fC/home/user/code/project\-b/subdir\-a\fR .PP In this example, the following .envrc files will not be implicitly allowed (although they can be explicitly allowed by running \fB\fCdirenv allow\fR): .IP \(bu 2 \fB\fC/home/user/code/project\-b/subproject\-c/.envrc\fR .IP \(bu 2 \fB\fC/home/user/code/.envrc\fR .SH \fB\fCbash\_path\fR .PP This allows to hard\-code the position of bash. It maybe be useful to set this to avoid having direnv to fail when PATH is being mutated. .SH COPYRIGHT .PP Copyright (C) 2018 zimbatm \[la]http://zimbatm.com\[ra] and contributors under the MIT licence. .SH SEE ALSO .PP direnv(1) direnv-2.15.0/man/direnv.toml.1.md000066400000000000000000000063551324410474700166020ustar00rootroot00000000000000DIRENV.TOML "FEBRUARY 2018" direnv "User Manuals" ================================================== NAME ---- direnv.toml - the direnv configuration file DESCRIPTION ----------- A configuration file in [TOML](https://github.com/toml-lang/toml) format to specify a variety of configuration options for direnv. Resides at CONFIGURATION_DIR/config.toml. For many users, this will be located at $HOME/.config/direnv/config.toml. FORMAT ------ See the [TOML GitHub Repository](https://github.com/toml-lang/toml) for details about the syntax of the configuration file. CONFIG ------ The configuration is specified in sections which each have their own top-level [tables](https://github.com/toml-lang/toml#table), with key/value pairs specified in each section. Example: ```toml [section] key = "value" ``` The following sections are supported: ## `whitelist` Specifying whitelist directives marks specific directory hierarchies or specific directories as "trusted" -- direnv will evaluate any matching .envrc files regardless of whether they have been specifically allowed. **This feature should be used with great care**, as anyone with the ability to write files to that directory (including collaborators on VCS repositories) will be able to execute arbitrary code on your computer. There are two types of whitelist directives supported: ### `prefix` Accepts an array of strings. If any of the strings in this list are a prefix of an .envrc file's absolute path, that file will be implicitly allowed, regardless of contents or past usage of `direnv allow` or `direnv deny`. Example: ```toml [whitelist] prefix = [ "/home/user/code/project-a" ] ``` In this example, the following .envrc files will be implicitly allowed: * `/home/user/code/project-a/.envrc` * `/home/user/code/project-a/subdir/.envrc` * and so on In this example, the following .envrc files will not be implicitly allowed (although they can be explicitly allowed by running `direnv allow`): * `/home/user/project-b/.envrc` * `/opt/random/.envrc` ### `exact` Accepts an array of strings. Each string can be a directory name or the full path to an .envrc file. If a directory name is passed, it will be treated as if it had been passed as itself with `/.envrc` appended. After resolving the filename, each string will be checked for being an exact match with an .envrc file's absolute path. If they match exactly, that .envrc file will be implicitly allowed, regardless of contents or past usage of `direnv allow` or `direnv deny`. Example: ```toml [whitelist] exact = [ "/home/user/project-b/.envrc", "/home/user/project-b/subdir-a" ] ``` In this example, the following .envrc files will be implicitly allowed, and no others: * `/home/user/code/project-b/.envrc` * `/home/user/code/project-b/subdir-a` In this example, the following .envrc files will not be implicitly allowed (although they can be explicitly allowed by running `direnv allow`): * `/home/user/code/project-b/subproject-c/.envrc` * `/home/user/code/.envrc` ## `bash_path` This allows to hard-code the position of bash. It maybe be useful to set this to avoid having direnv to fail when PATH is being mutated. COPYRIGHT --------- Copyright (C) 2018 zimbatm and contributors under the MIT licence. SEE ALSO -------- direnv(1) direnv-2.15.0/marshal.go000066400000000000000000000021511324410474700150510ustar00rootroot00000000000000package main import ( "bytes" "compress/zlib" "encoding/base64" "encoding/json" "fmt" "io" "strings" ) func marshal(obj interface{}) string { jsonData, err := json.Marshal(obj) if err != nil { panic(fmt.Errorf("marshal(): %v", err)) } zlibData := bytes.NewBuffer([]byte{}) w := zlib.NewWriter(zlibData) w.Write(jsonData) w.Close() base64Data := base64.URLEncoding.EncodeToString(zlibData.Bytes()) return base64Data } func unmarshal(base64env string, obj interface{}) error { base64env = strings.TrimSpace(base64env) data, err := base64.URLEncoding.DecodeString(base64env) if err != nil { return fmt.Errorf("unmarshal() base64 decoding: %v", err) } zlibReader := bytes.NewReader(data) w, err := zlib.NewReader(zlibReader) if err != nil { return fmt.Errorf("unmarshal() zlib opening: %v", err) } envData := bytes.NewBuffer([]byte{}) _, err = io.Copy(envData, w) if err != nil { return fmt.Errorf("unmarshal() zlib decoding: %v", err) } w.Close() err = json.Unmarshal(envData.Bytes(), &obj) if err != nil { return fmt.Errorf("unmarshal() json parsing: %v", err) } return nil } direnv-2.15.0/rc.go000066400000000000000000000112161324410474700140300ustar00rootroot00000000000000package main import ( "crypto/sha256" "fmt" "io" "io/ioutil" "os" "os/exec" "path/filepath" "strings" "time" ) type RC struct { path string allowPath string times FileTimes config *Config } func FindRC(wd string, config *Config) *RC { rcPath := findUp(wd, ".envrc") if rcPath == "" { return nil } return RCFromPath(rcPath, config) } func RCFromPath(path string, config *Config) *RC { hash, err := fileHash(path) if err != nil { return nil } allowPath := filepath.Join(config.AllowDir(), hash) times := NewFileTimes() times.Update(path) times.Update(allowPath) return &RC{path, allowPath, times, config} } func RCFromEnv(path, marshalled_times string, config *Config) *RC { times := NewFileTimes() times.Unmarshal(marshalled_times) return &RC{path, "", times, config} } func (self *RC) Allow() (err error) { if self.allowPath == "" { return fmt.Errorf("Cannot allow empty path") } if err = os.MkdirAll(filepath.Dir(self.allowPath), 0755); err != nil { return } if err = allow(self.path, self.allowPath); err != nil { return } self.times.Update(self.allowPath) return } func (self *RC) Deny() error { return os.Remove(self.allowPath) } func (self *RC) Allowed() bool { // happy path is if this envrc has been explicitly allowed, O(1)ish common case _, err := os.Stat(self.allowPath) if err == nil { return true } // when whitelisting we want to be (path) absolutely sure we've not been duped with a symlink path, err := filepath.Abs(self.path) // seems unlikely that we'd hit this, but have to handle it if err != nil { return false } // exact whitelists are O(1)ish to check, so look there first if self.config.WhitelistExact[path] { return true } // finally we check if any of our whitelist prefixes match for _, prefix := range self.config.WhitelistPrefix { if strings.HasPrefix(path, prefix) { return true } } return false } // Makes the path relative to the current directory. Except when both paths // are completely different. // Eg: /home/foo and /home/bar => ../foo // But: /home/foo and /tmp/bar => /home/foo func (self *RC) RelTo(wd string) string { if rootDir(wd) != rootDir(self.path) { return self.path } x, err := filepath.Rel(wd, self.path) if err != nil { panic(err) } return x } func (self *RC) Touch() error { return touch(self.path) } const NOT_ALLOWED = "%s is blocked. Run `direnv allow` to approve its content." func (self *RC) Load(config *Config, env Env) (newEnv Env, err error) { wd := config.WorkDir direnv := config.SelfPath shellEnv := env.Copy() shellEnv[DIRENV_WATCHES] = self.times.Marshal() if !self.Allowed() { return nil, fmt.Errorf(NOT_ALLOWED, self.RelTo(wd)) } argtmpl := `eval "$("%s" stdlib)" >&2 && source_env "%s" >&2 && "%s" dump` arg := fmt.Sprintf(argtmpl, direnv, self.RelTo(wd), direnv) cmd := exec.Command(config.BashPath, "--noprofile", "--norc", "-c", arg) cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr cmd.Env = shellEnv.ToGoEnv() cmd.Dir = wd out, err := cmd.Output() if err != nil { return } newEnv, err = LoadEnv(string(out)) if err != nil { return } self.RecordState(env, newEnv) return } func (self *RC) RecordState(env Env, newEnv Env) { newEnv[DIRENV_DIR] = "-" + filepath.Dir(self.path) newEnv[DIRENV_DIFF] = env.Diff(newEnv).Serialize() } /// Utils func rootDir(path string) string { path, err := filepath.Abs(path) if err != nil { panic(err) } i := strings.Index(path[1:], "/") if i < 0 { return path } return path[:i+1] } func eachDir(path string) (paths []string) { path, err := filepath.Abs(path) if err != nil { return } paths = []string{path} if path == "/" { return } for i := len(path) - 1; i >= 0; i-- { if path[i] == os.PathSeparator { path = path[:i] if path == "" { path = "/" } paths = append(paths, path) } } return } func fileExists(path string) bool { _, err := os.Stat(path) return err == nil } func fileHash(path string) (hash string, err error) { if path, err = filepath.Abs(path); err != nil { return } fd, err := os.Open(path) if err != nil { return } hasher := sha256.New() hasher.Write([]byte(path + "\n")) if _, err = io.Copy(hasher, fd); err != nil { return } return fmt.Sprintf("%x", hasher.Sum(nil)), nil } // Creates a file func touch(path string) (err error) { t := time.Now() return os.Chtimes(path, t, t) } func allow(path string, allowPath string) (err error) { return ioutil.WriteFile(allowPath, []byte(path+"\n"), 0644) } func findUp(searchDir string, fileName string) (path string) { for _, dir := range eachDir(searchDir) { path = filepath.Join(dir, fileName) if fileExists(path) { return } } return "" } direnv-2.15.0/rc_test.go000066400000000000000000000006021324410474700150640ustar00rootroot00000000000000package main import ( "testing" ) func TestSomething(t *testing.T) { paths := eachDir("/foo/b//bar/") if len(paths) != 4 { t.Fail() } paths = eachDir("/") if len(paths) != 1 && paths[0] != "/" { t.Fail() } } func TestRootDir(t *testing.T) { var r string r = rootDir("/foo") if r != "/foo" { t.Error(r) } r = rootDir("/foo/bar") if r != "/foo" { t.Error(r) } } direnv-2.15.0/script/000077500000000000000000000000001324410474700144005ustar00rootroot00000000000000direnv-2.15.0/script/str2go000077500000000000000000000001311324410474700155410ustar00rootroot00000000000000#!/bin/sh # # Usage: str2go # exec go run "$0.go" -- "$@" direnv-2.15.0/script/str2go.go000066400000000000000000000016601324410474700161520ustar00rootroot00000000000000package main import ( "bufio" "flag" "fmt" "io" "os" "unicode" ) const ( BackSlash = '\\' NewLine = '\n' DoubleQuote = '"' ) func printRune(w *bufio.Writer, r rune) { switch r { case BackSlash: w.WriteRune(BackSlash) w.WriteRune(BackSlash) case NewLine: w.WriteString("\\n\" +\n\t\"") case DoubleQuote: w.WriteRune(BackSlash) w.WriteRune(DoubleQuote) default: if !IsASCII(r) { panic("only ASCII is supported") } w.WriteRune(r) } } func IsASCII(r rune) bool { return r < unicode.MaxASCII } func main() { flag.Parse() packageName := flag.Arg(0) constantName := flag.Arg(1) in := bufio.NewReader(os.Stdin) out := bufio.NewWriter(os.Stdout) defer out.Flush() fmt.Fprintf(out, "package %s\n\nconst %s = \"", packageName, constantName) for { r, _, err := in.ReadRune() if err != nil { if err == io.EOF { break } panic(err) } printRune(out, r) } fmt.Fprint(out, "\"\n") } direnv-2.15.0/shell.go000066400000000000000000000012721324410474700145340ustar00rootroot00000000000000package main import ( "path/filepath" ) /* * Shells */ type Shell interface { Hook() (string, error) Export(e ShellExport) string } // Used to describe what to generate for the shell type ShellExport map[string]*string func (e ShellExport) Add(key, value string) { e[key] = &value } func (e ShellExport) Remove(key string) { e[key] = nil } func DetectShell(target string) Shell { target = filepath.Base(target) // $0 starts with "-" if target[0:1] == "-" { target = target[1:] } switch target { case "bash": return BASH case "zsh": return ZSH case "fish": return FISH case "vim": return VIM case "tcsh": return TCSH case "json": return JSON } return nil } direnv-2.15.0/shell_bash.go000066400000000000000000000057621324410474700155410ustar00rootroot00000000000000package main import "fmt" type bash int var BASH bash const BASH_HOOK = ` _direnv_hook() { local previous_exit_status=$?; eval "$(direnv export bash)"; return $previous_exit_status; }; if ! [[ "$PROMPT_COMMAND" =~ _direnv_hook ]]; then PROMPT_COMMAND="_direnv_hook;$PROMPT_COMMAND"; fi ` func (b bash) Hook() (string, error) { return BASH_HOOK, nil } func (b bash) Export(e ShellExport) (out string) { for key, value := range e { if value == nil { out += b.unset(key) } else { out += b.export(key, *value) } } return out } func (b bash) export(key, value string) string { return "export " + b.escape(key) + "=" + b.escape(value) + ";" } func (b bash) unset(key string) string { return "unset " + b.escape(key) + ";" } func (b bash) escape(str string) string { return BashEscape(str) } /* * Escaping */ const ( ACK = 6 TAB = 9 LF = 10 CR = 13 US = 31 SPACE = 32 AMPERSTAND = 38 SINGLE_QUOTE = 39 PLUS = 43 NINE = 57 QUESTION = 63 LOWERCASE_Z = 90 OPEN_BRACKET = 91 BACKSLASH = 92 UNDERSCORE = 95 CLOSE_BRACKET = 93 BACKTICK = 96 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 "''" } in := []byte(str) out := "" i := 0 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 == 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 <= LOWERCASE_Z: literal(char) case char == OPEN_BRACKET: quoted(char) case char == BACKSLASH: backslash(char) case char <= CLOSE_BRACKET: quoted(char) case char == UNDERSCORE: literal(char) case char <= BACKTICK: quoted(char) case char <= LOWERCASE_Z: literal(char) case char <= TILDA: quoted(char) case char == DEL: hex(char) default: hex(char) } i += 1 } if escape { out = "$'" + out + "'" } return out } direnv-2.15.0/shell_fish.go000066400000000000000000000030651324410474700155470ustar00rootroot00000000000000package main import ( "fmt" "strings" ) type fish int var FISH fish const FISH_HOOK = ` function __direnv_export_eval --on-event fish_prompt; eval (direnv export fish); end ` func (f fish) Hook() (string, error) { return FISH_HOOK, nil } func (f fish) Export(e ShellExport) (out string) { for key, value := range e { if value == nil { out += f.unset(key) } else { out += f.export(key, *value) } } return out } func (f fish) export(key, value string) string { if key == "PATH" { command := "set -x -g PATH" for _, path := range strings.Split(value, ":") { command += " " + f.escape(path) } return command + ";" } return "set -x -g " + f.escape(key) + " " + f.escape(value) + ";" } func (f fish) unset(key string) string { return "set -e -g " + f.escape(key) + ";" } func (f fish) escape(str string) string { in := []byte(str) out := "'" i := 0 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 += 1 } out += "'" return out } direnv-2.15.0/shell_json.go000066400000000000000000000005631324410474700155670ustar00rootroot00000000000000package main import ( "encoding/json" "errors" ) type jsonShell int var JSON jsonShell func (s jsonShell) Hook() (string, error) { return "", errors.New("this feature is not supported") } func (s jsonShell) Export(e ShellExport) string { out, err := json.MarshalIndent(e, "", " ") if err != nil { // Should never happen panic(err) } return string(out) } direnv-2.15.0/shell_tcsh.go000066400000000000000000000037751324410474700155670ustar00rootroot00000000000000package main import ( "fmt" "strings" ) type tcsh int var TCSH tcsh func (f tcsh) Hook() (string, error) { return "alias precmd 'eval `direnv export tcsh`' ", nil } func (f tcsh) Export(e ShellExport) (out string) { for key, value := range e { if value == nil { out += f.unset(key) } else { out += f.export(key, *value) } } return out } func (f tcsh) export(key, value string) string { if key == "PATH" { command := "set path = (" for _, path := range strings.Split(value, ":") { command += " " + f.escape(path) } return command + " );" } return "setenv " + f.escape(key) + " " + f.escape(value) + " ;" } func (f tcsh) unset(key string) string { return "unsetenv " + f.escape(key) + " ;" } func (f tcsh) escape(str string) string { if str == "" { return "''" } in := []byte(str) out := "" i := 0 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 } quoted := func(char byte) { out += string([]byte{char}) } 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 == SPACE: backslash(char) 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 <= LOWERCASE_Z: literal(char) case char == OPEN_BRACKET: quoted(char) case char == BACKSLASH: backslash(char) case char <= CLOSE_BRACKET: quoted(char) case char == UNDERSCORE: literal(char) case char <= BACKTICK: quoted(char) case char <= LOWERCASE_Z: literal(char) case char <= TILDA: quoted(char) case char == DEL: hex(char) default: hex(char) } i += 1 } return out } direnv-2.15.0/shell_test.go000066400000000000000000000015511324410474700155730ustar00rootroot00000000000000package main import ( "testing" ) func TestBashEscape(t *testing.T) { assertEqual(t, `''`, BashEscape("")) assertEqual(t, `$'escape\'quote'`, BashEscape("escape'quote")) assertEqual(t, `$'foo\r\n\tbar'`, BashEscape("foo\r\n\tbar")) assertEqual(t, `$'foo bar'`, BashEscape("foo bar")) assertEqual(t, `$'\xc3\xa9'`, BashEscape("é")) } func TestShellDetection(t *testing.T) { assertNotNil(t, DetectShell("-bash")) assertNotNil(t, DetectShell("-/bin/bash")) assertNotNil(t, DetectShell("-/usr/local/bin/bash")) assertNotNil(t, DetectShell("-zsh")) assertNotNil(t, DetectShell("-/bin/zsh")) assertNotNil(t, DetectShell("-/usr/local/bin/zsh")) } func assertNotNil(t *testing.T, a Shell) { if a == nil { t.Error("Expected not to be nil") } } func assertEqual(t *testing.T, a, b string) { if a != b { t.Errorf("Expected \"%v\" to equal \"%v\"", b, a) } } direnv-2.15.0/shell_vim.go000066400000000000000000000015421324410474700154070ustar00rootroot00000000000000package main import ( "errors" "strings" ) type vim int var VIM vim func (x vim) Hook() (string, error) { return "", errors.New("this feature is not supported. Install the direnv.vim plugin instead.") } func (x vim) Export(e ShellExport) (out string) { for key, value := range e { if value == nil { out += x.unset(key) } else { out += x.export(key, *value) } } return out } func (x vim) export(key, value string) string { return "let $" + x.escapeKey(key) + " = " + x.escapeValue(value) + "\n" } func (x vim) unset(key string) string { return "let $" + x.escapeKey(key) + " = ''\n" } // TODO: support keys with special chars or fail func (x vim) escapeKey(str string) string { return str } // TODO: Make sure this escaping is valid func (x vim) escapeValue(str string) string { return "'" + strings.Replace(str, "'", "''", -1) + "'" } direnv-2.15.0/shell_zsh.go000066400000000000000000000014251324410474700154200ustar00rootroot00000000000000package main // ZSH is a singleton instance of ZSH_T type zsh int var ZSH zsh const ZSH_HOOK = ` _direnv_hook() { eval "$(direnv export zsh)"; } typeset -ag precmd_functions; if [[ -z ${precmd_functions[(r)_direnv_hook]} ]]; then precmd_functions+=_direnv_hook; fi ` func (z zsh) Hook() (string, error) { return ZSH_HOOK, nil } func (z zsh) Export(e ShellExport) (out string) { for key, value := range e { if value == nil { out += z.unset(key) } else { out += z.export(key, *value) } } return out } func (z zsh) export(key, value string) string { return "export " + z.escape(key) + "=" + z.escape(value) + ";" } func (z zsh) unset(key string) string { return "unset " + z.escape(key) + ";" } func (z zsh) escape(str string) string { return BashEscape(str) } direnv-2.15.0/stdlib.go000066400000000000000000000523721324410474700147150ustar00rootroot00000000000000package main const STDLIB = "#!bash\n" + "#\n" + "# These are the commands available in an .envrc context\n" + "#\n" + "set -e\n" + "direnv=\"%s\"\n" + "\n" + "# Config, change in the direnvrc\n" + "DIRENV_LOG_FORMAT=\"${DIRENV_LOG_FORMAT-direnv: %%s}\"\n" + "\n" + "# Usage: direnv_layout_dir\n" + "#\n" + "# Prints the folder path that direnv should use to store layout content.\n" + "# This needs to be a function as $PWD might change during source_env/up.\n" + "#\n" + "# The output defaults to $PWD/.direnv.\n" + "\n" + "direnv_layout_dir() {\n" + " echo \"${direnv_layout_dir:-$PWD/.direnv}\"\n" + "}\n" + "\n" + "# Usage: log_status [ ...]\n" + "#\n" + "# Logs a status message. Acts like echo,\n" + "# but wraps output in the standard direnv log format\n" + "# (controlled by $DIRENV_LOG_FORMAT), and directs it\n" + "# to stderr rather than stdout.\n" + "#\n" + "# Example:\n" + "#\n" + "# log_status \"Loading ...\"\n" + "#\n" + "log_status() {\n" + " if [[ -n $DIRENV_LOG_FORMAT ]]; then\n" + " local msg=$*\n" + " # shellcheck disable=SC2059\n" + " printf \"${DIRENV_LOG_FORMAT}\\n\" \"$msg\" >&2\n" + " fi\n" + "}\n" + "\n" + "# Usage: log_error [ ...]\n" + "#\n" + "# Logs an error message. Acts like echo,\n" + "# but wraps output in the standard direnv log format\n" + "# (controlled by $DIRENV_LOG_FORMAT), and directs it\n" + "# to stderr rather than stdout.\n" + "#\n" + "# Example:\n" + "#\n" + "# log_error \"Unable to find specified directory!\"\n" + "\n" + "log_error() {\n" + " local color_normal\n" + " local color_error\n" + " color_normal=$(tput sgr0)\n" + " color_error=$(tput setaf 1)\n" + " if [[ -n $DIRENV_LOG_FORMAT ]]; then\n" + " local msg=$*\n" + " # shellcheck disable=SC2059\n" + " printf \"${color_error}${DIRENV_LOG_FORMAT}${color_normal}\\n\" \"$msg\" >&2\n" + " fi\n" + "}\n" + "\n" + "# Usage: has \n" + "#\n" + "# Returns 0 if the is available. Returns 1 otherwise. It can be a\n" + "# binary in the PATH or a shell function.\n" + "#\n" + "# Example:\n" + "#\n" + "# if has curl; then\n" + "# echo \"Yes we do\"\n" + "# fi\n" + "#\n" + "has() {\n" + " type \"$1\" &>/dev/null\n" + "}\n" + "\n" + "# Usage: expand_path []\n" + "#\n" + "# Outputs the absolute path of relative to or the\n" + "# current directory.\n" + "#\n" + "# Example:\n" + "#\n" + "# cd /usr/local/games\n" + "# expand_path ../foo\n" + "# # output: /usr/local/foo\n" + "#\n" + "expand_path() {\n" + " \"$direnv\" expand_path \"$@\"\n" + "}\n" + "\n" + "# Usage: dotenv []\n" + "#\n" + "# Loads a \".env\" file into the current environment\n" + "#\n" + "dotenv() {\n" + " local path=$1\n" + " if [[ -z $path ]]; then\n" + " path=$PWD/.env\n" + " elif [[ -d $path ]]; then\n" + " path=$path/.env\n" + " fi\n" + " if ! [[ -f $path ]]; then\n" + " log_error \".env at $path not found\"\n" + " return 1\n" + " fi\n" + " eval \"$(\"$direnv\" dotenv bash \"$@\")\"\n" + " watch_file \"$path\"\n" + "}\n" + "\n" + "# Usage: user_rel_path \n" + "#\n" + "# Transforms an absolute path into a user-relative path if\n" + "# possible.\n" + "#\n" + "# Example:\n" + "#\n" + "# echo $HOME\n" + "# # output: /home/user\n" + "# user_rel_path /home/user/my/project\n" + "# # output: ~/my/project\n" + "# user_rel_path /usr/local/lib\n" + "# # output: /usr/local/lib\n" + "#\n" + "user_rel_path() {\n" + " local abs_path=${1#-}\n" + "\n" + " if [[ -z $abs_path ]]; then return; fi\n" + "\n" + " if [[ -n $HOME ]]; then\n" + " local rel_path=${abs_path#$HOME}\n" + " if [[ $rel_path != \"$abs_path\" ]]; then\n" + " abs_path=~$rel_path\n" + " fi\n" + " fi\n" + "\n" + " echo \"$abs_path\"\n" + "}\n" + "\n" + "# Usage: find_up \n" + "#\n" + "# Outputs the path of when searched from the current directory up to\n" + "# /. Returns 1 if the file has not been found.\n" + "#\n" + "# Example:\n" + "#\n" + "# cd /usr/local/my\n" + "# mkdir -p project/foo\n" + "# touch bar\n" + "# cd project/foo\n" + "# find_up bar\n" + "# # output: /usr/local/my/bar\n" + "#\n" + "find_up() {\n" + " (\n" + " while true; do\n" + " if [[ -f $1 ]]; then\n" + " echo \"$PWD/$1\"\n" + " return 0\n" + " fi\n" + " if [[ $PWD = / ]] || [[ $PWD = // ]]; then\n" + " return 1\n" + " fi\n" + " cd ..\n" + " done\n" + " )\n" + "}\n" + "\n" + "# Usage: source_env \n" + "#\n" + "# Loads another \".envrc\" either by specifying its path or filename.\n" + "#\n" + "# NOTE: the other \".envrc\" is not checked by the security framework.\n" + "source_env() {\n" + " local rcpath=${1/#\\~/$HOME}\n" + " local rcfile\n" + " if ! [[ -f $rcpath ]]; then\n" + " rcpath=$rcpath/.envrc\n" + " fi\n" + "\n" + " rcfile=$(user_rel_path \"$rcpath\")\n" + " watch_file \"$rcpath\"\n" + "\n" + " pushd \"$(pwd 2>/dev/null)\" > /dev/null\n" + " pushd \"$(dirname \"$rcpath\")\" > /dev/null\n" + " if [[ -f ./$(basename \"$rcpath\") ]]; then\n" + " log_status \"loading $rcfile\"\n" + " # shellcheck source=/dev/null\n" + " . \"./$(basename \"$rcpath\")\"\n" + " else\n" + " log_status \"referenced $rcfile does not exist\"\n" + " fi\n" + " popd > /dev/null\n" + " popd > /dev/null\n" + "}\n" + "\n" + "# Usage: watch_file \n" + "#\n" + "# Adds to the list of files that direnv will watch for changes - useful when the contents\n" + "# of a file influence how variables are set - especially in direnvrc\n" + "#\n" + "watch_file() {\n" + " local file=${1/#\\~/$HOME}\n" + "\n" + " eval \"$(\"$direnv\" watch \"$file\")\"\n" + "}\n" + "\n" + "\n" + "# Usage: source_up []\n" + "#\n" + "# Loads another \".envrc\" if found with the find_up command.\n" + "#\n" + "# NOTE: the other \".envrc\" is not checked by the security framework.\n" + "source_up() {\n" + " local file=$1\n" + " local dir\n" + " if [[ -z $file ]]; then\n" + " file=.envrc\n" + " fi\n" + " dir=$(cd .. && find_up \"$file\")\n" + " if [[ -n $dir ]]; then\n" + " source_env \"$dir\"\n" + " fi\n" + "}\n" + "\n" + "# Usage: direnv_load \n" + "# e.g: direnv_load opam-env exec -- direnv dump\n" + "#\n" + "# Applies the environment generated by running as a\n" + "# command. This is useful for adopting the environment of a child\n" + "# process - cause that process to run \"direnv dump\" and then wrap\n" + "# the results with direnv_load.\n" + "#\n" + "direnv_load() {\n" + " local exports\n" + " exports=$(\"$direnv\" apply_dump <(\"$@\"))\n" + " local es=$?\n" + " if [[ $es -ne 0 ]]; then\n" + " return $es\n" + " fi\n" + " eval \"$exports\"\n" + "}\n" + "\n" + "# Usage: PATH_add [ ...]\n" + "#\n" + "# Prepends the expanded to the PATH environment variable, in order.\n" + "# It prevents a common mistake where PATH is replaced by only the new ,\n" + "# or where a trailing colon is left in PATH, resulting in the current directory\n" + "# being considered in the PATH. Supports adding multiple directories at once.\n" + "#\n" + "# Example:\n" + "#\n" + "# pwd\n" + "# # output: /my/project\n" + "# PATH_add bin\n" + "# echo $PATH\n" + "# # output: /my/project/bin:/usr/bin:/bin\n" + "# PATH_add bam boum\n" + "# echo $PATH\n" + "# # output: /my/project/bam:/my/project/boum:/my/project/bin:/usr/bin:/bin\n" + "#\n" + "PATH_add() {\n" + " path_add PATH \"$@\"\n" + "}\n" + "\n" + "# Usage: path_add [ ...]\n" + "#\n" + "# Works like PATH_add except that it's for an arbitrary .\n" + "path_add() {\n" + " local var_name=\"$1\"\n" + " # split existing paths into an array\n" + " declare -a path_array\n" + " IFS=: read -ra path_array <<< \"${!1}\"\n" + " shift\n" + "\n" + " # prepend the passed paths in the right order\n" + " for (( i=$# ; i>0 ; i-- )); do\n" + " path_array=( \"$(expand_path \"${!i}\")\" \"${path_array[@]}\" )\n" + " done\n" + "\n" + " # join back all the paths\n" + " local path=$(IFS=:; echo \"${path_array[*]}\")\n" + "\n" + " # and finally export back the result to the original variable\n" + " export \"$var_name=$path\"\n" + "}\n" + "\n" + "# Usage: MANPATH_add \n" + "#\n" + "# Prepends a path to the MANPATH environment variable while making sure that\n" + "# `man` can still lookup the system manual pages.\n" + "#\n" + "# If MANPATH is not empty, man will only look in MANPATH.\n" + "# So if we set MANPATH=$path, man will only look in $path.\n" + "# Instead, prepend to `man -w` (which outputs man's default paths).\n" + "#\n" + "MANPATH_add() {\n" + " local old_paths=\"${MANPATH:-$(man -w)}\"\n" + " local dir\n" + " dir=$(expand_path \"$1\")\n" + " export \"MANPATH=$dir:$old_paths\"\n" + "}\n" + "\n" + "# Usage: load_prefix \n" + "#\n" + "# Expands some common path variables for the given prefix. This is\n" + "# useful if you installed something in the using\n" + "# $(./configure --prefix= && make install) and want to use it in\n" + "# the project.\n" + "#\n" + "# Variables set:\n" + "#\n" + "# CPATH\n" + "# LD_LIBRARY_PATH\n" + "# LIBRARY_PATH\n" + "# MANPATH\n" + "# PATH\n" + "# PKG_CONFIG_PATH\n" + "#\n" + "# Example:\n" + "#\n" + "# ./configure --prefix=$HOME/rubies/ruby-1.9.3\n" + "# make && make install\n" + "# # Then in the .envrc\n" + "# load_prefix ~/rubies/ruby-1.9.3\n" + "#\n" + "load_prefix() {\n" + " local dir\n" + " dir=$(expand_path \"$1\")\n" + " MANPATH_add \"$dir/man\"\n" + " MANPATH_add \"$dir/share/man\"\n" + " path_add CPATH \"$dir/include\"\n" + " path_add LD_LIBRARY_PATH \"$dir/lib\"\n" + " path_add LIBRARY_PATH \"$dir/lib\"\n" + " path_add PATH \"$dir/bin\"\n" + " path_add PKG_CONFIG_PATH \"$dir/lib/pkgconfig\"\n" + "}\n" + "\n" + "# Usage: layout \n" + "#\n" + "# A semantic dispatch used to describe common project layouts.\n" + "#\n" + "layout() {\n" + " local name=$1\n" + " shift\n" + " eval \"layout_$name\" \"$@\"\n" + "}\n" + "\n" + "# Usage: layout go\n" + "#\n" + "# Sets the GOPATH environment variable to the current directory.\n" + "#\n" + "layout_go() {\n" + " path_add GOPATH \"$PWD\"\n" + " PATH_add bin\n" + "}\n" + "\n" + "# Usage: layout node\n" + "#\n" + "# Adds \"$PWD/node_modules/.bin\" to the PATH environment variable.\n" + "layout_node() {\n" + " PATH_add node_modules/.bin\n" + "}\n" + "\n" + "# Usage: layout perl\n" + "#\n" + "# Setup environment variables required by perl's local::lib\n" + "# See http://search.cpan.org/dist/local-lib/lib/local/lib.pm for more details\n" + "#\n" + "layout_perl() {\n" + " local libdir=$(direnv_layout_dir)/perl5\n" + " export LOCAL_LIB_DIR=$libdir\n" + " export PERL_MB_OPT=\"--install_base '$libdir'\"\n" + " export PERL_MM_OPT=\"INSTALL_BASE=$libdir\"\n" + " path_add PERL5LIB \"$libdir/lib/perl5\"\n" + " path_add PERL_LOCAL_LIB_ROOT \"$libdir\"\n" + " PATH_add \"$libdir/bin\"\n" + "}\n" + "\n" + "# Usage: layout python \n" + "#\n" + "# Creates and loads a virtualenv environment under\n" + "# \"$direnv_layout_dir/python-$python_version\".\n" + "# This forces the installation of any egg into the project's sub-folder.\n" + "#\n" + "# It's possible to specify the python executable if you want to use different\n" + "# versions of python.\n" + "#\n" + "layout_python() {\n" + " local python=${1:-python}\n" + " [[ $# -gt 0 ]] && shift\n" + " local old_env=$(direnv_layout_dir)/virtualenv\n" + " unset PYTHONHOME\n" + " if [[ -d $old_env && $python = python ]]; then\n" + " export VIRTUAL_ENV=$old_env\n" + " else\n" + " local python_version\n" + " python_version=$(\"$python\" -c \"import platform as p;print(p.python_version())\")\n" + " if [[ -z $python_version ]]; then\n" + " log_error \"Could not find python's version\"\n" + " return 1\n" + " fi\n" + "\n" + " export VIRTUAL_ENV=$(direnv_layout_dir)/python-$python_version\n" + " if [[ ! -d $VIRTUAL_ENV ]]; then\n" + " virtualenv \"--python=$python\" \"$@\" \"$VIRTUAL_ENV\"\n" + " fi\n" + " fi\n" + " PATH_add \"$VIRTUAL_ENV/bin\"\n" + "}\n" + "\n" + "# Usage: layout python2\n" + "#\n" + "# A shortcut for $(layout python python2)\n" + "#\n" + "layout_python2() {\n" + " layout_python python2 \"$@\"\n" + "}\n" + "\n" + "# Usage: layout python3\n" + "#\n" + "# A shortcut for $(layout python python3)\n" + "#\n" + "layout_python3() {\n" + " layout_python python3 \"$@\"\n" + "}\n" + "\n" + "# Usage: layout anaconda []\n" + "#\n" + "# Activates anaconda for the named environment. If the environment\n" + "# hasn't been created, it will be using the environment.yml file in\n" + "# the current directory. is optional and will default to\n" + "# the one found in the system environment.\n" + "#\n" + "layout_anaconda() {\n" + " local env_name=$1\n" + " local conda\n" + " if [[ $# -gt 1 ]]; then\n" + " conda=${2}\n" + " else\n" + " conda=$(command -v conda)\n" + " fi\n" + " PATH_add $(dirname \"$conda\")\n" + " local env_loc=$(\"$conda\" env list | grep -- \"$env_name\")\n" + " if [[ ! \"$env_loc\" == $env_name*$env_name ]]; then\n" + " if [[ -e environment.yml ]]; then\n" + " log_status \"creating conda enviroment\"\n" + " \"$conda\" env create\n" + " else\n" + " log_error \"Could not find environment.yml\"\n" + " return 1\n" + " fi\n" + " fi\n" + "\n" + " source activate \"$env_name\"\n" + "}\n" + "\n" + "# Usage: layout pipenv\n" + "#\n" + "# Similar to layout_python, but uses Pipenv to build a\n" + "# virtualenv from the Pipfile located in the same directory.\n" + "#\n" + "layout_pipenv() {\n" + " if [[ ! -f Pipfile ]]; then\n" + " log_error 'No Pipfile found. Use `pipenv` to create a Pipfile first.'\n" + " exit 2\n" + " fi\n" + "\n" + " local VENV=$(pipenv --bare --venv 2>/dev/null)\n" + " if [[ -z $VENV || ! -d $VENV ]]; then\n" + " pipenv install --dev\n" + " fi\n" + "\n" + " export VIRTUAL_ENV=$(pipenv --venv)\n" + " PATH_add \"$VIRTUAL_ENV/bin\"\n" + " export PIPENV_ACTIVE=1\n" + "}\n" + "\n" + "# Usage: layout ruby\n" + "#\n" + "# Sets the GEM_HOME environment variable to \"$(direnv_layout_dir)/ruby/RUBY_VERSION\".\n" + "# This forces the installation of any gems into the project's sub-folder.\n" + "# If you're using bundler it will create wrapper programs that can be invoked\n" + "# directly instead of using the $(bundle exec) prefix.\n" + "#\n" + "layout_ruby() {\n" + " if ruby -e \"exit Gem::VERSION > '2.2.0'\" 2>/dev/null; then\n" + " export GEM_HOME=$(direnv_layout_dir)/ruby\n" + " else\n" + " local ruby_version\n" + " ruby_version=$(ruby -e\"puts (defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby') + '-' + RUBY_VERSION\")\n" + " export GEM_HOME=$(direnv_layout_dir)/ruby-${ruby_version}\n" + " fi\n" + " export BUNDLE_BIN=$(direnv_layout_dir)/bin\n" + "\n" + " PATH_add \"$GEM_HOME/bin\"\n" + " PATH_add \"$BUNDLE_BIN\"\n" + "}\n" + "\n" + "# Usage: use []\n" + "#\n" + "# A semantic command dispatch intended for loading external dependencies into\n" + "# the environment.\n" + "#\n" + "# Example:\n" + "#\n" + "# use_ruby() {\n" + "# echo \"Ruby $1\"\n" + "# }\n" + "# use ruby 1.9.3\n" + "# # output: Ruby 1.9.3\n" + "#\n" + "use() {\n" + " local cmd=$1\n" + " log_status \"using $*\"\n" + " shift\n" + " \"use_$cmd\" \"$@\"\n" + "}\n" + "\n" + "# Usage: use rbenv\n" + "#\n" + "# Loads rbenv which add the ruby wrappers available on the PATH.\n" + "#\n" + "use_rbenv() {\n" + " eval \"$(rbenv init -)\"\n" + "}\n" + "\n" + "# Usage: rvm [...]\n" + "#\n" + "# Should work just like in the shell if you have rvm installed.#\n" + "#\n" + "rvm() {\n" + " unset rvm\n" + " if [[ -n ${rvm_scripts_path:-} ]]; then\n" + " # shellcheck source=/dev/null\n" + " source \"${rvm_scripts_path}/rvm\"\n" + " elif [[ -n ${rvm_path:-} ]]; then\n" + " # shellcheck source=/dev/null\n" + " source \"${rvm_path}/scripts/rvm\"\n" + " else\n" + " # shellcheck source=/dev/null\n" + " source \"$HOME/.rvm/scripts/rvm\"\n" + " fi\n" + " rvm \"$@\"\n" + "}\n" + "\n" + "# Usage: use node\n" + "# Loads NodeJS version from a `.node-version` or `.nvmrc` file.\n" + "#\n" + "# Usage: use node \n" + "# Loads specified NodeJS version.\n" + "#\n" + "# If you specify a partial NodeJS version (i.e. `4.2`), a fuzzy match\n" + "# is performed and the highest matching version installed is selected.\n" + "#\n" + "# Environment Variables:\n" + "#\n" + "# - $NODE_VERSIONS (required)\n" + "# You must specify a path to your installed NodeJS versions via the `$NODE_VERSIONS` variable.\n" + "#\n" + "# - $NODE_VERSION_PREFIX (optional) [default=\"node-v\"]\n" + "# Overrides the default version prefix.\n" + "\n" + "use_node() {\n" + " local version=$1\n" + " local via=\"\"\n" + " local node_version_prefix=${NODE_VERSION_PREFIX-node-v}\n" + " local node_wanted\n" + " local node_prefix\n" + "\n" + " if [[ -z $NODE_VERSIONS ]] || [[ ! -d $NODE_VERSIONS ]]; then\n" + " log_error \"You must specify a \\$NODE_VERSIONS environment variable and the directory specified must exist!\"\n" + " return 1\n" + " fi\n" + "\n" + " if [[ -z $version ]] && [[ -f .nvmrc ]]; then\n" + " version=$(< .nvmrc)\n" + " via=\".nvmrc\"\n" + " fi\n" + "\n" + " if [[ -z $version ]] && [[ -f .node-version ]]; then\n" + " version=$(< .node-version)\n" + " via=\".node-version\"\n" + " fi\n" + "\n" + " if [[ -z $version ]]; then\n" + " log_error \"I do not know which NodeJS version to load because one has not been specified!\"\n" + " return 1\n" + " fi\n" + "\n" + " node_wanted=${node_version_prefix}${version}\n" + " node_prefix=$(\n" + " # Look for matching node versions in $NODE_VERSIONS path\n" + " find \"$NODE_VERSIONS\" -maxdepth 1 -mindepth 1 -type d -name \"$node_wanted*\" |\n" + "\n" + " # Strip possible \"/\" suffix from $NODE_VERSIONS, then use that to\n" + " # Strip $NODE_VERSIONS/$NODE_VERSION_PREFIX prefix from line.\n" + " while IFS= read -r line; do echo \"${line#${NODE_VERSIONS%/}/${node_version_prefix}}\"; done |\n" + "\n" + " # Sort by version: split by \".\" then reverse numeric sort for each piece of the version string\n" + " sort -t . -k 1,1rn -k 2,2rn -k 3,3rn |\n" + "\n" + " # The first one is the highest\n" + " head -1\n" + " )\n" + "\n" + " node_prefix=\"${NODE_VERSIONS}/${node_version_prefix}${node_prefix}\"\n" + "\n" + " if [[ ! -d $node_prefix ]]; then\n" + " log_error \"Unable to find NodeJS version ($version) in ($NODE_VERSIONS)!\"\n" + " return 1\n" + " fi\n" + "\n" + " if [[ ! -x $node_prefix/bin/node ]]; then\n" + " log_error \"Unable to load NodeJS binary (node) for version ($version) in ($NODE_VERSIONS)!\"\n" + " return 1\n" + " fi\n" + "\n" + " load_prefix \"$node_prefix\"\n" + "\n" + " if [[ -z $via ]]; then\n" + " log_status \"Successfully loaded NodeJS $(node --version), from prefix ($node_prefix)\"\n" + " else\n" + " log_status \"Successfully loaded NodeJS $(node --version) (via $via), from prefix ($node_prefix)\"\n" + " fi\n" + "}\n" + "\n" + "# Usage: use_nix [...]\n" + "#\n" + "# Load environment variables from `nix-shell`.\n" + "# If you have a `default.nix` or `shell.nix` these will be\n" + "# used by default, but you can also specify packages directly\n" + "# (e.g `use nix -p ocaml`).\n" + "#\n" + "use_nix() {\n" + " local orig_IN_NIX_SHELL=\"$IN_NIX_SHELL\"\n" + "\n" + " direnv_load nix-shell --show-trace \"$@\" --run 'direnv dump'\n" + " if [[ $# = 0 ]]; then\n" + " watch_file default.nix\n" + " watch_file shell.nix\n" + " fi\n" + "\n" + " # Don't change the IN_NIX_SHELL env var\n" + " if [[ -z $orig_IN_NIX_SHELL ]]; then\n" + " unset IN_NIX_SHELL\n" + " else\n" + " export IN_NIX_SHELL=\"$orig_IN_NIX_SHELL\"\n" + " fi\n" + "}\n" + "\n" + "# Usage: use_guix [...]\n" + "#\n" + "# Load environment variables from `guix environment`.\n" + "# Any arguments given will be passed to guix environment. For example,\n" + "# `use guix hello` would setup an environment with the dependencies of\n" + "# the hello package. To create an environment including hello, the\n" + "# `--ad-hoc` flag is used `use guix --ad-hoc hello`. Other options\n" + "# include `--load` which allows loading an environment from a\n" + "# file. For a full list of options, consult the documentation for the\n" + "# `guix environment` command.\n" + "use_guix() {\n" + " eval \"$(guix environment \"$@\" --search-paths)\"\n" + "}\n" + "\n" + "## Load the global ~/.direnvrc if present\n" + "if [[ -f ${XDG_CONFIG_HOME:-$HOME/.config}/direnv/direnvrc ]]; then\n" + " source \"${XDG_CONFIG_HOME:-$HOME/.config}/direnv/direnvrc\" >&2\n" + "elif [[ -f $HOME/.direnvrc ]]; then\n" + " source \"$HOME/.direnvrc\" >&2\n" + "fi\n" + "" direnv-2.15.0/stdlib.sh000066400000000000000000000405521324410474700147170ustar00rootroot00000000000000#!bash # # These are the commands available in an .envrc context # set -e direnv="%s" # Config, change in the direnvrc DIRENV_LOG_FORMAT="${DIRENV_LOG_FORMAT-direnv: %%s}" # Usage: direnv_layout_dir # # Prints the folder path that direnv should use to store layout content. # This needs to be a function as $PWD might change during source_env/up. # # The output defaults to $PWD/.direnv. direnv_layout_dir() { echo "${direnv_layout_dir:-$PWD/.direnv}" } # Usage: log_status [ ...] # # Logs a status message. Acts like echo, # but wraps output in the standard direnv log format # (controlled by $DIRENV_LOG_FORMAT), and directs it # to stderr rather than stdout. # # Example: # # log_status "Loading ..." # log_status() { if [[ -n $DIRENV_LOG_FORMAT ]]; then local msg=$* # shellcheck disable=SC2059 printf "${DIRENV_LOG_FORMAT}\n" "$msg" >&2 fi } # Usage: log_error [ ...] # # Logs an error message. Acts like echo, # but wraps output in the standard direnv log format # (controlled by $DIRENV_LOG_FORMAT), and directs it # to stderr rather than stdout. # # Example: # # log_error "Unable to find specified directory!" log_error() { local color_normal local color_error color_normal=$(tput sgr0) color_error=$(tput setaf 1) if [[ -n $DIRENV_LOG_FORMAT ]]; then local msg=$* # shellcheck disable=SC2059 printf "${color_error}${DIRENV_LOG_FORMAT}${color_normal}\n" "$msg" >&2 fi } # Usage: has # # Returns 0 if the is available. Returns 1 otherwise. It can be a # binary in the PATH or a shell function. # # Example: # # if has curl; then # echo "Yes we do" # fi # has() { type "$1" &>/dev/null } # Usage: expand_path [] # # Outputs the absolute path of relative to or the # current directory. # # Example: # # cd /usr/local/games # expand_path ../foo # # output: /usr/local/foo # expand_path() { "$direnv" expand_path "$@" } # Usage: dotenv [] # # Loads a ".env" file into the current environment # dotenv() { local path=$1 if [[ -z $path ]]; then path=$PWD/.env elif [[ -d $path ]]; then path=$path/.env fi if ! [[ -f $path ]]; then log_error ".env at $path not found" return 1 fi eval "$("$direnv" dotenv bash "$@")" watch_file "$path" } # Usage: user_rel_path # # Transforms an absolute path into a user-relative path if # possible. # # Example: # # echo $HOME # # output: /home/user # user_rel_path /home/user/my/project # # output: ~/my/project # user_rel_path /usr/local/lib # # output: /usr/local/lib # user_rel_path() { local abs_path=${1#-} if [[ -z $abs_path ]]; then return; fi if [[ -n $HOME ]]; then local rel_path=${abs_path#$HOME} if [[ $rel_path != "$abs_path" ]]; then abs_path=~$rel_path fi fi echo "$abs_path" } # Usage: find_up # # Outputs the path of when searched from the current directory up to # /. Returns 1 if the file has not been found. # # Example: # # cd /usr/local/my # mkdir -p project/foo # touch bar # cd project/foo # find_up bar # # output: /usr/local/my/bar # find_up() { ( while true; do if [[ -f $1 ]]; then echo "$PWD/$1" return 0 fi if [[ $PWD = / ]] || [[ $PWD = // ]]; then return 1 fi cd .. done ) } # Usage: source_env # # Loads another ".envrc" either by specifying its path or filename. # # NOTE: the other ".envrc" is not checked by the security framework. source_env() { local rcpath=${1/#\~/$HOME} local rcfile if ! [[ -f $rcpath ]]; then rcpath=$rcpath/.envrc fi rcfile=$(user_rel_path "$rcpath") watch_file "$rcpath" pushd "$(pwd 2>/dev/null)" > /dev/null pushd "$(dirname "$rcpath")" > /dev/null if [[ -f ./$(basename "$rcpath") ]]; then log_status "loading $rcfile" # shellcheck source=/dev/null . "./$(basename "$rcpath")" else log_status "referenced $rcfile does not exist" fi popd > /dev/null popd > /dev/null } # Usage: watch_file # # Adds to the list of files that direnv will watch for changes - useful when the contents # of a file influence how variables are set - especially in direnvrc # watch_file() { local file=${1/#\~/$HOME} eval "$("$direnv" watch "$file")" } # Usage: source_up [] # # Loads another ".envrc" if found with the find_up command. # # NOTE: the other ".envrc" is not checked by the security framework. source_up() { local file=$1 local dir if [[ -z $file ]]; then file=.envrc fi dir=$(cd .. && find_up "$file") if [[ -n $dir ]]; then source_env "$dir" fi } # Usage: direnv_load # e.g: direnv_load opam-env exec -- direnv dump # # Applies the environment generated by running as a # command. This is useful for adopting the environment of a child # process - cause that process to run "direnv dump" and then wrap # the results with direnv_load. # direnv_load() { local exports exports=$("$direnv" apply_dump <("$@")) local es=$? if [[ $es -ne 0 ]]; then return $es fi eval "$exports" } # Usage: PATH_add [ ...] # # Prepends the expanded to the PATH environment variable, in order. # It prevents a common mistake where PATH is replaced by only the new , # or where a trailing colon is left in PATH, resulting in the current directory # being considered in the PATH. Supports adding multiple directories at once. # # Example: # # pwd # # output: /my/project # PATH_add bin # echo $PATH # # output: /my/project/bin:/usr/bin:/bin # PATH_add bam boum # echo $PATH # # output: /my/project/bam:/my/project/boum:/my/project/bin:/usr/bin:/bin # PATH_add() { path_add PATH "$@" } # Usage: path_add [ ...] # # Works like PATH_add except that it's for an arbitrary . path_add() { local var_name="$1" # split existing paths into an array declare -a path_array IFS=: read -ra path_array <<< "${!1}" shift # prepend the passed paths in the right order for (( i=$# ; i>0 ; i-- )); do path_array=( "$(expand_path "${!i}")" "${path_array[@]}" ) done # join back all the paths local path=$(IFS=:; echo "${path_array[*]}") # and finally export back the result to the original variable export "$var_name=$path" } # Usage: MANPATH_add # # Prepends a path to the MANPATH environment variable while making sure that # `man` can still lookup the system manual pages. # # If MANPATH is not empty, man will only look in MANPATH. # So if we set MANPATH=$path, man will only look in $path. # Instead, prepend to `man -w` (which outputs man's default paths). # MANPATH_add() { local old_paths="${MANPATH:-$(man -w)}" local dir dir=$(expand_path "$1") export "MANPATH=$dir:$old_paths" } # Usage: load_prefix # # Expands some common path variables for the given prefix. This is # useful if you installed something in the using # $(./configure --prefix= && make install) and want to use it in # the project. # # Variables set: # # CPATH # LD_LIBRARY_PATH # LIBRARY_PATH # MANPATH # PATH # PKG_CONFIG_PATH # # Example: # # ./configure --prefix=$HOME/rubies/ruby-1.9.3 # make && make install # # Then in the .envrc # load_prefix ~/rubies/ruby-1.9.3 # load_prefix() { local dir dir=$(expand_path "$1") MANPATH_add "$dir/man" MANPATH_add "$dir/share/man" path_add CPATH "$dir/include" path_add LD_LIBRARY_PATH "$dir/lib" path_add LIBRARY_PATH "$dir/lib" path_add PATH "$dir/bin" path_add PKG_CONFIG_PATH "$dir/lib/pkgconfig" } # Usage: layout # # A semantic dispatch used to describe common project layouts. # layout() { local name=$1 shift eval "layout_$name" "$@" } # Usage: layout go # # Sets the GOPATH environment variable to the current directory. # layout_go() { path_add GOPATH "$PWD" PATH_add bin } # Usage: layout node # # Adds "$PWD/node_modules/.bin" to the PATH environment variable. layout_node() { PATH_add node_modules/.bin } # Usage: layout perl # # Setup environment variables required by perl's local::lib # See http://search.cpan.org/dist/local-lib/lib/local/lib.pm for more details # layout_perl() { local libdir=$(direnv_layout_dir)/perl5 export LOCAL_LIB_DIR=$libdir export PERL_MB_OPT="--install_base '$libdir'" export PERL_MM_OPT="INSTALL_BASE=$libdir" path_add PERL5LIB "$libdir/lib/perl5" path_add PERL_LOCAL_LIB_ROOT "$libdir" PATH_add "$libdir/bin" } # Usage: layout python # # Creates and loads a virtualenv environment under # "$direnv_layout_dir/python-$python_version". # This forces the installation of any egg into the project's sub-folder. # # It's possible to specify the python executable if you want to use different # versions of python. # layout_python() { local python=${1:-python} [[ $# -gt 0 ]] && shift local old_env=$(direnv_layout_dir)/virtualenv unset PYTHONHOME if [[ -d $old_env && $python = python ]]; then export VIRTUAL_ENV=$old_env else local python_version python_version=$("$python" -c "import platform as p;print(p.python_version())") if [[ -z $python_version ]]; then log_error "Could not find python's version" return 1 fi export VIRTUAL_ENV=$(direnv_layout_dir)/python-$python_version if [[ ! -d $VIRTUAL_ENV ]]; then virtualenv "--python=$python" "$@" "$VIRTUAL_ENV" fi fi PATH_add "$VIRTUAL_ENV/bin" } # Usage: layout python2 # # A shortcut for $(layout python python2) # layout_python2() { layout_python python2 "$@" } # Usage: layout python3 # # A shortcut for $(layout python python3) # layout_python3() { layout_python python3 "$@" } # Usage: layout anaconda [] # # Activates anaconda for the named environment. If the environment # hasn't been created, it will be using the environment.yml file in # the current directory. is optional and will default to # the one found in the system environment. # layout_anaconda() { local env_name=$1 local conda if [[ $# -gt 1 ]]; then conda=${2} else conda=$(command -v conda) fi PATH_add $(dirname "$conda") local env_loc=$("$conda" env list | grep -- "$env_name") if [[ ! "$env_loc" == $env_name*$env_name ]]; then if [[ -e environment.yml ]]; then log_status "creating conda enviroment" "$conda" env create else log_error "Could not find environment.yml" return 1 fi fi source activate "$env_name" } # Usage: layout pipenv # # Similar to layout_python, but uses Pipenv to build a # virtualenv from the Pipfile located in the same directory. # layout_pipenv() { if [[ ! -f Pipfile ]]; then log_error 'No Pipfile found. Use `pipenv` to create a Pipfile first.' exit 2 fi local VENV=$(pipenv --bare --venv 2>/dev/null) if [[ -z $VENV || ! -d $VENV ]]; then pipenv install --dev fi export VIRTUAL_ENV=$(pipenv --venv) PATH_add "$VIRTUAL_ENV/bin" export PIPENV_ACTIVE=1 } # Usage: layout ruby # # Sets the GEM_HOME environment variable to "$(direnv_layout_dir)/ruby/RUBY_VERSION". # This forces the installation of any gems into the project's sub-folder. # If you're using bundler it will create wrapper programs that can be invoked # directly instead of using the $(bundle exec) prefix. # layout_ruby() { if ruby -e "exit Gem::VERSION > '2.2.0'" 2>/dev/null; then export GEM_HOME=$(direnv_layout_dir)/ruby else local ruby_version ruby_version=$(ruby -e"puts (defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby') + '-' + RUBY_VERSION") export GEM_HOME=$(direnv_layout_dir)/ruby-${ruby_version} fi export BUNDLE_BIN=$(direnv_layout_dir)/bin PATH_add "$GEM_HOME/bin" PATH_add "$BUNDLE_BIN" } # Usage: use [] # # A semantic command dispatch intended for loading external dependencies into # the environment. # # Example: # # use_ruby() { # echo "Ruby $1" # } # use ruby 1.9.3 # # output: Ruby 1.9.3 # use() { local cmd=$1 log_status "using $*" shift "use_$cmd" "$@" } # Usage: use rbenv # # Loads rbenv which add the ruby wrappers available on the PATH. # use_rbenv() { eval "$(rbenv init -)" } # Usage: rvm [...] # # Should work just like in the shell if you have rvm installed.# # rvm() { unset rvm if [[ -n ${rvm_scripts_path:-} ]]; then # shellcheck source=/dev/null source "${rvm_scripts_path}/rvm" elif [[ -n ${rvm_path:-} ]]; then # shellcheck source=/dev/null source "${rvm_path}/scripts/rvm" else # shellcheck source=/dev/null source "$HOME/.rvm/scripts/rvm" fi rvm "$@" } # Usage: use node # Loads NodeJS version from a `.node-version` or `.nvmrc` file. # # Usage: use node # Loads specified NodeJS version. # # If you specify a partial NodeJS version (i.e. `4.2`), a fuzzy match # is performed and the highest matching version installed is selected. # # Environment Variables: # # - $NODE_VERSIONS (required) # You must specify a path to your installed NodeJS versions via the `$NODE_VERSIONS` variable. # # - $NODE_VERSION_PREFIX (optional) [default="node-v"] # Overrides the default version prefix. use_node() { local version=$1 local via="" local node_version_prefix=${NODE_VERSION_PREFIX-node-v} local node_wanted local node_prefix if [[ -z $NODE_VERSIONS ]] || [[ ! -d $NODE_VERSIONS ]]; then log_error "You must specify a \$NODE_VERSIONS environment variable and the directory specified must exist!" return 1 fi if [[ -z $version ]] && [[ -f .nvmrc ]]; then version=$(< .nvmrc) via=".nvmrc" fi if [[ -z $version ]] && [[ -f .node-version ]]; then version=$(< .node-version) via=".node-version" fi if [[ -z $version ]]; then log_error "I do not know which NodeJS version to load because one has not been specified!" return 1 fi node_wanted=${node_version_prefix}${version} node_prefix=$( # Look for matching node versions in $NODE_VERSIONS path find "$NODE_VERSIONS" -maxdepth 1 -mindepth 1 -type d -name "$node_wanted*" | # Strip possible "/" suffix from $NODE_VERSIONS, then use that to # Strip $NODE_VERSIONS/$NODE_VERSION_PREFIX prefix from line. while IFS= read -r line; do echo "${line#${NODE_VERSIONS%/}/${node_version_prefix}}"; done | # Sort by version: split by "." then reverse numeric sort for each piece of the version string sort -t . -k 1,1rn -k 2,2rn -k 3,3rn | # The first one is the highest head -1 ) node_prefix="${NODE_VERSIONS}/${node_version_prefix}${node_prefix}" if [[ ! -d $node_prefix ]]; then log_error "Unable to find NodeJS version ($version) in ($NODE_VERSIONS)!" return 1 fi if [[ ! -x $node_prefix/bin/node ]]; then log_error "Unable to load NodeJS binary (node) for version ($version) in ($NODE_VERSIONS)!" return 1 fi load_prefix "$node_prefix" if [[ -z $via ]]; then log_status "Successfully loaded NodeJS $(node --version), from prefix ($node_prefix)" else log_status "Successfully loaded NodeJS $(node --version) (via $via), from prefix ($node_prefix)" fi } # Usage: use_nix [...] # # Load environment variables from `nix-shell`. # If you have a `default.nix` or `shell.nix` these will be # used by default, but you can also specify packages directly # (e.g `use nix -p ocaml`). # use_nix() { local orig_IN_NIX_SHELL="$IN_NIX_SHELL" direnv_load nix-shell --show-trace "$@" --run 'direnv dump' if [[ $# = 0 ]]; then watch_file default.nix watch_file shell.nix fi # Don't change the IN_NIX_SHELL env var if [[ -z $orig_IN_NIX_SHELL ]]; then unset IN_NIX_SHELL else export IN_NIX_SHELL="$orig_IN_NIX_SHELL" fi } # Usage: use_guix [...] # # Load environment variables from `guix environment`. # Any arguments given will be passed to guix environment. For example, # `use guix hello` would setup an environment with the dependencies of # the hello package. To create an environment including hello, the # `--ad-hoc` flag is used `use guix --ad-hoc hello`. Other options # include `--load` which allows loading an environment from a # file. For a full list of options, consult the documentation for the # `guix environment` command. use_guix() { eval "$(guix environment "$@" --search-paths)" } ## Load the global ~/.direnvrc if present if [[ -f ${XDG_CONFIG_HOME:-$HOME/.config}/direnv/direnvrc ]]; then source "${XDG_CONFIG_HOME:-$HOME/.config}/direnv/direnvrc" >&2 elif [[ -f $HOME/.direnvrc ]]; then source "$HOME/.direnvrc" >&2 fi direnv-2.15.0/test/000077500000000000000000000000001324410474700140535ustar00rootroot00000000000000direnv-2.15.0/test/.envrc000066400000000000000000000000001324410474700151570ustar00rootroot00000000000000direnv-2.15.0/test/config/000077500000000000000000000000001324410474700153205ustar00rootroot00000000000000direnv-2.15.0/test/config/direnv/000077500000000000000000000000001324410474700166075ustar00rootroot00000000000000direnv-2.15.0/test/config/direnv/direnvrc000066400000000000000000000000001324410474700203340ustar00rootroot00000000000000direnv-2.15.0/test/direnv-test.fish000077500000000000000000000017421324410474700172010ustar00rootroot00000000000000#!/usr/bin/env fish function eq --argument-names a b if not test (count $argv) = 2 echo "Error: " (count $argv) " arguments passed to `eq`: $argv" exit 1 end if not test $a = $b printf "Error:\n - expected: %s\n - got: %s\n" "$a" "$b" exit 1 end end cd (dirname (status -f)) set TEST_DIR $PWD set -gx PATH (dirname $TEST_DIR) $PATH # Reset the direnv loading if any set -x DIRENV_CONFIG $PWD set -e DIRENV_BASH set -e DIRENV_DIR set -e DIRENV_WATCHES set -e DIRENV_MTIME set -e DIRENV_DIFF function direnv_eval #direnv export fish # for debugging eval (direnv export fish) end function test_start -a name cd "$TEST_DIR/scenarios/$name" direnv allow echo "## Testing $name ##" pwd end function test_stop cd $TEST_DIR direnv_eval end ### RUN ### direnv allow direnv_eval test_start dump set -ex LS_COLORS direnv_eval eq "$LS_COLORS" "*.ogg=38;5;45:*.wav=38;5;45" eq "$LESSOPEN" "||/usr/bin/lesspipe.sh %s" eq "$THREE_BACKSLASHES" "\\\\\\" test_stop direnv-2.15.0/test/direnv-test.sh000077500000000000000000000062221324410474700166600ustar00rootroot00000000000000#!/usr/bin/env bash set -e cd `dirname $0` TEST_DIR=$PWD export PATH=`dirname $TEST_DIR`:$PATH # Reset the direnv loading if any export DIRENV_CONFIG=$PWD unset DIRENV_BASH unset DIRENV_DIR unset DIRENV_MTIME unset DIRENV_WATCHES unset DIRENV_DIFF export XDG_CONFIG_HOME=${TEST_DIR}/config mkdir -p ${XDG_CONFIG_HOME}/direnv touch ${XDG_CONFIG_HOME}/direnv/direnvrc direnv_eval() { eval `direnv export bash` } test_start() { cd "$TEST_DIR/scenarios/$1" direnv allow if [ "$DIRENV_DEBUG" == "1" ]; then echo fi echo "## Testing $1 ##" if [ "$DIRENV_DEBUG" == "1" ]; then echo fi } test_stop() { cd $TEST_DIR direnv_eval } test_eq() { if [ "$1" != "$2" ]; then echo "FAILED: '$1' == '$2'" exit 1 fi } test_neq() { if [ "$1" == "$2" ]; then echo "FAILED: '$1' != '$2'" exit 1 fi } ### RUN ### direnv allow || true direnv_eval test_start base echo "Setting up" direnv_eval test_eq "$HELLO" "world" WATCHES=$DIRENV_WATCHES echo "Reloading (should be no-op)" direnv_eval test_eq "$WATCHES" "$DIRENV_WATCHES" sleep 1 echo "Updating envrc and reloading (should reload)" touch .envrc direnv_eval test_neq "$WATCHES" "$DIRENV_WATCHES" echo "Leaving dir (should clear env set by dir's envrc)" cd .. direnv_eval echo "${HELLO}" test -z "${HELLO}" test_stop test_start inherit cp ../base/.envrc ../inherited/.envrc direnv_eval echo "HELLO should be world:" $HELLO sleep 1 echo "export HELLO=goodbye" > ../inherited/.envrc direnv_eval test_eq "$HELLO" "goodbye" test_stop test_start "ruby-layout" direnv_eval test_neq "$GEM_HOME" "" test_stop # Make sure directories with spaces are fine test_start "space dir" direnv_eval test_eq "$SPACE_DIR" "true" test_stop test_start "child-env" direnv_eval test_eq "$PARENT_PRE" "1" test_eq "$CHILD" "1" test_eq "$PARENT_POST" "1" test -z "$REMOVE_ME" test_stop test_start "special-vars" export DIRENV_BASH=`which bash` export DIRENV_CONFIG=foobar direnv_eval || true test -n "$DIRENV_BASH" test_eq "$DIRENV_CONFIG" "foobar" unset DIRENV_BASH unset DIRENV_CONFIG test_stop test_start "dump" direnv_eval test_eq "$LS_COLORS" "*.ogg=38;5;45:*.wav=38;5;45" test_eq "$THREE_BACKSLASHES" '\\\' test_eq "$LESSOPEN" "||/usr/bin/lesspipe.sh %s" test_stop test_start "empty-var" direnv_eval test_neq "${FOO-unset}" "unset" test_eq "${FOO}" "" test_stop test_start "empty-var-unset" export FOO="" direnv_eval test_eq "${FOO-unset}" "unset" unset FOO test_stop test_start "missing-file-source-env" direnv_eval test_stop # Context: foo/bar is a symlink to ../baz. foo/ contains and .envrc file # BUG: foo/bar is resolved in the .envrc execution context and so can't find # the .envrc file. # # Apparently, the CHDIR syscall does that so I don't know how to work around # the issue. # # test_start "symlink-bug" # cd foo/bar # direnv_eval # test_stop # Pending: test that the mtime is looked on the original file # test_start "utils" # LINK_TIME=`direnv file-mtime link-to-somefile` # touch somefile # NEW_LINK_TIME=`direnv file-mtime link-to-somefile` # test "$LINK_TIME" = "$NEW_LINK_TIME" # test_stop direnv-2.15.0/test/direnv-test.tcsh000077500000000000000000000056111324410474700172100ustar00rootroot00000000000000#!/usr/bin/env tcsh -e -x # set -e cd `dirname $0` setenv TEST_DIR $PWD setenv PATH `dirname $TEST_DIR`:$PATH # Reset the direnv loading if any setenv DIRENV_CONFIG $PWD unsetenv DIRENV_BASH unsetenv DIRENV_DIR unsetenv DIRENV_MTIME unsetenv DIRENV_WATCHES unsetenv DIRENV_DIFF # direnv_eval() { # eval `direnv export bash` # } alias direnv_eval 'eval `direnv export tcsh`' # test_start() { # cd "$TEST_DIR/scenarios/$1" # direnv allow # echo "## Testing $1 ##" # } # test_stop { # cd $TEST_DIR # direnv_eval # } ### RUN ### direnv allow || true direnv_eval cd $TEST_DIR/scenarios/base echo "Testing base" direnv_eval test "$HELLO" = "world" setenv WATCHES $DIRENV_WATCHES direnv_eval test "$WATCHES" = "$DIRENV_WATCHES" sleep 1 touch .envrc direnv_eval test "$WATCHES" != "$DIRENV_WATCHES" cd .. direnv_eval echo "$?HELLO" test 0 -eq "$?HELLO" cd $TEST_DIR ; direnv_eval cd $TEST_DIR/scenarios/inherit direnv allow echo "Testing inherit" direnv_eval test "$HELLO" = "world" cd $TEST_DIR ; direnv_eval cd $TEST_DIR/scenarios/ruby-layout direnv allow echo "Testing ruby-layout" direnv_eval test "$GEM_HOME" != "" cd $TEST_DIR ; direnv_eval # Make sure directories with spaces are fine cd $TEST_DIR/scenarios/"space dir" direnv allow echo "Testing space dir" direnv_eval test "$SPACE_DIR" = "true" cd $TEST_DIR ; direnv_eval cd $TEST_DIR/scenarios/child-env direnv allow echo "Testing child-env" direnv_eval test "$PARENT_PRE" = "1" test "$CHILD" = "1" test "$PARENT_POST" = "1" test 0 -eq "$?REMOVE_ME" cd $TEST_DIR ; direnv_eval # cd $TEST_DIR/scenarios/special-vars # direnv allow # echo "Testing special-vars" # setenv DIRENV_BASH `which bash` # setenv DIRENV_CONFIG foobar # direnv_eval || true # test -n "$DIRENV_BASH" # test "$DIRENV_CONFIG" = "foobar" # unsetenv DIRENV_BASH # unsetenv DIRENV_CONFIG # cd $TEST_DIR ; direnv_eval cd $TEST_DIR/scenarios/"empty-var" direnv allow echo "Testing empty-var" direnv_eval test "$?FOO" -eq 1 test "$FOO" = "" cd $TEST_DIR ; direnv_eval cd $TEST_DIR/scenarios/"empty-var-unset" direnv allow echo "Testing empty-var-unset" setenv FOO "" direnv_eval test "$?FOO" -eq '0' unsetenv FOO cd $TEST_DIR ; direnv_eval # Context: foo/bar is a symlink to ../baz. foo/ contains and .envrc file # BUG: foo/bar is resolved in the .envrc execution context and so can't find # the .envrc file. # # Apparently, the CHDIR syscall does that so I don't know how to work around # the issue. # # cd $TEST_DIR/scenarios/"symlink-bug" # cd foo/bar # direnv_eval # cd $TEST_DIR ; direnv_eval # Pending: test that the mtime is looked on the original file # cd $TEST_DIR/scenarios/"utils" # LINK_TIME=`direnv file-mtime link-to-somefile` # touch somefile # NEW_LINK_TIME=`direnv file-mtime link-to-somefile` # test "$LINK_TIME" = "$NEW_LINK_TIME" # cd $TEST_DIR ; direnv_eval direnv-2.15.0/test/scenarios/000077500000000000000000000000001324410474700160415ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/base/000077500000000000000000000000001324410474700167535ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/base/.envrc000066400000000000000000000000231324410474700200640ustar00rootroot00000000000000export HELLO=world direnv-2.15.0/test/scenarios/child-env/000077500000000000000000000000001324410474700177125ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/child-env/.envrc000066400000000000000000000002061324410474700210260ustar00rootroot00000000000000set -e export PARENT_PRE=1 export REMOVE_ME=1 direnv_load bash -c 'export CHILD=1; unset REMOVE_ME; direnv dump' export PARENT_POST=1 direnv-2.15.0/test/scenarios/dump/000077500000000000000000000000001324410474700170065ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/dump/.envrc000066400000000000000000000002301324410474700201170ustar00rootroot00000000000000direnv_load env \ LS_COLORS='*.ogg=38;5;45:*.wav=38;5;45' \ LESSOPEN='||/usr/bin/lesspipe.sh %s' \ THREE_BACKSLASHES='\\\' \ bash -c "direnv dump" direnv-2.15.0/test/scenarios/empty-var-unset/000077500000000000000000000000001324410474700211215ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/empty-var-unset/.envrc000066400000000000000000000000111324410474700222270ustar00rootroot00000000000000unset FOOdirenv-2.15.0/test/scenarios/empty-var/000077500000000000000000000000001324410474700177655ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/empty-var/.envrc000066400000000000000000000000151324410474700210770ustar00rootroot00000000000000export FOO=""direnv-2.15.0/test/scenarios/inherit/000077500000000000000000000000001324410474700175035ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/inherit/.envrc000066400000000000000000000000531324410474700206170ustar00rootroot00000000000000source_env ../inherited/.envrc echo $HELLO direnv-2.15.0/test/scenarios/inherited/000077500000000000000000000000001324410474700200145ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/inherited/.gitkeep000066400000000000000000000000001324410474700214330ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/missing-file-source-env/000077500000000000000000000000001324410474700225135ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/missing-file-source-env/.envrc000066400000000000000000000000451324410474700236300ustar00rootroot00000000000000source_env "$(mktemp -d -t $RANDOM)" direnv-2.15.0/test/scenarios/ruby-layout.env000066400000000000000000000001731324410474700210500ustar00rootroot00000000000000export PATH=`pwd`/ruby-layout/bin:$PATH export RUBYLIB=`pwd`/ruby-layout/lib export GEM_HOME=`pwd`/ruby-layout/vendor/gems direnv-2.15.0/test/scenarios/ruby-layout/000077500000000000000000000000001324410474700203355ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/ruby-layout/.envrc000066400000000000000000000000161324410474700214500ustar00rootroot00000000000000layout "ruby" direnv-2.15.0/test/scenarios/space dir/000077500000000000000000000000001324410474700176735ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/space dir/.envrc000066400000000000000000000000451324410474700210100ustar00rootroot00000000000000PATH_add "bin" export SPACE_DIR=true direnv-2.15.0/test/scenarios/special-vars/000077500000000000000000000000001324410474700204325ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/special-vars/.envrc000066400000000000000000000000001324410474700215360ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/symlink-bug/000077500000000000000000000000001324410474700203025ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/symlink-bug/baz/000077500000000000000000000000001324410474700210565ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/symlink-bug/baz/.keep000066400000000000000000000000001324410474700217710ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/symlink-bug/foo/000077500000000000000000000000001324410474700210655ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/symlink-bug/foo/.envrc000066400000000000000000000000001324410474700221710ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/symlink-bug/foo/bar000077700000000000000000000000001324410474700217052..ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/use-rvm/000077500000000000000000000000001324410474700174375ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/use-rvm/.envrc000066400000000000000000000000161324410474700205520ustar00rootroot00000000000000rvm use 1.8.7 direnv-2.15.0/test/scenarios/utils/000077500000000000000000000000001324410474700172015ustar00rootroot00000000000000direnv-2.15.0/test/scenarios/utils/link-to-file000077700000000000000000000000001324410474700231372somefileustar00rootroot00000000000000direnv-2.15.0/test/scenarios/utils/somefile000066400000000000000000000000001324410474700207150ustar00rootroot00000000000000direnv-2.15.0/test/show-direnv-diff.sh000077500000000000000000000003341324410474700175650ustar00rootroot00000000000000#!/bin/sh # # Small util to display the content of the current DIRENV_DIFF env var. # GZIP_HEADER="\x1f\x8b\x08\x00\x00\x00\x00\x00" (printf $GZIP_HEADER; echo $DIRENV_DIFF | base64 -D) | gzip -dc | python -mjson.tool direnv-2.15.0/vendor/000077500000000000000000000000001324410474700143715ustar00rootroot00000000000000direnv-2.15.0/vendor/github.com/000077500000000000000000000000001324410474700164305ustar00rootroot00000000000000direnv-2.15.0/vendor/github.com/BurntSushi/000077500000000000000000000000001324410474700205365ustar00rootroot00000000000000direnv-2.15.0/vendor/github.com/BurntSushi/toml/000077500000000000000000000000001324410474700215115ustar00rootroot00000000000000direnv-2.15.0/vendor/github.com/BurntSushi/toml/.gitignore000066400000000000000000000000571324410474700235030ustar00rootroot00000000000000TAGS tags .*.swp tomlcheck/tomlcheck toml.test direnv-2.15.0/vendor/github.com/BurntSushi/toml/.travis.yml000066400000000000000000000003211324410474700236160ustar00rootroot00000000000000language: go go: - 1.1 - 1.2 - 1.3 - 1.4 - 1.5 - 1.6 - tip install: - go install ./... - go get github.com/BurntSushi/toml-test script: - export PATH="$PATH:$HOME/gopath/bin" - make test direnv-2.15.0/vendor/github.com/BurntSushi/toml/COMPATIBLE000066400000000000000000000001611324410474700230510ustar00rootroot00000000000000Compatible with TOML version [v0.4.0](https://github.com/toml-lang/toml/blob/v0.4.0/versions/en/toml-v0.4.0.md) direnv-2.15.0/vendor/github.com/BurntSushi/toml/COPYING000066400000000000000000000007441324410474700225510ustar00rootroot00000000000000 DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 Copyright (C) 2004 Sam Hocevar Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO. direnv-2.15.0/vendor/github.com/BurntSushi/toml/Makefile000066400000000000000000000004411324410474700231500ustar00rootroot00000000000000install: go install ./... test: install go test -v toml-test toml-test-decoder toml-test -encoder toml-test-encoder fmt: gofmt -w *.go */*.go colcheck *.go */*.go tags: find ./ -name '*.go' -print0 | xargs -0 gotags > TAGS push: git push origin master git push github master direnv-2.15.0/vendor/github.com/BurntSushi/toml/README.md000066400000000000000000000103571324410474700227760ustar00rootroot00000000000000## TOML parser and encoder for Go with reflection TOML stands for Tom's Obvious, Minimal Language. This Go package provides a reflection interface similar to Go's standard library `json` and `xml` packages. This package also supports the `encoding.TextUnmarshaler` and `encoding.TextMarshaler` interfaces so that you can define custom data representations. (There is an example of this below.) Spec: https://github.com/toml-lang/toml Compatible with TOML version [v0.4.0](https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md) Documentation: https://godoc.org/github.com/BurntSushi/toml Installation: ```bash go get github.com/BurntSushi/toml ``` Try the toml validator: ```bash go get github.com/BurntSushi/toml/cmd/tomlv tomlv some-toml-file.toml ``` [![Build Status](https://travis-ci.org/BurntSushi/toml.svg?branch=master)](https://travis-ci.org/BurntSushi/toml) [![GoDoc](https://godoc.org/github.com/BurntSushi/toml?status.svg)](https://godoc.org/github.com/BurntSushi/toml) ### Testing This package passes all tests in [toml-test](https://github.com/BurntSushi/toml-test) for both the decoder and the encoder. ### Examples This package works similarly to how the Go standard library handles `XML` and `JSON`. Namely, data is loaded into Go values via reflection. For the simplest example, consider some TOML file as just a list of keys and values: ```toml Age = 25 Cats = [ "Cauchy", "Plato" ] Pi = 3.14 Perfection = [ 6, 28, 496, 8128 ] DOB = 1987-07-05T05:45:00Z ``` Which could be defined in Go as: ```go type Config struct { Age int Cats []string Pi float64 Perfection []int DOB time.Time // requires `import time` } ``` And then decoded with: ```go var conf Config if _, err := toml.Decode(tomlData, &conf); err != nil { // handle error } ``` You can also use struct tags if your struct field name doesn't map to a TOML key value directly: ```toml some_key_NAME = "wat" ``` ```go type TOML struct { ObscureKey string `toml:"some_key_NAME"` } ``` ### Using the `encoding.TextUnmarshaler` interface Here's an example that automatically parses duration strings into `time.Duration` values: ```toml [[song]] name = "Thunder Road" duration = "4m49s" [[song]] name = "Stairway to Heaven" duration = "8m03s" ``` Which can be decoded with: ```go type song struct { Name string Duration duration } type songs struct { Song []song } var favorites songs if _, err := toml.Decode(blob, &favorites); err != nil { log.Fatal(err) } for _, s := range favorites.Song { fmt.Printf("%s (%s)\n", s.Name, s.Duration) } ``` And you'll also need a `duration` type that satisfies the `encoding.TextUnmarshaler` interface: ```go type duration struct { time.Duration } func (d *duration) UnmarshalText(text []byte) error { var err error d.Duration, err = time.ParseDuration(string(text)) return err } ``` ### More complex usage Here's an example of how to load the example from the official spec page: ```toml # This is a TOML document. Boom. title = "TOML Example" [owner] name = "Tom Preston-Werner" organization = "GitHub" bio = "GitHub Cofounder & CEO\nLikes tater tots and beer." dob = 1979-05-27T07:32:00Z # First class dates? Why not? [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ] connection_max = 5000 enabled = true [servers] # You can indent as you please. Tabs or spaces. TOML don't care. [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" [servers.beta] ip = "10.0.0.2" dc = "eqdc10" [clients] data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it # Line breaks are OK when inside arrays hosts = [ "alpha", "omega" ] ``` And the corresponding Go types are: ```go type tomlConfig struct { Title string Owner ownerInfo DB database `toml:"database"` Servers map[string]server Clients clients } type ownerInfo struct { Name string Org string `toml:"organization"` Bio string DOB time.Time } type database struct { Server string Ports []int ConnMax int `toml:"connection_max"` Enabled bool } type server struct { IP string DC string } type clients struct { Data [][]interface{} Hosts []string } ``` Note that a case insensitive match will be tried if an exact match can't be found. A working example of the above can be found in `_examples/example.{go,toml}`. direnv-2.15.0/vendor/github.com/BurntSushi/toml/_examples/000077500000000000000000000000001324410474700234665ustar00rootroot00000000000000direnv-2.15.0/vendor/github.com/BurntSushi/toml/_examples/example.go000066400000000000000000000022761324410474700254570ustar00rootroot00000000000000package main import ( "fmt" "time" "github.com/BurntSushi/toml" ) type tomlConfig struct { Title string Owner ownerInfo DB database `toml:"database"` Servers map[string]server Clients clients } type ownerInfo struct { Name string Org string `toml:"organization"` Bio string DOB time.Time } type database struct { Server string Ports []int ConnMax int `toml:"connection_max"` Enabled bool } type server struct { IP string DC string } type clients struct { Data [][]interface{} Hosts []string } func main() { var config tomlConfig if _, err := toml.DecodeFile("example.toml", &config); err != nil { fmt.Println(err) return } fmt.Printf("Title: %s\n", config.Title) fmt.Printf("Owner: %s (%s, %s), Born: %s\n", config.Owner.Name, config.Owner.Org, config.Owner.Bio, config.Owner.DOB) fmt.Printf("Database: %s %v (Max conn. %d), Enabled? %v\n", config.DB.Server, config.DB.Ports, config.DB.ConnMax, config.DB.Enabled) for serverName, server := range config.Servers { fmt.Printf("Server: %s (%s, %s)\n", serverName, server.IP, server.DC) } fmt.Printf("Client data: %v\n", config.Clients.Data) fmt.Printf("Client hosts: %v\n", config.Clients.Hosts) } direnv-2.15.0/vendor/github.com/BurntSushi/toml/_examples/example.toml000066400000000000000000000012621324410474700260170ustar00rootroot00000000000000# This is a TOML document. Boom. title = "TOML Example" [owner] name = "Tom Preston-Werner" organization = "GitHub" bio = "GitHub Cofounder & CEO\nLikes tater tots and beer." dob = 1979-05-27T07:32:00Z # First class dates? Why not? [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ] connection_max = 5000 enabled = true [servers] # You can indent as you please. Tabs or spaces. TOML don't care. [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" [servers.beta] ip = "10.0.0.2" dc = "eqdc10" [clients] data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it # Line breaks are OK when inside arrays hosts = [ "alpha", "omega" ] direnv-2.15.0/vendor/github.com/BurntSushi/toml/_examples/hard.toml000066400000000000000000000015301324410474700253000ustar00rootroot00000000000000# Test file for TOML # Only this one tries to emulate a TOML file written by a user of the kind of parser writers probably hate # This part you'll really hate [the] test_string = "You'll hate me after this - #" # " Annoying, isn't it? [the.hard] test_array = [ "] ", " # "] # ] There you go, parse this! test_array2 = [ "Test #11 ]proved that", "Experiment #9 was a success" ] # You didn't think it'd as easy as chucking out the last #, did you? another_test_string = " Same thing, but with a string #" harder_test_string = " And when \"'s are in the string, along with # \"" # "and comments are there too" # Things will get harder [the.hard.bit#] what? = "You don't think some user won't do that?" multi_line_array = [ "]", # ] Oh yes I did ] direnv-2.15.0/vendor/github.com/BurntSushi/toml/_examples/implicit.toml000066400000000000000000000001121324410474700261670ustar00rootroot00000000000000# [x] you # [x.y] don't # [x.y.z] need these [x.y.z.w] # for this to work direnv-2.15.0/vendor/github.com/BurntSushi/toml/_examples/invalid-apples.toml000066400000000000000000000001011324410474700272630ustar00rootroot00000000000000# DO NOT WANT [fruit] type = "apple" [fruit.type] apple = "yes" direnv-2.15.0/vendor/github.com/BurntSushi/toml/_examples/invalid.toml000066400000000000000000000013401324410474700260070ustar00rootroot00000000000000# This is an INVALID TOML document. Boom. # Can you spot the error without help? title = "TOML Example" [owner] name = "Tom Preston-Werner" organization = "GitHub" bio = "GitHub Cofounder & CEO\nLikes tater tots and beer." dob = 1979-05-27T7:32:00Z # First class dates? Why not? [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ] connection_max = 5000 enabled = true [servers] # You can indent as you please. Tabs or spaces. TOML don't care. [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" [servers.beta] ip = "10.0.0.2" dc = "eqdc10" [clients] data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it # Line breaks are OK when inside arrays hosts = [ "alpha", "omega" ] direnv-2.15.0/vendor/github.com/BurntSushi/toml/_examples/readme1.toml000066400000000000000000000001551324410474700257020ustar00rootroot00000000000000Age = 25 Cats = [ "Cauchy", "Plato" ] Pi = 3.14 Perfection = [ 6, 28, 496, 8128 ] DOB = 1987-07-05T05:45:00Z direnv-2.15.0/vendor/github.com/BurntSushi/toml/_examples/readme2.toml000066400000000000000000000000261324410474700257000ustar00rootroot00000000000000some_key_NAME = "wat" direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/000077500000000000000000000000001324410474700222545ustar00rootroot00000000000000direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/toml-test-decoder/000077500000000000000000000000001324410474700256075ustar00rootroot00000000000000direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/toml-test-decoder/COPYING000066400000000000000000000007441324410474700266470ustar00rootroot00000000000000 DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 Copyright (C) 2004 Sam Hocevar Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO. direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/toml-test-decoder/README.md000066400000000000000000000007771324410474700271010ustar00rootroot00000000000000# Implements the TOML test suite interface This is an implementation of the interface expected by [toml-test](https://github.com/BurntSushi/toml-test) for my [toml parser written in Go](https://github.com/BurntSushi/toml). In particular, it maps TOML data on `stdin` to a JSON format on `stdout`. Compatible with TOML version [v0.4.0](https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md) Compatible with `toml-test` version [v0.2.0](https://github.com/BurntSushi/toml-test/tree/v0.2.0) direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/toml-test-decoder/main.go000066400000000000000000000037101324410474700270630ustar00rootroot00000000000000// Command toml-test-decoder satisfies the toml-test interface for testing // TOML decoders. Namely, it accepts TOML on stdin and outputs JSON on stdout. package main import ( "encoding/json" "flag" "fmt" "log" "os" "path" "time" "github.com/BurntSushi/toml" ) func init() { log.SetFlags(0) flag.Usage = usage flag.Parse() } func usage() { log.Printf("Usage: %s < toml-file\n", path.Base(os.Args[0])) flag.PrintDefaults() os.Exit(1) } func main() { if flag.NArg() != 0 { flag.Usage() } var tmp interface{} if _, err := toml.DecodeReader(os.Stdin, &tmp); err != nil { log.Fatalf("Error decoding TOML: %s", err) } typedTmp := translate(tmp) if err := json.NewEncoder(os.Stdout).Encode(typedTmp); err != nil { log.Fatalf("Error encoding JSON: %s", err) } } func translate(tomlData interface{}) interface{} { switch orig := tomlData.(type) { case map[string]interface{}: typed := make(map[string]interface{}, len(orig)) for k, v := range orig { typed[k] = translate(v) } return typed case []map[string]interface{}: typed := make([]map[string]interface{}, len(orig)) for i, v := range orig { typed[i] = translate(v).(map[string]interface{}) } return typed case []interface{}: typed := make([]interface{}, len(orig)) for i, v := range orig { typed[i] = translate(v) } // We don't really need to tag arrays, but let's be future proof. // (If TOML ever supports tuples, we'll need this.) return tag("array", typed) case time.Time: return tag("datetime", orig.Format("2006-01-02T15:04:05Z")) case bool: return tag("bool", fmt.Sprintf("%v", orig)) case int64: return tag("integer", fmt.Sprintf("%d", orig)) case float64: return tag("float", fmt.Sprintf("%v", orig)) case string: return tag("string", orig) } panic(fmt.Sprintf("Unknown type: %T", tomlData)) } func tag(typeName string, data interface{}) map[string]interface{} { return map[string]interface{}{ "type": typeName, "value": data, } } direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/toml-test-encoder/000077500000000000000000000000001324410474700256215ustar00rootroot00000000000000direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/toml-test-encoder/COPYING000066400000000000000000000007441324410474700266610ustar00rootroot00000000000000 DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 Copyright (C) 2004 Sam Hocevar Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO. direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/toml-test-encoder/README.md000066400000000000000000000010051324410474700270740ustar00rootroot00000000000000# Implements the TOML test suite interface for TOML encoders This is an implementation of the interface expected by [toml-test](https://github.com/BurntSushi/toml-test) for the [TOML encoder](https://github.com/BurntSushi/toml). In particular, it maps JSON data on `stdin` to a TOML format on `stdout`. Compatible with TOML version [v0.4.0](https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md) Compatible with `toml-test` version [v0.2.0](https://github.com/BurntSushi/toml-test/tree/v0.2.0) direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/toml-test-encoder/main.go000066400000000000000000000054271324410474700271040ustar00rootroot00000000000000// Command toml-test-encoder satisfies the toml-test interface for testing // TOML encoders. Namely, it accepts JSON on stdin and outputs TOML on stdout. package main import ( "encoding/json" "flag" "log" "os" "path" "strconv" "time" "github.com/BurntSushi/toml" ) func init() { log.SetFlags(0) flag.Usage = usage flag.Parse() } func usage() { log.Printf("Usage: %s < json-file\n", path.Base(os.Args[0])) flag.PrintDefaults() os.Exit(1) } func main() { if flag.NArg() != 0 { flag.Usage() } var tmp interface{} if err := json.NewDecoder(os.Stdin).Decode(&tmp); err != nil { log.Fatalf("Error decoding JSON: %s", err) } tomlData := translate(tmp) if err := toml.NewEncoder(os.Stdout).Encode(tomlData); err != nil { log.Fatalf("Error encoding TOML: %s", err) } } func translate(typedJson interface{}) interface{} { switch v := typedJson.(type) { case map[string]interface{}: if len(v) == 2 && in("type", v) && in("value", v) { return untag(v) } m := make(map[string]interface{}, len(v)) for k, v2 := range v { m[k] = translate(v2) } return m case []interface{}: tabArray := make([]map[string]interface{}, len(v)) for i := range v { if m, ok := translate(v[i]).(map[string]interface{}); ok { tabArray[i] = m } else { log.Fatalf("JSON arrays may only contain objects. This " + "corresponds to only tables being allowed in " + "TOML table arrays.") } } return tabArray } log.Fatalf("Unrecognized JSON format '%T'.", typedJson) panic("unreachable") } func untag(typed map[string]interface{}) interface{} { t := typed["type"].(string) v := typed["value"] switch t { case "string": return v.(string) case "integer": v := v.(string) n, err := strconv.Atoi(v) if err != nil { log.Fatalf("Could not parse '%s' as integer: %s", v, err) } return n case "float": v := v.(string) f, err := strconv.ParseFloat(v, 64) if err != nil { log.Fatalf("Could not parse '%s' as float64: %s", v, err) } return f case "datetime": v := v.(string) t, err := time.Parse("2006-01-02T15:04:05Z", v) if err != nil { log.Fatalf("Could not parse '%s' as a datetime: %s", v, err) } return t case "bool": v := v.(string) switch v { case "true": return true case "false": return false } log.Fatalf("Could not parse '%s' as a boolean.", v) case "array": v := v.([]interface{}) array := make([]interface{}, len(v)) for i := range v { if m, ok := v[i].(map[string]interface{}); ok { array[i] = untag(m) } else { log.Fatalf("Arrays may only contain other arrays or "+ "primitive values, but found a '%T'.", m) } } return array } log.Fatalf("Unrecognized tag type '%s'.", t) panic("unreachable") } func in(key string, m map[string]interface{}) bool { _, ok := m[key] return ok } direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/tomlv/000077500000000000000000000000001324410474700234155ustar00rootroot00000000000000direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/tomlv/COPYING000066400000000000000000000007441324410474700244550ustar00rootroot00000000000000 DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 Copyright (C) 2004 Sam Hocevar Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO. direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/tomlv/README.md000066400000000000000000000010421324410474700246710ustar00rootroot00000000000000# TOML Validator If Go is installed, it's simple to try it out: ```bash go get github.com/BurntSushi/toml/cmd/tomlv tomlv some-toml-file.toml ``` You can see the types of every key in a TOML file with: ```bash tomlv -types some-toml-file.toml ``` At the moment, only one error message is reported at a time. Error messages include line numbers. No output means that the files given are valid TOML, or there is a bug in `tomlv`. Compatible with TOML version [v0.4.0](https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md) direnv-2.15.0/vendor/github.com/BurntSushi/toml/cmd/tomlv/main.go000066400000000000000000000020031324410474700246630ustar00rootroot00000000000000// Command tomlv validates TOML documents and prints each key's type. package main import ( "flag" "fmt" "log" "os" "path" "strings" "text/tabwriter" "github.com/BurntSushi/toml" ) var ( flagTypes = false ) func init() { log.SetFlags(0) flag.BoolVar(&flagTypes, "types", flagTypes, "When set, the types of every defined key will be shown.") flag.Usage = usage flag.Parse() } func usage() { log.Printf("Usage: %s toml-file [ toml-file ... ]\n", path.Base(os.Args[0])) flag.PrintDefaults() os.Exit(1) } func main() { if flag.NArg() < 1 { flag.Usage() } for _, f := range flag.Args() { var tmp interface{} md, err := toml.DecodeFile(f, &tmp) if err != nil { log.Fatalf("Error in '%s': %s", f, err) } if flagTypes { printTypes(md) } } } func printTypes(md toml.MetaData) { tabw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) for _, key := range md.Keys() { fmt.Fprintf(tabw, "%s%s\t%s\n", strings.Repeat(" ", len(key)-1), key, md.Type(key...)) } tabw.Flush() } direnv-2.15.0/vendor/github.com/BurntSushi/toml/decode.go000066400000000000000000000341141324410474700232660ustar00rootroot00000000000000package toml import ( "fmt" "io" "io/ioutil" "math" "reflect" "strings" "time" ) func e(format string, args ...interface{}) error { return fmt.Errorf("toml: "+format, args...) } // Unmarshaler is the interface implemented by objects that can unmarshal a // TOML description of themselves. type Unmarshaler interface { UnmarshalTOML(interface{}) error } // Unmarshal decodes the contents of `p` in TOML format into a pointer `v`. func Unmarshal(p []byte, v interface{}) error { _, err := Decode(string(p), v) return err } // Primitive is a TOML value that hasn't been decoded into a Go value. // When using the various `Decode*` functions, the type `Primitive` may // be given to any value, and its decoding will be delayed. // // A `Primitive` value can be decoded using the `PrimitiveDecode` function. // // The underlying representation of a `Primitive` value is subject to change. // Do not rely on it. // // N.B. Primitive values are still parsed, so using them will only avoid // the overhead of reflection. They can be useful when you don't know the // exact type of TOML data until run time. type Primitive struct { undecoded interface{} context Key } // DEPRECATED! // // Use MetaData.PrimitiveDecode instead. func PrimitiveDecode(primValue Primitive, v interface{}) error { md := MetaData{decoded: make(map[string]bool)} return md.unify(primValue.undecoded, rvalue(v)) } // PrimitiveDecode is just like the other `Decode*` functions, except it // decodes a TOML value that has already been parsed. Valid primitive values // can *only* be obtained from values filled by the decoder functions, // including this method. (i.e., `v` may contain more `Primitive` // values.) // // Meta data for primitive values is included in the meta data returned by // the `Decode*` functions with one exception: keys returned by the Undecoded // method will only reflect keys that were decoded. Namely, any keys hidden // behind a Primitive will be considered undecoded. Executing this method will // update the undecoded keys in the meta data. (See the example.) func (md *MetaData) PrimitiveDecode(primValue Primitive, v interface{}) error { md.context = primValue.context defer func() { md.context = nil }() return md.unify(primValue.undecoded, rvalue(v)) } // Decode will decode the contents of `data` in TOML format into a pointer // `v`. // // TOML hashes correspond to Go structs or maps. (Dealer's choice. They can be // used interchangeably.) // // TOML arrays of tables correspond to either a slice of structs or a slice // of maps. // // TOML datetimes correspond to Go `time.Time` values. // // All other TOML types (float, string, int, bool and array) correspond // to the obvious Go types. // // An exception to the above rules is if a type implements the // encoding.TextUnmarshaler interface. In this case, any primitive TOML value // (floats, strings, integers, booleans and datetimes) will be converted to // a byte string and given to the value's UnmarshalText method. See the // Unmarshaler example for a demonstration with time duration strings. // // Key mapping // // TOML keys can map to either keys in a Go map or field names in a Go // struct. The special `toml` struct tag may be used to map TOML keys to // struct fields that don't match the key name exactly. (See the example.) // A case insensitive match to struct names will be tried if an exact match // can't be found. // // The mapping between TOML values and Go values is loose. That is, there // may exist TOML values that cannot be placed into your representation, and // there may be parts of your representation that do not correspond to // TOML values. This loose mapping can be made stricter by using the IsDefined // and/or Undecoded methods on the MetaData returned. // // This decoder will not handle cyclic types. If a cyclic type is passed, // `Decode` will not terminate. func Decode(data string, v interface{}) (MetaData, error) { rv := reflect.ValueOf(v) if rv.Kind() != reflect.Ptr { return MetaData{}, e("Decode of non-pointer %s", reflect.TypeOf(v)) } if rv.IsNil() { return MetaData{}, e("Decode of nil %s", reflect.TypeOf(v)) } p, err := parse(data) if err != nil { return MetaData{}, err } md := MetaData{ p.mapping, p.types, p.ordered, make(map[string]bool, len(p.ordered)), nil, } return md, md.unify(p.mapping, indirect(rv)) } // DecodeFile is just like Decode, except it will automatically read the // contents of the file at `fpath` and decode it for you. func DecodeFile(fpath string, v interface{}) (MetaData, error) { bs, err := ioutil.ReadFile(fpath) if err != nil { return MetaData{}, err } return Decode(string(bs), v) } // DecodeReader is just like Decode, except it will consume all bytes // from the reader and decode it for you. func DecodeReader(r io.Reader, v interface{}) (MetaData, error) { bs, err := ioutil.ReadAll(r) if err != nil { return MetaData{}, err } return Decode(string(bs), v) } // unify performs a sort of type unification based on the structure of `rv`, // which is the client representation. // // Any type mismatch produces an error. Finding a type that we don't know // how to handle produces an unsupported type error. func (md *MetaData) unify(data interface{}, rv reflect.Value) error { // Special case. Look for a `Primitive` value. if rv.Type() == reflect.TypeOf((*Primitive)(nil)).Elem() { // Save the undecoded data and the key context into the primitive // value. context := make(Key, len(md.context)) copy(context, md.context) rv.Set(reflect.ValueOf(Primitive{ undecoded: data, context: context, })) return nil } // Special case. Unmarshaler Interface support. if rv.CanAddr() { if v, ok := rv.Addr().Interface().(Unmarshaler); ok { return v.UnmarshalTOML(data) } } // Special case. Handle time.Time values specifically. // TODO: Remove this code when we decide to drop support for Go 1.1. // This isn't necessary in Go 1.2 because time.Time satisfies the encoding // interfaces. if rv.Type().AssignableTo(rvalue(time.Time{}).Type()) { return md.unifyDatetime(data, rv) } // Special case. Look for a value satisfying the TextUnmarshaler interface. if v, ok := rv.Interface().(TextUnmarshaler); ok { return md.unifyText(data, v) } // BUG(burntsushi) // The behavior here is incorrect whenever a Go type satisfies the // encoding.TextUnmarshaler interface but also corresponds to a TOML // hash or array. In particular, the unmarshaler should only be applied // to primitive TOML values. But at this point, it will be applied to // all kinds of values and produce an incorrect error whenever those values // are hashes or arrays (including arrays of tables). k := rv.Kind() // laziness if k >= reflect.Int && k <= reflect.Uint64 { return md.unifyInt(data, rv) } switch k { case reflect.Ptr: elem := reflect.New(rv.Type().Elem()) err := md.unify(data, reflect.Indirect(elem)) if err != nil { return err } rv.Set(elem) return nil case reflect.Struct: return md.unifyStruct(data, rv) case reflect.Map: return md.unifyMap(data, rv) case reflect.Array: return md.unifyArray(data, rv) case reflect.Slice: return md.unifySlice(data, rv) case reflect.String: return md.unifyString(data, rv) case reflect.Bool: return md.unifyBool(data, rv) case reflect.Interface: // we only support empty interfaces. if rv.NumMethod() > 0 { return e("unsupported type %s", rv.Type()) } return md.unifyAnything(data, rv) case reflect.Float32: fallthrough case reflect.Float64: return md.unifyFloat64(data, rv) } return e("unsupported type %s", rv.Kind()) } func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { tmap, ok := mapping.(map[string]interface{}) if !ok { if mapping == nil { return nil } return e("type mismatch for %s: expected table but found %T", rv.Type().String(), mapping) } for key, datum := range tmap { var f *field fields := cachedTypeFields(rv.Type()) for i := range fields { ff := &fields[i] if ff.name == key { f = ff break } if f == nil && strings.EqualFold(ff.name, key) { f = ff } } if f != nil { subv := rv for _, i := range f.index { subv = indirect(subv.Field(i)) } if isUnifiable(subv) { md.decoded[md.context.add(key).String()] = true md.context = append(md.context, key) if err := md.unify(datum, subv); err != nil { return err } md.context = md.context[0 : len(md.context)-1] } else if f.name != "" { // Bad user! No soup for you! return e("cannot write unexported field %s.%s", rv.Type().String(), f.name) } } } return nil } func (md *MetaData) unifyMap(mapping interface{}, rv reflect.Value) error { tmap, ok := mapping.(map[string]interface{}) if !ok { if tmap == nil { return nil } return badtype("map", mapping) } if rv.IsNil() { rv.Set(reflect.MakeMap(rv.Type())) } for k, v := range tmap { md.decoded[md.context.add(k).String()] = true md.context = append(md.context, k) rvkey := indirect(reflect.New(rv.Type().Key())) rvval := reflect.Indirect(reflect.New(rv.Type().Elem())) if err := md.unify(v, rvval); err != nil { return err } md.context = md.context[0 : len(md.context)-1] rvkey.SetString(k) rv.SetMapIndex(rvkey, rvval) } return nil } func (md *MetaData) unifyArray(data interface{}, rv reflect.Value) error { datav := reflect.ValueOf(data) if datav.Kind() != reflect.Slice { if !datav.IsValid() { return nil } return badtype("slice", data) } sliceLen := datav.Len() if sliceLen != rv.Len() { return e("expected array length %d; got TOML array of length %d", rv.Len(), sliceLen) } return md.unifySliceArray(datav, rv) } func (md *MetaData) unifySlice(data interface{}, rv reflect.Value) error { datav := reflect.ValueOf(data) if datav.Kind() != reflect.Slice { if !datav.IsValid() { return nil } return badtype("slice", data) } n := datav.Len() if rv.IsNil() || rv.Cap() < n { rv.Set(reflect.MakeSlice(rv.Type(), n, n)) } rv.SetLen(n) return md.unifySliceArray(datav, rv) } func (md *MetaData) unifySliceArray(data, rv reflect.Value) error { sliceLen := data.Len() for i := 0; i < sliceLen; i++ { v := data.Index(i).Interface() sliceval := indirect(rv.Index(i)) if err := md.unify(v, sliceval); err != nil { return err } } return nil } func (md *MetaData) unifyDatetime(data interface{}, rv reflect.Value) error { if _, ok := data.(time.Time); ok { rv.Set(reflect.ValueOf(data)) return nil } return badtype("time.Time", data) } func (md *MetaData) unifyString(data interface{}, rv reflect.Value) error { if s, ok := data.(string); ok { rv.SetString(s) return nil } return badtype("string", data) } func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { if num, ok := data.(float64); ok { switch rv.Kind() { case reflect.Float32: fallthrough case reflect.Float64: rv.SetFloat(num) default: panic("bug") } return nil } return badtype("float", data) } func (md *MetaData) unifyInt(data interface{}, rv reflect.Value) error { if num, ok := data.(int64); ok { if rv.Kind() >= reflect.Int && rv.Kind() <= reflect.Int64 { switch rv.Kind() { case reflect.Int, reflect.Int64: // No bounds checking necessary. case reflect.Int8: if num < math.MinInt8 || num > math.MaxInt8 { return e("value %d is out of range for int8", num) } case reflect.Int16: if num < math.MinInt16 || num > math.MaxInt16 { return e("value %d is out of range for int16", num) } case reflect.Int32: if num < math.MinInt32 || num > math.MaxInt32 { return e("value %d is out of range for int32", num) } } rv.SetInt(num) } else if rv.Kind() >= reflect.Uint && rv.Kind() <= reflect.Uint64 { unum := uint64(num) switch rv.Kind() { case reflect.Uint, reflect.Uint64: // No bounds checking necessary. case reflect.Uint8: if num < 0 || unum > math.MaxUint8 { return e("value %d is out of range for uint8", num) } case reflect.Uint16: if num < 0 || unum > math.MaxUint16 { return e("value %d is out of range for uint16", num) } case reflect.Uint32: if num < 0 || unum > math.MaxUint32 { return e("value %d is out of range for uint32", num) } } rv.SetUint(unum) } else { panic("unreachable") } return nil } return badtype("integer", data) } func (md *MetaData) unifyBool(data interface{}, rv reflect.Value) error { if b, ok := data.(bool); ok { rv.SetBool(b) return nil } return badtype("boolean", data) } func (md *MetaData) unifyAnything(data interface{}, rv reflect.Value) error { rv.Set(reflect.ValueOf(data)) return nil } func (md *MetaData) unifyText(data interface{}, v TextUnmarshaler) error { var s string switch sdata := data.(type) { case TextMarshaler: text, err := sdata.MarshalText() if err != nil { return err } s = string(text) case fmt.Stringer: s = sdata.String() case string: s = sdata case bool: s = fmt.Sprintf("%v", sdata) case int64: s = fmt.Sprintf("%d", sdata) case float64: s = fmt.Sprintf("%f", sdata) default: return badtype("primitive (string-like)", data) } if err := v.UnmarshalText([]byte(s)); err != nil { return err } return nil } // rvalue returns a reflect.Value of `v`. All pointers are resolved. func rvalue(v interface{}) reflect.Value { return indirect(reflect.ValueOf(v)) } // indirect returns the value pointed to by a pointer. // Pointers are followed until the value is not a pointer. // New values are allocated for each nil pointer. // // An exception to this rule is if the value satisfies an interface of // interest to us (like encoding.TextUnmarshaler). func indirect(v reflect.Value) reflect.Value { if v.Kind() != reflect.Ptr { if v.CanSet() { pv := v.Addr() if _, ok := pv.Interface().(TextUnmarshaler); ok { return pv } } return v } if v.IsNil() { v.Set(reflect.New(v.Type().Elem())) } return indirect(reflect.Indirect(v)) } func isUnifiable(rv reflect.Value) bool { if rv.CanSet() { return true } if _, ok := rv.Interface().(TextUnmarshaler); ok { return true } return false } func badtype(expected string, data interface{}) error { return e("cannot load TOML value of type %T into a Go %s", data, expected) } direnv-2.15.0/vendor/github.com/BurntSushi/toml/decode_meta.go000066400000000000000000000062021324410474700242710ustar00rootroot00000000000000package toml import "strings" // MetaData allows access to meta information about TOML data that may not // be inferrable via reflection. In particular, whether a key has been defined // and the TOML type of a key. type MetaData struct { mapping map[string]interface{} types map[string]tomlType keys []Key decoded map[string]bool context Key // Used only during decoding. } // IsDefined returns true if the key given exists in the TOML data. The key // should be specified hierarchially. e.g., // // // access the TOML key 'a.b.c' // IsDefined("a", "b", "c") // // IsDefined will return false if an empty key given. Keys are case sensitive. func (md *MetaData) IsDefined(key ...string) bool { if len(key) == 0 { return false } var hash map[string]interface{} var ok bool var hashOrVal interface{} = md.mapping for _, k := range key { if hash, ok = hashOrVal.(map[string]interface{}); !ok { return false } if hashOrVal, ok = hash[k]; !ok { return false } } return true } // Type returns a string representation of the type of the key specified. // // Type will return the empty string if given an empty key or a key that // does not exist. Keys are case sensitive. func (md *MetaData) Type(key ...string) string { fullkey := strings.Join(key, ".") if typ, ok := md.types[fullkey]; ok { return typ.typeString() } return "" } // Key is the type of any TOML key, including key groups. Use (MetaData).Keys // to get values of this type. type Key []string func (k Key) String() string { return strings.Join(k, ".") } func (k Key) maybeQuotedAll() string { var ss []string for i := range k { ss = append(ss, k.maybeQuoted(i)) } return strings.Join(ss, ".") } func (k Key) maybeQuoted(i int) string { quote := false for _, c := range k[i] { if !isBareKeyChar(c) { quote = true break } } if quote { return "\"" + strings.Replace(k[i], "\"", "\\\"", -1) + "\"" } return k[i] } func (k Key) add(piece string) Key { newKey := make(Key, len(k)+1) copy(newKey, k) newKey[len(k)] = piece return newKey } // Keys returns a slice of every key in the TOML data, including key groups. // Each key is itself a slice, where the first element is the top of the // hierarchy and the last is the most specific. // // The list will have the same order as the keys appeared in the TOML data. // // All keys returned are non-empty. func (md *MetaData) Keys() []Key { return md.keys } // Undecoded returns all keys that have not been decoded in the order in which // they appear in the original TOML document. // // This includes keys that haven't been decoded because of a Primitive value. // Once the Primitive value is decoded, the keys will be considered decoded. // // Also note that decoding into an empty interface will result in no decoding, // and so no keys will be considered decoded. // // In this sense, the Undecoded keys correspond to keys in the TOML document // that do not have a concrete type in your representation. func (md *MetaData) Undecoded() []Key { undecoded := make([]Key, 0, len(md.keys)) for _, key := range md.keys { if !md.decoded[key.String()] { undecoded = append(undecoded, key) } } return undecoded } direnv-2.15.0/vendor/github.com/BurntSushi/toml/decode_test.go000066400000000000000000000737711324410474700243410ustar00rootroot00000000000000package toml import ( "fmt" "log" "math" "reflect" "strings" "testing" "time" ) func TestDecodeSimple(t *testing.T) { var testSimple = ` age = 250 andrew = "gallant" kait = "brady" now = 1987-07-05T05:45:00Z yesOrNo = true pi = 3.14 colors = [ ["red", "green", "blue"], ["cyan", "magenta", "yellow", "black"], ] [My.Cats] plato = "cat 1" cauchy = "cat 2" ` type cats struct { Plato string Cauchy string } type simple struct { Age int Colors [][]string Pi float64 YesOrNo bool Now time.Time Andrew string Kait string My map[string]cats } var val simple _, err := Decode(testSimple, &val) if err != nil { t.Fatal(err) } now, err := time.Parse("2006-01-02T15:04:05", "1987-07-05T05:45:00") if err != nil { panic(err) } var answer = simple{ Age: 250, Andrew: "gallant", Kait: "brady", Now: now, YesOrNo: true, Pi: 3.14, Colors: [][]string{ {"red", "green", "blue"}, {"cyan", "magenta", "yellow", "black"}, }, My: map[string]cats{ "Cats": {Plato: "cat 1", Cauchy: "cat 2"}, }, } if !reflect.DeepEqual(val, answer) { t.Fatalf("Expected\n-----\n%#v\n-----\nbut got\n-----\n%#v\n", answer, val) } } func TestDecodeEmbedded(t *testing.T) { type Dog struct{ Name string } type Age int type cat struct{ Name string } for _, test := range []struct { label string input string decodeInto interface{} wantDecoded interface{} }{ { label: "embedded struct", input: `Name = "milton"`, decodeInto: &struct{ Dog }{}, wantDecoded: &struct{ Dog }{Dog{"milton"}}, }, { label: "embedded non-nil pointer to struct", input: `Name = "milton"`, decodeInto: &struct{ *Dog }{}, wantDecoded: &struct{ *Dog }{&Dog{"milton"}}, }, { label: "embedded nil pointer to struct", input: ``, decodeInto: &struct{ *Dog }{}, wantDecoded: &struct{ *Dog }{nil}, }, { label: "unexported embedded struct", input: `Name = "socks"`, decodeInto: &struct{ cat }{}, wantDecoded: &struct{ cat }{cat{"socks"}}, }, { label: "embedded int", input: `Age = -5`, decodeInto: &struct{ Age }{}, wantDecoded: &struct{ Age }{-5}, }, } { _, err := Decode(test.input, test.decodeInto) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(test.wantDecoded, test.decodeInto) { t.Errorf("%s: want decoded == %+v, got %+v", test.label, test.wantDecoded, test.decodeInto) } } } func TestDecodeIgnoredFields(t *testing.T) { type simple struct { Number int `toml:"-"` } const input = ` Number = 123 - = 234 ` var s simple if _, err := Decode(input, &s); err != nil { t.Fatal(err) } if s.Number != 0 { t.Errorf("got: %d; want 0", s.Number) } } func TestTableArrays(t *testing.T) { var tomlTableArrays = ` [[albums]] name = "Born to Run" [[albums.songs]] name = "Jungleland" [[albums.songs]] name = "Meeting Across the River" [[albums]] name = "Born in the USA" [[albums.songs]] name = "Glory Days" [[albums.songs]] name = "Dancing in the Dark" ` type Song struct { Name string } type Album struct { Name string Songs []Song } type Music struct { Albums []Album } expected := Music{[]Album{ {"Born to Run", []Song{{"Jungleland"}, {"Meeting Across the River"}}}, {"Born in the USA", []Song{{"Glory Days"}, {"Dancing in the Dark"}}}, }} var got Music if _, err := Decode(tomlTableArrays, &got); err != nil { t.Fatal(err) } if !reflect.DeepEqual(expected, got) { t.Fatalf("\n%#v\n!=\n%#v\n", expected, got) } } func TestTableNesting(t *testing.T) { for _, tt := range []struct { t string want []string }{ {"[a.b.c]", []string{"a", "b", "c"}}, {`[a."b.c"]`, []string{"a", "b.c"}}, {`[a.'b.c']`, []string{"a", "b.c"}}, {`[a.' b ']`, []string{"a", " b "}}, {"[ d.e.f ]", []string{"d", "e", "f"}}, {"[ g . h . i ]", []string{"g", "h", "i"}}, {`[ j . "ʞ" . 'l' ]`, []string{"j", "ʞ", "l"}}, } { var m map[string]interface{} if _, err := Decode(tt.t, &m); err != nil { t.Errorf("Decode(%q): got error: %s", tt.t, err) continue } if keys := extractNestedKeys(m); !reflect.DeepEqual(keys, tt.want) { t.Errorf("Decode(%q): got nested keys %#v; want %#v", tt.t, keys, tt.want) } } } func extractNestedKeys(v map[string]interface{}) []string { var result []string for { if len(v) != 1 { return result } for k, m := range v { result = append(result, k) var ok bool v, ok = m.(map[string]interface{}) if !ok { return result } } } } // Case insensitive matching tests. // A bit more comprehensive than needed given the current implementation, // but implementations change. // Probably still missing demonstrations of some ugly corner cases regarding // case insensitive matching and multiple fields. func TestCase(t *testing.T) { var caseToml = ` tOpString = "string" tOpInt = 1 tOpFloat = 1.1 tOpBool = true tOpdate = 2006-01-02T15:04:05Z tOparray = [ "array" ] Match = "i should be in Match only" MatcH = "i should be in MatcH only" once = "just once" [nEst.eD] nEstedString = "another string" ` type InsensitiveEd struct { NestedString string } type InsensitiveNest struct { Ed InsensitiveEd } type Insensitive struct { TopString string TopInt int TopFloat float64 TopBool bool TopDate time.Time TopArray []string Match string MatcH string Once string OncE string Nest InsensitiveNest } tme, err := time.Parse(time.RFC3339, time.RFC3339[:len(time.RFC3339)-5]) if err != nil { panic(err) } expected := Insensitive{ TopString: "string", TopInt: 1, TopFloat: 1.1, TopBool: true, TopDate: tme, TopArray: []string{"array"}, MatcH: "i should be in MatcH only", Match: "i should be in Match only", Once: "just once", OncE: "", Nest: InsensitiveNest{ Ed: InsensitiveEd{NestedString: "another string"}, }, } var got Insensitive if _, err := Decode(caseToml, &got); err != nil { t.Fatal(err) } if !reflect.DeepEqual(expected, got) { t.Fatalf("\n%#v\n!=\n%#v\n", expected, got) } } func TestPointers(t *testing.T) { type Object struct { Type string Description string } type Dict struct { NamedObject map[string]*Object BaseObject *Object Strptr *string Strptrs []*string } s1, s2, s3 := "blah", "abc", "def" expected := &Dict{ Strptr: &s1, Strptrs: []*string{&s2, &s3}, NamedObject: map[string]*Object{ "foo": {"FOO", "fooooo!!!"}, "bar": {"BAR", "ba-ba-ba-ba-barrrr!!!"}, }, BaseObject: &Object{"BASE", "da base"}, } ex1 := ` Strptr = "blah" Strptrs = ["abc", "def"] [NamedObject.foo] Type = "FOO" Description = "fooooo!!!" [NamedObject.bar] Type = "BAR" Description = "ba-ba-ba-ba-barrrr!!!" [BaseObject] Type = "BASE" Description = "da base" ` dict := new(Dict) _, err := Decode(ex1, dict) if err != nil { t.Errorf("Decode error: %v", err) } if !reflect.DeepEqual(expected, dict) { t.Fatalf("\n%#v\n!=\n%#v\n", expected, dict) } } func TestDecodeDatetime(t *testing.T) { const noTimestamp = "2006-01-02T15:04:05" for _, tt := range []struct { s string t string format string }{ {"1979-05-27T07:32:00Z", "1979-05-27T07:32:00Z", time.RFC3339}, {"1979-05-27T00:32:00-07:00", "1979-05-27T00:32:00-07:00", time.RFC3339}, { "1979-05-27T00:32:00.999999-07:00", "1979-05-27T00:32:00.999999-07:00", time.RFC3339, }, {"1979-05-27T07:32:00", "1979-05-27T07:32:00", noTimestamp}, { "1979-05-27T00:32:00.999999", "1979-05-27T00:32:00.999999", noTimestamp, }, {"1979-05-27", "1979-05-27T00:00:00", noTimestamp}, } { var x struct{ D time.Time } input := "d = " + tt.s if _, err := Decode(input, &x); err != nil { t.Errorf("Decode(%q): got error: %s", input, err) continue } want, err := time.ParseInLocation(tt.format, tt.t, time.Local) if err != nil { panic(err) } if !x.D.Equal(want) { t.Errorf("Decode(%q): got %s; want %s", input, x.D, want) } } } func TestDecodeBadDatetime(t *testing.T) { var x struct{ T time.Time } for _, s := range []string{ "123", "2006-01-50T00:00:00Z", "2006-01-30T00:00", "2006-01-30T", } { input := "T = " + s if _, err := Decode(input, &x); err == nil { t.Errorf("Expected invalid DateTime error for %q", s) } } } func TestDecodeMultilineStrings(t *testing.T) { var x struct { S string } const s0 = `s = """ a b \n c d e f """` if _, err := Decode(s0, &x); err != nil { t.Fatal(err) } if want := "a b \n c\nd e f\n"; x.S != want { t.Errorf("got: %q; want: %q", x.S, want) } const s1 = `s = """a b c\ """` if _, err := Decode(s1, &x); err != nil { t.Fatal(err) } if want := "a b c"; x.S != want { t.Errorf("got: %q; want: %q", x.S, want) } } type sphere struct { Center [3]float64 Radius float64 } func TestDecodeSimpleArray(t *testing.T) { var s1 sphere if _, err := Decode(`center = [0.0, 1.5, 0.0]`, &s1); err != nil { t.Fatal(err) } } func TestDecodeArrayWrongSize(t *testing.T) { var s1 sphere if _, err := Decode(`center = [0.1, 2.3]`, &s1); err == nil { t.Fatal("Expected array type mismatch error") } } func TestDecodeLargeIntoSmallInt(t *testing.T) { type table struct { Value int8 } var tab table if _, err := Decode(`value = 500`, &tab); err == nil { t.Fatal("Expected integer out-of-bounds error.") } } func TestDecodeSizedInts(t *testing.T) { type table struct { U8 uint8 U16 uint16 U32 uint32 U64 uint64 U uint I8 int8 I16 int16 I32 int32 I64 int64 I int } answer := table{1, 1, 1, 1, 1, -1, -1, -1, -1, -1} toml := ` u8 = 1 u16 = 1 u32 = 1 u64 = 1 u = 1 i8 = -1 i16 = -1 i32 = -1 i64 = -1 i = -1 ` var tab table if _, err := Decode(toml, &tab); err != nil { t.Fatal(err.Error()) } if answer != tab { t.Fatalf("Expected %#v but got %#v", answer, tab) } } func TestDecodeInts(t *testing.T) { for _, tt := range []struct { s string want int64 }{ {"0", 0}, {"+99", 99}, {"-10", -10}, {"1_234_567", 1234567}, {"1_2_3_4", 1234}, {"-9_223_372_036_854_775_808", math.MinInt64}, {"9_223_372_036_854_775_807", math.MaxInt64}, } { var x struct{ N int64 } input := "n = " + tt.s if _, err := Decode(input, &x); err != nil { t.Errorf("Decode(%q): got error: %s", input, err) continue } if x.N != tt.want { t.Errorf("Decode(%q): got %d; want %d", input, x.N, tt.want) } } } func TestDecodeFloats(t *testing.T) { for _, tt := range []struct { s string want float64 }{ {"+1.0", 1}, {"3.1415", 3.1415}, {"-0.01", -0.01}, {"5e+22", 5e22}, {"1e6", 1e6}, {"-2E-2", -2e-2}, {"6.626e-34", 6.626e-34}, {"9_224_617.445_991_228_313", 9224617.445991228313}, {"9_876.54_32e1_0", 9876.5432e10}, } { var x struct{ N float64 } input := "n = " + tt.s if _, err := Decode(input, &x); err != nil { t.Errorf("Decode(%q): got error: %s", input, err) continue } if x.N != tt.want { t.Errorf("Decode(%q): got %f; want %f", input, x.N, tt.want) } } } func TestDecodeMalformedNumbers(t *testing.T) { for _, tt := range []struct { s string want string }{ {"++99", "expected a digit"}, {"0..1", "must be followed by one or more digits"}, {"0.1.2", "Invalid float value"}, {"1e2.3", "Invalid float value"}, {"1e2e3", "Invalid float value"}, {"_123", "expected value"}, {"123_", "surrounded by digits"}, {"1._23", "surrounded by digits"}, {"1e__23", "surrounded by digits"}, {"123.", "must be followed by one or more digits"}, {"1.e2", "must be followed by one or more digits"}, } { var x struct{ N interface{} } input := "n = " + tt.s _, err := Decode(input, &x) if err == nil { t.Errorf("Decode(%q): got nil, want error containing %q", input, tt.want) continue } if !strings.Contains(err.Error(), tt.want) { t.Errorf("Decode(%q): got %q, want error containing %q", input, err, tt.want) } } } func TestDecodeBadValues(t *testing.T) { for _, tt := range []struct { v interface{} want string }{ {3, "non-pointer int"}, {(*int)(nil), "nil"}, } { _, err := Decode(`x = 3`, tt.v) if err == nil { t.Errorf("Decode(%v): got nil; want error containing %q", tt.v, tt.want) continue } if !strings.Contains(err.Error(), tt.want) { t.Errorf("Decode(%v): got %q; want error containing %q", tt.v, err, tt.want) } } } func TestUnmarshaler(t *testing.T) { var tomlBlob = ` [dishes.hamboogie] name = "Hamboogie with fries" price = 10.99 [[dishes.hamboogie.ingredients]] name = "Bread Bun" [[dishes.hamboogie.ingredients]] name = "Lettuce" [[dishes.hamboogie.ingredients]] name = "Real Beef Patty" [[dishes.hamboogie.ingredients]] name = "Tomato" [dishes.eggsalad] name = "Egg Salad with rice" price = 3.99 [[dishes.eggsalad.ingredients]] name = "Egg" [[dishes.eggsalad.ingredients]] name = "Mayo" [[dishes.eggsalad.ingredients]] name = "Rice" ` m := &menu{} if _, err := Decode(tomlBlob, m); err != nil { t.Fatal(err) } if len(m.Dishes) != 2 { t.Log("two dishes should be loaded with UnmarshalTOML()") t.Errorf("expected %d but got %d", 2, len(m.Dishes)) } eggSalad := m.Dishes["eggsalad"] if _, ok := interface{}(eggSalad).(dish); !ok { t.Errorf("expected a dish") } if eggSalad.Name != "Egg Salad with rice" { t.Errorf("expected the dish to be named 'Egg Salad with rice'") } if len(eggSalad.Ingredients) != 3 { t.Log("dish should be loaded with UnmarshalTOML()") t.Errorf("expected %d but got %d", 3, len(eggSalad.Ingredients)) } found := false for _, i := range eggSalad.Ingredients { if i.Name == "Rice" { found = true break } } if !found { t.Error("Rice was not loaded in UnmarshalTOML()") } // test on a value - must be passed as * o := menu{} if _, err := Decode(tomlBlob, &o); err != nil { t.Fatal(err) } } func TestDecodeInlineTable(t *testing.T) { input := ` [CookieJar] Types = {Chocolate = "yummy", Oatmeal = "best ever"} [Seasons] Locations = {NY = {Temp = "not cold", Rating = 4}, MI = {Temp = "freezing", Rating = 9}} ` type cookieJar struct { Types map[string]string } type properties struct { Temp string Rating int } type seasons struct { Locations map[string]properties } type wrapper struct { CookieJar cookieJar Seasons seasons } var got wrapper meta, err := Decode(input, &got) if err != nil { t.Fatal(err) } want := wrapper{ CookieJar: cookieJar{ Types: map[string]string{ "Chocolate": "yummy", "Oatmeal": "best ever", }, }, Seasons: seasons{ Locations: map[string]properties{ "NY": { Temp: "not cold", Rating: 4, }, "MI": { Temp: "freezing", Rating: 9, }, }, }, } if !reflect.DeepEqual(got, want) { t.Fatalf("after decode, got:\n\n%#v\n\nwant:\n\n%#v", got, want) } if len(meta.keys) != 12 { t.Errorf("after decode, got %d meta keys; want 12", len(meta.keys)) } if len(meta.types) != 12 { t.Errorf("after decode, got %d meta types; want 12", len(meta.types)) } } func TestDecodeInlineTableArray(t *testing.T) { type point struct { X, Y, Z int } var got struct { Points []point } // Example inline table array from the spec. const in = ` points = [ { x = 1, y = 2, z = 3 }, { x = 7, y = 8, z = 9 }, { x = 2, y = 4, z = 8 } ] ` if _, err := Decode(in, &got); err != nil { t.Fatal(err) } want := []point{ {X: 1, Y: 2, Z: 3}, {X: 7, Y: 8, Z: 9}, {X: 2, Y: 4, Z: 8}, } if !reflect.DeepEqual(got.Points, want) { t.Errorf("got %#v; want %#v", got.Points, want) } } func TestDecodeMalformedInlineTable(t *testing.T) { for _, tt := range []struct { s string want string }{ {"{,}", "unexpected comma"}, {"{x = 3 y = 4}", "expected a comma or an inline table terminator"}, {"{x=3,,y=4}", "unexpected comma"}, {"{x=3,\ny=4}", "newlines not allowed"}, {"{x=3\n,y=4}", "newlines not allowed"}, } { var x struct{ A map[string]int } input := "a = " + tt.s _, err := Decode(input, &x) if err == nil { t.Errorf("Decode(%q): got nil, want error containing %q", input, tt.want) continue } if !strings.Contains(err.Error(), tt.want) { t.Errorf("Decode(%q): got %q, want error containing %q", input, err, tt.want) } } } type menu struct { Dishes map[string]dish } func (m *menu) UnmarshalTOML(p interface{}) error { m.Dishes = make(map[string]dish) data, _ := p.(map[string]interface{}) dishes := data["dishes"].(map[string]interface{}) for n, v := range dishes { if d, ok := v.(map[string]interface{}); ok { nd := dish{} nd.UnmarshalTOML(d) m.Dishes[n] = nd } else { return fmt.Errorf("not a dish") } } return nil } type dish struct { Name string Price float32 Ingredients []ingredient } func (d *dish) UnmarshalTOML(p interface{}) error { data, _ := p.(map[string]interface{}) d.Name, _ = data["name"].(string) d.Price, _ = data["price"].(float32) ingredients, _ := data["ingredients"].([]map[string]interface{}) for _, e := range ingredients { n, _ := interface{}(e).(map[string]interface{}) name, _ := n["name"].(string) i := ingredient{name} d.Ingredients = append(d.Ingredients, i) } return nil } type ingredient struct { Name string } func TestDecodeSlices(t *testing.T) { type T struct { S []string } for i, tt := range []struct { v T input string want T }{ {T{}, "", T{}}, {T{[]string{}}, "", T{[]string{}}}, {T{[]string{"a", "b"}}, "", T{[]string{"a", "b"}}}, {T{}, "S = []", T{[]string{}}}, {T{[]string{}}, "S = []", T{[]string{}}}, {T{[]string{"a", "b"}}, "S = []", T{[]string{}}}, {T{}, `S = ["x"]`, T{[]string{"x"}}}, {T{[]string{}}, `S = ["x"]`, T{[]string{"x"}}}, {T{[]string{"a", "b"}}, `S = ["x"]`, T{[]string{"x"}}}, } { if _, err := Decode(tt.input, &tt.v); err != nil { t.Errorf("[%d] %s", i, err) continue } if !reflect.DeepEqual(tt.v, tt.want) { t.Errorf("[%d] got %#v; want %#v", i, tt.v, tt.want) } } } func TestDecodePrimitive(t *testing.T) { type S struct { P Primitive } type T struct { S []int } slicep := func(s []int) *[]int { return &s } arrayp := func(a [2]int) *[2]int { return &a } mapp := func(m map[string]int) *map[string]int { return &m } for i, tt := range []struct { v interface{} input string want interface{} }{ // slices {slicep(nil), "", slicep(nil)}, {slicep([]int{}), "", slicep([]int{})}, {slicep([]int{1, 2, 3}), "", slicep([]int{1, 2, 3})}, {slicep(nil), "P = [1,2]", slicep([]int{1, 2})}, {slicep([]int{}), "P = [1,2]", slicep([]int{1, 2})}, {slicep([]int{1, 2, 3}), "P = [1,2]", slicep([]int{1, 2})}, // arrays {arrayp([2]int{2, 3}), "", arrayp([2]int{2, 3})}, {arrayp([2]int{2, 3}), "P = [3,4]", arrayp([2]int{3, 4})}, // maps {mapp(nil), "", mapp(nil)}, {mapp(map[string]int{}), "", mapp(map[string]int{})}, {mapp(map[string]int{"a": 1}), "", mapp(map[string]int{"a": 1})}, {mapp(nil), "[P]\na = 2", mapp(map[string]int{"a": 2})}, {mapp(map[string]int{}), "[P]\na = 2", mapp(map[string]int{"a": 2})}, {mapp(map[string]int{"a": 1, "b": 3}), "[P]\na = 2", mapp(map[string]int{"a": 2, "b": 3})}, // structs {&T{nil}, "[P]", &T{nil}}, {&T{[]int{}}, "[P]", &T{[]int{}}}, {&T{[]int{1, 2, 3}}, "[P]", &T{[]int{1, 2, 3}}}, {&T{nil}, "[P]\nS = [1,2]", &T{[]int{1, 2}}}, {&T{[]int{}}, "[P]\nS = [1,2]", &T{[]int{1, 2}}}, {&T{[]int{1, 2, 3}}, "[P]\nS = [1,2]", &T{[]int{1, 2}}}, } { var s S md, err := Decode(tt.input, &s) if err != nil { t.Errorf("[%d] Decode error: %s", i, err) continue } if err := md.PrimitiveDecode(s.P, tt.v); err != nil { t.Errorf("[%d] PrimitiveDecode error: %s", i, err) continue } if !reflect.DeepEqual(tt.v, tt.want) { t.Errorf("[%d] got %#v; want %#v", i, tt.v, tt.want) } } } func TestDecodeErrors(t *testing.T) { for _, s := range []string{ `x="`, `x='`, `x='''`, // Cases found by fuzzing in // https://github.com/BurntSushi/toml/issues/155. `""�`, // used to panic with index out of range `e="""`, // used to hang } { var x struct{} _, err := Decode(s, &x) if err == nil { t.Errorf("Decode(%q): got nil error", s) } } } // Test for https://github.com/BurntSushi/toml/pull/166. func TestDecodeBoolArray(t *testing.T) { for _, tt := range []struct { s string got interface{} want interface{} }{ { "a = [true, false]", &struct{ A []bool }{}, &struct{ A []bool }{[]bool{true, false}}, }, { "a = {a = true, b = false}", &struct{ A map[string]bool }{}, &struct{ A map[string]bool }{map[string]bool{"a": true, "b": false}}, }, } { if _, err := Decode(tt.s, tt.got); err != nil { t.Errorf("Decode(%q): %s", tt.s, err) continue } if !reflect.DeepEqual(tt.got, tt.want) { t.Errorf("Decode(%q): got %#v; want %#v", tt.s, tt.got, tt.want) } } } func ExampleMetaData_PrimitiveDecode() { var md MetaData var err error var tomlBlob = ` ranking = ["Springsteen", "J Geils"] [bands.Springsteen] started = 1973 albums = ["Greetings", "WIESS", "Born to Run", "Darkness"] [bands."J Geils"] started = 1970 albums = ["The J. Geils Band", "Full House", "Blow Your Face Out"] ` type band struct { Started int Albums []string } type classics struct { Ranking []string Bands map[string]Primitive } // Do the initial decode. Reflection is delayed on Primitive values. var music classics if md, err = Decode(tomlBlob, &music); err != nil { log.Fatal(err) } // MetaData still includes information on Primitive values. fmt.Printf("Is `bands.Springsteen` defined? %v\n", md.IsDefined("bands", "Springsteen")) // Decode primitive data into Go values. for _, artist := range music.Ranking { // A band is a primitive value, so we need to decode it to get a // real `band` value. primValue := music.Bands[artist] var aBand band if err = md.PrimitiveDecode(primValue, &aBand); err != nil { log.Fatal(err) } fmt.Printf("%s started in %d.\n", artist, aBand.Started) } // Check to see if there were any fields left undecoded. // Note that this won't be empty before decoding the Primitive value! fmt.Printf("Undecoded: %q\n", md.Undecoded()) // Output: // Is `bands.Springsteen` defined? true // Springsteen started in 1973. // J Geils started in 1970. // Undecoded: [] } func ExampleDecode() { var tomlBlob = ` # Some comments. [alpha] ip = "10.0.0.1" [alpha.config] Ports = [ 8001, 8002 ] Location = "Toronto" Created = 1987-07-05T05:45:00Z [beta] ip = "10.0.0.2" [beta.config] Ports = [ 9001, 9002 ] Location = "New Jersey" Created = 1887-01-05T05:55:00Z ` type serverConfig struct { Ports []int Location string Created time.Time } type server struct { IP string `toml:"ip,omitempty"` Config serverConfig `toml:"config"` } type servers map[string]server var config servers if _, err := Decode(tomlBlob, &config); err != nil { log.Fatal(err) } for _, name := range []string{"alpha", "beta"} { s := config[name] fmt.Printf("Server: %s (ip: %s) in %s created on %s\n", name, s.IP, s.Config.Location, s.Config.Created.Format("2006-01-02")) fmt.Printf("Ports: %v\n", s.Config.Ports) } // Output: // Server: alpha (ip: 10.0.0.1) in Toronto created on 1987-07-05 // Ports: [8001 8002] // Server: beta (ip: 10.0.0.2) in New Jersey created on 1887-01-05 // Ports: [9001 9002] } type duration struct { time.Duration } func (d *duration) UnmarshalText(text []byte) error { var err error d.Duration, err = time.ParseDuration(string(text)) return err } // Example Unmarshaler shows how to decode TOML strings into your own // custom data type. func Example_unmarshaler() { blob := ` [[song]] name = "Thunder Road" duration = "4m49s" [[song]] name = "Stairway to Heaven" duration = "8m03s" ` type song struct { Name string Duration duration } type songs struct { Song []song } var favorites songs if _, err := Decode(blob, &favorites); err != nil { log.Fatal(err) } // Code to implement the TextUnmarshaler interface for `duration`: // // type duration struct { // time.Duration // } // // func (d *duration) UnmarshalText(text []byte) error { // var err error // d.Duration, err = time.ParseDuration(string(text)) // return err // } for _, s := range favorites.Song { fmt.Printf("%s (%s)\n", s.Name, s.Duration) } // Output: // Thunder Road (4m49s) // Stairway to Heaven (8m3s) } // Example StrictDecoding shows how to detect whether there are keys in the // TOML document that weren't decoded into the value given. This is useful // for returning an error to the user if they've included extraneous fields // in their configuration. func Example_strictDecoding() { var blob = ` key1 = "value1" key2 = "value2" key3 = "value3" ` type config struct { Key1 string Key3 string } var conf config md, err := Decode(blob, &conf) if err != nil { log.Fatal(err) } fmt.Printf("Undecoded keys: %q\n", md.Undecoded()) // Output: // Undecoded keys: ["key2"] } // Example UnmarshalTOML shows how to implement a struct type that knows how to // unmarshal itself. The struct must take full responsibility for mapping the // values passed into the struct. The method may be used with interfaces in a // struct in cases where the actual type is not known until the data is // examined. func Example_unmarshalTOML() { var blob = ` [[parts]] type = "valve" id = "valve-1" size = 1.2 rating = 4 [[parts]] type = "valve" id = "valve-2" size = 2.1 rating = 5 [[parts]] type = "pipe" id = "pipe-1" length = 2.1 diameter = 12 [[parts]] type = "cable" id = "cable-1" length = 12 rating = 3.1 ` o := &order{} err := Unmarshal([]byte(blob), o) if err != nil { log.Fatal(err) } fmt.Println(len(o.parts)) for _, part := range o.parts { fmt.Println(part.Name()) } // Code to implement UmarshalJSON. // type order struct { // // NOTE `order.parts` is a private slice of type `part` which is an // // interface and may only be loaded from toml using the // // UnmarshalTOML() method of the Umarshaler interface. // parts parts // } // func (o *order) UnmarshalTOML(data interface{}) error { // // NOTE the example below contains detailed type casting to show how // // the 'data' is retrieved. In operational use, a type cast wrapper // // may be preferred e.g. // // // // func AsMap(v interface{}) (map[string]interface{}, error) { // // return v.(map[string]interface{}) // // } // // // // resulting in: // // d, _ := AsMap(data) // // // d, _ := data.(map[string]interface{}) // parts, _ := d["parts"].([]map[string]interface{}) // for _, p := range parts { // typ, _ := p["type"].(string) // id, _ := p["id"].(string) // // detect the type of part and handle each case // switch p["type"] { // case "valve": // size := float32(p["size"].(float64)) // rating := int(p["rating"].(int64)) // valve := &valve{ // Type: typ, // ID: id, // Size: size, // Rating: rating, // } // o.parts = append(o.parts, valve) // case "pipe": // length := float32(p["length"].(float64)) // diameter := int(p["diameter"].(int64)) // pipe := &pipe{ // Type: typ, // ID: id, // Length: length, // Diameter: diameter, // } // o.parts = append(o.parts, pipe) // case "cable": // length := int(p["length"].(int64)) // rating := float32(p["rating"].(float64)) // cable := &cable{ // Type: typ, // ID: id, // Length: length, // Rating: rating, // } // o.parts = append(o.parts, cable) // } // } // return nil // } // type parts []part // type part interface { // Name() string // } // type valve struct { // Type string // ID string // Size float32 // Rating int // } // func (v *valve) Name() string { // return fmt.Sprintf("VALVE: %s", v.ID) // } // type pipe struct { // Type string // ID string // Length float32 // Diameter int // } // func (p *pipe) Name() string { // return fmt.Sprintf("PIPE: %s", p.ID) // } // type cable struct { // Type string // ID string // Length int // Rating float32 // } // func (c *cable) Name() string { // return fmt.Sprintf("CABLE: %s", c.ID) // } // Output: // 4 // VALVE: valve-1 // VALVE: valve-2 // PIPE: pipe-1 // CABLE: cable-1 } type order struct { // NOTE `order.parts` is a private slice of type `part` which is an // interface and may only be loaded from toml using the UnmarshalTOML() // method of the Umarshaler interface. parts parts } func (o *order) UnmarshalTOML(data interface{}) error { // NOTE the example below contains detailed type casting to show how // the 'data' is retrieved. In operational use, a type cast wrapper // may be preferred e.g. // // func AsMap(v interface{}) (map[string]interface{}, error) { // return v.(map[string]interface{}) // } // // resulting in: // d, _ := AsMap(data) // d, _ := data.(map[string]interface{}) parts, _ := d["parts"].([]map[string]interface{}) for _, p := range parts { typ, _ := p["type"].(string) id, _ := p["id"].(string) // detect the type of part and handle each case switch p["type"] { case "valve": size := float32(p["size"].(float64)) rating := int(p["rating"].(int64)) valve := &valve{ Type: typ, ID: id, Size: size, Rating: rating, } o.parts = append(o.parts, valve) case "pipe": length := float32(p["length"].(float64)) diameter := int(p["diameter"].(int64)) pipe := &pipe{ Type: typ, ID: id, Length: length, Diameter: diameter, } o.parts = append(o.parts, pipe) case "cable": length := int(p["length"].(int64)) rating := float32(p["rating"].(float64)) cable := &cable{ Type: typ, ID: id, Length: length, Rating: rating, } o.parts = append(o.parts, cable) } } return nil } type parts []part type part interface { Name() string } type valve struct { Type string ID string Size float32 Rating int } func (v *valve) Name() string { return fmt.Sprintf("VALVE: %s", v.ID) } type pipe struct { Type string ID string Length float32 Diameter int } func (p *pipe) Name() string { return fmt.Sprintf("PIPE: %s", p.ID) } type cable struct { Type string ID string Length int Rating float32 } func (c *cable) Name() string { return fmt.Sprintf("CABLE: %s", c.ID) } direnv-2.15.0/vendor/github.com/BurntSushi/toml/doc.go000066400000000000000000000021201324410474700226000ustar00rootroot00000000000000/* Package toml provides facilities for decoding and encoding TOML configuration files via reflection. There is also support for delaying decoding with the Primitive type, and querying the set of keys in a TOML document with the MetaData type. The specification implemented: https://github.com/toml-lang/toml The sub-command github.com/BurntSushi/toml/cmd/tomlv can be used to verify whether a file is a valid TOML document. It can also be used to print the type of each key in a TOML document. Testing There are two important types of tests used for this package. The first is contained inside '*_test.go' files and uses the standard Go unit testing framework. These tests are primarily devoted to holistically testing the decoder and encoder. The second type of testing is used to verify the implementation's adherence to the TOML specification. These tests have been factored into their own project: https://github.com/BurntSushi/toml-test The reason the tests are in a separate project is so that they can be used by any implementation of TOML. Namely, it is language agnostic. */ package toml direnv-2.15.0/vendor/github.com/BurntSushi/toml/encode.go000066400000000000000000000351731324410474700233060ustar00rootroot00000000000000package toml import ( "bufio" "errors" "fmt" "io" "reflect" "sort" "strconv" "strings" "time" ) type tomlEncodeError struct{ error } var ( errArrayMixedElementTypes = errors.New( "toml: cannot encode array with mixed element types") errArrayNilElement = errors.New( "toml: cannot encode array with nil element") errNonString = errors.New( "toml: cannot encode a map with non-string key type") errAnonNonStruct = errors.New( "toml: cannot encode an anonymous field that is not a struct") errArrayNoTable = errors.New( "toml: TOML array element cannot contain a table") errNoKey = errors.New( "toml: top-level values must be Go maps or structs") errAnything = errors.New("") // used in testing ) var quotedReplacer = strings.NewReplacer( "\t", "\\t", "\n", "\\n", "\r", "\\r", "\"", "\\\"", "\\", "\\\\", ) // Encoder controls the encoding of Go values to a TOML document to some // io.Writer. // // The indentation level can be controlled with the Indent field. type Encoder struct { // A single indentation level. By default it is two spaces. Indent string // hasWritten is whether we have written any output to w yet. hasWritten bool w *bufio.Writer } // NewEncoder returns a TOML encoder that encodes Go values to the io.Writer // given. By default, a single indentation level is 2 spaces. func NewEncoder(w io.Writer) *Encoder { return &Encoder{ w: bufio.NewWriter(w), Indent: " ", } } // Encode writes a TOML representation of the Go value to the underlying // io.Writer. If the value given cannot be encoded to a valid TOML document, // then an error is returned. // // The mapping between Go values and TOML values should be precisely the same // as for the Decode* functions. Similarly, the TextMarshaler interface is // supported by encoding the resulting bytes as strings. (If you want to write // arbitrary binary data then you will need to use something like base64 since // TOML does not have any binary types.) // // When encoding TOML hashes (i.e., Go maps or structs), keys without any // sub-hashes are encoded first. // // If a Go map is encoded, then its keys are sorted alphabetically for // deterministic output. More control over this behavior may be provided if // there is demand for it. // // Encoding Go values without a corresponding TOML representation---like map // types with non-string keys---will cause an error to be returned. Similarly // for mixed arrays/slices, arrays/slices with nil elements, embedded // non-struct types and nested slices containing maps or structs. // (e.g., [][]map[string]string is not allowed but []map[string]string is OK // and so is []map[string][]string.) func (enc *Encoder) Encode(v interface{}) error { rv := eindirect(reflect.ValueOf(v)) if err := enc.safeEncode(Key([]string{}), rv); err != nil { return err } return enc.w.Flush() } func (enc *Encoder) safeEncode(key Key, rv reflect.Value) (err error) { defer func() { if r := recover(); r != nil { if terr, ok := r.(tomlEncodeError); ok { err = terr.error return } panic(r) } }() enc.encode(key, rv) return nil } func (enc *Encoder) encode(key Key, rv reflect.Value) { // Special case. Time needs to be in ISO8601 format. // Special case. If we can marshal the type to text, then we used that. // Basically, this prevents the encoder for handling these types as // generic structs (or whatever the underlying type of a TextMarshaler is). switch rv.Interface().(type) { case time.Time, TextMarshaler: enc.keyEqElement(key, rv) return } k := rv.Kind() switch k { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String, reflect.Bool: enc.keyEqElement(key, rv) case reflect.Array, reflect.Slice: if typeEqual(tomlArrayHash, tomlTypeOfGo(rv)) { enc.eArrayOfTables(key, rv) } else { enc.keyEqElement(key, rv) } case reflect.Interface: if rv.IsNil() { return } enc.encode(key, rv.Elem()) case reflect.Map: if rv.IsNil() { return } enc.eTable(key, rv) case reflect.Ptr: if rv.IsNil() { return } enc.encode(key, rv.Elem()) case reflect.Struct: enc.eTable(key, rv) default: panic(e("unsupported type for key '%s': %s", key, k)) } } // eElement encodes any value that can be an array element (primitives and // arrays). func (enc *Encoder) eElement(rv reflect.Value) { switch v := rv.Interface().(type) { case time.Time: // Special case time.Time as a primitive. Has to come before // TextMarshaler below because time.Time implements // encoding.TextMarshaler, but we need to always use UTC. enc.wf(v.UTC().Format("2006-01-02T15:04:05Z")) return case TextMarshaler: // Special case. Use text marshaler if it's available for this value. if s, err := v.MarshalText(); err != nil { encPanic(err) } else { enc.writeQuoted(string(s)) } return } switch rv.Kind() { case reflect.Bool: enc.wf(strconv.FormatBool(rv.Bool())) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: enc.wf(strconv.FormatInt(rv.Int(), 10)) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: enc.wf(strconv.FormatUint(rv.Uint(), 10)) case reflect.Float32: enc.wf(floatAddDecimal(strconv.FormatFloat(rv.Float(), 'f', -1, 32))) case reflect.Float64: enc.wf(floatAddDecimal(strconv.FormatFloat(rv.Float(), 'f', -1, 64))) case reflect.Array, reflect.Slice: enc.eArrayOrSliceElement(rv) case reflect.Interface: enc.eElement(rv.Elem()) case reflect.String: enc.writeQuoted(rv.String()) default: panic(e("unexpected primitive type: %s", rv.Kind())) } } // By the TOML spec, all floats must have a decimal with at least one // number on either side. func floatAddDecimal(fstr string) string { if !strings.Contains(fstr, ".") { return fstr + ".0" } return fstr } func (enc *Encoder) writeQuoted(s string) { enc.wf("\"%s\"", quotedReplacer.Replace(s)) } func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) { length := rv.Len() enc.wf("[") for i := 0; i < length; i++ { elem := rv.Index(i) enc.eElement(elem) if i != length-1 { enc.wf(", ") } } enc.wf("]") } func (enc *Encoder) eArrayOfTables(key Key, rv reflect.Value) { if len(key) == 0 { encPanic(errNoKey) } for i := 0; i < rv.Len(); i++ { trv := rv.Index(i) if isNil(trv) { continue } panicIfInvalidKey(key) enc.newline() enc.wf("%s[[%s]]", enc.indentStr(key), key.maybeQuotedAll()) enc.newline() enc.eMapOrStruct(key, trv) } } func (enc *Encoder) eTable(key Key, rv reflect.Value) { panicIfInvalidKey(key) if len(key) == 1 { // Output an extra newline between top-level tables. // (The newline isn't written if nothing else has been written though.) enc.newline() } if len(key) > 0 { enc.wf("%s[%s]", enc.indentStr(key), key.maybeQuotedAll()) enc.newline() } enc.eMapOrStruct(key, rv) } func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value) { switch rv := eindirect(rv); rv.Kind() { case reflect.Map: enc.eMap(key, rv) case reflect.Struct: enc.eStruct(key, rv) default: panic("eTable: unhandled reflect.Value Kind: " + rv.Kind().String()) } } func (enc *Encoder) eMap(key Key, rv reflect.Value) { rt := rv.Type() if rt.Key().Kind() != reflect.String { encPanic(errNonString) } // Sort keys so that we have deterministic output. And write keys directly // underneath this key first, before writing sub-structs or sub-maps. var mapKeysDirect, mapKeysSub []string for _, mapKey := range rv.MapKeys() { k := mapKey.String() if typeIsHash(tomlTypeOfGo(rv.MapIndex(mapKey))) { mapKeysSub = append(mapKeysSub, k) } else { mapKeysDirect = append(mapKeysDirect, k) } } var writeMapKeys = func(mapKeys []string) { sort.Strings(mapKeys) for _, mapKey := range mapKeys { mrv := rv.MapIndex(reflect.ValueOf(mapKey)) if isNil(mrv) { // Don't write anything for nil fields. continue } enc.encode(key.add(mapKey), mrv) } } writeMapKeys(mapKeysDirect) writeMapKeys(mapKeysSub) } func (enc *Encoder) eStruct(key Key, rv reflect.Value) { // Write keys for fields directly under this key first, because if we write // a field that creates a new table, then all keys under it will be in that // table (not the one we're writing here). rt := rv.Type() var fieldsDirect, fieldsSub [][]int var addFields func(rt reflect.Type, rv reflect.Value, start []int) addFields = func(rt reflect.Type, rv reflect.Value, start []int) { for i := 0; i < rt.NumField(); i++ { f := rt.Field(i) // skip unexported fields if f.PkgPath != "" && !f.Anonymous { continue } frv := rv.Field(i) if f.Anonymous { t := f.Type switch t.Kind() { case reflect.Struct: // Treat anonymous struct fields with // tag names as though they are not // anonymous, like encoding/json does. if getOptions(f.Tag).name == "" { addFields(t, frv, f.Index) continue } case reflect.Ptr: if t.Elem().Kind() == reflect.Struct && getOptions(f.Tag).name == "" { if !frv.IsNil() { addFields(t.Elem(), frv.Elem(), f.Index) } continue } // Fall through to the normal field encoding logic below // for non-struct anonymous fields. } } if typeIsHash(tomlTypeOfGo(frv)) { fieldsSub = append(fieldsSub, append(start, f.Index...)) } else { fieldsDirect = append(fieldsDirect, append(start, f.Index...)) } } } addFields(rt, rv, nil) var writeFields = func(fields [][]int) { for _, fieldIndex := range fields { sft := rt.FieldByIndex(fieldIndex) sf := rv.FieldByIndex(fieldIndex) if isNil(sf) { // Don't write anything for nil fields. continue } opts := getOptions(sft.Tag) if opts.skip { continue } keyName := sft.Name if opts.name != "" { keyName = opts.name } if opts.omitempty && isEmpty(sf) { continue } if opts.omitzero && isZero(sf) { continue } enc.encode(key.add(keyName), sf) } } writeFields(fieldsDirect) writeFields(fieldsSub) } // tomlTypeName returns the TOML type name of the Go value's type. It is // used to determine whether the types of array elements are mixed (which is // forbidden). If the Go value is nil, then it is illegal for it to be an array // element, and valueIsNil is returned as true. // Returns the TOML type of a Go value. The type may be `nil`, which means // no concrete TOML type could be found. func tomlTypeOfGo(rv reflect.Value) tomlType { if isNil(rv) || !rv.IsValid() { return nil } switch rv.Kind() { case reflect.Bool: return tomlBool case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return tomlInteger case reflect.Float32, reflect.Float64: return tomlFloat case reflect.Array, reflect.Slice: if typeEqual(tomlHash, tomlArrayType(rv)) { return tomlArrayHash } return tomlArray case reflect.Ptr, reflect.Interface: return tomlTypeOfGo(rv.Elem()) case reflect.String: return tomlString case reflect.Map: return tomlHash case reflect.Struct: switch rv.Interface().(type) { case time.Time: return tomlDatetime case TextMarshaler: return tomlString default: return tomlHash } default: panic("unexpected reflect.Kind: " + rv.Kind().String()) } } // tomlArrayType returns the element type of a TOML array. The type returned // may be nil if it cannot be determined (e.g., a nil slice or a zero length // slize). This function may also panic if it finds a type that cannot be // expressed in TOML (such as nil elements, heterogeneous arrays or directly // nested arrays of tables). func tomlArrayType(rv reflect.Value) tomlType { if isNil(rv) || !rv.IsValid() || rv.Len() == 0 { return nil } firstType := tomlTypeOfGo(rv.Index(0)) if firstType == nil { encPanic(errArrayNilElement) } rvlen := rv.Len() for i := 1; i < rvlen; i++ { elem := rv.Index(i) switch elemType := tomlTypeOfGo(elem); { case elemType == nil: encPanic(errArrayNilElement) case !typeEqual(firstType, elemType): encPanic(errArrayMixedElementTypes) } } // If we have a nested array, then we must make sure that the nested // array contains ONLY primitives. // This checks arbitrarily nested arrays. if typeEqual(firstType, tomlArray) || typeEqual(firstType, tomlArrayHash) { nest := tomlArrayType(eindirect(rv.Index(0))) if typeEqual(nest, tomlHash) || typeEqual(nest, tomlArrayHash) { encPanic(errArrayNoTable) } } return firstType } type tagOptions struct { skip bool // "-" name string omitempty bool omitzero bool } func getOptions(tag reflect.StructTag) tagOptions { t := tag.Get("toml") if t == "-" { return tagOptions{skip: true} } var opts tagOptions parts := strings.Split(t, ",") opts.name = parts[0] for _, s := range parts[1:] { switch s { case "omitempty": opts.omitempty = true case "omitzero": opts.omitzero = true } } return opts } func isZero(rv reflect.Value) bool { switch rv.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return rv.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return rv.Uint() == 0 case reflect.Float32, reflect.Float64: return rv.Float() == 0.0 } return false } func isEmpty(rv reflect.Value) bool { switch rv.Kind() { case reflect.Array, reflect.Slice, reflect.Map, reflect.String: return rv.Len() == 0 case reflect.Bool: return !rv.Bool() } return false } func (enc *Encoder) newline() { if enc.hasWritten { enc.wf("\n") } } func (enc *Encoder) keyEqElement(key Key, val reflect.Value) { if len(key) == 0 { encPanic(errNoKey) } panicIfInvalidKey(key) enc.wf("%s%s = ", enc.indentStr(key), key.maybeQuoted(len(key)-1)) enc.eElement(val) enc.newline() } func (enc *Encoder) wf(format string, v ...interface{}) { if _, err := fmt.Fprintf(enc.w, format, v...); err != nil { encPanic(err) } enc.hasWritten = true } func (enc *Encoder) indentStr(key Key) string { return strings.Repeat(enc.Indent, len(key)-1) } func encPanic(err error) { panic(tomlEncodeError{err}) } func eindirect(v reflect.Value) reflect.Value { switch v.Kind() { case reflect.Ptr, reflect.Interface: return eindirect(v.Elem()) default: return v } } func isNil(rv reflect.Value) bool { switch rv.Kind() { case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return rv.IsNil() default: return false } } func panicIfInvalidKey(key Key) { for _, k := range key { if len(k) == 0 { encPanic(e("Key '%s' is not a valid table name. Key names "+ "cannot be empty.", key.maybeQuotedAll())) } } } func isValidKeyName(s string) bool { return len(s) != 0 } direnv-2.15.0/vendor/github.com/BurntSushi/toml/encode_test.go000066400000000000000000000351541324410474700243440ustar00rootroot00000000000000package toml import ( "bytes" "fmt" "log" "net" "testing" "time" ) func TestEncodeRoundTrip(t *testing.T) { type Config struct { Age int Cats []string Pi float64 Perfection []int DOB time.Time Ipaddress net.IP } var inputs = Config{ 13, []string{"one", "two", "three"}, 3.145, []int{11, 2, 3, 4}, time.Now(), net.ParseIP("192.168.59.254"), } var firstBuffer bytes.Buffer e := NewEncoder(&firstBuffer) err := e.Encode(inputs) if err != nil { t.Fatal(err) } var outputs Config if _, err := Decode(firstBuffer.String(), &outputs); err != nil { t.Logf("Could not decode:\n-----\n%s\n-----\n", firstBuffer.String()) t.Fatal(err) } // could test each value individually, but I'm lazy var secondBuffer bytes.Buffer e2 := NewEncoder(&secondBuffer) err = e2.Encode(outputs) if err != nil { t.Fatal(err) } if firstBuffer.String() != secondBuffer.String() { t.Error( firstBuffer.String(), "\n\n is not identical to\n\n", secondBuffer.String()) } } // XXX(burntsushi) // I think these tests probably should be removed. They are good, but they // ought to be obsolete by toml-test. func TestEncode(t *testing.T) { type Embedded struct { Int int `toml:"_int"` } type NonStruct int date := time.Date(2014, 5, 11, 20, 30, 40, 0, time.FixedZone("IST", 3600)) dateStr := "2014-05-11T19:30:40Z" tests := map[string]struct { input interface{} wantOutput string wantError error }{ "bool field": { input: struct { BoolTrue bool BoolFalse bool }{true, false}, wantOutput: "BoolTrue = true\nBoolFalse = false\n", }, "int fields": { input: struct { Int int Int8 int8 Int16 int16 Int32 int32 Int64 int64 }{1, 2, 3, 4, 5}, wantOutput: "Int = 1\nInt8 = 2\nInt16 = 3\nInt32 = 4\nInt64 = 5\n", }, "uint fields": { input: struct { Uint uint Uint8 uint8 Uint16 uint16 Uint32 uint32 Uint64 uint64 }{1, 2, 3, 4, 5}, wantOutput: "Uint = 1\nUint8 = 2\nUint16 = 3\nUint32 = 4" + "\nUint64 = 5\n", }, "float fields": { input: struct { Float32 float32 Float64 float64 }{1.5, 2.5}, wantOutput: "Float32 = 1.5\nFloat64 = 2.5\n", }, "string field": { input: struct{ String string }{"foo"}, wantOutput: "String = \"foo\"\n", }, "string field and unexported field": { input: struct { String string unexported int }{"foo", 0}, wantOutput: "String = \"foo\"\n", }, "datetime field in UTC": { input: struct{ Date time.Time }{date}, wantOutput: fmt.Sprintf("Date = %s\n", dateStr), }, "datetime field as primitive": { // Using a map here to fail if isStructOrMap() returns true for // time.Time. input: map[string]interface{}{ "Date": date, "Int": 1, }, wantOutput: fmt.Sprintf("Date = %s\nInt = 1\n", dateStr), }, "array fields": { input: struct { IntArray0 [0]int IntArray3 [3]int }{[0]int{}, [3]int{1, 2, 3}}, wantOutput: "IntArray0 = []\nIntArray3 = [1, 2, 3]\n", }, "slice fields": { input: struct{ IntSliceNil, IntSlice0, IntSlice3 []int }{ nil, []int{}, []int{1, 2, 3}, }, wantOutput: "IntSlice0 = []\nIntSlice3 = [1, 2, 3]\n", }, "datetime slices": { input: struct{ DatetimeSlice []time.Time }{ []time.Time{date, date}, }, wantOutput: fmt.Sprintf("DatetimeSlice = [%s, %s]\n", dateStr, dateStr), }, "nested arrays and slices": { input: struct { SliceOfArrays [][2]int ArrayOfSlices [2][]int SliceOfArraysOfSlices [][2][]int ArrayOfSlicesOfArrays [2][][2]int SliceOfMixedArrays [][2]interface{} ArrayOfMixedSlices [2][]interface{} }{ [][2]int{{1, 2}, {3, 4}}, [2][]int{{1, 2}, {3, 4}}, [][2][]int{ { {1, 2}, {3, 4}, }, { {5, 6}, {7, 8}, }, }, [2][][2]int{ { {1, 2}, {3, 4}, }, { {5, 6}, {7, 8}, }, }, [][2]interface{}{ {1, 2}, {"a", "b"}, }, [2][]interface{}{ {1, 2}, {"a", "b"}, }, }, wantOutput: `SliceOfArrays = [[1, 2], [3, 4]] ArrayOfSlices = [[1, 2], [3, 4]] SliceOfArraysOfSlices = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] ArrayOfSlicesOfArrays = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] SliceOfMixedArrays = [[1, 2], ["a", "b"]] ArrayOfMixedSlices = [[1, 2], ["a", "b"]] `, }, "empty slice": { input: struct{ Empty []interface{} }{[]interface{}{}}, wantOutput: "Empty = []\n", }, "(error) slice with element type mismatch (string and integer)": { input: struct{ Mixed []interface{} }{[]interface{}{1, "a"}}, wantError: errArrayMixedElementTypes, }, "(error) slice with element type mismatch (integer and float)": { input: struct{ Mixed []interface{} }{[]interface{}{1, 2.5}}, wantError: errArrayMixedElementTypes, }, "slice with elems of differing Go types, same TOML types": { input: struct { MixedInts []interface{} MixedFloats []interface{} }{ []interface{}{ int(1), int8(2), int16(3), int32(4), int64(5), uint(1), uint8(2), uint16(3), uint32(4), uint64(5), }, []interface{}{float32(1.5), float64(2.5)}, }, wantOutput: "MixedInts = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]\n" + "MixedFloats = [1.5, 2.5]\n", }, "(error) slice w/ element type mismatch (one is nested array)": { input: struct{ Mixed []interface{} }{ []interface{}{1, []interface{}{2}}, }, wantError: errArrayMixedElementTypes, }, "(error) slice with 1 nil element": { input: struct{ NilElement1 []interface{} }{[]interface{}{nil}}, wantError: errArrayNilElement, }, "(error) slice with 1 nil element (and other non-nil elements)": { input: struct{ NilElement []interface{} }{ []interface{}{1, nil}, }, wantError: errArrayNilElement, }, "simple map": { input: map[string]int{"a": 1, "b": 2}, wantOutput: "a = 1\nb = 2\n", }, "map with interface{} value type": { input: map[string]interface{}{"a": 1, "b": "c"}, wantOutput: "a = 1\nb = \"c\"\n", }, "map with interface{} value type, some of which are structs": { input: map[string]interface{}{ "a": struct{ Int int }{2}, "b": 1, }, wantOutput: "b = 1\n\n[a]\n Int = 2\n", }, "nested map": { input: map[string]map[string]int{ "a": {"b": 1}, "c": {"d": 2}, }, wantOutput: "[a]\n b = 1\n\n[c]\n d = 2\n", }, "nested struct": { input: struct{ Struct struct{ Int int } }{ struct{ Int int }{1}, }, wantOutput: "[Struct]\n Int = 1\n", }, "nested struct and non-struct field": { input: struct { Struct struct{ Int int } Bool bool }{struct{ Int int }{1}, true}, wantOutput: "Bool = true\n\n[Struct]\n Int = 1\n", }, "2 nested structs": { input: struct{ Struct1, Struct2 struct{ Int int } }{ struct{ Int int }{1}, struct{ Int int }{2}, }, wantOutput: "[Struct1]\n Int = 1\n\n[Struct2]\n Int = 2\n", }, "deeply nested structs": { input: struct { Struct1, Struct2 struct{ Struct3 *struct{ Int int } } }{ struct{ Struct3 *struct{ Int int } }{&struct{ Int int }{1}}, struct{ Struct3 *struct{ Int int } }{nil}, }, wantOutput: "[Struct1]\n [Struct1.Struct3]\n Int = 1" + "\n\n[Struct2]\n", }, "nested struct with nil struct elem": { input: struct { Struct struct{ Inner *struct{ Int int } } }{ struct{ Inner *struct{ Int int } }{nil}, }, wantOutput: "[Struct]\n", }, "nested struct with no fields": { input: struct { Struct struct{ Inner struct{} } }{ struct{ Inner struct{} }{struct{}{}}, }, wantOutput: "[Struct]\n [Struct.Inner]\n", }, "struct with tags": { input: struct { Struct struct { Int int `toml:"_int"` } `toml:"_struct"` Bool bool `toml:"_bool"` }{ struct { Int int `toml:"_int"` }{1}, true, }, wantOutput: "_bool = true\n\n[_struct]\n _int = 1\n", }, "embedded struct": { input: struct{ Embedded }{Embedded{1}}, wantOutput: "_int = 1\n", }, "embedded *struct": { input: struct{ *Embedded }{&Embedded{1}}, wantOutput: "_int = 1\n", }, "nested embedded struct": { input: struct { Struct struct{ Embedded } `toml:"_struct"` }{struct{ Embedded }{Embedded{1}}}, wantOutput: "[_struct]\n _int = 1\n", }, "nested embedded *struct": { input: struct { Struct struct{ *Embedded } `toml:"_struct"` }{struct{ *Embedded }{&Embedded{1}}}, wantOutput: "[_struct]\n _int = 1\n", }, "embedded non-struct": { input: struct{ NonStruct }{5}, wantOutput: "NonStruct = 5\n", }, "array of tables": { input: struct { Structs []*struct{ Int int } `toml:"struct"` }{ []*struct{ Int int }{{1}, {3}}, }, wantOutput: "[[struct]]\n Int = 1\n\n[[struct]]\n Int = 3\n", }, "array of tables order": { input: map[string]interface{}{ "map": map[string]interface{}{ "zero": 5, "arr": []map[string]int{ { "friend": 5, }, }, }, }, wantOutput: "[map]\n zero = 5\n\n [[map.arr]]\n friend = 5\n", }, "(error) top-level slice": { input: []struct{ Int int }{{1}, {2}, {3}}, wantError: errNoKey, }, "(error) slice of slice": { input: struct { Slices [][]struct{ Int int } }{ [][]struct{ Int int }{{{1}}, {{2}}, {{3}}}, }, wantError: errArrayNoTable, }, "(error) map no string key": { input: map[int]string{1: ""}, wantError: errNonString, }, "(error) empty key name": { input: map[string]int{"": 1}, wantError: errAnything, }, "(error) empty map name": { input: map[string]interface{}{ "": map[string]int{"v": 1}, }, wantError: errAnything, }, } for label, test := range tests { encodeExpected(t, label, test.input, test.wantOutput, test.wantError) } } func TestEncodeNestedTableArrays(t *testing.T) { type song struct { Name string `toml:"name"` } type album struct { Name string `toml:"name"` Songs []song `toml:"songs"` } type springsteen struct { Albums []album `toml:"albums"` } value := springsteen{ []album{ {"Born to Run", []song{{"Jungleland"}, {"Meeting Across the River"}}}, {"Born in the USA", []song{{"Glory Days"}, {"Dancing in the Dark"}}}, }, } expected := `[[albums]] name = "Born to Run" [[albums.songs]] name = "Jungleland" [[albums.songs]] name = "Meeting Across the River" [[albums]] name = "Born in the USA" [[albums.songs]] name = "Glory Days" [[albums.songs]] name = "Dancing in the Dark" ` encodeExpected(t, "nested table arrays", value, expected, nil) } func TestEncodeArrayHashWithNormalHashOrder(t *testing.T) { type Alpha struct { V int } type Beta struct { V int } type Conf struct { V int A Alpha B []Beta } val := Conf{ V: 1, A: Alpha{2}, B: []Beta{{3}}, } expected := "V = 1\n\n[A]\n V = 2\n\n[[B]]\n V = 3\n" encodeExpected(t, "array hash with normal hash order", val, expected, nil) } func TestEncodeWithOmitEmpty(t *testing.T) { type simple struct { Bool bool `toml:"bool,omitempty"` String string `toml:"string,omitempty"` Array [0]byte `toml:"array,omitempty"` Slice []int `toml:"slice,omitempty"` Map map[string]string `toml:"map,omitempty"` } var v simple encodeExpected(t, "fields with omitempty are omitted when empty", v, "", nil) v = simple{ Bool: true, String: " ", Slice: []int{2, 3, 4}, Map: map[string]string{"foo": "bar"}, } expected := `bool = true string = " " slice = [2, 3, 4] [map] foo = "bar" ` encodeExpected(t, "fields with omitempty are not omitted when non-empty", v, expected, nil) } func TestEncodeWithOmitZero(t *testing.T) { type simple struct { Number int `toml:"number,omitzero"` Real float64 `toml:"real,omitzero"` Unsigned uint `toml:"unsigned,omitzero"` } value := simple{0, 0.0, uint(0)} expected := "" encodeExpected(t, "simple with omitzero, all zero", value, expected, nil) value.Number = 10 value.Real = 20 value.Unsigned = 5 expected = `number = 10 real = 20.0 unsigned = 5 ` encodeExpected(t, "simple with omitzero, non-zero", value, expected, nil) } func TestEncodeOmitemptyWithEmptyName(t *testing.T) { type simple struct { S []int `toml:",omitempty"` } v := simple{[]int{1, 2, 3}} expected := "S = [1, 2, 3]\n" encodeExpected(t, "simple with omitempty, no name, non-empty field", v, expected, nil) } func TestEncodeAnonymousStruct(t *testing.T) { type Inner struct{ N int } type Outer0 struct{ Inner } type Outer1 struct { Inner `toml:"inner"` } v0 := Outer0{Inner{3}} expected := "N = 3\n" encodeExpected(t, "embedded anonymous untagged struct", v0, expected, nil) v1 := Outer1{Inner{3}} expected = "[inner]\n N = 3\n" encodeExpected(t, "embedded anonymous tagged struct", v1, expected, nil) } func TestEncodeAnonymousStructPointerField(t *testing.T) { type Inner struct{ N int } type Outer0 struct{ *Inner } type Outer1 struct { *Inner `toml:"inner"` } v0 := Outer0{} expected := "" encodeExpected(t, "nil anonymous untagged struct pointer field", v0, expected, nil) v0 = Outer0{&Inner{3}} expected = "N = 3\n" encodeExpected(t, "non-nil anonymous untagged struct pointer field", v0, expected, nil) v1 := Outer1{} expected = "" encodeExpected(t, "nil anonymous tagged struct pointer field", v1, expected, nil) v1 = Outer1{&Inner{3}} expected = "[inner]\n N = 3\n" encodeExpected(t, "non-nil anonymous tagged struct pointer field", v1, expected, nil) } func TestEncodeIgnoredFields(t *testing.T) { type simple struct { Number int `toml:"-"` } value := simple{} expected := "" encodeExpected(t, "ignored field", value, expected, nil) } func encodeExpected( t *testing.T, label string, val interface{}, wantStr string, wantErr error, ) { var buf bytes.Buffer enc := NewEncoder(&buf) err := enc.Encode(val) if err != wantErr { if wantErr != nil { if wantErr == errAnything && err != nil { return } t.Errorf("%s: want Encode error %v, got %v", label, wantErr, err) } else { t.Errorf("%s: Encode failed: %s", label, err) } } if err != nil { return } if got := buf.String(); wantStr != got { t.Errorf("%s: want\n-----\n%q\n-----\nbut got\n-----\n%q\n-----\n", label, wantStr, got) } } func ExampleEncoder_Encode() { date, _ := time.Parse(time.RFC822, "14 Mar 10 18:00 UTC") var config = map[string]interface{}{ "date": date, "counts": []int{1, 1, 2, 3, 5, 8}, "hash": map[string]string{ "key1": "val1", "key2": "val2", }, } buf := new(bytes.Buffer) if err := NewEncoder(buf).Encode(config); err != nil { log.Fatal(err) } fmt.Println(buf.String()) // Output: // counts = [1, 1, 2, 3, 5, 8] // date = 2010-03-14T18:00:00Z // // [hash] // key1 = "val1" // key2 = "val2" } direnv-2.15.0/vendor/github.com/BurntSushi/toml/encoding_types.go000066400000000000000000000010351324410474700250510ustar00rootroot00000000000000// +build go1.2 package toml // In order to support Go 1.1, we define our own TextMarshaler and // TextUnmarshaler types. For Go 1.2+, we just alias them with the // standard library interfaces. import ( "encoding" ) // TextMarshaler is a synonym for encoding.TextMarshaler. It is defined here // so that Go 1.1 can be supported. type TextMarshaler encoding.TextMarshaler // TextUnmarshaler is a synonym for encoding.TextUnmarshaler. It is defined // here so that Go 1.1 can be supported. type TextUnmarshaler encoding.TextUnmarshaler direnv-2.15.0/vendor/github.com/BurntSushi/toml/encoding_types_1.1.go000066400000000000000000000007731324410474700254400ustar00rootroot00000000000000// +build !go1.2 package toml // These interfaces were introduced in Go 1.2, so we add them manually when // compiling for Go 1.1. // TextMarshaler is a synonym for encoding.TextMarshaler. It is defined here // so that Go 1.1 can be supported. type TextMarshaler interface { MarshalText() (text []byte, err error) } // TextUnmarshaler is a synonym for encoding.TextUnmarshaler. It is defined // here so that Go 1.1 can be supported. type TextUnmarshaler interface { UnmarshalText(text []byte) error } direnv-2.15.0/vendor/github.com/BurntSushi/toml/lex.go000066400000000000000000000533021324410474700226330ustar00rootroot00000000000000package toml import ( "fmt" "strings" "unicode" "unicode/utf8" ) type itemType int const ( itemError itemType = iota itemNIL // used in the parser to indicate no type itemEOF itemText itemString itemRawString itemMultilineString itemRawMultilineString itemBool itemInteger itemFloat itemDatetime itemArray // the start of an array itemArrayEnd itemTableStart itemTableEnd itemArrayTableStart itemArrayTableEnd itemKeyStart itemCommentStart itemInlineTableStart itemInlineTableEnd ) const ( eof = 0 comma = ',' tableStart = '[' tableEnd = ']' arrayTableStart = '[' arrayTableEnd = ']' tableSep = '.' keySep = '=' arrayStart = '[' arrayEnd = ']' commentStart = '#' stringStart = '"' stringEnd = '"' rawStringStart = '\'' rawStringEnd = '\'' inlineTableStart = '{' inlineTableEnd = '}' ) type stateFn func(lx *lexer) stateFn type lexer struct { input string start int pos int line int state stateFn items chan item // Allow for backing up up to three runes. // This is necessary because TOML contains 3-rune tokens (""" and '''). prevWidths [3]int nprev int // how many of prevWidths are in use // If we emit an eof, we can still back up, but it is not OK to call // next again. atEOF bool // A stack of state functions used to maintain context. // The idea is to reuse parts of the state machine in various places. // For example, values can appear at the top level or within arbitrarily // nested arrays. The last state on the stack is used after a value has // been lexed. Similarly for comments. stack []stateFn } type item struct { typ itemType val string line int } func (lx *lexer) nextItem() item { for { select { case item := <-lx.items: return item default: lx.state = lx.state(lx) } } } func lex(input string) *lexer { lx := &lexer{ input: input, state: lexTop, line: 1, items: make(chan item, 10), stack: make([]stateFn, 0, 10), } return lx } func (lx *lexer) push(state stateFn) { lx.stack = append(lx.stack, state) } func (lx *lexer) pop() stateFn { if len(lx.stack) == 0 { return lx.errorf("BUG in lexer: no states to pop") } last := lx.stack[len(lx.stack)-1] lx.stack = lx.stack[0 : len(lx.stack)-1] return last } func (lx *lexer) current() string { return lx.input[lx.start:lx.pos] } func (lx *lexer) emit(typ itemType) { lx.items <- item{typ, lx.current(), lx.line} lx.start = lx.pos } func (lx *lexer) emitTrim(typ itemType) { lx.items <- item{typ, strings.TrimSpace(lx.current()), lx.line} lx.start = lx.pos } func (lx *lexer) next() (r rune) { if lx.atEOF { panic("next called after EOF") } if lx.pos >= len(lx.input) { lx.atEOF = true return eof } if lx.input[lx.pos] == '\n' { lx.line++ } lx.prevWidths[2] = lx.prevWidths[1] lx.prevWidths[1] = lx.prevWidths[0] if lx.nprev < 3 { lx.nprev++ } r, w := utf8.DecodeRuneInString(lx.input[lx.pos:]) lx.prevWidths[0] = w lx.pos += w return r } // ignore skips over the pending input before this point. func (lx *lexer) ignore() { lx.start = lx.pos } // backup steps back one rune. Can be called only twice between calls to next. func (lx *lexer) backup() { if lx.atEOF { lx.atEOF = false return } if lx.nprev < 1 { panic("backed up too far") } w := lx.prevWidths[0] lx.prevWidths[0] = lx.prevWidths[1] lx.prevWidths[1] = lx.prevWidths[2] lx.nprev-- lx.pos -= w if lx.pos < len(lx.input) && lx.input[lx.pos] == '\n' { lx.line-- } } // accept consumes the next rune if it's equal to `valid`. func (lx *lexer) accept(valid rune) bool { if lx.next() == valid { return true } lx.backup() return false } // peek returns but does not consume the next rune in the input. func (lx *lexer) peek() rune { r := lx.next() lx.backup() return r } // skip ignores all input that matches the given predicate. func (lx *lexer) skip(pred func(rune) bool) { for { r := lx.next() if pred(r) { continue } lx.backup() lx.ignore() return } } // errorf stops all lexing by emitting an error and returning `nil`. // Note that any value that is a character is escaped if it's a special // character (newlines, tabs, etc.). func (lx *lexer) errorf(format string, values ...interface{}) stateFn { lx.items <- item{ itemError, fmt.Sprintf(format, values...), lx.line, } return nil } // lexTop consumes elements at the top level of TOML data. func lexTop(lx *lexer) stateFn { r := lx.next() if isWhitespace(r) || isNL(r) { return lexSkip(lx, lexTop) } switch r { case commentStart: lx.push(lexTop) return lexCommentStart case tableStart: return lexTableStart case eof: if lx.pos > lx.start { return lx.errorf("unexpected EOF") } lx.emit(itemEOF) return nil } // At this point, the only valid item can be a key, so we back up // and let the key lexer do the rest. lx.backup() lx.push(lexTopEnd) return lexKeyStart } // lexTopEnd is entered whenever a top-level item has been consumed. (A value // or a table.) It must see only whitespace, and will turn back to lexTop // upon a newline. If it sees EOF, it will quit the lexer successfully. func lexTopEnd(lx *lexer) stateFn { r := lx.next() switch { case r == commentStart: // a comment will read to a newline for us. lx.push(lexTop) return lexCommentStart case isWhitespace(r): return lexTopEnd case isNL(r): lx.ignore() return lexTop case r == eof: lx.emit(itemEOF) return nil } return lx.errorf("expected a top-level item to end with a newline, "+ "comment, or EOF, but got %q instead", r) } // lexTable lexes the beginning of a table. Namely, it makes sure that // it starts with a character other than '.' and ']'. // It assumes that '[' has already been consumed. // It also handles the case that this is an item in an array of tables. // e.g., '[[name]]'. func lexTableStart(lx *lexer) stateFn { if lx.peek() == arrayTableStart { lx.next() lx.emit(itemArrayTableStart) lx.push(lexArrayTableEnd) } else { lx.emit(itemTableStart) lx.push(lexTableEnd) } return lexTableNameStart } func lexTableEnd(lx *lexer) stateFn { lx.emit(itemTableEnd) return lexTopEnd } func lexArrayTableEnd(lx *lexer) stateFn { if r := lx.next(); r != arrayTableEnd { return lx.errorf("expected end of table array name delimiter %q, "+ "but got %q instead", arrayTableEnd, r) } lx.emit(itemArrayTableEnd) return lexTopEnd } func lexTableNameStart(lx *lexer) stateFn { lx.skip(isWhitespace) switch r := lx.peek(); { case r == tableEnd || r == eof: return lx.errorf("unexpected end of table name " + "(table names cannot be empty)") case r == tableSep: return lx.errorf("unexpected table separator " + "(table names cannot be empty)") case r == stringStart || r == rawStringStart: lx.ignore() lx.push(lexTableNameEnd) return lexValue // reuse string lexing default: return lexBareTableName } } // lexBareTableName lexes the name of a table. It assumes that at least one // valid character for the table has already been read. func lexBareTableName(lx *lexer) stateFn { r := lx.next() if isBareKeyChar(r) { return lexBareTableName } lx.backup() lx.emit(itemText) return lexTableNameEnd } // lexTableNameEnd reads the end of a piece of a table name, optionally // consuming whitespace. func lexTableNameEnd(lx *lexer) stateFn { lx.skip(isWhitespace) switch r := lx.next(); { case isWhitespace(r): return lexTableNameEnd case r == tableSep: lx.ignore() return lexTableNameStart case r == tableEnd: return lx.pop() default: return lx.errorf("expected '.' or ']' to end table name, "+ "but got %q instead", r) } } // lexKeyStart consumes a key name up until the first non-whitespace character. // lexKeyStart will ignore whitespace. func lexKeyStart(lx *lexer) stateFn { r := lx.peek() switch { case r == keySep: return lx.errorf("unexpected key separator %q", keySep) case isWhitespace(r) || isNL(r): lx.next() return lexSkip(lx, lexKeyStart) case r == stringStart || r == rawStringStart: lx.ignore() lx.emit(itemKeyStart) lx.push(lexKeyEnd) return lexValue // reuse string lexing default: lx.ignore() lx.emit(itemKeyStart) return lexBareKey } } // lexBareKey consumes the text of a bare key. Assumes that the first character // (which is not whitespace) has not yet been consumed. func lexBareKey(lx *lexer) stateFn { switch r := lx.next(); { case isBareKeyChar(r): return lexBareKey case isWhitespace(r): lx.backup() lx.emit(itemText) return lexKeyEnd case r == keySep: lx.backup() lx.emit(itemText) return lexKeyEnd default: return lx.errorf("bare keys cannot contain %q", r) } } // lexKeyEnd consumes the end of a key and trims whitespace (up to the key // separator). func lexKeyEnd(lx *lexer) stateFn { switch r := lx.next(); { case r == keySep: return lexSkip(lx, lexValue) case isWhitespace(r): return lexSkip(lx, lexKeyEnd) default: return lx.errorf("expected key separator %q, but got %q instead", keySep, r) } } // lexValue starts the consumption of a value anywhere a value is expected. // lexValue will ignore whitespace. // After a value is lexed, the last state on the next is popped and returned. func lexValue(lx *lexer) stateFn { // We allow whitespace to precede a value, but NOT newlines. // In array syntax, the array states are responsible for ignoring newlines. r := lx.next() switch { case isWhitespace(r): return lexSkip(lx, lexValue) case isDigit(r): lx.backup() // avoid an extra state and use the same as above return lexNumberOrDateStart } switch r { case arrayStart: lx.ignore() lx.emit(itemArray) return lexArrayValue case inlineTableStart: lx.ignore() lx.emit(itemInlineTableStart) return lexInlineTableValue case stringStart: if lx.accept(stringStart) { if lx.accept(stringStart) { lx.ignore() // Ignore """ return lexMultilineString } lx.backup() } lx.ignore() // ignore the '"' return lexString case rawStringStart: if lx.accept(rawStringStart) { if lx.accept(rawStringStart) { lx.ignore() // Ignore """ return lexMultilineRawString } lx.backup() } lx.ignore() // ignore the "'" return lexRawString case '+', '-': return lexNumberStart case '.': // special error case, be kind to users return lx.errorf("floats must start with a digit, not '.'") } if unicode.IsLetter(r) { // Be permissive here; lexBool will give a nice error if the // user wrote something like // x = foo // (i.e. not 'true' or 'false' but is something else word-like.) lx.backup() return lexBool } return lx.errorf("expected value but found %q instead", r) } // lexArrayValue consumes one value in an array. It assumes that '[' or ',' // have already been consumed. All whitespace and newlines are ignored. func lexArrayValue(lx *lexer) stateFn { r := lx.next() switch { case isWhitespace(r) || isNL(r): return lexSkip(lx, lexArrayValue) case r == commentStart: lx.push(lexArrayValue) return lexCommentStart case r == comma: return lx.errorf("unexpected comma") case r == arrayEnd: // NOTE(caleb): The spec isn't clear about whether you can have // a trailing comma or not, so we'll allow it. return lexArrayEnd } lx.backup() lx.push(lexArrayValueEnd) return lexValue } // lexArrayValueEnd consumes everything between the end of an array value and // the next value (or the end of the array): it ignores whitespace and newlines // and expects either a ',' or a ']'. func lexArrayValueEnd(lx *lexer) stateFn { r := lx.next() switch { case isWhitespace(r) || isNL(r): return lexSkip(lx, lexArrayValueEnd) case r == commentStart: lx.push(lexArrayValueEnd) return lexCommentStart case r == comma: lx.ignore() return lexArrayValue // move on to the next value case r == arrayEnd: return lexArrayEnd } return lx.errorf( "expected a comma or array terminator %q, but got %q instead", arrayEnd, r, ) } // lexArrayEnd finishes the lexing of an array. // It assumes that a ']' has just been consumed. func lexArrayEnd(lx *lexer) stateFn { lx.ignore() lx.emit(itemArrayEnd) return lx.pop() } // lexInlineTableValue consumes one key/value pair in an inline table. // It assumes that '{' or ',' have already been consumed. Whitespace is ignored. func lexInlineTableValue(lx *lexer) stateFn { r := lx.next() switch { case isWhitespace(r): return lexSkip(lx, lexInlineTableValue) case isNL(r): return lx.errorf("newlines not allowed within inline tables") case r == commentStart: lx.push(lexInlineTableValue) return lexCommentStart case r == comma: return lx.errorf("unexpected comma") case r == inlineTableEnd: return lexInlineTableEnd } lx.backup() lx.push(lexInlineTableValueEnd) return lexKeyStart } // lexInlineTableValueEnd consumes everything between the end of an inline table // key/value pair and the next pair (or the end of the table): // it ignores whitespace and expects either a ',' or a '}'. func lexInlineTableValueEnd(lx *lexer) stateFn { r := lx.next() switch { case isWhitespace(r): return lexSkip(lx, lexInlineTableValueEnd) case isNL(r): return lx.errorf("newlines not allowed within inline tables") case r == commentStart: lx.push(lexInlineTableValueEnd) return lexCommentStart case r == comma: lx.ignore() return lexInlineTableValue case r == inlineTableEnd: return lexInlineTableEnd } return lx.errorf("expected a comma or an inline table terminator %q, "+ "but got %q instead", inlineTableEnd, r) } // lexInlineTableEnd finishes the lexing of an inline table. // It assumes that a '}' has just been consumed. func lexInlineTableEnd(lx *lexer) stateFn { lx.ignore() lx.emit(itemInlineTableEnd) return lx.pop() } // lexString consumes the inner contents of a string. It assumes that the // beginning '"' has already been consumed and ignored. func lexString(lx *lexer) stateFn { r := lx.next() switch { case r == eof: return lx.errorf("unexpected EOF") case isNL(r): return lx.errorf("strings cannot contain newlines") case r == '\\': lx.push(lexString) return lexStringEscape case r == stringEnd: lx.backup() lx.emit(itemString) lx.next() lx.ignore() return lx.pop() } return lexString } // lexMultilineString consumes the inner contents of a string. It assumes that // the beginning '"""' has already been consumed and ignored. func lexMultilineString(lx *lexer) stateFn { switch lx.next() { case eof: return lx.errorf("unexpected EOF") case '\\': return lexMultilineStringEscape case stringEnd: if lx.accept(stringEnd) { if lx.accept(stringEnd) { lx.backup() lx.backup() lx.backup() lx.emit(itemMultilineString) lx.next() lx.next() lx.next() lx.ignore() return lx.pop() } lx.backup() } } return lexMultilineString } // lexRawString consumes a raw string. Nothing can be escaped in such a string. // It assumes that the beginning "'" has already been consumed and ignored. func lexRawString(lx *lexer) stateFn { r := lx.next() switch { case r == eof: return lx.errorf("unexpected EOF") case isNL(r): return lx.errorf("strings cannot contain newlines") case r == rawStringEnd: lx.backup() lx.emit(itemRawString) lx.next() lx.ignore() return lx.pop() } return lexRawString } // lexMultilineRawString consumes a raw string. Nothing can be escaped in such // a string. It assumes that the beginning "'''" has already been consumed and // ignored. func lexMultilineRawString(lx *lexer) stateFn { switch lx.next() { case eof: return lx.errorf("unexpected EOF") case rawStringEnd: if lx.accept(rawStringEnd) { if lx.accept(rawStringEnd) { lx.backup() lx.backup() lx.backup() lx.emit(itemRawMultilineString) lx.next() lx.next() lx.next() lx.ignore() return lx.pop() } lx.backup() } } return lexMultilineRawString } // lexMultilineStringEscape consumes an escaped character. It assumes that the // preceding '\\' has already been consumed. func lexMultilineStringEscape(lx *lexer) stateFn { // Handle the special case first: if isNL(lx.next()) { return lexMultilineString } lx.backup() lx.push(lexMultilineString) return lexStringEscape(lx) } func lexStringEscape(lx *lexer) stateFn { r := lx.next() switch r { case 'b': fallthrough case 't': fallthrough case 'n': fallthrough case 'f': fallthrough case 'r': fallthrough case '"': fallthrough case '\\': return lx.pop() case 'u': return lexShortUnicodeEscape case 'U': return lexLongUnicodeEscape } return lx.errorf("invalid escape character %q; only the following "+ "escape characters are allowed: "+ `\b, \t, \n, \f, \r, \", \\, \uXXXX, and \UXXXXXXXX`, r) } func lexShortUnicodeEscape(lx *lexer) stateFn { var r rune for i := 0; i < 4; i++ { r = lx.next() if !isHexadecimal(r) { return lx.errorf(`expected four hexadecimal digits after '\u', `+ "but got %q instead", lx.current()) } } return lx.pop() } func lexLongUnicodeEscape(lx *lexer) stateFn { var r rune for i := 0; i < 8; i++ { r = lx.next() if !isHexadecimal(r) { return lx.errorf(`expected eight hexadecimal digits after '\U', `+ "but got %q instead", lx.current()) } } return lx.pop() } // lexNumberOrDateStart consumes either an integer, a float, or datetime. func lexNumberOrDateStart(lx *lexer) stateFn { r := lx.next() if isDigit(r) { return lexNumberOrDate } switch r { case '_': return lexNumber case 'e', 'E': return lexFloat case '.': return lx.errorf("floats must start with a digit, not '.'") } return lx.errorf("expected a digit but got %q", r) } // lexNumberOrDate consumes either an integer, float or datetime. func lexNumberOrDate(lx *lexer) stateFn { r := lx.next() if isDigit(r) { return lexNumberOrDate } switch r { case '-': return lexDatetime case '_': return lexNumber case '.', 'e', 'E': return lexFloat } lx.backup() lx.emit(itemInteger) return lx.pop() } // lexDatetime consumes a Datetime, to a first approximation. // The parser validates that it matches one of the accepted formats. func lexDatetime(lx *lexer) stateFn { r := lx.next() if isDigit(r) { return lexDatetime } switch r { case '-', 'T', ':', '.', 'Z': return lexDatetime } lx.backup() lx.emit(itemDatetime) return lx.pop() } // lexNumberStart consumes either an integer or a float. It assumes that a sign // has already been read, but that *no* digits have been consumed. // lexNumberStart will move to the appropriate integer or float states. func lexNumberStart(lx *lexer) stateFn { // We MUST see a digit. Even floats have to start with a digit. r := lx.next() if !isDigit(r) { if r == '.' { return lx.errorf("floats must start with a digit, not '.'") } return lx.errorf("expected a digit but got %q", r) } return lexNumber } // lexNumber consumes an integer or a float after seeing the first digit. func lexNumber(lx *lexer) stateFn { r := lx.next() if isDigit(r) { return lexNumber } switch r { case '_': return lexNumber case '.', 'e', 'E': return lexFloat } lx.backup() lx.emit(itemInteger) return lx.pop() } // lexFloat consumes the elements of a float. It allows any sequence of // float-like characters, so floats emitted by the lexer are only a first // approximation and must be validated by the parser. func lexFloat(lx *lexer) stateFn { r := lx.next() if isDigit(r) { return lexFloat } switch r { case '_', '.', '-', '+', 'e', 'E': return lexFloat } lx.backup() lx.emit(itemFloat) return lx.pop() } // lexBool consumes a bool string: 'true' or 'false. func lexBool(lx *lexer) stateFn { var rs []rune for { r := lx.next() if !unicode.IsLetter(r) { lx.backup() break } rs = append(rs, r) } s := string(rs) switch s { case "true", "false": lx.emit(itemBool) return lx.pop() } return lx.errorf("expected value but found %q instead", s) } // lexCommentStart begins the lexing of a comment. It will emit // itemCommentStart and consume no characters, passing control to lexComment. func lexCommentStart(lx *lexer) stateFn { lx.ignore() lx.emit(itemCommentStart) return lexComment } // lexComment lexes an entire comment. It assumes that '#' has been consumed. // It will consume *up to* the first newline character, and pass control // back to the last state on the stack. func lexComment(lx *lexer) stateFn { r := lx.peek() if isNL(r) || r == eof { lx.emit(itemText) return lx.pop() } lx.next() return lexComment } // lexSkip ignores all slurped input and moves on to the next state. func lexSkip(lx *lexer, nextState stateFn) stateFn { return func(lx *lexer) stateFn { lx.ignore() return nextState } } // isWhitespace returns true if `r` is a whitespace character according // to the spec. func isWhitespace(r rune) bool { return r == '\t' || r == ' ' } func isNL(r rune) bool { return r == '\n' || r == '\r' } func isDigit(r rune) bool { return r >= '0' && r <= '9' } func isHexadecimal(r rune) bool { return (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F') } func isBareKeyChar(r rune) bool { return (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-' } func (itype itemType) String() string { switch itype { case itemError: return "Error" case itemNIL: return "NIL" case itemEOF: return "EOF" case itemText: return "Text" case itemString, itemRawString, itemMultilineString, itemRawMultilineString: return "String" case itemBool: return "Bool" case itemInteger: return "Integer" case itemFloat: return "Float" case itemDatetime: return "DateTime" case itemTableStart: return "TableStart" case itemTableEnd: return "TableEnd" case itemKeyStart: return "KeyStart" case itemArray: return "Array" case itemArrayEnd: return "ArrayEnd" case itemCommentStart: return "CommentStart" } panic(fmt.Sprintf("BUG: Unknown type '%d'.", int(itype))) } func (item item) String() string { return fmt.Sprintf("(%s, %s)", item.typ.String(), item.val) } direnv-2.15.0/vendor/github.com/BurntSushi/toml/parse.go000066400000000000000000000364501324410474700231620ustar00rootroot00000000000000package toml import ( "fmt" "strconv" "strings" "time" "unicode" "unicode/utf8" ) type parser struct { mapping map[string]interface{} types map[string]tomlType lx *lexer // A list of keys in the order that they appear in the TOML data. ordered []Key // the full key for the current hash in scope context Key // the base key name for everything except hashes currentKey string // rough approximation of line number approxLine int // A map of 'key.group.names' to whether they were created implicitly. implicits map[string]bool } type parseError string func (pe parseError) Error() string { return string(pe) } func parse(data string) (p *parser, err error) { defer func() { if r := recover(); r != nil { var ok bool if err, ok = r.(parseError); ok { return } panic(r) } }() p = &parser{ mapping: make(map[string]interface{}), types: make(map[string]tomlType), lx: lex(data), ordered: make([]Key, 0), implicits: make(map[string]bool), } for { item := p.next() if item.typ == itemEOF { break } p.topLevel(item) } return p, nil } func (p *parser) panicf(format string, v ...interface{}) { msg := fmt.Sprintf("Near line %d (last key parsed '%s'): %s", p.approxLine, p.current(), fmt.Sprintf(format, v...)) panic(parseError(msg)) } func (p *parser) next() item { it := p.lx.nextItem() if it.typ == itemError { p.panicf("%s", it.val) } return it } func (p *parser) bug(format string, v ...interface{}) { panic(fmt.Sprintf("BUG: "+format+"\n\n", v...)) } func (p *parser) expect(typ itemType) item { it := p.next() p.assertEqual(typ, it.typ) return it } func (p *parser) assertEqual(expected, got itemType) { if expected != got { p.bug("Expected '%s' but got '%s'.", expected, got) } } func (p *parser) topLevel(item item) { switch item.typ { case itemCommentStart: p.approxLine = item.line p.expect(itemText) case itemTableStart: kg := p.next() p.approxLine = kg.line var key Key for ; kg.typ != itemTableEnd && kg.typ != itemEOF; kg = p.next() { key = append(key, p.keyString(kg)) } p.assertEqual(itemTableEnd, kg.typ) p.establishContext(key, false) p.setType("", tomlHash) p.ordered = append(p.ordered, key) case itemArrayTableStart: kg := p.next() p.approxLine = kg.line var key Key for ; kg.typ != itemArrayTableEnd && kg.typ != itemEOF; kg = p.next() { key = append(key, p.keyString(kg)) } p.assertEqual(itemArrayTableEnd, kg.typ) p.establishContext(key, true) p.setType("", tomlArrayHash) p.ordered = append(p.ordered, key) case itemKeyStart: kname := p.next() p.approxLine = kname.line p.currentKey = p.keyString(kname) val, typ := p.value(p.next()) p.setValue(p.currentKey, val) p.setType(p.currentKey, typ) p.ordered = append(p.ordered, p.context.add(p.currentKey)) p.currentKey = "" default: p.bug("Unexpected type at top level: %s", item.typ) } } // Gets a string for a key (or part of a key in a table name). func (p *parser) keyString(it item) string { switch it.typ { case itemText: return it.val case itemString, itemMultilineString, itemRawString, itemRawMultilineString: s, _ := p.value(it) return s.(string) default: p.bug("Unexpected key type: %s", it.typ) panic("unreachable") } } // value translates an expected value from the lexer into a Go value wrapped // as an empty interface. func (p *parser) value(it item) (interface{}, tomlType) { switch it.typ { case itemString: return p.replaceEscapes(it.val), p.typeOfPrimitive(it) case itemMultilineString: trimmed := stripFirstNewline(stripEscapedWhitespace(it.val)) return p.replaceEscapes(trimmed), p.typeOfPrimitive(it) case itemRawString: return it.val, p.typeOfPrimitive(it) case itemRawMultilineString: return stripFirstNewline(it.val), p.typeOfPrimitive(it) case itemBool: switch it.val { case "true": return true, p.typeOfPrimitive(it) case "false": return false, p.typeOfPrimitive(it) } p.bug("Expected boolean value, but got '%s'.", it.val) case itemInteger: if !numUnderscoresOK(it.val) { p.panicf("Invalid integer %q: underscores must be surrounded by digits", it.val) } val := strings.Replace(it.val, "_", "", -1) num, err := strconv.ParseInt(val, 10, 64) if err != nil { // Distinguish integer values. Normally, it'd be a bug if the lexer // provides an invalid integer, but it's possible that the number is // out of range of valid values (which the lexer cannot determine). // So mark the former as a bug but the latter as a legitimate user // error. if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange { p.panicf("Integer '%s' is out of the range of 64-bit "+ "signed integers.", it.val) } else { p.bug("Expected integer value, but got '%s'.", it.val) } } return num, p.typeOfPrimitive(it) case itemFloat: parts := strings.FieldsFunc(it.val, func(r rune) bool { switch r { case '.', 'e', 'E': return true } return false }) for _, part := range parts { if !numUnderscoresOK(part) { p.panicf("Invalid float %q: underscores must be "+ "surrounded by digits", it.val) } } if !numPeriodsOK(it.val) { // As a special case, numbers like '123.' or '1.e2', // which are valid as far as Go/strconv are concerned, // must be rejected because TOML says that a fractional // part consists of '.' followed by 1+ digits. p.panicf("Invalid float %q: '.' must be followed "+ "by one or more digits", it.val) } val := strings.Replace(it.val, "_", "", -1) num, err := strconv.ParseFloat(val, 64) if err != nil { if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange { p.panicf("Float '%s' is out of the range of 64-bit "+ "IEEE-754 floating-point numbers.", it.val) } else { p.panicf("Invalid float value: %q", it.val) } } return num, p.typeOfPrimitive(it) case itemDatetime: var t time.Time var ok bool var err error for _, format := range []string{ "2006-01-02T15:04:05Z07:00", "2006-01-02T15:04:05", "2006-01-02", } { t, err = time.ParseInLocation(format, it.val, time.Local) if err == nil { ok = true break } } if !ok { p.panicf("Invalid TOML Datetime: %q.", it.val) } return t, p.typeOfPrimitive(it) case itemArray: array := make([]interface{}, 0) types := make([]tomlType, 0) for it = p.next(); it.typ != itemArrayEnd; it = p.next() { if it.typ == itemCommentStart { p.expect(itemText) continue } val, typ := p.value(it) array = append(array, val) types = append(types, typ) } return array, p.typeOfArray(types) case itemInlineTableStart: var ( hash = make(map[string]interface{}) outerContext = p.context outerKey = p.currentKey ) p.context = append(p.context, p.currentKey) p.currentKey = "" for it := p.next(); it.typ != itemInlineTableEnd; it = p.next() { if it.typ != itemKeyStart { p.bug("Expected key start but instead found %q, around line %d", it.val, p.approxLine) } if it.typ == itemCommentStart { p.expect(itemText) continue } // retrieve key k := p.next() p.approxLine = k.line kname := p.keyString(k) // retrieve value p.currentKey = kname val, typ := p.value(p.next()) // make sure we keep metadata up to date p.setType(kname, typ) p.ordered = append(p.ordered, p.context.add(p.currentKey)) hash[kname] = val } p.context = outerContext p.currentKey = outerKey return hash, tomlHash } p.bug("Unexpected value type: %s", it.typ) panic("unreachable") } // numUnderscoresOK checks whether each underscore in s is surrounded by // characters that are not underscores. func numUnderscoresOK(s string) bool { accept := false for _, r := range s { if r == '_' { if !accept { return false } accept = false continue } accept = true } return accept } // numPeriodsOK checks whether every period in s is followed by a digit. func numPeriodsOK(s string) bool { period := false for _, r := range s { if period && !isDigit(r) { return false } period = r == '.' } return !period } // establishContext sets the current context of the parser, // where the context is either a hash or an array of hashes. Which one is // set depends on the value of the `array` parameter. // // Establishing the context also makes sure that the key isn't a duplicate, and // will create implicit hashes automatically. func (p *parser) establishContext(key Key, array bool) { var ok bool // Always start at the top level and drill down for our context. hashContext := p.mapping keyContext := make(Key, 0) // We only need implicit hashes for key[0:-1] for _, k := range key[0 : len(key)-1] { _, ok = hashContext[k] keyContext = append(keyContext, k) // No key? Make an implicit hash and move on. if !ok { p.addImplicit(keyContext) hashContext[k] = make(map[string]interface{}) } // If the hash context is actually an array of tables, then set // the hash context to the last element in that array. // // Otherwise, it better be a table, since this MUST be a key group (by // virtue of it not being the last element in a key). switch t := hashContext[k].(type) { case []map[string]interface{}: hashContext = t[len(t)-1] case map[string]interface{}: hashContext = t default: p.panicf("Key '%s' was already created as a hash.", keyContext) } } p.context = keyContext if array { // If this is the first element for this array, then allocate a new // list of tables for it. k := key[len(key)-1] if _, ok := hashContext[k]; !ok { hashContext[k] = make([]map[string]interface{}, 0, 5) } // Add a new table. But make sure the key hasn't already been used // for something else. if hash, ok := hashContext[k].([]map[string]interface{}); ok { hashContext[k] = append(hash, make(map[string]interface{})) } else { p.panicf("Key '%s' was already created and cannot be used as "+ "an array.", keyContext) } } else { p.setValue(key[len(key)-1], make(map[string]interface{})) } p.context = append(p.context, key[len(key)-1]) } // setValue sets the given key to the given value in the current context. // It will make sure that the key hasn't already been defined, account for // implicit key groups. func (p *parser) setValue(key string, value interface{}) { var tmpHash interface{} var ok bool hash := p.mapping keyContext := make(Key, 0) for _, k := range p.context { keyContext = append(keyContext, k) if tmpHash, ok = hash[k]; !ok { p.bug("Context for key '%s' has not been established.", keyContext) } switch t := tmpHash.(type) { case []map[string]interface{}: // The context is a table of hashes. Pick the most recent table // defined as the current hash. hash = t[len(t)-1] case map[string]interface{}: hash = t default: p.bug("Expected hash to have type 'map[string]interface{}', but "+ "it has '%T' instead.", tmpHash) } } keyContext = append(keyContext, key) if _, ok := hash[key]; ok { // Typically, if the given key has already been set, then we have // to raise an error since duplicate keys are disallowed. However, // it's possible that a key was previously defined implicitly. In this // case, it is allowed to be redefined concretely. (See the // `tests/valid/implicit-and-explicit-after.toml` test in `toml-test`.) // // But we have to make sure to stop marking it as an implicit. (So that // another redefinition provokes an error.) // // Note that since it has already been defined (as a hash), we don't // want to overwrite it. So our business is done. if p.isImplicit(keyContext) { p.removeImplicit(keyContext) return } // Otherwise, we have a concrete key trying to override a previous // key, which is *always* wrong. p.panicf("Key '%s' has already been defined.", keyContext) } hash[key] = value } // setType sets the type of a particular value at a given key. // It should be called immediately AFTER setValue. // // Note that if `key` is empty, then the type given will be applied to the // current context (which is either a table or an array of tables). func (p *parser) setType(key string, typ tomlType) { keyContext := make(Key, 0, len(p.context)+1) for _, k := range p.context { keyContext = append(keyContext, k) } if len(key) > 0 { // allow type setting for hashes keyContext = append(keyContext, key) } p.types[keyContext.String()] = typ } // addImplicit sets the given Key as having been created implicitly. func (p *parser) addImplicit(key Key) { p.implicits[key.String()] = true } // removeImplicit stops tagging the given key as having been implicitly // created. func (p *parser) removeImplicit(key Key) { p.implicits[key.String()] = false } // isImplicit returns true if the key group pointed to by the key was created // implicitly. func (p *parser) isImplicit(key Key) bool { return p.implicits[key.String()] } // current returns the full key name of the current context. func (p *parser) current() string { if len(p.currentKey) == 0 { return p.context.String() } if len(p.context) == 0 { return p.currentKey } return fmt.Sprintf("%s.%s", p.context, p.currentKey) } func stripFirstNewline(s string) string { if len(s) == 0 || s[0] != '\n' { return s } return s[1:] } func stripEscapedWhitespace(s string) string { esc := strings.Split(s, "\\\n") if len(esc) > 1 { for i := 1; i < len(esc); i++ { esc[i] = strings.TrimLeftFunc(esc[i], unicode.IsSpace) } } return strings.Join(esc, "") } func (p *parser) replaceEscapes(str string) string { var replaced []rune s := []byte(str) r := 0 for r < len(s) { if s[r] != '\\' { c, size := utf8.DecodeRune(s[r:]) r += size replaced = append(replaced, c) continue } r += 1 if r >= len(s) { p.bug("Escape sequence at end of string.") return "" } switch s[r] { default: p.bug("Expected valid escape code after \\, but got %q.", s[r]) return "" case 'b': replaced = append(replaced, rune(0x0008)) r += 1 case 't': replaced = append(replaced, rune(0x0009)) r += 1 case 'n': replaced = append(replaced, rune(0x000A)) r += 1 case 'f': replaced = append(replaced, rune(0x000C)) r += 1 case 'r': replaced = append(replaced, rune(0x000D)) r += 1 case '"': replaced = append(replaced, rune(0x0022)) r += 1 case '\\': replaced = append(replaced, rune(0x005C)) r += 1 case 'u': // At this point, we know we have a Unicode escape of the form // `uXXXX` at [r, r+5). (Because the lexer guarantees this // for us.) escaped := p.asciiEscapeToUnicode(s[r+1 : r+5]) replaced = append(replaced, escaped) r += 5 case 'U': // At this point, we know we have a Unicode escape of the form // `uXXXX` at [r, r+9). (Because the lexer guarantees this // for us.) escaped := p.asciiEscapeToUnicode(s[r+1 : r+9]) replaced = append(replaced, escaped) r += 9 } } return string(replaced) } func (p *parser) asciiEscapeToUnicode(bs []byte) rune { s := string(bs) hex, err := strconv.ParseUint(strings.ToLower(s), 16, 32) if err != nil { p.bug("Could not parse '%s' as a hexadecimal number, but the "+ "lexer claims it's OK: %s", s, err) } if !utf8.ValidRune(rune(hex)) { p.panicf("Escaped character '\\u%s' is not valid UTF-8.", s) } return rune(hex) } func isStringType(ty itemType) bool { return ty == itemString || ty == itemMultilineString || ty == itemRawString || ty == itemRawMultilineString } direnv-2.15.0/vendor/github.com/BurntSushi/toml/session.vim000066400000000000000000000000671324410474700237140ustar00rootroot00000000000000au BufWritePost *.go silent!make tags > /dev/null 2>&1 direnv-2.15.0/vendor/github.com/BurntSushi/toml/type_check.go000066400000000000000000000047021324410474700241610ustar00rootroot00000000000000package toml // tomlType represents any Go type that corresponds to a TOML type. // While the first draft of the TOML spec has a simplistic type system that // probably doesn't need this level of sophistication, we seem to be militating // toward adding real composite types. type tomlType interface { typeString() string } // typeEqual accepts any two types and returns true if they are equal. func typeEqual(t1, t2 tomlType) bool { if t1 == nil || t2 == nil { return false } return t1.typeString() == t2.typeString() } func typeIsHash(t tomlType) bool { return typeEqual(t, tomlHash) || typeEqual(t, tomlArrayHash) } type tomlBaseType string func (btype tomlBaseType) typeString() string { return string(btype) } func (btype tomlBaseType) String() string { return btype.typeString() } var ( tomlInteger tomlBaseType = "Integer" tomlFloat tomlBaseType = "Float" tomlDatetime tomlBaseType = "Datetime" tomlString tomlBaseType = "String" tomlBool tomlBaseType = "Bool" tomlArray tomlBaseType = "Array" tomlHash tomlBaseType = "Hash" tomlArrayHash tomlBaseType = "ArrayHash" ) // typeOfPrimitive returns a tomlType of any primitive value in TOML. // Primitive values are: Integer, Float, Datetime, String and Bool. // // Passing a lexer item other than the following will cause a BUG message // to occur: itemString, itemBool, itemInteger, itemFloat, itemDatetime. func (p *parser) typeOfPrimitive(lexItem item) tomlType { switch lexItem.typ { case itemInteger: return tomlInteger case itemFloat: return tomlFloat case itemDatetime: return tomlDatetime case itemString: return tomlString case itemMultilineString: return tomlString case itemRawString: return tomlString case itemRawMultilineString: return tomlString case itemBool: return tomlBool } p.bug("Cannot infer primitive type of lex item '%s'.", lexItem) panic("unreachable") } // typeOfArray returns a tomlType for an array given a list of types of its // values. // // In the current spec, if an array is homogeneous, then its type is always // "Array". If the array is not homogeneous, an error is generated. func (p *parser) typeOfArray(types []tomlType) tomlType { // Empty arrays are cool. if len(types) == 0 { return tomlArray } theType := types[0] for _, t := range types[1:] { if !typeEqual(theType, t) { p.panicf("Array contains values of type '%s' and '%s', but "+ "arrays must be homogeneous.", theType, t) } } return tomlArray } direnv-2.15.0/vendor/github.com/BurntSushi/toml/type_fields.go000066400000000000000000000145071324410474700243560ustar00rootroot00000000000000package toml // Struct field handling is adapted from code in encoding/json: // // Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the Go distribution. import ( "reflect" "sort" "sync" ) // A field represents a single field found in a struct. type field struct { name string // the name of the field (`toml` tag included) tag bool // whether field has a `toml` tag index []int // represents the depth of an anonymous field typ reflect.Type // the type of the field } // byName sorts field by name, breaking ties with depth, // then breaking ties with "name came from toml tag", then // breaking ties with index sequence. type byName []field func (x byName) Len() int { return len(x) } func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byName) Less(i, j int) bool { if x[i].name != x[j].name { return x[i].name < x[j].name } if len(x[i].index) != len(x[j].index) { return len(x[i].index) < len(x[j].index) } if x[i].tag != x[j].tag { return x[i].tag } return byIndex(x).Less(i, j) } // byIndex sorts field by index sequence. type byIndex []field func (x byIndex) Len() int { return len(x) } func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byIndex) Less(i, j int) bool { for k, xik := range x[i].index { if k >= len(x[j].index) { return false } if xik != x[j].index[k] { return xik < x[j].index[k] } } return len(x[i].index) < len(x[j].index) } // typeFields returns a list of fields that TOML should recognize for the given // type. The algorithm is breadth-first search over the set of structs to // include - the top struct and then any reachable anonymous structs. func typeFields(t reflect.Type) []field { // Anonymous fields to explore at the current level and the next. current := []field{} next := []field{{typ: t}} // Count of queued names for current level and the next. count := map[reflect.Type]int{} nextCount := map[reflect.Type]int{} // Types already visited at an earlier level. visited := map[reflect.Type]bool{} // Fields found. var fields []field for len(next) > 0 { current, next = next, current[:0] count, nextCount = nextCount, map[reflect.Type]int{} for _, f := range current { if visited[f.typ] { continue } visited[f.typ] = true // Scan f.typ for fields to include. for i := 0; i < f.typ.NumField(); i++ { sf := f.typ.Field(i) if sf.PkgPath != "" && !sf.Anonymous { // unexported continue } opts := getOptions(sf.Tag) if opts.skip { continue } index := make([]int, len(f.index)+1) copy(index, f.index) index[len(f.index)] = i ft := sf.Type if ft.Name() == "" && ft.Kind() == reflect.Ptr { // Follow pointer. ft = ft.Elem() } // Record found field and index sequence. if opts.name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { tagged := opts.name != "" name := opts.name if name == "" { name = sf.Name } fields = append(fields, field{name, tagged, index, ft}) if count[f.typ] > 1 { // If there were multiple instances, add a second, // so that the annihilation code will see a duplicate. // It only cares about the distinction between 1 or 2, // so don't bother generating any more copies. fields = append(fields, fields[len(fields)-1]) } continue } // Record new anonymous struct to explore in next round. nextCount[ft]++ if nextCount[ft] == 1 { f := field{name: ft.Name(), index: index, typ: ft} next = append(next, f) } } } } sort.Sort(byName(fields)) // Delete all fields that are hidden by the Go rules for embedded fields, // except that fields with TOML tags are promoted. // The fields are sorted in primary order of name, secondary order // of field index length. Loop over names; for each name, delete // hidden fields by choosing the one dominant field that survives. out := fields[:0] for advance, i := 0, 0; i < len(fields); i += advance { // One iteration per name. // Find the sequence of fields with the name of this first field. fi := fields[i] name := fi.name for advance = 1; i+advance < len(fields); advance++ { fj := fields[i+advance] if fj.name != name { break } } if advance == 1 { // Only one field with this name out = append(out, fi) continue } dominant, ok := dominantField(fields[i : i+advance]) if ok { out = append(out, dominant) } } fields = out sort.Sort(byIndex(fields)) return fields } // dominantField looks through the fields, all of which are known to // have the same name, to find the single field that dominates the // others using Go's embedding rules, modified by the presence of // TOML tags. If there are multiple top-level fields, the boolean // will be false: This condition is an error in Go and we skip all // the fields. func dominantField(fields []field) (field, bool) { // The fields are sorted in increasing index-length order. The winner // must therefore be one with the shortest index length. Drop all // longer entries, which is easy: just truncate the slice. length := len(fields[0].index) tagged := -1 // Index of first tagged field. for i, f := range fields { if len(f.index) > length { fields = fields[:i] break } if f.tag { if tagged >= 0 { // Multiple tagged fields at the same level: conflict. // Return no field. return field{}, false } tagged = i } } if tagged >= 0 { return fields[tagged], true } // All remaining fields have the same length. If there's more than one, // we have a conflict (two fields named "X" at the same level) and we // return no field. if len(fields) > 1 { return field{}, false } return fields[0], true } var fieldCache struct { sync.RWMutex m map[reflect.Type][]field } // cachedTypeFields is like typeFields but uses a cache to avoid repeated work. func cachedTypeFields(t reflect.Type) []field { fieldCache.RLock() f := fieldCache.m[t] fieldCache.RUnlock() if f != nil { return f } // Compute fields without lock. // Might duplicate effort but won't hold other computations back. f = typeFields(t) if f == nil { f = []field{} } fieldCache.Lock() if fieldCache.m == nil { fieldCache.m = map[reflect.Type][]field{} } fieldCache.m[t] = f fieldCache.Unlock() return f } direnv-2.15.0/vendor/github.com/direnv/000077500000000000000000000000001324410474700177175ustar00rootroot00000000000000direnv-2.15.0/vendor/github.com/direnv/go-dotenv/000077500000000000000000000000001324410474700216215ustar00rootroot00000000000000direnv-2.15.0/vendor/github.com/direnv/go-dotenv/LICENSE.md000066400000000000000000000021721324410474700232270ustar00rootroot00000000000000(The MIT License) Copyright (c) 2017 zimbatm and [contributors](https://github.com/direnv/go-dotenv/graphs/contributors) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. direnv-2.15.0/vendor/github.com/direnv/go-dotenv/README.md000066400000000000000000000012141324410474700230760ustar00rootroot00000000000000# go-dotenv Go parsing library for the dotenv format. There is no formal definition of the dotenv format but it has been introduced by https://github.com/bkeepers/dotenv which is thus canonical. This library is a port of that. This library was developed specifically for [direnv](https://direnv.net). ## Features * `k=v` format * bash `export k=v` format * yaml `k: v` format * comments ## Missing * support for variable expansion, probably needs API breakage ## Alternatives Some other good alternatives with various variations. * https://github.com/joho/godotenv * https://github.com/lazureykis/dotenv * https://github.com/subosito/gotenv direnv-2.15.0/vendor/github.com/direnv/go-dotenv/parse.go000066400000000000000000000046461324410474700232740ustar00rootroot00000000000000// Package dotenv implements the parsing of the .env format. // // There is no formal definition of the format but it has been introduced by // https://github.com/bkeepers/dotenv which is thus canonical. package dotenv import ( "fmt" "regexp" "strings" ) // LINE is the regexp matching a single line const LINE = ` \A \s* (?:|#.*| # comment line (?:export\s+)? # optional export ([\w\.]+) # key (?:\s*=\s*|:\s+?) # separator ( # optional value begin '(?:\'|[^'])*' # single quoted value | # or "(?:\"|[^"])*" # double quoted value | # or [^#\n]+ # unquoted value )? # value end \s* (?:\#.*)? # optional comment ) \z ` var linesRe = regexp.MustCompile("[\\r\\n]+") var lineRe = regexp.MustCompile( regexp.MustCompile("\\s+").ReplaceAllLiteralString( regexp.MustCompile("\\s+# .*").ReplaceAllLiteralString(LINE, ""), "")) // Parse reads a string in the .env format and returns a map of the extracted key=values. // // Ported from https://github.com/bkeepers/dotenv/blob/84f33f48107c492c3a99bd41c1059e7b4c1bb67a/lib/dotenv/parser.rb func Parse(data string) (map[string]string, error) { var dotenv = make(map[string]string) for _, line := range linesRe.Split(data, -1) { if !lineRe.MatchString(line) { return nil, fmt.Errorf("invalid line: %s", line) } match := lineRe.FindStringSubmatch(line) // commented or empty line if len(match) == 0 { continue } if len(match[1]) == 0 { continue } key := match[1] value := parseValue(match[2]) dotenv[key] = value } return dotenv, nil } // MustParse works the same as Parse but panics on error func MustParse(data string) map[string]string { env, err := Parse(data) if err != nil { panic(err) } return env } func parseValue(value string) string { if len(value) <= 1 { return value } if value[0:1] == "'" && value[len(value)-1:] == "'" { value = value[1 : len(value)-1] } else if value[0:1] == `"` && value[len(value)-1:] == `"` { value = value[1 : len(value)-1] value = expandNewLines(value) value = unescapeCharacters(value) } return value } var escRe = regexp.MustCompile("\\\\([^$])") func unescapeCharacters(value string) string { return escRe.ReplaceAllString(value, "$1") } func expandNewLines(value string) string { value = strings.Replace(value, "\\n", "\n", -1) value = strings.Replace(value, "\\r", "\r", -1) return value } direnv-2.15.0/vendor/github.com/direnv/go-dotenv/parse_test.go000066400000000000000000000067651324410474700243370ustar00rootroot00000000000000package dotenv_test import ( "testing" "github.com/direnv/go-dotenv" ) func shouldNotHaveEmptyKey(t *testing.T, env map[string]string) { if _, ok := env[""]; ok { t.Error("should not have empty key") } } // See the reference implementation: // https://github.com/bkeepers/dotenv/blob/master/lib/dotenv/environment.rb // TODO: support shell variable expansions const TEST_EXPORTED = `export OPTION_A=2 export OPTION_B='\n' # foo #export OPTION_C=3 export OPTION_D= export OPTION_E="foo" ` func TestDotEnvExported(t *testing.T) { env := dotenv.MustParse(TEST_EXPORTED) shouldNotHaveEmptyKey(t, env) if env["OPTION_A"] != "2" { t.Error("OPTION_A") } if env["OPTION_B"] != "\\n" { t.Error("OPTION_B") } if env["OPTION_C"] != "" { t.Error("OPTION_C", env["OPTION_C"]) } if v, ok := env["OPTION_D"]; !(v == "" && ok) { t.Error("OPTION_D") } if env["OPTION_E"] != "foo" { t.Error("OPTION_E") } } const TEST_PLAIN = `OPTION_A=1 OPTION_B=2 OPTION_C= 3 OPTION_D =4 OPTION_E = 5 OPTION_F= OPTION_G = ` func TestDotEnvPlain(t *testing.T) { env := dotenv.MustParse(TEST_PLAIN) shouldNotHaveEmptyKey(t, env) if env["OPTION_A"] != "1" { t.Error("OPTION_A") } if env["OPTION_B"] != "2" { t.Error("OPTION_B") } if env["OPTION_C"] != "3" { t.Error("OPTION_C") } if env["OPTION_D"] != "4" { t.Error("OPTION_D") } if env["OPTION_E"] != "5" { t.Error("OPTION_E") } if v, ok := env["OPTION_F"]; !(v == "" && ok) { t.Error("OPTION_F") } if v, ok := env["OPTION_G"]; !(v == "" && ok) { t.Error("OPTION_G") } } const TEST_SOLO_EMPTY = "SOME_VAR=" func TestSoloEmpty(t *testing.T) { env := dotenv.MustParse(TEST_SOLO_EMPTY) shouldNotHaveEmptyKey(t, env) v, ok := env["SOME_VAR"] if !ok { t.Error("SOME_VAR missing") } if v != "" { t.Error("SOME_VAR should be empty") } } const TEST_QUOTED = `OPTION_A='1' OPTION_B='2' OPTION_C='' OPTION_D='\n' OPTION_E="1" OPTION_F="2" OPTION_G="" OPTION_H="\n" #OPTION_I="3" ` func TestDotEnvQuoted(t *testing.T) { env := dotenv.MustParse(TEST_QUOTED) shouldNotHaveEmptyKey(t, env) if env["OPTION_A"] != "1" { t.Error("OPTION_A") } if env["OPTION_B"] != "2" { t.Error("OPTION_B") } if env["OPTION_C"] != "" { t.Error("OPTION_C") } if env["OPTION_D"] != "\\n" { t.Error("OPTION_D") } if env["OPTION_E"] != "1" { t.Error("OPTION_E") } if env["OPTION_F"] != "2" { t.Error("OPTION_F") } if env["OPTION_G"] != "" { t.Error("OPTION_G") } if env["OPTION_H"] != "\n" { t.Error("OPTION_H") } if env["OPTION_I"] != "" { t.Error("OPTION_I") } } const TEST_YAML = `OPTION_A: 1 OPTION_B: '2' OPTION_C: '' OPTION_D: '\n' #OPTION_E: '333' OPTION_F: ` func TestDotEnvYAML(t *testing.T) { env := dotenv.MustParse(TEST_YAML) shouldNotHaveEmptyKey(t, env) if env["OPTION_A"] != "1" { t.Error("OPTION_A") } if env["OPTION_B"] != "2" { t.Error("OPTION_B") } if env["OPTION_C"] != "" { t.Error("OPTION_C") } if env["OPTION_D"] != "\\n" { t.Error("OPTION_D") } if env["OPTION_E"] != "" { t.Error("OPTION_E") } if v, ok := env["OPTION_F"]; !(v == "" && ok) { t.Error("OPTION_F") } } func TestFailingMustParse(t *testing.T) { defer func() { r := recover() if r == nil { t.Error("should panic") } }() dotenv.MustParse("...") } const TEST_COMMENT_OVERRIDE = ` VARIABLE=value #VARIABLE=disabled_value ` func TestCommentOverride(t *testing.T) { env := dotenv.MustParse(TEST_COMMENT_OVERRIDE) shouldNotHaveEmptyKey(t, env) if env["VARIABLE"] != "value" { t.Error("VARIABLE should == value, not", env["VARIABLE"]) } } direnv-2.15.0/version.go000066400000000000000000000000471324410474700151110ustar00rootroot00000000000000package main const VERSION = "2.15.0" direnv-2.15.0/version.txt000066400000000000000000000000071324410474700153170ustar00rootroot000000000000002.15.0 direnv-2.15.0/xdg.go000066400000000000000000000010031324410474700141770ustar00rootroot00000000000000package main import ( "path/filepath" ) // Loosely // http://standards.freedesktop.org/basedir-spec/basedir-spec-0.8.html // We don't handle XDG_CONFIG_DIRS yet func XdgConfigDir(env Env, programName string) string { if env["XDG_CONFIG_HOME"] != "" { return filepath.Join(env["XDG_CONFIG_HOME"], programName) } else if env["HOME"] != "" { return filepath.Join(env["HOME"], ".config", programName) } // In theory we could also read /etc/passwd and look for the home matching the process' Uid return "" }