pax_global_header00006660000000000000000000000064142543744070014524gustar00rootroot0000000000000052 comment=23c1f925d843ef4575637602ea5278a09cb0d93c direnv-2.32.1/000077500000000000000000000000001425437440700131005ustar00rootroot00000000000000direnv-2.32.1/.github/000077500000000000000000000000001425437440700144405ustar00rootroot00000000000000direnv-2.32.1/.github/ISSUE_TEMPLATE/000077500000000000000000000000001425437440700166235ustar00rootroot00000000000000direnv-2.32.1/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000010031425437440700213070ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve title: '' labels: 'Bug' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: **Expected behavior** A clear and concise description of what you expected to happen. **Environment** - OS: [e.g. macOS Mojave, Ubuntu 18.04, ...] - Shell: [e.g. bash, zsh, ...] - Direnv version [e.g. 2.20.0] **Additional context** Add any other context about the problem here. direnv-2.32.1/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000011321425437440700223450ustar00rootroot00000000000000--- name: Feature request about: Suggest an idea for this project title: '' labels: 'Feature' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. direnv-2.32.1/.github/dependabot.yml000066400000000000000000000003171425437440700172710ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "gomod" directory: "/" schedule: interval: "weekly" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" direnv-2.32.1/.github/workflows/000077500000000000000000000000001425437440700164755ustar00rootroot00000000000000direnv-2.32.1/.github/workflows/codeql.yml000066400000000000000000000045251425437440700204750ustar00rootroot00000000000000# For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: push: branches: [ master ] pull_request: # The branches below must be a subset of the branches above branches: [ master ] jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ 'go' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support steps: - name: Checkout repository uses: actions/checkout@v3 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v2 # â„šī¸ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language #- run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 direnv-2.32.1/.github/workflows/go.yml000066400000000000000000000034551425437440700176340ustar00rootroot00000000000000name: Go on: push: branches: [ master ] pull_request: {} permissions: contents: read jobs: build: name: Build runs-on: ${{ matrix.os }} strategy: matrix: os: - macos-latest - ubuntu-latest - windows-latest steps: - name: Set up Go uses: actions/setup-go@v3.2.0 with: go-version: 1.16 id: go - name: Set up Python if: runner.os != 'Windows' uses: actions/setup-python@v4.0.0 with: python-version: "3.9" id: python - name: Check out code into the Go module directory uses: actions/checkout@v3.0.2 - name: Build env: GO111MODULE: on run: go build -v . - name: Test env: GO111MODULE: on run: go test -v ./... - name: Test Host bash # FIXME: make this work on Windows as well if: runner.os != 'Windows' env: GO111MODULE: on run: make test-stdlib test-bash - name: GitHub Actions Env Test Setup # FIXME: make this work on Windows as well if: runner.os != 'Windows' run: | cd test/scenarios/github-actions/ ../../../direnv allow ../../../direnv export gha >> "$GITHUB_ENV" - name: GitHub Actions Env Test Verification # FIXME: make this work on Windows as well if: runner.os != 'Windows' run: | [[ -z ${TEST_EXPORT_DIRENV_GITHUB_ACTIONS:-} ]] && echo "TEST_EXPORT_DIRENV_GITHUB_ACTIONS is unset or empty" >&2 && exit 1 tee TEST_EXPORT_DIRENV_GITHUB_ACTIONS.got <<<"$TEST_EXPORT_DIRENV_GITHUB_ACTIONS" echo "${GITHUB_SHA}"$'\n'"${GITHUB_RUN_ID}"$'\n'"${GITHUB_RUN_NUMBER}" | tee TEST_EXPORT_DIRENV_GITHUB_ACTIONS.want diff -u TEST_EXPORT_DIRENV_GITHUB_ACTIONS.want TEST_EXPORT_DIRENV_GITHUB_ACTIONS.got direnv-2.32.1/.github/workflows/nix.yml000066400000000000000000000013771425437440700200260ustar00rootroot00000000000000name: Nix on: push: branches: [ master ] pull_request: {} permissions: contents: read jobs: build: name: Build runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3.0.2 with: fetch-depth: 0 - uses: cachix/install-nix-action@v17 - name: Build run: nix-build # Run the more comprehensive test suite with nix because we have # access to all the build dependencies. - name: Test run: NIX_PATH=nixpkgs=$PWD/nix nix-shell --pure --run "make test" # Test that the release generation works - name: Test Dist run: NIX_PATH=nixpkgs=$PWD/nix nix-shell --pure --run "make dist" strategy: matrix: os: [ubuntu-latest, macos-latest] direnv-2.32.1/.github/workflows/release.yml000066400000000000000000000022021425437440700206340ustar00rootroot00000000000000on: push: # Sequence of patterns matched against refs/tags tags: - 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10 # TODO: also publish the dist name: Create Release permissions: contents: read jobs: build: permissions: contents: write # for actions/create-release to create a release name: Create Release runs-on: ubuntu-latest steps: - name: Set up Go 1.16 uses: actions/setup-go@v3.2.0 with: go-version: 1.16 - name: Checkout code uses: actions/checkout@v3.0.2 - name: Get release notes id: release-notes run: | go run ./script/issue-command/main.go set-output \ --name=body \ "$(go run ./script/release-changelog/main.go)" - name: Create Release id: create_release uses: actions/create-release@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: ${{ github.ref }} release_name: Release ${{ github.ref }} body: "${{ steps.release-notes.outputs.body }}" draft: true prerelease: false direnv-2.32.1/.gitignore000066400000000000000000000001521425437440700150660ustar00rootroot00000000000000*.sw? .direnv .gopath /direnv /direnv.test /dist /test/config /test/data /test/scenarios/inherited/.envrc direnv-2.32.1/.golangci.yml000066400000000000000000000003131425437440700154610ustar00rootroot00000000000000linters: presets: - bugs - unused enable: - gofmt - misspell - revive - stylecheck disable: # direnv is not a web server, context is not strictly necessary. - noctx direnv-2.32.1/CHANGELOG.md000066400000000000000000000570631425437440700147240ustar00rootroot00000000000000 2.32.1 / 2022-06-21 ================== * feat: Support custom VIRTUAL_ENV for layout_python (#876) * fix: vendor go-dotenv (#955) 2.32.0 / 2022-06-13 ================== * feat: Add gha shell for GitHub Actions (#910) * feat: Enable ppc64le builds (#947) * feat: allow conda environment names to be detected from environment.yml (#909) * feat: source_up_if_exists: A strict_env compatible version of source_up (#921) * feat: Expand ~/ in whitelist paths (#931) * feat: Add "block" and "revoke" as aliases of the "deny" command (#935) * feat: Add "permit" and "grant" as aliases of the "allow" command (#935) * fix: update go-dotenv * fix: fetchurl: store files as hex (#930) * fix: fetchurl: only store 200 responses (#944) * fix: Ensure status log messages are printed with normal color (#884) * fix: Clarify handling of .env files (#941) * fix: Update shell_elvish.go (#896) * fix: stdlib.sh: remove dependency on tput (#932) * fix: Use setenv in vim to allow non alphanumeric vars (#901) * fix: install.sh: add information about bin_path (#920) * fix: Treat `mingw*` as windows (direnv/direnv#918) (#919) * fix: man: clarify paths (#929) * fix: installation.md: Fix Fedora package link (#915) * Merge pull request #874 from direnv/refactor * chore: rc: stop using --noprofile --norc * chore: rc: prepare stdin earlier * chore: rc: install interrupt handler earlier * chore: stdlib: factor out stdlib preparation * chore: fix CI * chore: source_env: show full path (#870) * chore: Sort shells in DetectShell * chore: Enable codeql action (#938) * chore: Set permissions for GitHub actions (#937) * go: bump golang.org/x/sys for linux/loong64 support (#946) * build(deps): bump actions/checkout from 2.4.0 to 3.0.0 (#922) * build(deps): bump actions/checkout from 3.0.0 to 3.0.1 (#933) * build(deps): bump actions/checkout from 3.0.1 to 3.0.2 (#936) * build(deps): bump actions/setup-go from 2.1.5 to 3.0.0 (#923) * build(deps): bump actions/setup-go from 3.0.0 to 3.1.0 (#943) * build(deps): bump actions/setup-go from 3.1.0 to 3.2.0 (#950) * build(deps): bump cachix/install-nix-action from 16 to 17 (#925) * build(deps): bump github.com/BurntSushi/toml from 0.4.1 to 1.1.0 (#924) 2.31.0 / 2022-03-26 ================== * Don't load .env files by default (#911) * doc: `~/.config/direnv/direnvrc` is the default * doc: fix the broken link to arch linux (#892) * Re-add accidentally deleted comment line (#881) * fix version test 2.30.3 / 2022-01-05 ================== * Allow skipping `.env` autoload (#878) * stdlib: add `env_vars_required` (#872) (#872) * Test whether version.txt contains semantic version (#871) 2.30.2 / 2021-12-28 ================== * FIX: version: trim surrounding spaces (#869) * build(deps): bump actions/setup-go from 2.1.4 to 2.1.5 (#866) * move most code under internal/cmd (#865) 2.30.1 / 2021-12-24 ================== * FIX: ignore .envrc and .env if they are not files (#864) 2.30.0 / 2021-12-23 ================== * Add automatic `.env` load (#845) * Resolve symlinks during `direnv deny` (#851) * update installer for Apple Silicon (#849) * stdlib: use_flake handle no layout dir (#861) * embed stdlib.sh (#782) * embed version.txt * go mod update * make dist: remove references to Go 2.29.0 / 2021-11-28 ================== * stdlib: add use_flake function (#847) * docs(direnv.toml) Add config.toml clarification (#831) * docs(install): fix macos links (#841) * Corrects stdlib link in Ruby docs (#837) * stdlib.sh: Fix removal of temp file (#830) * install.sh: add aarch64 support * Updated conditional for zsh hook to be more forgiving (#808) * Add -r flag for matching Git branches with a regexp (#800) * Add docs about pipenv (#797) * Enable syntax hilights to the quick demo code (#752) * Fixed extra quotes for lower alpha characters (#783) * Remove noisy warning about PS1 again (#781) 2.28.0 / 2021-03-12 ================== * Merge pull request #779 from wingrunr21/go_1_16 * Build for darwin/arm64. Resolves #738 * Update to go 1.16 * test: Fix errors for elvish test (#767) * tcsh: fix variable escaping (#778) * Change DESTDIR to PREFIX in development.md (#774) * go: use the /v2 prefix (#765) * Relax README's recommendation for nix-direnv (#763) * man/direnv.1.md: add FILES section (fix #758) (#759) * Add/update fish tests (#754) * build(deps): bump golang.org/x/mod from 0.4.0 to 0.4.1 (#749) * Fix typo "avaible" in install.sh (#750) * docs: improve the use_node documentation 2.27.0 / 2021-01-01 ================== * fixed fish shell hook to work with eval (#743) * dist: remove darwin/386 * nix: update to nixpkgs@nixos-20.09 * packaging: stop vendoring the Go code (#739) * packaging: change packaging. DESTDIR -> PREFIX, fish hook (#741) 2.26.0 / 2020-12-27 ================== * updated fish hook support issue (#732) * ci: add basic windows CI (#737) * test: fix shellcheck usage in ./test/stdlib.bash * test: fix use_julia test for NixOS * remove dead code: rootDir * fix: create temp dir in current working dir for one test (#735) * Add `dotenv_if_exists` (#734) * stdlib: add watch_dir command (#697) 2.25.2 / 2020-12-12 ================== There was a generation issue in 2.25.1. This release only bumps the version to do another release. 2.25.1 / 2020-12-11 ================== * stdlib.go: re-generate (fixes #707) * README: remove old Azure badge * build(deps): bump golang.org/x/mod from 0.3.0 to 0.4.0 (#730) 2.25.0 / 2020-12-03 ================== * dist: add linux/arm64 and linux/ppc64 * Added use_nodenv to stdlib (#727) * Fix proposal for #707, broken direnv compatibility under Windows (#723) * fix: layout anaconda (#717) * Add on_git_branch command to detect whether a specific git branch is checked out (#702) 2.24.0 / 2020-11-15 ================== * direnv_load: avoid leaking DIRENV_DUMP_FILE_PATH (#715) * Add strict_env and unstrict_env (#572) * stdlib: add `use_vim` to source local vimrc (#497) * stdlib: add source_env_if_exists (#714) * Wording (#713) * build(deps): bump actions/checkout from v2.3.3 to v2.3.4 (#709) * build(deps): bump cachix/install-nix-action from v11 to v12 (#710) * Fix XDG_CACHE_HOME path (#711) * rc: make file existence check more robust (#706) 2.23.1 / 2020-10-22 ================== * fix: handle links on Mac when using `allow` (#696) * fix: use restored env in exec (#695) * stdlib: add basename and dirname from realpath (#693) * stdlib.sh: remove tabs * dist: compile all the binaries statically 2.23.0 / 2020-10-10 ================== * stdlib: add source_url function (#562) * direnv: add fetchurl command (#686) * shell: Update Elvish hook to replace deprecated `explode` (#685) 2.22.1 / 2020-10-06 ================== * Look for stdlib in DIRENV_CONFIG (#679) * stdlib: use Bash 3.0-compatible array expansion (#676) * Clarify path to direnv.toml (#678) * stdlib/use_julia: fix a bug in parameter substitution for empty or (#667) * man: update the layout_go documentation * stdlib: adds GOPATH/bin to PATH (#670) 2.22.0 / 2020-09-01 ================== * stdlib: use_julia (#666) * stdlib: semver_search (#665) * direnv-stdlib.1: add layout julia (#661) * README: spelling correction (#660) * README.md: add shadowenv to similar projects (#659) * docs: remove Snap from the installations * OSX -> macOS (#655) * Update shell_fish.go to use \X for UTF encoding (#584) * Change XDG_CONFIG_DIR to XDG_CONFIG_HOME (#641) * Streamline core algorithm of export and exec (#636) * test: add failure test-case (#637) 2.21.3 / 2020-05-08 ================== * Replace `direnv expand_path` with pure bash (#631) * Fix #594 - write error to fd 3 on Windows (#634) * Make direnv hook output work on Windows (#632) * Update hook.md to remove ">" typo in Fish instructions (#624) * stdlib: `layout go` adds layout dir to GOPATH (#622) * direnv-stdlib.1: add layout php (#619) * stdlib: add PATH_rm [ ...] (#615) * Error handling tuples (#610) * Merge pull request #607 from punitagrawal/master * test: elvish: Fix evaluation function * stdlib.sh: Re-write grep pattern to avoid shell escape * man: Escape '.' at the beginning of line to remove manpage warning * stdlib: fix direnv_config_dir usage (#601) * direnv version: improve error message (#599) * README: fix NixOS link in installation.md (#589) * stdlib: add direnv_apply_dump (#587) * Simplify direnv_load and make it work even when the command crashes. (#568) * docs: fix fish installation instruction * test: test for utf-8 compatibility * config: add [global] section * config: add strict_env option * config: fix warn_timeout parsing (#582) * Github action for releases * config: fix the configuration file selection * stdlib: fix shellcheck warnings 2.21.2 / 2020-01-28 ================== Making things stable again. * stdlib: revert the `set -euo pipefail` change. It was causing too many issues for users. * direnv allow: fix the allow migration by also creating the parent target directory. 2.21.1 / 2020-01-26 ================== Fix release * stdlib: fix unused variable in `use node` * stdlib: fix unused variable in `source_up` * test: add stdlib test skeleton * add dist release utility 2.21.0 / 2020-01-25 ================== This is a massive release! ## Highlights You can now hit Ctrl-C during a long reload in bash and zsh and it will not loop anymore. Commands that use `direnv_load` won't fail when there is an output to stdout anymore (eg: `use_nix`). Direnv now also loads files from `.config/direnv/lib/*.sh`. This is intended to be used by third-party tools to augment direnv with their own stdlib functions. The `.envrc` is now loaded with `set -euo pipefail`. This will more likely expose issues with existing `.envrc` files. ## docs * Update README.md (#536) * Add link to asdf-direnv. (#535) * docs: fix invalid link (#533) * adds experimental curl based installer (#539) ## commands * change where the allow files are being stored * direnv status: also show the config * direnv exec: improve the error message * warn if PS1 is being exported * handle SIGINT during export in bash * export: display the full RC path instead of a relative one * direnv exec: the DIR argument is always required (#493) ## build * ci: use GitHub Actions instead of Azure Pipelines * staticcheck (#543) * use go modules * make: handle when /dev/stderr doesn't exist (#491) * site: use jekyll to render the website * Pin nixpkgs to current NixOS 19.09 channel (#526) ## shells * fix elvish hook * Use `fish_preexec` hook instead of `fish_prompt` (#512) * Use `fish_postexec` to make sure direnv hook executed 'after' the directory has changed when using `cd`. * improve zsh hook (#514) ## config.toml * rename the configuration from config.toml to direnv.toml (#498) * add warn_timeout option. DIRENV_WARN_TIMEOUT is now deprecated. ## stdlib * `direnv_load` can now handle stdout outputs * stdlib: add layout_julia * Handle failing pipenv on empty file and avoid an extra pipenv execution (#510) * fix `source_env` behaviour when the file doesn't exists (#487) * `watch_file` can now watch multiple files in a single invocation (#524) * `layout_python`: prefer venv over virtualenv. Do not export VIRUAL_ENV if $python_version is unavailable or a virtual environment does not exist/can't be created * Adds layout_pyenv (#505) * Fix `source_up` docs to explain that search starts in parent directory (#518) * fix `path_add` to not leak local variables * `layout_pyenv`: support multiple python versions (#525) * Add a `direnv_version ` command to check the direnv version. * `dotenv`: handle undefined variables * source files from `.config/direnv/lib/*.sh` * stdlib: set `-euo pipefail` 2.20.1 / 2019-03-31 ================== * ci: try to fix releases 2.20.0 / 2019-03-31 ================== * CHANGE: Use source instead of eval on fish hook * DOC: Remove duplicate build badge (#465) * DOC: add note about auth (#463) * DOC: change nixos link (#460) * FIX: Corrects reverse patching when using exec cmd. (#466) * FIX: Perform stricter search for existing Anaconda environments (#462) * FIX: arity mismatch for elvish (#482) * FIX: avoid reloading on each prompt after error (#468) * FIX: improve bash hook handlign of empty PROMPT_COMMAND (#473) * FIX: improved the tests for bash, zsh, fish and tcsh (#469) * MISC: migrated from Travis CI to Azure Pipelines (#484) 2.19.2 / 2019-02-09 ================== * FIX: file_times: check Stat and Lstat (#457) 2.19.1 / 2019-01-31 ================== * FIX: watched files now handle symlinks properly. Thanks @grahamc! #452 2.19.0 / 2019-01-11 ================== * NEW: add support for .env variable expansion. Thanks to @hakamadare! 2.18.2 / 2018-11-23 ================== * make: generate direnv.exe on windows (#417) 2.18.1 / 2018-11-22 ================== * travis: fix the release process 2.18.0 / 2018-11-22 ================== A lot of changes! * stdlib: add DIRENV_IN_ENVRC (#414) * Fix typo in readme. (#412) * Merge pull request #407 from zimbatm/direnv-dump-shell * direnv dump can now dump to arbitrary shells * add a new "gzenv" shell * move gzenv into new package * shell: introduce a dump capability * cleanup the shells * Add alias '--version' to version command. Closes #377. (#404) * Correctes spelling of openSUSE (#403) * testing: elvish 0.12 is released now (#402) * Merge pull request #397 from zimbatm/readme-packaging-status * README: add packaging status badge * README: remove equinox installation * direnv show_dump: new command to debug encoded env (#395) * Document possibility to unset vars (#392) * stdlib: fix typo * go dep: update Gopkg.lock * make: don't make shfmt a dependency * Avoid to add unnecessary trailing semicolon character (#384) * add asdf to the list of known projects * stdlib.go: re-generate * Add PHP layout to stdlib (#346) * make: fix formatting * README: add build status badge * Overhaul the build system (#375) * stdlib, layout_pipenv: handle `$PIPENV_PIPFILE` (#371) * README: improve the source build instructions 2.17.0 / 2018-06-17 ================== * CHANGE: hook expands the direnv path. Ensures that direnv can be executed even if the PATH is changed #369. * CHANGE: stdlib: direnv_load: disallow watching in child Allows the `use nix --pure` scenario in #368 * README: add OpenSuSE to the list of distros * Revert "use_nix: unset IN_NIX_SHELL" 2.16.0 / 2018-05-09 ================== * NEW: add support for elvish (#356) * NEW: config: allow to disable stdin on eval (#351) * DOC: Add the usage of source_up to the README (#347) * FIX: default.nix: fix compilation 2.15.2 / 2018-02-25 ================== * FIX: lintian warnings (#340) * FIX: release process (#342) 2.15.1 / 2018-02-24 ================== * FIX: support for go 1.10 (#339) 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.32.1/CNAME000066400000000000000000000000131425437440700136400ustar00rootroot00000000000000direnv.net direnv-2.32.1/GNUmakefile000066400000000000000000000104141425437440700151520ustar00rootroot00000000000000############################################################################ # Variables ############################################################################ # Set this to change the target installation path PREFIX = /usr/local BINDIR = ${PREFIX}/bin SHAREDIR = ${PREFIX}/share MANDIR = ${SHAREDIR}/man DISTDIR ?= dist # filename of the executable exe = direnv$(shell go env GOEXE) # Override the go executable GO = go # BASH_PATH can also be passed to hard-code the path to bash at build time SHELL = bash ############################################################################ # Common ############################################################################ .PHONY: all all: build man export GO111MODULE=on ############################################################################ # Build ############################################################################ .PHONY: build build: direnv .PHONY: clean clean: rm -rf \ .gopath \ direnv GO_LDFLAGS = 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 ifneq ($(strip $(GO_LDFLAGS)),) GO_BUILD_FLAGS = -ldflags '$(GO_LDFLAGS)' endif direnv: *.go $(GO) build $(GO_BUILD_FLAGS) -o $(exe) ############################################################################ # Format all the things ############################################################################ .PHONY: fmt fmt-go fmt-sh fmt: fmt-go fmt-sh fmt-go: $(GO) fmt fmt-sh: @command -v shfmt >/dev/null || (echo "Could not format stdlib.sh because shfmt is missing. Run: go get -u mvdan.cc/sh/cmd/shfmt"; false) shfmt -i 2 -w stdlib.sh ############################################################################ # Documentation ############################################################################ man_md = $(wildcard man/*.md) roffs = $(man_md:.md=) .PHONY: man man: $(roffs) %.1: %.1.md @command -v go-md2man >/dev/null || (echo "Could not generate man page because go-md2man is missing. Run: go get -u github.com/cpuguy83/go-md2man/v2"; false) go-md2man -in $< -out $@ ############################################################################ # Testing ############################################################################ tests = \ test-shellcheck \ test-stdlib \ test-go \ test-go-lint \ test-go-fmt \ test-bash \ test-elvish \ test-fish \ test-tcsh \ test-zsh .PHONY: $(tests) test: build $(tests) @echo @echo SUCCESS! test-shellcheck: shellcheck stdlib.sh shellcheck ./test/stdlib.bash test-stdlib: build ./test/stdlib.bash test-go: $(GO) test -v ./... test-go-lint: golangci-lint run test-bash: bash ./test/direnv-test.bash # Needs elvish 0.12+ test-elvish: elvish ./test/direnv-test.elv test-fish: fish ./test/direnv-test.fish test-tcsh: tcsh -e ./test/direnv-test.tcsh test-zsh: zsh ./test/direnv-test.zsh ############################################################################ # Installation ############################################################################ .PHONY: install install: all install -d $(DESTDIR)$(BINDIR) install $(exe) $(DESTDIR)$(BINDIR) install -d $(DESTDIR)$(MANDIR)/man1 cp -R man/*.1 $(DESTDIR)$(MANDIR)/man1 install -d $(DESTDIR)$(SHAREDIR)/fish/vendor_conf.d echo "$(BINDIR)/direnv hook fish | source" > $(DESTDIR)$(SHAREDIR)/fish/vendor_conf.d/direnv.fish .PHONY: dist dist: @command -v gox >/dev/null || (echo "Could not generate dist because gox is missing. Run: go get -u github.com/mitchellh/gox"; false) CGO_ENABLED=0 GOFLAGS="-trimpath" \ gox -output "$(DISTDIR)/direnv.{{.OS}}-{{.Arch}}" \ -osarch darwin/amd64 \ -osarch darwin/arm64 \ -osarch freebsd/386 \ -osarch freebsd/amd64 \ -osarch freebsd/arm \ -osarch linux/386 \ -osarch linux/amd64 \ -osarch linux/arm \ -osarch linux/arm64 \ -osarch linux/mips \ -osarch linux/mips64 \ -osarch linux/mips64le \ -osarch linux/mipsle \ -osarch linux/ppc64 \ -osarch linux/ppc64le \ -osarch linux/s390x \ -osarch netbsd/386 \ -osarch netbsd/amd64 \ -osarch netbsd/arm \ -osarch openbsd/386 \ -osarch openbsd/amd64 \ -osarch windows/386 \ -osarch windows/amd64 \ && true direnv-2.32.1/LICENSE000066400000000000000000000020711425437440700141050ustar00rootroot00000000000000MIT License Copyright (c) 2019 zimbatm and 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.32.1/README.md000066400000000000000000000156611425437440700143700ustar00rootroot00000000000000direnv -- unclutter your .profile ================================= [![Built with Nix](https://builtwithnix.org/badge.svg)](https://builtwithnix.org) [![Packaging status](https://repology.org/badge/tiny-repos/direnv.svg)](https://repology.org/project/direnv/versions) [![latest packaged version(s)](https://repology.org/badge/latest-versions/direnv.svg)](https://repology.org/project/direnv/versions) [![Support room on Matrix](https://img.shields.io/matrix/direnv:numtide.com.svg?label=%23direnv%3Anumtide.com&logo=matrix&server_fqdn=matrix.numtide.com)](https://matrix.to/#/#direnv:numtide.com) `direnv` is an extension for your shell. It augments existing shells with a new feature that can load and unload environment variables depending on the current directory. ## Use cases * Load 12factor apps environment variables * Create per-project isolated development environments * Load secrets for deployment ## How it works Before each prompt, direnv checks for the existence of a `.envrc` file (and [optionally](man/direnv.toml.1.md#load_dotenv) a `.env` 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. It supports hooks for all the common shells like bash, zsh, tcsh and fish. This allows project-specific environment variables without cluttering the `~/.profile` file. 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. ## Getting Started ### Prerequisites * Unix-like operating system (macOS, Linux, ...) * A supported shell (bash, zsh, tcsh, fish, elvish) ### Basic Installation 1. direnv is packaged in most distributions already. See [the installation documentation](docs/installation.md) for details. 2. [hook direnv into your shell](docs/hook.md). Now restart your shell. ### Quick demo To follow along in your shell once direnv is installed. ```shell # Create a new folder for demo purposes. $ mkdir ~/my-project $ cd ~/my-project # Show that the FOO environment variable is not loaded. $ echo ${FOO-nope} nope # Create a new .envrc. This file is bash code that is going to be loaded by # direnv. $ echo export FOO=foo > .envrc .envrc is not allowed # The security mechanism didn't allow to load the .envrc. Since we trust it, # let's allow its execution. $ direnv allow . direnv: reloading direnv: loading .envrc direnv export: +FOO # Show that the FOO environment variable is loaded. $ echo ${FOO-nope} foo # Exit the project $ cd .. direnv: unloading # And now FOO is unset again $ echo ${FOO-nope} nope ``` ### 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](man/direnv-stdlib.1.md). It's also possible to create your own extensions by creating a bash file at `~/.config/direnv/direnvrc` or `~/.config/direnv/lib/*.sh`. This file is loaded before your `.envrc` and thus allows you to make your own extensions to direnv. Note that this functionality is not supported in `.env` files. If the coexistence of both is needed, one can use `.envrc` for leveraging stdlib and append `dotenv` at the end of it to instruct direnv to also read the `.env` file next. ## Docs * [Install direnv](docs/installation.md) * [Hook into your shell](docs/hook.md) * [Develop for direnv](docs/development.md) * [Manage your rubies with direnv and ruby-install](docs/ruby.md) * [Community Wiki](https://github.com/direnv/direnv/wiki) Make sure to take a look at the wiki! It contains all sorts of useful information such as common recipes, editor integration, tips-and-tricks. ### Man pages * [direnv(1) man page](man/direnv.1.md) * [direnv-stdlib(1) man page](man/direnv-stdlib.1.md) * [direnv.toml(1) man page](man/direnv.toml.1.md) ### FAQ Based on GitHub issues interactions, 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. 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 `~/.config/direnv/direnvrc`. This file is loaded and it's content made available to any `.envrc` file. 3. direnv is not loading the `.envrc` into the current shell. It's creating a new bash sub-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. ## Contributing Bug reports, contributions and forks are welcome. All bugs or other forms of discussion happen on http://github.com/direnv/direnv/issues . Or drop by on [Matrix](https://matrix.to/#/#direnv:numtide.com) to have a chat. If you ask a question make sure to stay around as not everyone is active all day. ## Complementary projects Here is a list of projects you might want to look into if you are using direnv. * [starship](https://starship.rs/) - A cross-shell prompt. * [Projects for Nix integration](https://github.com/direnv/direnv/wiki/Nix) - choose from one of a variety of projects offering improvements over Direnv's built-in `use_nix` implementation. ## Related projects Here is a list of other projects found in the same design space. Feel free to submit new ones. * [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). * [asdf](https://github.com/asdf-vm/asdf) - a pure bash solution that has a plugin system. The [asdf-direnv](https://github.com/asdf-community/asdf-direnv) plugin allows using asdf managed tools with direnv. * [ondir](https://github.com/alecthomas/ondir) - OnDir is a small program to automate tasks specific to certain directories * [shadowenv](https://shopify.github.io/shadowenv/) - uses an s-expression format to define environment changes that should be executed ## COPYRIGHT [MIT licence](LICENSE) - Copyright (C) 2019 @zimbatm and [contributors](https://github.com/direnv/direnv/graphs/contributors) direnv-2.32.1/_config.yml000066400000000000000000000011241425437440700152250ustar00rootroot00000000000000theme: jekyll-theme-primer title: direnv description: "unclutter your .profile" url: "https://direnv.net" exclude: - test # see https://github.com/github/pages-gem/blob/754a725e4766d4329bb1dd0e07c638a045ad2c04/lib/github-pages/plugins.rb#L6-L42 plugins: - jemoji - jekyll-avatar - jekyll-default-layout - jekyll-feed - jekyll-mentions - jekyll-readme-index - jekyll-sitemap markdown: CommonMarkGhPages # see https://github.com/gjtorikian/commonmarker#parse-options commonmark: options: - FOOTNOTES - SMART extensions: - autolink - strikethrough - table direnv-2.32.1/default.nix000066400000000000000000000014641425437440700152510ustar00rootroot00000000000000{ pkgs ? import ./nix { } }: let inherit (pkgs) bash buildGoModule lib stdenv ; in buildGoModule rec { name = "direnv-${version}"; version = lib.fileContents ./version.txt; subPackages = [ "." ]; vendorSha256 = "sha256-u/LukIOYRudFYOrrlZTMtDAlM3+WjoSBiueR7aySSVU="; src = builtins.fetchGit ./.; # FIXME: find out why there is a Go reference lingering allowGoReference = true; # we have no bash at the moment for windows makeFlags = lib.optional (!stdenv.hostPlatform.isWindows) [ "BASH_PATH=${bash}/bin/bash" ]; installPhase = '' make install PREFIX=$out ''; meta = { description = "A shell extension that manages your environment"; homepage = https://direnv.net; license = lib.licenses.mit; maintainers = [ lib.maintainers.zimbatm ]; }; } direnv-2.32.1/docs/000077500000000000000000000000001425437440700140305ustar00rootroot00000000000000direnv-2.32.1/docs/development.md000066400000000000000000000006021425437440700166720ustar00rootroot00000000000000# Development Setup a go environment https://golang.org/doc/install > go >= 1.16 is required Clone the project: $ git clone git@github.com:direnv/direnv.git Build by just typing make: $ cd direnv $ make Test the projects: $ make test To install to /usr/local: $ make install Or to a different location like `~/.local`: $ make install PREFIX=~/.local direnv-2.32.1/docs/hook.md000066400000000000000000000025721425437440700153200ustar00rootroot00000000000000# Setup For direnv to work properly it needs to be hooked into the shell. Each shell has its own extension mechanism. Once the hook is configured, restart your shell for direnv to be activated. ## 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 direnv hook fish | source ``` Fish supports 3 modes you can set with with the global environment variable `direnv_fish_mode`: ```fish set -g direnv_fish_mode eval_on_arrow # trigger direnv at prompt, and on every arrow-based directory change (default) set -g direnv_fish_mode eval_after_arrow # trigger direnv at prompt, and only after arrow-based directory changes before executing command set -g direnv_fish_mode disable_arrow # trigger direnv at prompt only, this is similar functionality to the original behavior ``` ## TCSH Add the following line at the end of the `~/.cshrc` file: ```sh eval `direnv hook tcsh` ``` ## Elvish (0.12+) Run: ``` $> direnv hook elvish > ~/.elvish/lib/direnv.elv ``` and add the following line to your `~/.elvish/rc.elv` file: ``` use direnv ``` direnv-2.32.1/docs/installation.md000066400000000000000000000030371425437440700170560ustar00rootroot00000000000000# Installation The installation has two parts. 1. Install the package or binary, which is presented in this document 2. [hook into your shell](hook.md). ## From system packages direnv is packaged for a variety of systems: * [Fedora](https://src.fedoraproject.org/rpms/direnv) * [Arch Linux](https://archlinux.org/packages/community/x86_64/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?query=direnv) * [macOS Homebrew](https://formulae.brew.sh/formula/direnv#default) * [openSUSE](https://build.opensuse.org/package/show/openSUSE%3AFactory/direnv) * [MacPorts](https://ports.macports.org/port/direnv/) * [Ubuntu](https://packages.ubuntu.com/search?keywords=direnv&searchon=names&suite=all§ion=all) * [GNU Guix](https://www.gnu.org/software/guix/) See also: [![Packaging status](https://repology.org/badge/vertical-allrepos/direnv.svg)](https://repology.org/metapackage/direnv) ## From binary builds To install binary builds you can run this bash installer: ```sh curl -sfL https://direnv.net/install.sh | bash ``` 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`. ## Compile from source See the [Development](development.md) page. # Next step [hook installation](hook.md) direnv-2.32.1/docs/ruby.md000066400000000000000000000067611425437440700153450ustar00rootroot00000000000000# 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](/man/direnv-stdlib.1.md) and expand it a bit in the `~/.config/direnv/direnvrc` file. Add this to the `~/.config/direnv/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](/man/direnv-stdlib.1.md) 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.32.1/go.mod000066400000000000000000000003321425437440700142040ustar00rootroot00000000000000module github.com/direnv/direnv/v2 go 1.16 require ( github.com/BurntSushi/toml v1.1.0 github.com/mattn/go-isatty v0.0.14 golang.org/x/mod v0.5.1 golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect ) direnv-2.32.1/go.sum000066400000000000000000000036701425437440700142410ustar00rootroot00000000000000github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I= github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/mod v0.5.1 h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a h1:dGzPydgVsqGcTRVwiLJ1jVbufYwmzD3LfVPLKsKg+0k= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= direnv-2.32.1/gzenv/000077500000000000000000000000001425437440700142315ustar00rootroot00000000000000direnv-2.32.1/gzenv/gzenv.go000066400000000000000000000027051425437440700157150ustar00rootroot00000000000000// the gzenv format: json+gzip+base64 // a quickly designed format to export the whole environment back into itself package gzenv import ( "bytes" "compress/zlib" "encoding/base64" "encoding/json" "fmt" "io" "strings" ) // Marshal encodes the object into the gzenv format func Marshal(obj interface{}) string { jsonData, err := json.Marshal(obj) if err != nil { panic(fmt.Errorf("marshal(): %w", err)) } zlibData := bytes.NewBuffer([]byte{}) w := zlib.NewWriter(zlibData) // we assume the zlib writer would never fail _, _ = w.Write(jsonData) w.Close() base64Data := base64.URLEncoding.EncodeToString(zlibData.Bytes()) return base64Data } // Unmarshal restores the gzenv format back into a Go object func Unmarshal(gzenv string, obj interface{}) error { gzenv = strings.TrimSpace(gzenv) data, err := base64.URLEncoding.DecodeString(gzenv) if err != nil { return fmt.Errorf("unmarshal() base64 decoding: %w", err) } zlibReader := bytes.NewReader(data) w, err := zlib.NewReader(zlibReader) if err != nil { return fmt.Errorf("unmarshal() zlib opening: %w", err) } envData := bytes.NewBuffer([]byte{}) // G110: Potential DoS vulnerability via decompression bomb (gosec) // #nosec _, err = io.Copy(envData, w) if err != nil { return fmt.Errorf("unmarshal() zlib decoding: %w", err) } w.Close() err = json.Unmarshal(envData.Bytes(), &obj) if err != nil { return fmt.Errorf("unmarshal() json parsing: %w", err) } return nil } direnv-2.32.1/install.sh000077500000000000000000000043341425437440700151110ustar00rootroot00000000000000#!/usr/bin/env bash # # A good old bash | curl script for direnv. # set -euo pipefail { # Prevent execution if this script was only partially downloaded log() { echo "[installer] $*" >&2 } die() { log "$@" exit 1 } at_exit() { ret=$? if [[ $ret -gt 0 ]]; then log "the script failed with error $ret.\n" \ "\n" \ "To report installation errors, submit an issue to\n" \ " https://github.com/direnv/direnv/issues/new/choose" fi exit "$ret" } trap at_exit EXIT kernel=$(uname -s | tr "[:upper:]" "[:lower:]") case "${kernel}" in mingw*) kernel=windows ;; esac case "$(uname -m)" in x86_64) machine=amd64 ;; i686 | i386) machine=386 ;; aarch64 | arm64) machine=arm64 ;; *) die "Machine $(uname -m) not supported by the installer.\n" \ "Go to https://direnv for alternate installation methods." ;; esac log "kernel=$kernel machine=$machine" : "${use_sudo:=}" : "${bin_path:=}" if [[ -z "$bin_path" ]]; then log "bin_path is not set, you can set bin_path to specify the installation path" log "e.g. export bin_path=/path/to/installation before installing" log "looking for a writeable path from PATH environment variable" for path in $(echo "$PATH" | tr ':' '\n'); do if [[ -w $path ]]; then bin_path=$path break fi done fi if [[ -z "$bin_path" ]]; then die "did not find a writeable path in $PATH" fi echo "bin_path=$bin_path" log "looking for a download URL" download_url=$( curl -fL https://api.github.com/repos/direnv/direnv/releases/latest \ | grep browser_download_url \ | cut -d '"' -f 4 \ | grep "direnv.$kernel.$machine" ) echo "download_url=$download_url" log "downloading" curl -o "$bin_path/direnv" -fL "$download_url" chmod +x "$bin_path/direnv" cat < 1 { if rcPath, err = filepath.Abs(args[1]); err != nil { return err } if rcPath, err = filepath.EvalSymlinks(rcPath); err != nil { return err } } else { if rcPath, err = os.Getwd(); err != nil { return err } } if _, err = os.Stat(config.AllowDir()); os.IsNotExist(err) { oldAllowDir := filepath.Join(config.ConfDir, "allow") if _, err = os.Stat(oldAllowDir); err == nil { fmt.Println(migrationMessage) fmt.Printf("moving %s to %s\n", oldAllowDir, config.AllowDir()) if err = os.MkdirAll(filepath.Dir(config.AllowDir()), 0755); err != nil { return err } if err = os.Rename(oldAllowDir, config.AllowDir()); err != nil { return err } fmt.Printf("creating a symlink back from %s to %s for back-compat.\n", config.AllowDir(), oldAllowDir) if err = os.Symlink(config.AllowDir(), oldAllowDir); err != nil { return err } fmt.Println("") fmt.Println("All done, have a nice day!") } } rc, err := FindRC(rcPath, config) if err != nil { return err } else if rc == nil { if config.LoadDotenv { return fmt.Errorf(".envrc or .env file not found") } return fmt.Errorf(".envrc file not found") } return rc.Allow() } direnv-2.32.1/internal/cmd/cmd_apply_dump.go000066400000000000000000000015501425437440700210040ustar00rootroot00000000000000package cmd import ( "fmt" "io/ioutil" ) // CmdApplyDump is `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, Action: actionSimple(cmdApplyDumpAction), } func cmdApplyDumpAction(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.32.1/internal/cmd/cmd_current.go000066400000000000000000000011571425437440700203170ustar00rootroot00000000000000package cmd import ( "errors" ) // CmdCurrent is `direnv current` var CmdCurrent = &Cmd{ Name: "current", Desc: "Reports whether direnv's view of a file is current (or stale)", Args: []string{"PATH"}, Private: true, Action: actionSimple(cmdCurrentAction), } func cmdCurrentAction(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 { err = watches.Unmarshal(watchString) if err != nil { return } } err = watches.CheckOne(path) return } direnv-2.32.1/internal/cmd/cmd_deny.go000066400000000000000000000016101425437440700175660ustar00rootroot00000000000000package cmd import ( "fmt" "os" "path/filepath" ) // CmdDeny is `direnv deny [PATH_TO_RC]` var CmdDeny = &Cmd{ Name: "block", Desc: "Revokes the authorization of a given .envrc or .env file.", Args: []string{"[PATH_TO_RC]"}, Aliases: []string{"deny", "revoke"}, Action: actionWithConfig(cmdDenyAction), } func cmdDenyAction(env Env, args []string, config *Config) (err error) { var rcPath string if len(args) > 1 { if rcPath, err = filepath.Abs(args[1]); err != nil { return err } if rcPath, err = filepath.EvalSymlinks(rcPath); err != nil { return err } } else { if rcPath, err = os.Getwd(); err != nil { return } } rc, err := FindRC(rcPath, config) if err != nil { return err } else if rc == nil { if config.LoadDotenv { return fmt.Errorf(".envrc or .env file not found") } return fmt.Errorf(".envrc file not found") } return rc.Deny() } direnv-2.32.1/internal/cmd/cmd_dotenv.go000066400000000000000000000020121425437440700201230ustar00rootroot00000000000000package cmd import ( "fmt" "io/ioutil" "github.com/direnv/direnv/v2/pkg/dotenv" ) // CmdDotEnv is `direnv dotenv [SHELL [PATH_TO_DOTENV]]` // Transforms a .env file to evaluatable `export KEY=PAIR` statements. // // See: https://github.com/bkeepers/dotenv and // https://github.com/ddollar/foreman var CmdDotEnv = &Cmd{ Name: "dotenv", Desc: "Transforms a .env file to evaluatable `export KEY=PAIR` statements", Args: []string{"[SHELL]", "[PATH_TO_DOTENV]"}, Private: true, Action: actionSimple(cmdDotEnvAction), } func cmdDotEnvAction(env Env, args []string) (err error) { var shell Shell var newenv Env 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 } newenv, err = dotenv.Parse(string(data)) if err != nil { return err } str := newenv.ToShell(shell) fmt.Println(str) return } direnv-2.32.1/internal/cmd/cmd_dump.go000066400000000000000000000016511425437440700176010ustar00rootroot00000000000000package cmd import ( "fmt" "os" "strconv" ) // CmdDump is `direnv dump` var CmdDump = &Cmd{ Name: "dump", Desc: "Used to export the inner bash state at the end of execution", Args: []string{"[SHELL]", "[FILE]"}, Private: true, Action: actionSimple(cmdDumpAction), } func cmdDumpAction(env Env, args []string) (err error) { target := "gzenv" w := os.Stdout if len(args) > 1 { target = args[1] } var filePath string if len(args) > 2 { filePath = args[2] } else { filePath = os.Getenv(DIRENV_DUMP_FILE_PATH) } if filePath != "" { if num, err := strconv.Atoi(filePath); err == nil { w = os.NewFile(uintptr(num), filePath) } else { w, err = os.OpenFile(filePath, os.O_WRONLY, 0666) if err != nil { return err } } } shell := DetectShell(target) if shell == nil { return fmt.Errorf("unknown target shell '%s'", target) } _, err = fmt.Fprintln(w, shell.Dump(env)) return } direnv-2.32.1/internal/cmd/cmd_edit.go000066400000000000000000000043341425437440700175620ustar00rootroot00000000000000package cmd import ( "fmt" "log" "os" "os/exec" "path/filepath" "strings" ) // CmdEdit is `direnv edit [PATH_TO_RC]` var CmdEdit = &Cmd{ Name: "edit", Desc: `Opens PATH_TO_RC or the current .envrc or .env into an $EDITOR and allow the file to be loaded afterwards.`, Args: []string{"[PATH_TO_RC]"}, Action: actionWithConfig(cmdEditAction), } func cmdEditAction(env Env, args []string, config *Config) (err error) { var rcPath string var times *FileTimes var foundRC *RC defer log.SetPrefix(log.Prefix()) log.SetPrefix(log.Prefix() + "cmd_edit: ") foundRC, err = config.FindRC() if err != nil { return err } 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 or .env not found. Use `direnv edit .` to create a new .envrc in the current directory") } rcPath = foundRC.path } editor := env["EDITOR"] if editor == "" { logError("$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)) // G204: Subprocess launched with function call as argument or cmd arguments // #nosec 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, err = FindRC(rcPath, config) logDebug("foundRC: %#v", foundRC) logDebug("times: %#v", times) if times != nil { logDebug("times.Check(): %#v", times.Check()) } if err == nil && foundRC != nil && (times == nil || times.Check() != nil) { err = foundRC.Allow() } return } // Utils // Editors contains a list of known editors and how to start them. 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.32.1/internal/cmd/cmd_exec.go000066400000000000000000000027251425437440700175630ustar00rootroot00000000000000package cmd import ( "fmt" "os" "path/filepath" "syscall" ) // CmdExec is `direnv exec DIR ...` var CmdExec = &Cmd{ Name: "exec", Desc: "Executes a command after loading the first .envrc or .env found in DIR", Args: []string{"DIR", "COMMAND", "[...ARGS]"}, Action: actionWithConfig(cmdExecAction), } func cmdExecAction(env Env, args []string, config *Config) (err error) { var ( newEnv Env previousEnv 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:] } // Restore pristine environment if needed if previousEnv, err = config.Revert(env); err != nil { return } previousEnv.CleanContext() // Load the rc if toLoad := findEnvUp(rcPath, config.LoadDotenv); toLoad != "" { if newEnv, err = config.EnvFromRC(toLoad, previousEnv); err != nil { return } } else { newEnv = previousEnv } var commandPath string commandPath, err = lookPath(command, newEnv["PATH"]) if err != nil { err = fmt.Errorf("command '%s' not found on PATH '%s'", command, newEnv["PATH"]) return } // #nosec G204 err = syscall.Exec(commandPath, args, newEnv.ToGoEnv()) return } direnv-2.32.1/internal/cmd/cmd_export.go000066400000000000000000000056211425437440700201560ustar00rootroot00000000000000package cmd import ( "fmt" "log" "sort" "strings" ) // CmdExport is `direnv export $0` var CmdExport = &Cmd{ Name: "export", Desc: "loads an .envrc or .env and prints the diff in terms of exports", Args: []string{"SHELL"}, Private: true, Action: cmdWithWarnTimeout(actionWithConfig(exportCommand)), } func exportCommand(currentEnv Env, args []string, config *Config) (err error) { defer log.SetPrefix(log.Prefix()) log.SetPrefix(log.Prefix() + "export:") logDebug("start") var target string if len(args) > 1 { target = args[1] } shell := DetectShell(target) if shell == nil { return fmt.Errorf("unknown target shell '%s'", target) } logDebug("loading RCs") loadedRC := config.LoadedRC() toLoad := findEnvUp(config.WorkDir, config.LoadDotenv) if loadedRC == nil && toLoad == "" { return } logDebug("updating RC") log.SetPrefix(log.Prefix() + "update:") logDebug("Determining action:") logDebug("toLoad: %#v", toLoad) logDebug("loadedRC: %#v", loadedRC) switch { case toLoad == "": logDebug("no RC found, unloading") case loadedRC == nil: logDebug("no RC (implies no DIRENV_DIFF),loading") case loadedRC.path != toLoad: logDebug("new RC, loading") case loadedRC.times.Check() != nil: logDebug("file changed, reloading") default: logDebug("no update needed") return } var previousEnv, newEnv Env if previousEnv, err = config.Revert(currentEnv); err != nil { err = fmt.Errorf("Revert() failed: %w", err) logDebug("err: %v", err) return } if toLoad == "" { logStatus(currentEnv, "unloading") newEnv = previousEnv.Copy() newEnv.CleanContext() } else { newEnv, err = config.EnvFromRC(toLoad, previousEnv) if err != nil { logDebug("err: %v", err) // If loading fails, fall through and deliver a diff anyway, // but still exit with an error. This prevents retrying on // every prompt. } if newEnv == nil { // unless of course, the error was in hashing and timestamp loading, // in which case we have to abort because we don't know what timestamp // to put in the diff! return } } if out := diffStatus(previousEnv.Diff(newEnv)); out != "" { logStatus(currentEnv, "export %s", out) } diffString := currentEnv.Diff(newEnv).ToShell(shell) logDebug("env diff %s", diffString) fmt.Print(diffString) return } // Return a string of +/-/~ indicators of an environment diff func diffStatus(oldDiff *EnvDiff) string { 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) return strings.Join(out, " ") } return "" } func direnvKey(key string) bool { return strings.HasPrefix(key, "DIRENV_") } direnv-2.32.1/internal/cmd/cmd_fetchurl.go000066400000000000000000000070421425437440700204500ustar00rootroot00000000000000package cmd import ( "fmt" "io" "io/ioutil" "net/http" "os" "path/filepath" "strings" "github.com/direnv/direnv/v2/pkg/sri" "github.com/mattn/go-isatty" ) // CmdFetchURL is `direnv fetchurl []` var CmdFetchURL = &Cmd{ Name: "fetchurl", Desc: "Fetches a given URL into direnv's CAS", Args: []string{"", "[]"}, Action: actionWithConfig(cmdFetchURL), } func cmdFetchURL(env Env, args []string, config *Config) (err error) { if len(args) < 2 { return fmt.Errorf("missing URL argument") } var ( algo sri.Algo = sri.SHA256 url string integrityHash string ) casDir := casDir(config) isTTY := isatty.IsTerminal(os.Stdout.Fd()) url = args[1] // Validate the SRI hash if it exists if len(args) > 2 { // Support Base64 where '/' have been replaced by '_' integrityHash = strings.ReplaceAll(args[2], "_", "/") hash, err := sri.Parse(integrityHash) if err != nil { return err } // Shortcut if the cache already has the file casFile := casPath(casDir, hash) if fileExists(casFile) { fmt.Println(casFile) return nil } } // Create the CAS directory if it doesn't exist if err = os.MkdirAll(casDir, os.FileMode(0755)); err != nil { return err } // Create a temporary file to copy the content into, before the CAS file // location can be calculated. tmpfile, err := ioutil.TempFile(casDir, "tmp") if err != nil { return err } defer os.Remove(tmpfile.Name()) // clean up // Get the URL // G107: Potential HTTP request made with variable url // #nosec resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() // Abort if we don't get a 200 back if resp.StatusCode != 200 { return fmt.Errorf("expected status code 200 but got %d", resp.StatusCode) } // While copying the content into the temporary location, also calculate the // SRI hash. w := sri.NewWriter(tmpfile, algo) if _, err = io.Copy(w, resp.Body); err != nil { return err } // Here is the new SRI hash calculatedHash := w.Sum() // Make the file read-only and executable for later if err = os.Chmod(tmpfile.Name(), os.FileMode(0500)); err != nil { return err } // Validate if a comparison hash was given if integrityHash != "" && calculatedHash.String() != integrityHash { return fmt.Errorf("hash mismatch. Expected '%s' but got '%s'", integrityHash, calculatedHash.String()) } // Derive the CAS file location from the SRI hash casFile := casPath(casDir, calculatedHash) // Put the file into the CAS store if it's not already there if !fileExists(casFile) { // Move the temporary file to the CAS location. if err = os.Rename(tmpfile.Name(), casFile); err != nil { return err } } if integrityHash == "" { if isTTY { // Print an example for terminal users fmt.Printf(`Found hash: %s Invoke fetchurl again with the hash as an argument to get the disk location: direnv fetchurl "%s" "%s" #=> %s `, calculatedHash, url, calculatedHash.String(), casFile) } else { // Only print the hash in scripting mode. Add one extra hurdle on // purpose to use fetchurl without the SRI hash. _, err = fmt.Println(calculatedHash) } } else { // Print the location to the CAS file _, err = fmt.Println(casFile) } return err } func casDir(c *Config) string { return filepath.Join(c.CacheDir, "cas") } // casPath returns filesystem path for SRI hashes func casPath(dir string, integrityHash *sri.Hash) string { // Use Hex encoding for the filesystem to avoid issues sriFile := integrityHash.Hex() return filepath.Join(dir, sriFile) } direnv-2.32.1/internal/cmd/cmd_help.go000066400000000000000000000016621425437440700175660ustar00rootroot00000000000000package cmd import ( "fmt" "strings" ) // CmdHelp is `direnv help` var CmdHelp = &Cmd{ Name: "help", Desc: "shows this help", Args: []string{"[SHOW_PRIVATE]"}, Aliases: []string{"--help"}, Action: actionSimple(func(env Env, args []string) (err error) { var showPrivate = len(args) > 1 fmt.Printf(`direnv v%s Usage: direnv COMMAND [...ARGS] Available commands ------------------ `, version) for _, cmd := range CmdList { var opts string if len(cmd.Args) > 0 { opts = " " + strings.Join(cmd.Args, " ") } if cmd.Private { if showPrivate { fmt.Printf("*%s%s:\n %s\n", cmd.Name, opts, cmd.Desc) } } else { fmt.Printf("%s%s:\n", cmd.Name, opts) for _, alias := range cmd.Aliases { if alias[0:1] != "-" { fmt.Printf("%s%s:\n", alias, opts) } } fmt.Printf(" %s\n", cmd.Desc) } } if showPrivate { fmt.Println("* = private commands") } return }), } direnv-2.32.1/internal/cmd/cmd_hook.go000066400000000000000000000020701425437440700175700ustar00rootroot00000000000000package cmd import ( "fmt" "os" "strings" "text/template" ) // HookContext are the variables available during hook template evaluation type HookContext struct { // SelfPath is the unescaped absolute path to direnv SelfPath string } // CmdHook is `direnv hook $0` var CmdHook = &Cmd{ Name: "hook", Desc: "Used to setup the shell hook", Args: []string{"SHELL"}, Action: actionSimple(cmdHookAction), } func cmdHookAction(env Env, args []string) (err error) { var target string if len(args) > 1 { target = args[1] } selfPath, err := os.Executable() if err != nil { return err } // Convert Windows path if needed selfPath = strings.Replace(selfPath, "\\", "/", -1) ctx := HookContext{selfPath} shell := DetectShell(target) if shell == nil { return fmt.Errorf("unknown target shell '%s'", target) } hookStr, err := shell.Hook() if err != nil { return err } hookTemplate, err := template.New("hook").Parse(hookStr) if err != nil { return err } err = hookTemplate.Execute(os.Stdout, ctx) if err != nil { return err } return } direnv-2.32.1/internal/cmd/cmd_prune.go000066400000000000000000000017501425437440700177650ustar00rootroot00000000000000package cmd import ( "io/ioutil" "os" "path" "strings" ) // CmdPrune is `direnv prune` var CmdPrune = &Cmd{ Name: "prune", Desc: "removes old allowed files", Action: actionWithConfig(cmdPruneAction), } func cmdPruneAction(env Env, args []string, config *Config) (err error) { var dir *os.File var fi os.FileInfo var dirList []string var envrc []byte allowed := config.AllowDir() if dir, err = os.Open(allowed); err != nil { return err } defer dir.Close() if dirList, err = dir.Readdirnames(0); err != nil { return err } for _, hash := range dirList { 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 } envrcStr := strings.TrimSpace(string(envrc)) // skip old files, w/o path inside if envrcStr == "" { continue } if !fileExists(envrcStr) { _ = os.Remove(filename) } } } return nil } direnv-2.32.1/internal/cmd/cmd_reload.go000066400000000000000000000006011425437440700200740ustar00rootroot00000000000000package cmd import ( "fmt" ) // CmdReload is `direnv reload` var CmdReload = &Cmd{ Name: "reload", Desc: "triggers an env reload", Action: actionWithConfig(func(env Env, args []string, config *Config) error { foundRC, err := config.FindRC() if err != nil { return err } if foundRC == nil { return fmt.Errorf(".envrc not found") } return foundRC.Touch() }), } direnv-2.32.1/internal/cmd/cmd_show_dump.go000066400000000000000000000011671425437440700206430ustar00rootroot00000000000000package cmd import ( "encoding/json" "fmt" "os" "github.com/direnv/direnv/v2/gzenv" ) // CmdShowDump is `direnv show_dump` var CmdShowDump = &Cmd{ Name: "show_dump", Desc: "Show the data inside of a dump for debugging purposes", Args: []string{"DUMP"}, Private: true, Action: actionSimple(cmdShowDumpAction), } func cmdShowDumpAction(env Env, args []string) (err error) { if len(args) < 2 { return fmt.Errorf("missing DUMP argument") } var f interface{} err = gzenv.Unmarshal(args[1], &f) if err != nil { return err } e := json.NewEncoder(os.Stdout) e.SetIndent("", " ") return e.Encode(f) } direnv-2.32.1/internal/cmd/cmd_status.go000066400000000000000000000023731425437440700201610ustar00rootroot00000000000000package cmd import ( "fmt" "path/filepath" ) // CmdStatus is `direnv status` var CmdStatus = &Cmd{ Name: "status", Desc: "prints some debug status information", Action: actionWithConfig(func(env Env, args []string, config *Config) error { fmt.Println("direnv exec path", config.SelfPath) fmt.Println("DIRENV_CONFIG", config.ConfDir) fmt.Println("bash_path", config.BashPath) fmt.Println("disable_stdin", config.DisableStdin) fmt.Println("warn_timeout", config.WarnTimeout) fmt.Println("whitelist.prefix", config.WhitelistPrefix) fmt.Println("whitelist.exact", config.WhitelistExact) loadedRC := config.LoadedRC() foundRC, err := config.FindRC() if err != nil { return err } if loadedRC != nil { formatRC("Loaded", loadedRC) } else { fmt.Println("No .envrc or .env loaded") } if foundRC != nil { formatRC("Found", foundRC) } else { fmt.Println("No .envrc or .env found") } return nil }), } 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.32.1/internal/cmd/cmd_stdlib.go000066400000000000000000000004631425437440700201150ustar00rootroot00000000000000package cmd import ( "fmt" ) // CmdStdlib is `direnv stdlib` var CmdStdlib = &Cmd{ Name: "stdlib", Desc: "Displays the stdlib available in the .envrc execution context", Action: actionWithConfig(func(env Env, args []string, config *Config) error { fmt.Println(getStdlib(config)) return nil }), } direnv-2.32.1/internal/cmd/cmd_version.go000066400000000000000000000016451425437440700203240ustar00rootroot00000000000000package cmd import ( "fmt" "strings" "golang.org/x/mod/semver" ) // CmdVersion is `direnv version` var CmdVersion = &Cmd{ Name: "version", Desc: "prints the version or checks that direnv is older than VERSION_AT_LEAST.", Args: []string{"[VERSION_AT_LEAST]"}, Aliases: []string{"--version"}, Action: actionSimple(func(env Env, args []string) error { semVersion := ensureVPrefixed(version) if len(args) > 1 { atLeast := ensureVPrefixed(args[1]) if !semver.IsValid(atLeast) { return fmt.Errorf("%s is not a valid semver version", atLeast) } cmp := semver.Compare(semVersion, atLeast) if cmp < 0 { return fmt.Errorf("current version %s is older than the desired version %s", semVersion, atLeast) } } else { fmt.Println(version) } return nil }), } func ensureVPrefixed(version string) string { if !strings.HasPrefix(version, "v") { return "v" + version } return version } direnv-2.32.1/internal/cmd/cmd_version_test.go000066400000000000000000000006631425437440700213620ustar00rootroot00000000000000package cmd import ( "golang.org/x/mod/semver" "io/ioutil" "strings" "testing" ) func TestVersionDotTxt(t *testing.T) { bs, err := ioutil.ReadFile("../../version.txt") if err != nil { t.Fatalf("failed to read ../../version.txt: %v", err) } version = strings.TrimSpace(string(bs)) if !semver.IsValid(ensureVPrefixed(string(version))) { t.Fatalf(`version.txt does not contain a valid semantic version: %q`, version) } } direnv-2.32.1/internal/cmd/cmd_watch.go000066400000000000000000000020041425437440700177330ustar00rootroot00000000000000package cmd import ( "fmt" "os" ) // CmdWatch is `direnv watch SHELL [PATH...]` var CmdWatch = &Cmd{ Name: "watch", Desc: "Adds a path to the list that direnv watches for changes", Args: []string{"SHELL", "PATH..."}, Private: true, Action: actionSimple(cmdWatchAction), } func cmdWatchAction(env Env, args []string) (err error) { var shellName string if len(args) < 2 { return fmt.Errorf("a path is required to add to the list of watches") } if len(args) >= 2 { shellName = args[1] } else { shellName = "bash" } shell := DetectShell(shellName) if shell == nil { return fmt.Errorf("unknown target shell '%s'", shellName) } watches := NewFileTimes() watchString, ok := env[DIRENV_WATCHES] if ok { err = watches.Unmarshal(watchString) if err != nil { return } } for _, arg := range args[2:] { err = watches.Update(arg) if err != nil { return } } e := make(ShellExport) e.Add(DIRENV_WATCHES, watches.Marshal()) os.Stdout.WriteString(shell.Export(e)) return } direnv-2.32.1/internal/cmd/cmd_watch_dir.go000066400000000000000000000024261425437440700206010ustar00rootroot00000000000000package cmd import ( "fmt" "os" "path/filepath" ) // CmdWatchDir is `direnv watch-dir SHELL PATH` var CmdWatchDir = &Cmd{ Name: "watch-dir", Desc: "Recursively adds a directory to the list that direnv watches for changes", Args: []string{"SHELL", "DIR"}, Private: true, Action: actionSimple(watchDirCommand), } func watchDirCommand(env Env, args []string) (err error) { if len(args) < 3 { return fmt.Errorf("a directory is required to add to the list of watches") } shellName := args[1] dir := args[2] shell := DetectShell(shellName) if shell == nil { return fmt.Errorf("unknown target shell '%s'", shellName) } if _, err := os.Stat(dir); os.IsNotExist(err) { return fmt.Errorf("dir '%s' does not exist", dir) } watches := NewFileTimes() watchString, ok := env[DIRENV_WATCHES] if ok { err = watches.Unmarshal(watchString) if err != nil { return err } } err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } return watches.NewTime(path, info.ModTime().Unix(), true) }) if err != nil { return fmt.Errorf("failed to recursively watch dir '%s': %w", dir, err) } e := make(ShellExport) e.Add(DIRENV_WATCHES, watches.Marshal()) os.Stdout.WriteString(shell.Export(e)) return } direnv-2.32.1/internal/cmd/cmd_watch_list.go000066400000000000000000000030331425437440700207710ustar00rootroot00000000000000package cmd import ( "bufio" "errors" "fmt" "io" "os" "strconv" "strings" ) // CmdWatchList is `direnv watch-list` var CmdWatchList = &Cmd{ Name: "watch-list", Desc: "Pipe pairs of `mtime path` to stdin to build a list of files to watch.", Args: []string{"[SHELL]"}, Private: true, Action: actionSimple(watchListCommand), } func watchListCommand(env Env, args []string) (err error) { var shellName string if len(args) >= 2 { shellName = args[1] } else { shellName = "bash" } shell := DetectShell(shellName) if shell == nil { return fmt.Errorf("unknown target shell '%s'", shellName) } watches := NewFileTimes() watchString, ok := env[DIRENV_WATCHES] if ok { err = watches.Unmarshal(watchString) if err != nil { return err } } // Read `mtime path` lines from stdin reader := bufio.NewReader(os.Stdin) i := 1 for { line, err := reader.ReadString('\n') if err == nil { elems := strings.SplitN(line, " ", 2) if len(elems) != 2 { return fmt.Errorf("line %d: expected to contain two elements", i) } mtime, err := strconv.Atoi(elems[0]) if err != nil { return fmt.Errorf("line %d: %w", i, err) } path := elems[1][:len(elems[1])-1] // add to watches err = watches.NewTime(path, int64(mtime), true) if err != nil { return err } } else if errors.Is(err, io.EOF) { break } else { return fmt.Errorf("line %d: %w", i, err) } i++ } e := make(ShellExport) e.Add(DIRENV_WATCHES, watches.Marshal()) os.Stdout.WriteString(shell.Export(e)) return } direnv-2.32.1/internal/cmd/commands.go000066400000000000000000000045111425437440700176100ustar00rootroot00000000000000package cmd import ( "fmt" "strings" "time" ) type actionSimple func(env Env, args []string) error func (fn actionSimple) Call(env Env, args []string, config *Config) error { return fn(env, args) } type actionWithConfig func(env Env, args []string, config *Config) error func (fn actionWithConfig) Call(env Env, args []string, config *Config) error { var err error if config == nil { config, err = LoadConfig(env) if err != nil { return err } } return fn(env, args, config) } type action interface { Call(env Env, args []string, config *Config) error } // Cmd represents a direnv sub-command type Cmd struct { Name string Desc string Args []string Aliases []string Private bool Action action } // CmdList contains the list of all direnv sub-commands var CmdList []*Cmd func init() { CmdList = []*Cmd{ CmdAllow, CmdApplyDump, CmdShowDump, CmdDeny, CmdDotEnv, CmdDump, CmdEdit, CmdExec, CmdExport, CmdFetchURL, CmdHelp, CmdHook, CmdPrune, CmdReload, CmdStatus, CmdStdlib, CmdVersion, CmdWatch, CmdWatchDir, CmdWatchList, CmdCurrent, } } func cmdWithWarnTimeout(fn action) action { return actionWithConfig(func(env Env, args []string, config *Config) (err error) { done := make(chan bool, 1) go func() { select { case <-done: return case <-time.After(config.WarnTimeout): logError("(%v) is taking a while to execute. Use CTRL-C to give up.", args) } }() err = fn.Call(env, args, config) done <- true return err }) } // CommandsDispatch is called by the main() function to dispatch to a sub-command 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) } return command.Action.Call(env, commandArgs, nil) } direnv-2.32.1/internal/cmd/config.go000066400000000000000000000150001425437440700172470ustar00rootroot00000000000000package cmd import ( "fmt" "os" "os/exec" "path/filepath" "strings" "time" toml "github.com/BurntSushi/toml" "github.com/direnv/direnv/v2/xdg" ) // Config represents the direnv configuration and state. type Config struct { Env Env WorkDir string // Current directory ConfDir string CacheDir string DataDir string SelfPath string BashPath string RCFile string TomlPath string DisableStdin bool StrictEnv bool LoadDotenv bool WarnTimeout time.Duration WhitelistPrefix []string WhitelistExact map[string]bool } type tomlDuration struct { time.Duration } func (d *tomlDuration) UnmarshalText(text []byte) error { var err error d.Duration, err = time.ParseDuration(string(text)) return err } type tomlConfig struct { *tomlGlobal // For backward-compatibility Global *tomlGlobal `toml:"global"` Whitelist tomlWhitelist `toml:"whitelist"` } type tomlGlobal struct { BashPath string `toml:"bash_path"` DisableStdin bool `toml:"disable_stdin"` StrictEnv bool `toml:"strict_env"` SkipDotenv bool `toml:"skip_dotenv"` // deprecated, use load_dotenv LoadDotenv bool `toml:"load_dotenv"` WarnTimeout tomlDuration `toml:"warn_timeout"` } type tomlWhitelist struct { Prefix []string Exact []string } // Expand a path string prefixed with ~/ to the current user's home directory. // Example: if current user is user1 with home directory in /home/user1, then // ~/project -> /home/user1/project // It's useful to allow paths with ~/, so that direnv.toml can be reused via // dotfiles repos across systems with different standard home paths // (compare Linux /home and macOS /Users). func expandTildePath(path string) (pathExpanded string) { pathExpanded = path if strings.HasPrefix(path, "~/") { if homedir, homedirErr := os.UserHomeDir(); homedirErr == nil { pathExpanded = filepath.Join(homedir, path[2:]) } } return pathExpanded } // LoadConfig opens up the direnv configuration from the Env. func LoadConfig(env Env) (config *Config, err error) { config = &Config{ Env: env, } config.ConfDir = env[DIRENV_CONFIG] if config.ConfDir == "" { config.ConfDir = xdg.ConfigDir(env, "direnv") } if config.ConfDir == "" { err = fmt.Errorf("couldn't find a configuration directory for direnv") return } var exePath string if exePath, err = os.Executable(); err != nil { err = fmt.Errorf("LoadConfig() os.Executable() failed: %w", err) return } // Fix for mingsys exePath = strings.Replace(exePath, "\\", "/", -1) config.SelfPath = exePath if config.WorkDir, err = os.Getwd(); err != nil { err = fmt.Errorf("LoadConfig() Getwd failed: %w", err) return } config.RCFile = env[DIRENV_FILE] config.WhitelistPrefix = make([]string, 0) config.WhitelistExact = make(map[string]bool) // Load the TOML config config.TomlPath = filepath.Join(config.ConfDir, "direnv.toml") if _, statErr := os.Stat(config.TomlPath); statErr != nil { config.TomlPath = filepath.Join(config.ConfDir, "config.toml") if _, statErr := os.Stat(config.TomlPath); statErr != nil { config.TomlPath = "" } } if config.TomlPath != "" { // Declare global once and then share it between the top-level and Global // keys. The goal here is to let the decoder fill global regardless of if // the values are in the [global] section or not. The reason we do that is // to keep backward-compatibility with the old top-level notation. var global tomlGlobal tomlConf := tomlConfig{ tomlGlobal: &global, Global: &global, } if _, err = toml.DecodeFile(config.TomlPath, &tomlConf); err != nil { err = fmt.Errorf("LoadConfig() failed to parse %s: %w", config.TomlPath, err) return } for _, path := range tomlConf.Whitelist.Prefix { config.WhitelistPrefix = append(config.WhitelistPrefix, expandTildePath(path)) } for _, path := range tomlConf.Whitelist.Exact { if !(strings.HasSuffix(path, "/.envrc") || strings.HasSuffix(path, "/.env")) { path = filepath.Join(path, ".envrc") } config.WhitelistExact[expandTildePath(path)] = true } if tomlConf.SkipDotenv { logError("skip_dotenv has been inverted to load_dotenv.") } config.BashPath = tomlConf.BashPath config.DisableStdin = tomlConf.DisableStdin config.LoadDotenv = tomlConf.LoadDotenv config.StrictEnv = tomlConf.StrictEnv config.WarnTimeout = tomlConf.WarnTimeout.Duration } if config.WarnTimeout == 0 { timeout, err := time.ParseDuration(env.Fetch("DIRENV_WARN_TIMEOUT", "5s")) if err != nil { logError("invalid DIRENV_WARN_TIMEOUT: " + err.Error()) timeout = 5 * time.Second } config.WarnTimeout = timeout } 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: %w", err) return } } if config.CacheDir == "" { config.CacheDir = xdg.CacheDir(env, "direnv") } if config.CacheDir == "" { err = fmt.Errorf("couldn't find a cache directory for direnv") return } if config.DataDir == "" { config.DataDir = xdg.DataDir(env, "direnv") } if config.DataDir == "" { err = fmt.Errorf("couldn't find a data directory for direnv") return } return } // AllowDir is the folder where all the "allow" files are stored. func (config *Config) AllowDir() string { return filepath.Join(config.DataDir, "allow") } // LoadedRC returns a RC file if any has been loaded func (config *Config) LoadedRC() *RC { if config.RCFile == "" { logDebug("RCFile is blank - loadedRC is nil") return nil } rcPath := config.RCFile timesString := config.Env[DIRENV_WATCHES] return RCFromEnv(rcPath, timesString, config) } // EnvFromRC loads an RC from a specified path and returns the new environment func (config *Config) EnvFromRC(path string, previousEnv Env) (Env, error) { rc, err := RCFromPath(path, config) if err != nil { return nil, err } return rc.Load(previousEnv) } // FindRC looks for a RC file in the config environment func (config *Config) FindRC() (*RC, error) { return FindRC(config.WorkDir, config) } // Revert undoes the recorded changes (if any) to the supplied environment, // returning a new environment func (config *Config) Revert(env Env) (Env, error) { if config.Env[DIRENV_DIFF] == "" { return env.Copy(), nil } diff, err := LoadEnvDiff(config.Env[DIRENV_DIFF]) if err == nil { return diff.Reverse().Patch(env), nil } return nil, err } direnv-2.32.1/internal/cmd/const.go000066400000000000000000000004651425437440700171410ustar00rootroot00000000000000package cmd //nolint const ( DIRENV_CONFIG = "DIRENV_CONFIG" DIRENV_BASH = "DIRENV_BASH" DIRENV_DEBUG = "DIRENV_DEBUG" DIRENV_DIR = "DIRENV_DIR" DIRENV_FILE = "DIRENV_FILE" DIRENV_WATCHES = "DIRENV_WATCHES" DIRENV_DIFF = "DIRENV_DIFF" DIRENV_DUMP_FILE_PATH = "DIRENV_DUMP_FILE_PATH" ) direnv-2.32.1/internal/cmd/env.go000066400000000000000000000054131425437440700166010ustar00rootroot00000000000000package cmd import ( "encoding/json" "os" "strings" "github.com/direnv/direnv/v2/gzenv" ) // Env is a map representation of environment variables. type Env map[string]string // GetEnv turns the classic unix environment variables into a map of // key->values which is more handy to work with. // // NOTE: We don't support having two variables with the same name. // I've never seen it used in the wild but 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 } // CleanContext removes all the direnv-related environment variables. Call // this after reverting the environment, otherwise direnv will just be amnesic // about the previously-loaded environment. func (env Env) CleanContext() { delete(env, DIRENV_DIFF) delete(env, DIRENV_DIR) delete(env, DIRENV_FILE) delete(env, DIRENV_DUMP_FILE_PATH) delete(env, DIRENV_WATCHES) } // LoadEnv unmarshals the env back from a gzenv string func LoadEnv(gzenvStr string) (env Env, err error) { env = make(Env) err = gzenv.Unmarshal(gzenvStr, &env) return } // LoadEnvJSON unmarshals the env back from a JSON string func LoadEnvJSON(jsonBytes []byte) (env Env, err error) { env = make(Env) err = json.Unmarshal(jsonBytes, &env) return env, err } // Copy returns a fresh copy of the env. Because the env is a map under the // hood, we want to get a copy whenever we mutate it and want to keep the // original around. func (env Env) Copy() Env { newEnv := make(Env) for key, value := range env { newEnv[key] = value } return newEnv } // ToGoEnv should really be named ToUnixEnv. It turns the env back into a list // of "key=value" strings like returns by os.Environ(). func (env Env) ToGoEnv() []string { goEnv := make([]string, len(env)) index := 0 for key, value := range env { goEnv[index] = strings.Join([]string{key, value}, "=") index++ } return goEnv } // ToShell outputs the environment into an evaluatable string that is // understood by the target shell func (env Env) ToShell(shell Shell) string { e := make(ShellExport) for key, value := range env { e.Add(key, value) } return shell.Export(e) } // Serialize marshals the env into the gzenv format func (env Env) Serialize() string { return gzenv.Marshal(env) } // Diff returns the diff between the current env and the passed env func (env Env) Diff(other Env) *EnvDiff { return BuildEnvDiff(env, other) } // Fetch tries to get the value associated with the given 'key', or returns // the provided default if none is set. // // Note that empty environment variables are considered to be set. func (env Env) Fetch(key, def string) string { v, ok := env[key] if !ok { v = def } return v } direnv-2.32.1/internal/cmd/env_diff.go000066400000000000000000000060761425437440700175770ustar00rootroot00000000000000package cmd import ( "strings" "github.com/direnv/direnv/v2/gzenv" ) // IgnoredKeys is list of keys we don't want to deal with var IgnoredKeys = map[string]bool{ // direnv env config "DIRENV_CONFIG": true, "DIRENV_BASH": true, // should only be available inside of the .envrc or .env "DIRENV_IN_ENVRC": 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, } // EnvDiff represents the diff between two environments type EnvDiff struct { Prev map[string]string `json:"p"` Next map[string]string `json:"n"` } // NewEnvDiff is an empty constructor for EnvDiff func NewEnvDiff() *EnvDiff { return &EnvDiff{make(map[string]string), make(map[string]string)} } // BuildEnvDiff analyses the changes between 'e1' and 'e2' and builds an // EnvDiff out of it. 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 } // LoadEnvDiff unmarshalls a gzenv string back into an EnvDiff. func LoadEnvDiff(gzenvStr string) (diff *EnvDiff, err error) { diff = new(EnvDiff) err = gzenv.Unmarshal(gzenvStr, diff) return } // Any returns if the diff contains any changes. func (diff *EnvDiff) Any() bool { return len(diff.Prev) > 0 || len(diff.Next) > 0 } // ToShell applies the env diff as a set of commands that are understood by // the target `shell`. The outputted string is then meant to be evaluated in // the target shell. func (diff *EnvDiff) ToShell(shell Shell) string { e := make(ShellExport) for key := range diff.Prev { _, ok := diff.Next[key] if !ok { e.Remove(key) } } for key, value := range diff.Next { e.Add(key, value) } return shell.Export(e) } // Patch applies the diff to the given env and returns a new env with the // changes applied. func (diff *EnvDiff) Patch(env Env) (newEnv Env) { newEnv = make(Env) for k, v := range env { newEnv[k] = v } for key := range diff.Prev { delete(newEnv, key) } for key, value := range diff.Next { newEnv[key] = value } return newEnv } // Reverse flips the diff so that it applies the other way around. func (diff *EnvDiff) Reverse() *EnvDiff { return &EnvDiff{diff.Next, diff.Prev} } // Serialize marshalls the environment diff to the gzenv format. func (diff *EnvDiff) Serialize() string { return gzenv.Marshal(diff) } //// Utils // IgnoredEnv returns true if the key should be ignored in environment diffs. func IgnoredEnv(key string) bool { if strings.HasPrefix(key, "__fish") { return true } if strings.HasPrefix(key, "BASH_FUNC_") { return true } _, found := IgnoredKeys[key] return found } direnv-2.32.1/internal/cmd/env_diff_test.go000066400000000000000000000020141425437440700206220ustar00rootroot00000000000000package cmd 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.32.1/internal/cmd/env_test.go000066400000000000000000000005021425437440700176320ustar00rootroot00000000000000package cmd 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.32.1/internal/cmd/file_times.go000066400000000000000000000107001425437440700201240ustar00rootroot00000000000000package cmd import ( "fmt" "os" "path/filepath" "time" "github.com/direnv/direnv/v2/gzenv" ) // FileTime represents a single recorded file status type FileTime struct { Path string Modtime int64 Exists bool } // FileTimes represent a record of all the known files and times type FileTimes struct { list *[]FileTime } // NewFileTimes creates a new empty FileTimes func NewFileTimes() (times FileTimes) { list := make([]FileTime, 0) times.list = &list return } // Update gets the latest stats on the path and updates the record. func (times *FileTimes) Update(path string) (err error) { var modtime int64 var exists bool stat, err := getLatestStat(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 } // NewTime add the file on path, with modtime and exists flag to the list of known // files. 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 } // Check validates all the recorded file times 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 } // CheckOne compares notes between the given path and the recorded times 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)} } // Check verifies that the file is good and hasn't changed func (times FileTime) Check() (err error) { stat, err := getLatestStat(times.Path) switch { case os.IsNotExist(err): if times.Exists { logDebug("Stat Check: %s: gone", times.Path) return checkFailed{fmt.Sprintf("File %q is missing (Stat)", times.Path)} } case err != nil: logDebug("Stat Check: %s: ERR: %v", times.Path, err) return err case !times.Exists: logDebug("Check: %s: appeared", times.Path) return checkFailed{fmt.Sprintf("File %q newly created", times.Path)} case stat.ModTime().Unix() != times.Modtime: logDebug("Check: %s: stale (stat: %v, lastcheck: %v)", times.Path, stat.ModTime().Unix(), times.Modtime) return checkFailed{fmt.Sprintf("File %q has changed", times.Path)} } logDebug("Check: %s: up to date", times.Path) return nil } // Formatted shows the times in a user-friendly format. func (times *FileTime) Formatted(relDir string) string { timeBytes, err := time.Unix(times.Modtime, 0).MarshalText() if err != nil { timeBytes = []byte("<>") } path, err := filepath.Rel(relDir, times.Path) if err != nil { path = times.Path } return fmt.Sprintf("%q - %s", path, timeBytes) } // Marshal dumps the times into gzenv format func (times *FileTimes) Marshal() string { return gzenv.Marshal(*times.list) } // Unmarshal loads the watches back from gzenv func (times *FileTimes) Unmarshal(from string) error { return gzenv.Unmarshal(from, times.list) } func getLatestStat(path string) (os.FileInfo, error) { var lstatModTime int64 var statModTime int64 // Check the examine-a-symlink case first: lstat, err := os.Lstat(path) if err != nil { logDebug("getLatestStat,Lstat: %s: error: %v", path, err) return nil, err } lstatModTime = lstat.ModTime().Unix() stat, err := os.Stat(path) if err != nil { logDebug("getLatestStat,Stat: %s: error: %v (Lstat time: %v)", path, err, lstatModTime) return nil, err } statModTime = stat.ModTime().Unix() if lstatModTime > statModTime { logDebug("getLatestStat: %s: Lstat: %v, Stat: %v -> preferring Lstat", path, lstatModTime, statModTime) return lstat, nil } logDebug("getLatestStat: %s: Lstat: %v, Stat: %v -> preferring Stat", path, lstatModTime, statModTime) return stat, nil } direnv-2.32.1/internal/cmd/file_times_test.go000066400000000000000000000044231425437440700211700ustar00rootroot00000000000000package cmd 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") rtChk := NewFileTimes() _ = rtChk.Unmarshal(watches.Marshal()) compareFTs(t, watches, rtChk, "length", func(ft FileTimes) interface{} { return len(*ft.list) }) compareFTs(t, watches, rtChk, "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.32.1/internal/cmd/log.go000066400000000000000000000023151425437440700165700ustar00rootroot00000000000000package cmd import ( "fmt" "log" "os" ) const ( 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 && val == "1" { debugging = true log.SetFlags(log.Ltime) log.SetPrefix("direnv: ") } } func logError(msg string, a ...interface{}) { if noColor { logMsg(errorLogFormat, msg, a...) } else { logMsg(errorLogFormatWithColor, msg, a...) } } func logStatus(env Env, msg string, a ...interface{}) { format, ok := env["DIRENV_LOG_FORMAT"] if !ok { format = defaultLogFormat } if format != "" { logMsg(format, msg, a...) } } func logDebug(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.32.1/internal/cmd/look_path.go000066400000000000000000000016771425437440700200010ustar00rootroot00000000000000package cmd 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.32.1/internal/cmd/mod.go000066400000000000000000000011071425437440700165640ustar00rootroot00000000000000package cmd import ( "os" ) var ( bashPath string stdlib string version string ) // Main is the main entrypoint to direnv func Main(env Env, args []string, modBashPath string, modStdlib string, modVersion string) error { // We drop $PWD from caller since it can include symlinks, which will // break relative path access when finding .envrc or .env in a parent. _ = os.Unsetenv("PWD") setupLogging(env) bashPath = modBashPath stdlib = modStdlib version = modVersion err := CommandsDispatch(env, args) if err != nil { logError("error %v", err) } return err } direnv-2.32.1/internal/cmd/rc.go000066400000000000000000000144641425437440700164230ustar00rootroot00000000000000package cmd import ( "context" "crypto/sha256" "fmt" "io" "io/ioutil" "os" "os/exec" "os/signal" "path/filepath" "strings" "time" ) // RC represents the .envrc or .env file type RC struct { path string allowPath string times FileTimes config *Config } // FindRC looks for ".envrc" and ".env" files up in the file hierarchy. func FindRC(wd string, config *Config) (*RC, error) { rcPath := findEnvUp(wd, config.LoadDotenv) if rcPath == "" { return nil, nil } return RCFromPath(rcPath, config) } // RCFromPath inits the RC from a given path func RCFromPath(path string, config *Config) (*RC, error) { hash, err := fileHash(path) if err != nil { return nil, err } allowPath := filepath.Join(config.AllowDir(), hash) times := NewFileTimes() err = times.Update(path) if err != nil { return nil, err } err = times.Update(allowPath) if err != nil { return nil, err } return &RC{path, allowPath, times, config}, nil } // RCFromEnv inits the RC from the environment func RCFromEnv(path, marshalledTimes string, config *Config) *RC { times := NewFileTimes() err := times.Unmarshal(marshalledTimes) if err != nil { return nil } return &RC{path, "", times, config} } // Allow grants the RC as allowed to load func (rc *RC) Allow() (err error) { if rc.allowPath == "" { return fmt.Errorf("cannot allow empty path") } if err = os.MkdirAll(filepath.Dir(rc.allowPath), 0755); err != nil { return } if err = allow(rc.path, rc.allowPath); err != nil { return } err = rc.times.Update(rc.allowPath) return } // Deny revokes the permission of the RC file to load func (rc *RC) Deny() error { return os.Remove(rc.allowPath) } // Allowed checks if the RC file has been granted loading func (rc *RC) Allowed() bool { // happy path is if this envrc has been explicitly allowed, O(1)ish common case _, err := os.Stat(rc.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(rc.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 rc.config.WhitelistExact[path] { return true } // finally we check if any of our whitelist prefixes match for _, prefix := range rc.config.WhitelistPrefix { if strings.HasPrefix(path, prefix) { return true } } return false } // Path returns the path to the RC file func (rc *RC) Path() string { return rc.path } // Touch updates the mtime of the RC file. This is mainly used to trigger a // reload in direnv. func (rc *RC) Touch() error { return touch(rc.path) } const notAllowed = "%s is blocked. Run `direnv allow` to approve its content" // Load evaluates the RC file and returns the new Env or error. // // This functions is key to the implementation of direnv. func (rc *RC) Load(previousEnv Env) (newEnv Env, err error) { config := rc.config wd := config.WorkDir direnv := config.SelfPath newEnv = previousEnv.Copy() newEnv[DIRENV_WATCHES] = rc.times.Marshal() defer func() { // Record directory changes even if load is disallowed or fails newEnv[DIRENV_DIR] = "-" + filepath.Dir(rc.path) newEnv[DIRENV_FILE] = rc.path newEnv[DIRENV_DIFF] = previousEnv.Diff(newEnv).Serialize() }() // Abort if the file is not allowed if !rc.Allowed() { err = fmt.Errorf(notAllowed, rc.Path()) return } // Allow RC loads to be canceled with SIGINT ctx, cancel := context.WithCancel(context.Background()) c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) go func() { <-c cancel() }() // check what type of RC we're processing // use different exec method for each fn := "source_env" if filepath.Base(rc.path) == ".env" { fn = "dotenv" } // Set stdin based on the config var stdin *os.File if config.DisableStdin { stdin, err = os.Open(os.DevNull) if err != nil { return } } else { stdin = os.Stdin } prelude := "" if config.StrictEnv { prelude = "set -euo pipefail && " } arg := fmt.Sprintf( `%seval "$("%s" stdlib)" && __main__ %s "%s"`, prelude, direnv, fn, rc.Path(), ) // G204: Subprocess launched with function call as argument or cmd arguments // #nosec cmd := exec.CommandContext(ctx, config.BashPath, "-c", arg) cmd.Dir = wd cmd.Env = newEnv.ToGoEnv() cmd.Stdin = stdin cmd.Stderr = os.Stderr var out []byte if out, err = cmd.Output(); err == nil && len(out) > 0 { var newEnv2 Env newEnv2, err = LoadEnvJSON(out) if err == nil { newEnv = newEnv2 } } return } /// Utils 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 { // Some broken filesystems like SSHFS return file information on stat() but // then cannot open the file. So we use os.Open. f, err := os.Open(path) if err != nil { return false } f.Close() // Next, check that the file is a regular file. fi, err := os.Stat(path) if err != nil { return false } return fi.Mode().IsRegular() } 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() _, err = hasher.Write([]byte(path + "\n")) if err != nil { return } 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) { // G306: Expect WriteFile permissions to be 0600 or less // #nosec return ioutil.WriteFile(allowPath, []byte(path+"\n"), 0644) } func findEnvUp(searchDir string, loadDotenv bool) (path string) { if loadDotenv { return findUp(searchDir, ".envrc", ".env") } return findUp(searchDir, ".envrc") } func findUp(searchDir string, fileNames ...string) (path string) { for _, dir := range eachDir(searchDir) { for _, fileName := range fileNames { path := filepath.Join(dir, fileName) if fileExists(path) { return path } } } return "" } direnv-2.32.1/internal/cmd/rc_test.go000066400000000000000000000004531425437440700174530ustar00rootroot00000000000000package cmd import ( "runtime" "testing" ) func TestSomething(t *testing.T) { paths := eachDir("/foo/b//bar/") if len(paths) != 4 { t.Fail() } // TODO: fix me for windows if runtime.GOOS != "windows" { paths = eachDir("/") if len(paths) != 1 && paths[0] != "/" { t.Fail() } } } direnv-2.32.1/internal/cmd/shell.go000066400000000000000000000026341425437440700171220ustar00rootroot00000000000000package cmd import ( "path/filepath" ) // Shell is the interface that represents the interaction with the host shell. type Shell interface { // Hook is the string that gets evaluated into the host shell config and // setups direnv as a prompt hook. Hook() (string, error) // Export outputs the ShellExport as an evaluatable string on the host shell Export(e ShellExport) string // Dump outputs and evaluatable string that sets the env in the host shell Dump(env Env) string } // ShellExport represents environment variables to add and remove on the host // shell. type ShellExport map[string]*string // Add represents the additon of a new environment variable func (e ShellExport) Add(key, value string) { e[key] = &value } // Remove represents the removal of a given `key` environment variable. func (e ShellExport) Remove(key string) { e[key] = nil } // DetectShell returns a Shell instance from the given target. // // target is usually $0 and can also be prefixed by `-` 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 "elvish": return Elvish case "fish": return Fish case "gha": return GitHubActions case "gzenv": return GzEnv case "json": return JSON case "tcsh": return Tcsh case "vim": return Vim case "zsh": return Zsh } return nil } direnv-2.32.1/internal/cmd/shell_bash.go000066400000000000000000000063571425437440700201250ustar00rootroot00000000000000package cmd import "fmt" type bash struct{} // Bash shell instance var Bash Shell = bash{} const bashHook = ` _direnv_hook() { local previous_exit_status=$?; trap -- '' SIGINT; eval "$("{{.SelfPath}}" export bash)"; trap - SIGINT; return $previous_exit_status; }; if ! [[ "${PROMPT_COMMAND:-}" =~ _direnv_hook ]]; then PROMPT_COMMAND="_direnv_hook${PROMPT_COMMAND:+;$PROMPT_COMMAND}" fi ` func (sh bash) Hook() (string, error) { return bashHook, nil } func (sh bash) Export(e ShellExport) (out string) { for key, value := range e { if value == nil { out += sh.unset(key) } else { out += sh.export(key, *value) } } return out } func (sh bash) Dump(env Env) (out string) { for key, value := range env { out += sh.export(key, value) } return out } func (sh bash) export(key, value string) string { return "export " + sh.escape(key) + "=" + sh.escape(value) + ";" } func (sh bash) unset(key string) string { return "unset " + sh.escape(key) + ";" } func (sh bash) escape(str string) string { return BashEscape(str) } /* * Escaping */ //nolint const ( ACK = 6 TAB = 9 LF = 10 CR = 13 US = 31 SPACE = 32 AMPERSTAND = 38 SINGLE_QUOTE = 39 PLUS = 43 NINE = 57 QUESTION = 63 UPPERCASE_Z = 90 OPEN_BRACKET = 91 BACKSLASH = 92 UNDERSCORE = 95 CLOSE_BRACKET = 93 BACKTICK = 96 LOWERCASE_Z = 122 TILDA = 126 DEL = 127 ) // https://github.com/solidsnack/shell-escape/blob/master/Text/ShellEscape/Bash.hs /* A Bash escaped string. The strings are wrapped in @$\'...\'@ if any bytes within them must be escaped; otherwise, they are left as is. Newlines and other control characters are represented as ANSI escape sequences. High bytes are represented as hex codes. Thus Bash escaped strings will always fit on one line and never contain non-ASCII bytes. */ func BashEscape(str string) string { if str == "" { return "''" } 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 == ACK: hex(char) case char == TAB: escaped(`\t`) case char == LF: escaped(`\n`) case char == CR: escaped(`\r`) case char <= US: hex(char) case char <= AMPERSTAND: quoted(char) case char == SINGLE_QUOTE: backslash(char) case char <= PLUS: quoted(char) case char <= NINE: literal(char) case char <= QUESTION: quoted(char) case char <= UPPERCASE_Z: literal(char) case char == OPEN_BRACKET: quoted(char) case char == BACKSLASH: backslash(char) case char == UNDERSCORE: literal(char) case char <= CLOSE_BRACKET: quoted(char) case char <= BACKTICK: quoted(char) case char <= TILDA: quoted(char) case char == DEL: hex(char) default: hex(char) } i++ } if escape { out = "$'" + out + "'" } return out } direnv-2.32.1/internal/cmd/shell_elvish.go000066400000000000000000000015761425437440700205000ustar00rootroot00000000000000package cmd import ( "bytes" "encoding/json" ) type elvish struct{} // Elvish add support for the elvish shell var Elvish Shell = elvish{} func (elvish) Hook() (string, error) { return `## hook for direnv set @edit:before-readline = $@edit:before-readline { try { var m = [("{{.SelfPath}}" export elvish | from-json)] if (> (count $m) 0) { set m = (all $m) keys $m | each { |k| if $m[$k] { set-env $k $m[$k] } else { unset-env $k } } } } except e { echo $e } } `, nil } func (sh elvish) Export(e ShellExport) string { buf := new(bytes.Buffer) err := json.NewEncoder(buf).Encode(e) if err != nil { panic(err) } return buf.String() } func (sh elvish) Dump(env Env) (out string) { buf := new(bytes.Buffer) err := json.NewEncoder(buf).Encode(env) if err != nil { panic(err) } return buf.String() } var ( _ Shell = (*elvish)(nil) ) direnv-2.32.1/internal/cmd/shell_fish.go000066400000000000000000000046251425437440700201350ustar00rootroot00000000000000package cmd import ( "fmt" "strings" ) type fish struct{} // Fish adds support for the fish shell as a host var Fish Shell = fish{} const fishHook = ` function __direnv_export_eval --on-event fish_prompt; "{{.SelfPath}}" export fish | source; if test "$direnv_fish_mode" != "disable_arrow"; function __direnv_cd_hook --on-variable PWD; if test "$direnv_fish_mode" = "eval_after_arrow"; set -g __direnv_export_again 0; else; "{{.SelfPath}}" export fish | source; end; end; end; end; function __direnv_export_eval_2 --on-event fish_preexec; if set -q __direnv_export_again; set -e __direnv_export_again; "{{.SelfPath}}" export fish | source; echo; end; functions --erase __direnv_cd_hook; end; ` func (sh fish) Hook() (string, error) { return fishHook, nil } func (sh fish) Export(e ShellExport) (out string) { for key, value := range e { if value == nil { out += sh.unset(key) } else { out += sh.export(key, *value) } } return out } func (sh fish) Dump(env Env) (out string) { for key, value := range env { out += sh.export(key, value) } return out } func (sh fish) export(key, value string) string { if key == "PATH" { command := "set -x -g PATH" for _, path := range strings.Split(value, ":") { command += " " + sh.escape(path) } return command + ";" } return "set -x -g " + sh.escape(key) + " " + sh.escape(value) + ";" } func (sh fish) unset(key string) string { return "set -e -g " + sh.escape(key) + ";" } func (sh fish) escape(str string) string { 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++ } out += "'" return out } direnv-2.32.1/internal/cmd/shell_gha.go000066400000000000000000000017171425437440700177420ustar00rootroot00000000000000package cmd import ( "fmt" "strings" ) type gha struct{} // GitHubActions shell instance var GitHubActions Shell = gha{} func (sh gha) Hook() (string, error) { return "", fmt.Errorf("Hook not implemented for GitHub Actions shell") } func (sh gha) Export(e ShellExport) string { var b strings.Builder for key, value := range e { if value == nil { sh.unset(&b, key) } else { sh.export(&b, key, *value) } } return b.String() } const ghaDelim = "DIRENV_GITHUB_ACTIONS_EOV\n" func (sh gha) Dump(env Env) string { var b strings.Builder for key, value := range env { sh.export(&b, key, value) } return b.String() } func (sh gha) export(b *strings.Builder, key, value string) { b.WriteString(key) b.WriteString("<<") b.WriteString(ghaDelim) b.WriteString(value) if value != "" && !strings.HasSuffix(value, "\n") { b.WriteByte('\n') } b.WriteString(ghaDelim) } func (sh gha) unset(b *strings.Builder, key string) { sh.export(b, key, "") } direnv-2.32.1/internal/cmd/shell_gzenv.go000066400000000000000000000007021425437440700203250ustar00rootroot00000000000000package cmd import ( "errors" "github.com/direnv/direnv/v2/gzenv" ) type gzenvShell int // GzEnv is not a real shell. used for internal purposes. var GzEnv Shell = gzenvShell(0) func (s gzenvShell) Hook() (string, error) { return "", errors.New("the gzenv shell doesn't support hooking") } func (s gzenvShell) Export(e ShellExport) string { return gzenv.Marshal(e) } func (s gzenvShell) Dump(env Env) string { return gzenv.Marshal(env) } direnv-2.32.1/internal/cmd/shell_json.go000066400000000000000000000013301425437440700201430ustar00rootroot00000000000000package cmd import ( "encoding/json" "errors" ) // jsonShell is not a real shell type jsonShell struct{} // JSON is not really a shell but it fits. Useful to add support to editor and // other external tools that understand JSON as a format. var JSON Shell = jsonShell{} func (sh jsonShell) Hook() (string, error) { return "", errors.New("this feature is not supported") } func (sh jsonShell) Export(e ShellExport) string { out, err := json.MarshalIndent(e, "", " ") if err != nil { // Should never happen panic(err) } return string(out) } func (sh jsonShell) Dump(env Env) string { out, err := json.MarshalIndent(env, "", " ") if err != nil { // Should never happen panic(err) } return string(out) } direnv-2.32.1/internal/cmd/shell_tcsh.go000066400000000000000000000043541425437440700201440ustar00rootroot00000000000000package cmd import ( "fmt" "strings" ) type tcsh struct{} // Tcsh adds support for the tickle shell var Tcsh Shell = tcsh{} func (sh tcsh) Hook() (string, error) { return "alias precmd 'eval `{{.SelfPath}} export tcsh`'", nil } func (sh tcsh) Export(e ShellExport) (out string) { for key, value := range e { if value == nil { out += sh.unset(key) } else { out += sh.export(key, *value) } } return out } func (sh tcsh) Dump(env Env) (out string) { for key, value := range env { out += sh.export(key, value) } return out } func (sh tcsh) export(key, value string) string { if key == "PATH" { command := "set path = (" for _, path := range strings.Split(value, ":") { command += " " + sh.escape(path) } return command + " );" } return "setenv " + sh.escape(key) + " " + sh.escape(value) + " ;" } func (sh tcsh) unset(key string) string { return "unsetenv " + sh.escape(key) + " ;" } func (sh 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 == ACK: hex(char) 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 <= UPPERCASE_Z: literal(char) case char == OPEN_BRACKET: quoted(char) case char == BACKSLASH: backslash(char) case char == UNDERSCORE: literal(char) case char <= LOWERCASE_Z: literal(char) case char <= CLOSE_BRACKET: quoted(char) case char <= BACKTICK: quoted(char) case char <= TILDA: quoted(char) case char == DEL: hex(char) default: hex(char) } i++ } return out } direnv-2.32.1/internal/cmd/shell_test.go000066400000000000000000000015501425437440700201550ustar00rootroot00000000000000package cmd 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.32.1/internal/cmd/shell_vim.go000066400000000000000000000021261425437440700177710ustar00rootroot00000000000000package cmd import ( "errors" "strings" ) type vim struct{} // Vim adds support for vim. Not really a shell but it's handly. var Vim Shell = vim{} func (sh vim) Hook() (string, error) { return "", errors.New("this feature is not supported. Install the direnv.vim plugin instead") } func (sh vim) Export(e ShellExport) (out string) { for key, value := range e { if value == nil { out += sh.unset(key) } else { out += sh.export(key, *value) } } return out } func (sh vim) Dump(env Env) (out string) { for key, value := range env { out += sh.export(key, value) } return out } func (sh vim) export(key, value string) string { return "call setenv(" + sh.escapeKey(key) + "," + sh.escapeValue(value) + ")\n" } func (sh vim) unset(key string) string { return "call setenv(" + sh.escapeKey(key) + ",v:null)\n" } // TODO: support keys with special chars or fail func (sh vim) escapeKey(str string) string { return sh.escapeValue(str) } // TODO: Make sure this escaping is valid func (sh vim) escapeValue(str string) string { return "'" + strings.Replace(str, "'", "''", -1) + "'" } direnv-2.32.1/internal/cmd/shell_zsh.go000066400000000000000000000022641425437440700200050ustar00rootroot00000000000000package cmd // ZSH is a singleton instance of ZSH_T type zsh struct{} // Zsh adds support for the venerable Z shell. var Zsh Shell = zsh{} const zshHook = ` _direnv_hook() { trap -- '' SIGINT; eval "$("{{.SelfPath}}" export zsh)"; trap - SIGINT; } typeset -ag precmd_functions; if [[ -z "${precmd_functions[(r)_direnv_hook]+1}" ]]; then precmd_functions=( _direnv_hook ${precmd_functions[@]} ) fi typeset -ag chpwd_functions; if [[ -z "${chpwd_functions[(r)_direnv_hook]+1}" ]]; then chpwd_functions=( _direnv_hook ${chpwd_functions[@]} ) fi ` func (sh zsh) Hook() (string, error) { return zshHook, nil } func (sh zsh) Export(e ShellExport) (out string) { for key, value := range e { if value == nil { out += sh.unset(key) } else { out += sh.export(key, *value) } } return out } func (sh zsh) Dump(env Env) (out string) { for key, value := range env { out += sh.export(key, value) } return out } func (sh zsh) export(key, value string) string { return "export " + sh.escape(key) + "=" + sh.escape(value) + ";" } func (sh zsh) unset(key string) string { return "unset " + sh.escape(key) + ";" } func (sh zsh) escape(str string) string { return BashEscape(str) } direnv-2.32.1/internal/cmd/stdlib.go000066400000000000000000000003351425437440700172700ustar00rootroot00000000000000package cmd import "strings" // getStdlib returns the stdlib.sh, with references to direnv replaced. func getStdlib(config *Config) string { return strings.Replace(stdlib, "$(command -v direnv)", config.SelfPath, 1) } direnv-2.32.1/main.go000066400000000000000000000006241425437440700143550ustar00rootroot00000000000000package main import ( _ "embed" "github.com/direnv/direnv/v2/internal/cmd" "os" "strings" ) var ( // Configured at compile time bashPath string //go:embed stdlib.sh stdlib string //go:embed version.txt version string ) func main() { var ( env = cmd.GetEnv() args = os.Args ) err := cmd.Main(env, args, bashPath, stdlib, strings.TrimSpace(version)) if err != nil { os.Exit(1) } } direnv-2.32.1/man/000077500000000000000000000000001425437440700136535ustar00rootroot00000000000000direnv-2.32.1/man/direnv-fetchurl.1000066400000000000000000000047531425437440700170470ustar00rootroot00000000000000.nh .TH DIRENV-FETCHURL 1 "2019" direnv "User Manuals" .SH NAME .PP direnv fetchurl - Fetch a URL to disk .SH SYNOPSIS .PP \fIdirenv fetchurl\fP [] .SH DESCRIPTION .PP This command downloads the given URL into a fixed disk location, based on the content of the retrieved file. .PP This has been introduced to avoid a dependency on \fB\fCcurl\fR or \fB\fCwget\fR, while also promoting a more secure way to fetch data from the Internet. Use this instead of \fB\fCcurl | sh\fR\&. .PP This command has two modes of operation: .RS .IP " 1." 5 Just pass the URL to discover the integrity hash. .IP " 2." 5 Pass the URL \fIand\fP the integrity hash to get back the on-disk location. .RE .PP Since the on-disk location is based on the hash, it also acts as a cache. One implication of this design is that URLs must be stable and always return the same content. .PP Downloaded files are marked as read-only and executable so it can also be used to fetch and execute static binaries. .SH OPTIONS .PP A HTTP URL that returns content on HTTP GET requests. 301 and other redirects are followed. .PP When passed, the integrity of the retrieved content will be validated against the given hash. The hash encoding is based on the SRI W3C specificiation (see https://www.w3.org/TR/SRI/ ). .SH OUTPUT .PP \fIdirenv fetchurl\fP outputs different content based on the argument. .PP If the \fB\fCintegrity-hash\fR is being passed, it will output the path to the on-disk location, if the retrieval was successful. .PP If only the \fB\fCurl\fR is being passed, it will output the hash as well as some human-readable instruction. If stdout is not a tty, only the hash will be displayed. .SH EXAMPLE .PP .RS .nf $ ./direnv fetchurl https://releases.nixos.org/nix/nix-2.3.7/install Found hash: sha256-7Gxl5GzI9juc/U30Igh/pY+p6+gj5Waohfwql3jHIds= Invoke fetchurl again with the hash as an argument to get the disk location: direnv fetchurl "https://releases.nixos.org/nix/nix-2.3.7/install" "sha256-7Gxl5GzI9juc/U30Igh/pY+p6+gj5Waohfwql3jHIds=" #=> /home/zimbatm/.cache/direnv/cas/sha256-7Gxl5GzI9juc_U30Igh_pY+p6+gj5Waohfwql3jHIds= .fi .RE .SH ENVIRONMENT VARIABLES .PP \fBXDG_CACHE_HOME\fP This variable is used to select the on-disk location of the fetched URLs as \fB\fC$XDG_CACHE_HOME/direnv/cas\fR\&. If \fBXDG_CACHE_HOME\fP is unset or empty, defaults to \fB\fC$HOME/.cache\fR\&. .SH COPYRIGHT .PP MIT licence - Copyright (C) 2019 @zimbatm and contributors .SH SEE ALSO .PP direnv-stdlib(1) direnv-2.32.1/man/direnv-fetchurl.1.md000066400000000000000000000047321425437440700174430ustar00rootroot00000000000000DIRENV-FETCHURL 1 "2019" direnv "User Manuals" ============================================== NAME ---- direnv fetchurl - Fetch a URL to disk SYNOPSIS -------- *direnv fetchurl* [] DESCRIPTION ----------- This command downloads the given URL into a fixed disk location, based on the content of the retrieved file. This has been introduced to avoid a dependency on `curl` or `wget`, while also promoting a more secure way to fetch data from the Internet. Use this instead of `curl | sh`. This command has two modes of operation: 1. Just pass the URL to discover the integrity hash. 2. Pass the URL *and* the integrity hash to get back the on-disk location. Since the on-disk location is based on the hash, it also acts as a cache. One implication of this design is that URLs must be stable and always return the same content. Downloaded files are marked as read-only and executable so it can also be used to fetch and execute static binaries. OPTIONS ------- A HTTP URL that returns content on HTTP GET requests. 301 and other redirects are followed. When passed, the integrity of the retrieved content will be validated against the given hash. The hash encoding is based on the SRI W3C specificiation (see https://www.w3.org/TR/SRI/ ). OUTPUT ------ *direnv fetchurl* outputs different content based on the argument. If the `integrity-hash` is being passed, it will output the path to the on-disk location, if the retrieval was successful. If only the `url` is being passed, it will output the hash as well as some human-readable instruction. If stdout is not a tty, only the hash will be displayed. EXAMPLE ------- $ ./direnv fetchurl https://releases.nixos.org/nix/nix-2.3.7/install Found hash: sha256-7Gxl5GzI9juc/U30Igh/pY+p6+gj5Waohfwql3jHIds= Invoke fetchurl again with the hash as an argument to get the disk location: direnv fetchurl "https://releases.nixos.org/nix/nix-2.3.7/install" "sha256-7Gxl5GzI9juc/U30Igh/pY+p6+gj5Waohfwql3jHIds=" #=> /home/zimbatm/.cache/direnv/cas/sha256-7Gxl5GzI9juc_U30Igh_pY+p6+gj5Waohfwql3jHIds= ENVIRONMENT VARIABLES --------------------- **XDG_CACHE_HOME** This variable is used to select the on-disk location of the fetched URLs as `$XDG_CACHE_HOME/direnv/cas`. If **XDG_CACHE_HOME** is unset or empty, defaults to `$HOME/.cache`. COPYRIGHT --------- MIT licence - Copyright (C) 2019 @zimbatm and contributors SEE ALSO -------- direnv-stdlib(1) direnv-2.32.1/man/direnv-stdlib.1000066400000000000000000000332011425437440700165020ustar00rootroot00000000000000.nh .TH DIRENV-STDLIB 1 "2019" direnv "User Manuals" .SH NAME .PP direnv-stdlib - functions for the \fB\fC\&.envrc\fR .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 \fB\fC\&.envrc\fR\&. In addition, it also loads the file in \fB\fC~/.config/direnv/direnvrc\fR if it exists. .SH STDLIB .SS \fB\fChas \fR .PP 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 .SS \fB\fCexpand_path []\fR .PP 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 .SS \fB\fCdotenv []\fR .PP Loads a ".env" file into the current environment. .SS \fB\fCdotenv_if_exists []\fR .PP Loads a ".env" file into the current environment, but only if it exists. .SS \fB\fCuser_rel_path \fR .PP 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 .SS \fB\fCfind_up \fR .PP 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 .SS \fB\fCsource_env \fR .PP Loads another \fB\fC\&.envrc\fR either by specifying its path or filename. .PP NOTE: the other \fB\fC\&.envrc\fR is not checked by the security framework. .SS \fB\fCsource_env_if_exists \fR .PP Loads another ".envrc", but only if it exists. .PP NOTE: contrary to \fB\fCsource_env\fR, this only works when passing a path to a file, not a directory. .PP Example: .PP .RS .nf source_env_if_exists .envrc.private .fi .RE .SS \fB\fCenv_vars_required [ ...]\fR .PP Logs error for every variable not present in the environment or having an empty value. .br Typically this is used in combination with source_env and source_env_if_exists. .PP Example: .PP .RS .nf # expect .envrc.private to provide tokens source_env .envrc.private # check presence of tokens env_vars_required GITHUB_TOKEN OTHER_TOKEN .fi .RE .SS \fB\fCsource_up []\fR .PP Loads another \fB\fC\&.envrc\fR if found with the find_up command. Returns 1 if no file is found. .PP NOTE: the other \fB\fC\&.envrc\fR is not checked by the security framework. .SS \fB\fCsource_up_if_exists []\fR .PP Loads another \fB\fC\&.envrc\fR if found with the find_up command. If one is not found, nothing happens. .PP NOTE: the other \fB\fC\&.envrc\fR is not checked by the security framework. .SS \fB\fCsource_url \fR .PP Loads another script from the given \fB\fCurl\fR\&. Before loading it it will check the integrity using the provided \fB\fCintegrity-hash\fR\&. .PP To find the value of the \fB\fCintegrity-hash\fR, call \fB\fCdirenv fetchurl \fR and extract the hash from the outputted message. .PP See also \fB\fCdirenv-fetchurl(1)\fR for more details. .SS \fB\fCfetchurl []\fR .PP Fetches the given \fB\fCurl\fR onto disk and outputs it's path location on stdout. .PP If the \fB\fCintegrity-hash\fR argument is provided, it will also check the integrity of the script. .PP See also \fB\fCdirenv-fetchurl(1)\fR for more details. .SS \fB\fCdirenv_apply_dump \fR .PP Loads the output of \fB\fCdirenv dump\fR that was stored in a file. .SS \fB\fCdirenv_load []\fR .PP 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 .SS \fB\fCPATH_add \fR .PP 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 .SS \fB\fCMANPATH_add \fR .PP Prepends the expanded \fIpath\fP to the MANPATH environment variable. It takes care of man-specific heuritic. .SS \fB\fCpath_add \fR .PP Works like \fB\fCPATH_add\fR except that it's for an arbitrary \fIvarname\fP\&. .SS \fB\fCPATH_rm [ ...]\fR .PP Removes directories that match any of the given shell patterns from the PATH environment variable. Order of the remaining directories is preserved in the resulting PATH. .PP Bash pattern syntax: https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html .PP Example: .PP .RS .nf echo $PATH # output: /dontremove/me:/remove/me:/usr/local/bin/:... PATH_rm '/remove/*' echo $PATH # output: /dontremove/me:/usr/local/bin/:... .fi .RE .SS \fB\fCload_prefix \fR .PP 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 .SS \fB\fCsemver_search \fR .PP Search a directory for the highest version number in SemVer format (X.Y.Z). .PP Examples: .PP .RS .nf $ tree . . |-- dir |-- program-1.4.0 |-- program-1.4.1 |-- program-1.5.0 $ semver_search "dir" "program-" "1.4.0" 1.4.0 $ semver_search "dir" "program-" "1.4" 1.4.1 $ semver_search "dir" "program-" "1" 1.5.0 .fi .RE .SS \fB\fClayout \fR .PP A semantic dispatch used to describe common project layouts. .SS \fB\fClayout go\fR .PP Adds "$(direnv_layout_dir)/go" to the GOPATH environment variable. And also adds "$PWD/bin" to the PATH environment variable. .SS \fB\fClayout julia\fR .PP Sets the \fB\fCJULIA_PROJECT\fR environment variable to the current directory. .SS \fB\fClayout node\fR .PP Adds "$PWD/node_modules/.bin" to the PATH environment variable. .SS \fB\fClayout php\fR .PP Adds "$PWD/vendor/bin" to the PATH environment variable. .SS \fB\fClayout perl\fR .PP Setup environment variables required by perl's local::lib See http://search.cpan.org/dist/local-lib/lib/local/lib.pm for more details. .SS \fB\fClayout pipenv\fR .PP Similar to \fB\fClayout python\fR, but uses Pipenv to build a virtualenv from the \fB\fCPipfile\fR located in the same directory. The path can be overridden by the \fB\fCPIPENV_PIPFILE\fR environment variable. .PP Note that unlike invoking Pipenv manually, this does not load environment variables from a \fB\fC\&.env\fR file automatically. You may want to add \fB\fCdotenv .env\fR to copy that behavior. .SS \fB\fClayout python []\fR .PP 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. .SS \fB\fClayout python3\fR .PP A shortcut for \fB\fClayout python python3\fR .SS \fB\fClayout ruby\fR .PP 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. .SS \fB\fCuse []\fR .PP 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 .SS \fB\fCuse julia \fR .PP Loads the specified Julia version. You must specify a path to the directory with installed Julia versions using $JULIA_VERSIONS. You can optionally override the prefix for folders inside $JULIA_VERSIONS (default \fB\fCjulia-\fR) using $JULIA_VERSION_PREFIX. If no exact match for \fB\fC\fR is found a search will be performed and the latest version will be loaded. .PP Examples (.envrc): .PP .RS .nf use julia 1.5.1 # loads $JULIA_VERSIONS/julia-1.5.1 use julia 1.5 # loads $JULIA_VERSIONS/julia-1.5.1 use julia master # loads $JULIA_VERSIONS/julia-master .fi .RE .SS \fB\fCuse rbenv\fR .PP Loads rbenv which add the ruby wrappers available on the PATH. .SS \fB\fCuse nix [...]\fR .PP 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 http://nixos.org/nix/manual/#sec-nix-shell .SS \fB\fCuse flake []\fR .PP Load the build environment of a derivation similar to \fB\fCnix develop\fR\&. .PP By default it will load the current folder flake.nix devShell attribute. Or pass an "installable" like "nixpkgs#hello" to load all the build dependencies of the hello package from the latest nixpkgs. .PP Note that the flakes feature is hidden behind an experimental flag, which you will have to enable on your own. Flakes is not considered stable yet. .SS \fB\fCuse guix [...]\fR .PP 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 https://www.gnu.org/software/guix/manual/html_node/Invoking-guix-environment.html .SS \fB\fCrvm [...]\fR .PP Should work just like in the shell if you have rvm installed. .SS \fB\fCuse node []\fR: .PP Loads the specified NodeJS version into the environment. .PP If a partial NodeJS version is passed (i.e. \fB\fC4.2\fR), a fuzzy match is performed and the highest matching version installed is selected. .PP If no version is passed, it will look at the '.nvmrc' or '.node-version' files in the current directory if they exist. .PP Environment Variables: .RS .IP \(bu 2 $NODE_VERSIONS (required) Points to a folder that contains all the installed Node versions. That folder must exist. .IP \(bu 2 $NODE_VERSION_PREFIX (optional) [default="node-v"] Overrides the default version prefix. .RE .SS \fB\fCuse vim []\fR .PP Prepends the specified vim script (or .vimrc.local by default) to the \fB\fCDIRENV_EXTRA_VIMRC\fR environment variable. .PP This variable is understood by the direnv/direnv.vim extension. When found, it will source it after opening files in the directory. .SS \fB\fCwatch_file [ ...]\fR .PP Adds each 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 .SS \fB\fCdirenv_version \fR .PP Checks that the direnv version is at least old as \fB\fCversion_at_least\fR\&. This can be useful when sharing an \fB\fC\&.envrc\fR and to make sure that the users are up to date. .SS \fB\fCstrict_env [ ...]\fR .PP Turns on shell execution strictness. This will force the .envrc evaluation context to exit immediately if: .RS .IP \(bu 2 any command in a pipeline returns a non-zero exit status that is not otherwise handled as part of \fB\fCif\fR, \fB\fCwhile\fR, or \fB\fCuntil\fR tests, return value negation (\fB\fC!\fR), or part of a boolean (\fB\fC&&\fR or \fB\fC||\fR) chain. .IP \(bu 2 any variable that has not explicitly been set or declared (with either \fB\fCdeclare\fR or \fB\fClocal\fR) is referenced. .RE .PP If followed by a command-line, the strictness applies for the duration of the command. .PP Example (Whole Script): .PP .RS .nf strict_env has curl .fi .RE .PP Example (Command): .PP .RS .nf strict_env has curl .fi .RE .SS \fB\fCunstrict_env [ ...]\fR .PP Turns off shell execution strictness. If followed by a command-line, the strictness applies for the duration of the command. .PP Example (Whole Script): .PP .RS .nf unstrict_env has curl .fi .RE .PP Example (Command): .PP .RS .nf unstrict_env has curl .fi .RE .SS \fB\fCon_git_branch []\fR .PP Returns 0 if within a git repository with given \fB\fCbranch_name\fR\&. If no branch name is provided, then returns 0 when within \fIany\fP branch. Requires the git command to be installed. Returns 1 otherwise. .PP When a branch is specified, then \fB\fC\&.git/HEAD\fR is watched so that entering/exiting a branch triggers a reload. .PP Example (.envrc): .PP .RS .nf if on_git_branch child_changes; then export MERGE_BASE_BRANCH=parent_changes fi if on_git_branch; then echo "Thanks for contributing to a GitHub project!" fi .fi .RE .SH COPYRIGHT .PP MIT licence - Copyright (C) 2019 @zimbatm and contributors .SH SEE ALSO .PP direnv(1), direnv.toml(1) direnv-2.32.1/man/direnv-stdlib.1.md000066400000000000000000000302651425437440700171100ustar00rootroot00000000000000DIRENV-STDLIB 1 "2019" direnv "User Manuals" ============================================ NAME ---- direnv-stdlib - functions for the `.envrc` 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 `~/.config/direnv/direnvrc` if it exists. STDLIB ------ ### `has ` 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 []` 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 []` Loads a ".env" file into the current environment. ### `dotenv_if_exists []` Loads a ".env" file into the current environment, but only if it exists. ### `user_rel_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 ` 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 ` Loads another `.envrc` either by specifying its path or filename. NOTE: the other `.envrc` is not checked by the security framework. ### `source_env_if_exists ` Loads another ".envrc", but only if it exists. NOTE: contrary to `source_env`, this only works when passing a path to a file, not a directory. Example: source_env_if_exists .envrc.private ### `env_vars_required [ ...]` Logs error for every variable not present in the environment or having an empty value. Typically this is used in combination with source_env and source_env_if_exists. Example: # expect .envrc.private to provide tokens source_env .envrc.private # check presence of tokens env_vars_required GITHUB_TOKEN OTHER_TOKEN ### `source_up []` Loads another `.envrc` if found when searching from the parent directory up to /. NOTE: the other `.envrc` is not checked by the security framework. ### `source_url ` Loads another script from the given `url`. Before loading it it will check the integrity using the provided `integrity-hash`. To find the value of the `integrity-hash`, call `direnv fetchurl ` and extract the hash from the outputted message. See also `direnv-fetchurl(1)` for more details. ### `fetchurl []` Fetches the given `url` onto disk and outputs it's path location on stdout. If the `integrity-hash` argument is provided, it will also check the integrity of the script. See also `direnv-fetchurl(1)` for more details. ### `direnv_apply_dump ` Loads the output of `direnv dump` that was stored in a file. ### `direnv_load []` 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 ` 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 ` Prepends the expanded *path* to the MANPATH environment variable. It takes care of man-specific heuritic. ### `path_add ` Works like `PATH_add` except that it's for an arbitrary *varname*. ### `PATH_rm [ ...]` Removes directories that match any of the given shell patterns from the PATH environment variable. Order of the remaining directories is preserved in the resulting PATH. Bash pattern syntax: https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html Example: echo $PATH # output: /dontremove/me:/remove/me:/usr/local/bin/:... PATH_rm '/remove/*' echo $PATH # output: /dontremove/me:/usr/local/bin/:... ### `load_prefix ` 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 ### `semver_search ` Search a directory for the highest version number in SemVer format (X.Y.Z). Examples: $ tree . . |-- dir |-- program-1.4.0 |-- program-1.4.1 |-- program-1.5.0 $ semver_search "dir" "program-" "1.4.0" 1.4.0 $ semver_search "dir" "program-" "1.4" 1.4.1 $ semver_search "dir" "program-" "1" 1.5.0 ### `layout ` A semantic dispatch used to describe common project layouts. ### `layout go` Adds "$(direnv_layout_dir)/go" to the GOPATH environment variable. And also adds "$PWD/bin" to the PATH environment variable. ### `layout julia` Sets the `JULIA_PROJECT` environment variable to the current directory. ### `layout node` Adds "$PWD/node_modules/.bin" to the PATH environment variable. ### `layout php` Adds "$PWD/vendor/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 pipenv` Similar to `layout python`, but uses Pipenv to build a virtualenv from the `Pipfile` located in the same directory. The path can be overridden by the `PIPENV_PIPFILE` environment variable. Note that unlike invoking Pipenv manually, this does not load environment variables from a `.env` file automatically. You may want to add `dotenv .env` to copy that behavior. ### `layout python []` 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 []` 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 julia ` Loads the specified Julia version. You must specify a path to the directory with installed Julia versions using $JULIA_VERSIONS. You can optionally override the prefix for folders inside $JULIA_VERSIONS (default `julia-`) using $JULIA_VERSION_PREFIX. If no exact match for `` is found a search will be performed and the latest version will be loaded. Examples (.envrc): use julia 1.5.1 # loads $JULIA_VERSIONS/julia-1.5.1 use julia 1.5 # loads $JULIA_VERSIONS/julia-1.5.1 use julia master # loads $JULIA_VERSIONS/julia-master ### `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 flake []` Load the build environment of a derivation similar to `nix develop`. By default it will load the current folder flake.nix devShell attribute. Or pass an "installable" like "nixpkgs#hello" to load all the build dependencies of the hello package from the latest nixpkgs. Note that the flakes feature is hidden behind an experimental flag, which you will have to enable on your own. Flakes is not considered stable yet. ### `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 the specified NodeJS version into the environment. If a partial NodeJS version is passed (i.e. `4.2`), a fuzzy match is performed and the highest matching version installed is selected. If no version is passed, it will look at the '.nvmrc' or '.node-version' files in the current directory if they exist. Environment Variables: - $NODE_VERSIONS (required) Points to a folder that contains all the installed Node versions. That folder must exist. - $NODE_VERSION_PREFIX (optional) [default="node-v"] Overrides the default version prefix. ### `use vim []` Prepends the specified vim script (or .vimrc.local by default) to the `DIRENV_EXTRA_VIMRC` environment variable. This variable is understood by the direnv/direnv.vim extension. When found, it will source it after opening files in the directory. ### `watch_file [ ...]` Adds each file to direnv's watch-list. If the file changes direnv will reload the environment on the next prompt. Example (.envrc): watch_file Gemfile ### `direnv_version ` Checks that the direnv version is at least old as `version_at_least`. This can be useful when sharing an `.envrc` and to make sure that the users are up to date. ### `strict_env [ ...]` Turns on shell execution strictness. This will force the .envrc evaluation context to exit immediately if: - any command in a pipeline returns a non-zero exit status that is not otherwise handled as part of `if`, `while`, or `until` tests, return value negation (`!`), or part of a boolean (`&&` or `||`) chain. - any variable that has not explicitly been set or declared (with either `declare` or `local`) is referenced. If followed by a command-line, the strictness applies for the duration of the command. Example (Whole Script): strict_env has curl Example (Command): strict_env has curl #### `unstrict_env [ ...]` Turns off shell execution strictness. If followed by a command-line, the strictness applies for the duration of the command. Example (Whole Script): unstrict_env has curl Example (Command): unstrict_env has curl ### `on_git_branch []` Returns 0 if within a git repository with given `branch_name`. If no branch name is provided, then returns 0 when within _any_ branch. Requires the git command to be installed. Returns 1 otherwise. When a branch is specified, then `.git/HEAD` is watched so that entering/exiting a branch triggers a reload. Example (.envrc): if on_git_branch child_changes; then export MERGE_BASE_BRANCH=parent_changes fi if on_git_branch; then echo "Thanks for contributing to a GitHub project!" fi COPYRIGHT --------- MIT licence - Copyright (C) 2019 @zimbatm and contributors SEE ALSO -------- direnv(1), direnv.toml(1) direnv-2.32.1/man/direnv.1000066400000000000000000000124351425437440700152310ustar00rootroot00000000000000.nh .TH DIRENV 1 "2019" 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 \fB\fC\&.envrc\fR 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, while unset variables are removed. .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 the \fB\fC~/.bashrc\fR file: .PP .RS .nf eval "$(direnv hook bash)" .fi .RE .PP Make sure it appears even after rvm, git-prompt and other shell extensions that manipulate the prompt. .SS ZSH .PP Add the following line at the end of the \fB\fC~/.zshrc\fR file: .PP .RS .nf eval "$(direnv hook zsh)" .fi .RE .SS FISH .PP Add the following line at the end of the \fB\fC$XDG_CONFIG_HOME/fish/config.fish\fR file: .PP .RS .nf direnv hook fish | source .fi .RE .PP Fish supports 3 modes you can set with with the global environment variable \fB\fCdirenv_fish_mode\fR: .PP .RS .nf set -g direnv_fish_mode eval_on_arrow # trigger direnv at prompt, and on every arrow-based directory change (default) set -g direnv_fish_mode eval_after_arrow # trigger direnv at prompt, and only after arrow-based directory changes before executing command set -g direnv_fish_mode disable_arrow # trigger direnv at prompt only, this is similar functionality to the original behavior .fi .RE .SS TCSH .PP Add the following line at the end of the \fB\fC~/.cshrc\fR file: .PP .RS .nf eval `direnv hook tcsh` .fi .RE .SS Elvish .PP Run: .PP .RS .nf $> direnv hook elvish > ~/.elvish/lib/direnv.elv .fi .RE .PP and add the following line to your \fB\fC~/.elvish/rc.elv\fR file: .PP .RS .nf use direnv .fi .RE .SH USAGE .PP In some target folder, create an \fB\fC\&.envrc\fR file and add some export(1) and unset(1) directives in it. .PP On the next prompt you will notice that direnv complains about the \fB\fC\&.envrc\fR 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 opens the file in your $EDITOR and automatically reloads 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 \fB\fC\&.envrc\fR file. Check the direnv-stdlib(1) man page for more details. You can also define your own extensions inside \fB\fC$XDG_CONFIG_HOME/direnv/direnvrc\fR or \fB\fC$XDG_CONFIG_HOME/direnv/lib/*.sh\fR files. .PP Hopefully this is enough to get you started. .SH ENVIRONMENT .TP \fB\fCXDG_CONFIG_HOME\fR Defaults to \fB\fC$HOME/.config\fR\&. .SH FILES .TP \fB\fC$XDG_CONFIG_HOME/direnv/direnv.toml\fR Direnv configuration. See direnv.toml(1). .TP \fB\fC$XDG_CONFIG_HOME/direnv/direnvrc\fR Bash code loaded before every \fB\fC\&.envrc\fR\&. Good for personal extensions. .TP \fB\fC$XDG_CONFIG_HOME/direnv/lib/*.sh\fR Bash code loaded before every \fB\fC\&.envrc\fR\&. Good for third-party extensions. .TP \fB\fC$XDG_DATA_HOME/direnv/allow\fR Records which \fB\fC\&.envrc\fR files have been \fB\fCdirenv allow\fRed. .SH CONTRIBUTE .PP Bug reports, contributions and forks are welcome. .PP All bugs or other forms of discussion happen on http://github.com/direnv/direnv/issues \[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 https://github.com/direnv/direnv/wiki \[la]https://github.com/direnv/direnv/wiki\[ra] .PP Or drop by on the #direnv channel on FreeNode \[la]irc://#direnv@FreeNode\[ra] to have a chat. .SH COPYRIGHT .PP MIT licence - Copyright (C) 2019 @zimbatm and contributors .SH SEE ALSO .PP direnv-stdlib(1), direnv.toml(1), direnv-fetchurl(1) direnv-2.32.1/man/direnv.1.md000066400000000000000000000115511425437440700156260ustar00rootroot00000000000000DIRENV 1 "2019" 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, while unset variables are removed. 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 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 `$XDG_CONFIG_HOME/fish/config.fish` file: ```fish direnv hook fish | source ``` Fish supports 3 modes you can set with with the global environment variable `direnv_fish_mode`: ```fish set -g direnv_fish_mode eval_on_arrow # trigger direnv at prompt, and on every arrow-based directory change (default) set -g direnv_fish_mode eval_after_arrow # trigger direnv at prompt, and only after arrow-based directory changes before executing command set -g direnv_fish_mode disable_arrow # trigger direnv at prompt only, this is similar functionality to the original behavior ``` ### TCSH Add the following line at the end of the `~/.cshrc` file: ```sh eval `direnv hook tcsh` ``` ### Elvish Run: ``` $> direnv hook elvish > ~/.elvish/lib/direnv.elv ``` and add the following line to your `~/.elvish/rc.elv` file: ``` use direnv ``` USAGE ----- In some target folder, create an `.envrc` file and add some export(1) and unset(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 opens the file in your $EDITOR and automatically reloads 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 `$XDG_CONFIG_HOME/direnv/direnvrc` or `$XDG_CONFIG_HOME/direnv/lib/*.sh` files. Hopefully this is enough to get you started. ENVIRONMENT ----------- `XDG_CONFIG_HOME` : Defaults to `$HOME/.config`. FILES ----- `$XDG_CONFIG_HOME/direnv/direnv.toml` : Direnv configuration. See direnv.toml(1). `$XDG_CONFIG_HOME/direnv/direnvrc` : Bash code loaded before every `.envrc`. Good for personal extensions. `$XDG_CONFIG_HOME/direnv/lib/*.sh` : Bash code loaded before every `.envrc`. Good for third-party extensions. `$XDG_DATA_HOME/direnv/allow` : Records which `.envrc` files have been `direnv allow`ed. 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 --------- MIT licence - Copyright (C) 2019 @zimbatm and contributors SEE ALSO -------- direnv-stdlib(1), direnv.toml(1), direnv-fetchurl(1) direnv-2.32.1/man/direnv.toml.1000066400000000000000000000107041425437440700162000ustar00rootroot00000000000000.nh .TH DIRENV.TOML 1 "2019" 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. The file is read from \fB\fC$XDG_CONFIG_HOME/direnv/direnv.toml\fR\&. .PP .RS .PP For versions v2.21.0 and below use config.toml instead of direnv.toml .RE .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 [global] .SS \fB\fCbash_path\fR .PP This allows one 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. .SS \fB\fCdisable_stdin\fR .PP If set to \fB\fCtrue\fR, stdin is disabled (redirected to /dev/null) during the \fB\fC\&.envrc\fR evaluation. .SS \fB\fCload_dotenv\fR .PP Also look for and load \fB\fC\&.env\fR files on top of the \fB\fC\&.envrc\fR files. If both \fB\fC\&.envrc\fR and \fB\fC\&.env\fR files exist, the \fB\fC\&.envrc\fR will always be chosen first. .SS \fB\fCstrict_env\fR .PP If set to true, the \fB\fC\&.envrc\fR will be loaded with \fB\fCset -euo pipefail\fR\&. This option will be the default in the future. .SS \fB\fCwarn_timeout\fR .PP Specify how long to wait before warning the user that the command is taking too long to execute. Defaults to "5s". .PP A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "Âĩs"), "ms", "s", "m", "h". .SH [whitelist] .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: .RS .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 .RE .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): .RS .IP \(bu 2 \fB\fC/home/user/project-b/.envrc\fR .IP \(bu 2 \fB\fC/opt/random/.envrc\fR .RE .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: .RS .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 .RE .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): .RS .IP \(bu 2 \fB\fC/home/user/code/project-b/subproject-c/.envrc\fR .IP \(bu 2 \fB\fC/home/user/code/.envrc\fR .RE .SH COPYRIGHT .PP MIT licence - Copyright (C) 2019 @zimbatm and contributors .SH SEE ALSO .PP direnv(1), direnv-stdlib(1) direnv-2.32.1/man/direnv.toml.1.md000066400000000000000000000077771425437440700166170ustar00rootroot00000000000000DIRENV.TOML 1 "2019" 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. The file is read from `$XDG_CONFIG_HOME/direnv/direnv.toml`. > For versions v2.21.0 and below use config.toml instead of direnv.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: ## [global] ### `bash_path` This allows one 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. ### `disable_stdin` If set to `true`, stdin is disabled (redirected to /dev/null) during the `.envrc` evaluation. ### `load_dotenv` Also look for and load `.env` files on top of the `.envrc` files. If both `.envrc` and `.env` files exist, the `.envrc` will always be chosen first. ### `strict_env` If set to true, the `.envrc` will be loaded with `set -euo pipefail`. This option will be the default in the future. ### `warn_timeout` Specify how long to wait before warning the user that the command is taking too long to execute. Defaults to "5s". A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "Âĩs"), "ms", "s", "m", "h". ## [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` COPYRIGHT --------- MIT licence - Copyright (C) 2019 @zimbatm and contributors SEE ALSO -------- direnv(1), direnv-stdlib(1) direnv-2.32.1/nix/000077500000000000000000000000001425437440700136765ustar00rootroot00000000000000direnv-2.32.1/nix/default.nix000066400000000000000000000001371425437440700160430ustar00rootroot00000000000000{ sources ? import ./sources.nix }: import sources.nixpkgs { config = {}; overlays = []; } direnv-2.32.1/nix/sources.json000066400000000000000000000011701425437440700162530ustar00rootroot00000000000000{ "nixpkgs": { "branch": "nixos-unstable", "builtin": true, "description": "Nixpkgs/NixOS branches that track the Nixpkgs/NixOS channels", "homepage": "https://github.com/NixOS/nixpkgs", "owner": "nixos", "repo": "nixpkgs", "rev": "73369f8d0864854d1acfa7f1e6217f7d6b6e3fa1", "sha256": "11z477rs1s2lhpw9h45npby86nqs7rqhi45ikh742ssxfwla52j1", "type": "tarball", "url": "https://github.com/nixos/nixpkgs/archive/73369f8d0864854d1acfa7f1e6217f7d6b6e3fa1.tar.gz", "url_template": "https://github.com///archive/.tar.gz" } } direnv-2.32.1/nix/sources.nix000066400000000000000000000150161425437440700161040ustar00rootroot00000000000000# This file has been generated by Niv. let # # The fetchers. fetch_ fetches specs of type . # fetch_file = pkgs: name: spec: let name' = sanitizeName name + "-src"; in if spec.builtin or true then builtins_fetchurl { inherit (spec) url sha256; name = name'; } else pkgs.fetchurl { inherit (spec) url sha256; name = name'; }; fetch_tarball = pkgs: name: spec: let name' = sanitizeName name + "-src"; in if spec.builtin or true then builtins_fetchTarball { name = name'; inherit (spec) url sha256; } else pkgs.fetchzip { name = name'; inherit (spec) url sha256; }; fetch_git = name: spec: let ref = if spec ? ref then spec.ref else if spec ? branch then "refs/heads/${spec.branch}" else if spec ? tag then "refs/tags/${spec.tag}" else abort "In git source '${name}': Please specify `ref`, `tag` or `branch`!"; in builtins.fetchGit { url = spec.repo; inherit (spec) rev; inherit ref; }; fetch_local = spec: spec.path; fetch_builtin-tarball = name: throw ''[${name}] The niv type "builtin-tarball" is deprecated. You should instead use `builtin = true`. $ niv modify ${name} -a type=tarball -a builtin=true''; fetch_builtin-url = name: throw ''[${name}] The niv type "builtin-url" will soon be deprecated. You should instead use `builtin = true`. $ niv modify ${name} -a type=file -a builtin=true''; # # Various helpers # # https://github.com/NixOS/nixpkgs/pull/83241/files#diff-c6f540a4f3bfa4b0e8b6bafd4cd54e8bR695 sanitizeName = name: ( concatMapStrings (s: if builtins.isList s then "-" else s) ( builtins.split "[^[:alnum:]+._?=-]+" ((x: builtins.elemAt (builtins.match "\\.*(.*)" x) 0) name) ) ); # The set of packages used when specs are fetched using non-builtins. mkPkgs = sources: system: let sourcesNixpkgs = import (builtins_fetchTarball { inherit (sources.nixpkgs) url sha256; }) { inherit system; }; hasNixpkgsPath = builtins.any (x: x.prefix == "nixpkgs") builtins.nixPath; hasThisAsNixpkgsPath = == ./.; in if builtins.hasAttr "nixpkgs" sources then sourcesNixpkgs else if hasNixpkgsPath && ! hasThisAsNixpkgsPath then import {} else abort '' Please specify either (through -I or NIX_PATH=nixpkgs=...) or add a package called "nixpkgs" to your sources.json. ''; # The actual fetching function. fetch = pkgs: name: spec: if ! builtins.hasAttr "type" spec then abort "ERROR: niv spec ${name} does not have a 'type' attribute" else if spec.type == "file" then fetch_file pkgs name spec else if spec.type == "tarball" then fetch_tarball pkgs name spec else if spec.type == "git" then fetch_git name spec else if spec.type == "local" then fetch_local spec else if spec.type == "builtin-tarball" then fetch_builtin-tarball name else if spec.type == "builtin-url" then fetch_builtin-url name else abort "ERROR: niv spec ${name} has unknown type ${builtins.toJSON spec.type}"; # If the environment variable NIV_OVERRIDE_${name} is set, then use # the path directly as opposed to the fetched source. replace = name: drv: let saneName = stringAsChars (c: if isNull (builtins.match "[a-zA-Z0-9]" c) then "_" else c) name; ersatz = builtins.getEnv "NIV_OVERRIDE_${saneName}"; in if ersatz == "" then drv else # this turns the string into an actual Nix path (for both absolute and # relative paths) if builtins.substring 0 1 ersatz == "/" then /. + ersatz else /. + builtins.getEnv "PWD" + "/${ersatz}"; # Ports of functions for older nix versions # a Nix version of mapAttrs if the built-in doesn't exist mapAttrs = builtins.mapAttrs or ( f: set: with builtins; listToAttrs (map (attr: { name = attr; value = f attr set.${attr}; }) (attrNames set)) ); # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/lists.nix#L295 range = first: last: if first > last then [] else builtins.genList (n: first + n) (last - first + 1); # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L257 stringToCharacters = s: map (p: builtins.substring p 1 s) (range 0 (builtins.stringLength s - 1)); # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L269 stringAsChars = f: s: concatStrings (map f (stringToCharacters s)); concatMapStrings = f: list: concatStrings (map f list); concatStrings = builtins.concatStringsSep ""; # https://github.com/NixOS/nixpkgs/blob/8a9f58a375c401b96da862d969f66429def1d118/lib/attrsets.nix#L331 optionalAttrs = cond: as: if cond then as else {}; # fetchTarball version that is compatible between all the versions of Nix builtins_fetchTarball = { url, name ? null, sha256 }@attrs: let inherit (builtins) lessThan nixVersion fetchTarball; in if lessThan nixVersion "1.12" then fetchTarball ({ inherit url; } // (optionalAttrs (!isNull name) { inherit name; })) else fetchTarball attrs; # fetchurl version that is compatible between all the versions of Nix builtins_fetchurl = { url, name ? null, sha256 }@attrs: let inherit (builtins) lessThan nixVersion fetchurl; in if lessThan nixVersion "1.12" then fetchurl ({ inherit url; } // (optionalAttrs (!isNull name) { inherit name; })) else fetchurl attrs; # Create the final "sources" from the config mkSources = config: mapAttrs ( name: spec: if builtins.hasAttr "outPath" spec then abort "The values in sources.json should not have an 'outPath' attribute" else spec // { outPath = replace name (fetch config.pkgs name spec); } ) config.sources; # The "config" used by the fetchers mkConfig = { sourcesFile ? if builtins.pathExists ./sources.json then ./sources.json else null , sources ? if isNull sourcesFile then {} else builtins.fromJSON (builtins.readFile sourcesFile) , system ? builtins.currentSystem , pkgs ? mkPkgs sources system }: rec { # The sources, i.e. the attribute set of spec name to spec inherit sources; # The "pkgs" (evaluated nixpkgs) to use for e.g. non-builtin fetchers inherit pkgs; }; in mkSources (mkConfig {}) // { __functor = _: settings: mkSources (mkConfig settings); } direnv-2.32.1/pkg/000077500000000000000000000000001425437440700136615ustar00rootroot00000000000000direnv-2.32.1/pkg/dotenv/000077500000000000000000000000001425437440700151605ustar00rootroot00000000000000direnv-2.32.1/pkg/dotenv/README.md000066400000000000000000000012631425437440700164410ustar00rootroot00000000000000# 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 * variable expansion, including default values as in `${FOO:-default}` * comments ## Missing * 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.32.1/pkg/dotenv/parse.go000066400000000000000000000067701425437440700166330ustar00rootroot00000000000000// 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" "os" "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 [^\s#\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 := match[2] parseValue(key, value, dotenv) } 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(key string, value string, dotenv map[string]string) { if len(value) <= 1 { dotenv[key] = value return } singleQuoted := false if value[0:1] == "'" && value[len(value)-1:] == "'" { // single-quoted string, do not expand singleQuoted = true 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) } if !singleQuoted { value = expandEnv(value, dotenv) } dotenv[key] = 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 } func expandEnv(value string, dotenv map[string]string) string { expander := func(value string) string { envKey, defaultValue, hasDefault := splitKeyAndDefault(value, ":-") expanded, found := lookupDotenv(envKey, dotenv) if found { return expanded } return getFromEnvOrDefault(envKey, defaultValue, hasDefault) } return os.Expand(value, expander) } func splitKeyAndDefault(value string, sep string) (string, string, bool) { var i = strings.Index(value, sep) if i == -1 { return value, "", false } return value[0:i], value[i+len(sep):], true } func lookupDotenv(value string, dotenv map[string]string) (string, bool) { retval, ok := dotenv[value] return retval, ok } func getFromEnvOrDefault(envKey string, defaultValue string, hasDefault bool) string { var envValue = os.Getenv(envKey) if len(envValue) == 0 && hasDefault { return defaultValue } return envValue } direnv-2.32.1/pkg/dotenv/parse_test.go000066400000000000000000000173401425437440700176650ustar00rootroot00000000000000package dotenv_test import ( "os" "testing" dotenv "github.com/direnv/direnv/v2/pkg/dotenv" ) func shouldNotHaveEmptyKey(t *testing.T, env map[string]string) { if _, ok := env[""]; ok { t.Error("should not have empty key") } } func envShouldContain(t *testing.T, env map[string]string, key string, value string) { if env[key] != value { t.Errorf("%s: %s, expected %s", key, env[key], value) } } // See the reference implementation: // https://github.com/bkeepers/dotenv/blob/master/lib/dotenv/environment.rb // TODO: support shell variable expansions const TestExportedEnv = `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(TestExportedEnv) 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 TestPlainEnv = `OPTION_A=1 OPTION_B=2 OPTION_C= 3 OPTION_D =4 OPTION_E = 5 OPTION_F= OPTION_G = SMTP_ADDRESS=smtp # This is a comment ` func TestDotEnvPlain(t *testing.T) { env := dotenv.MustParse(TestPlainEnv) 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") } if env["SMTP_ADDRESS"] != "smtp" { t.Error("SMTP_ADDRESS") } } const TestSoloEmptyEnv = "SOME_VAR=" func TestSoloEmpty(t *testing.T) { env := dotenv.MustParse(TestSoloEmptyEnv) 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 TestQuotedEnv = `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(TestQuotedEnv) 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 TestYAMLEnv = `OPTION_A: 1 OPTION_B: '2' OPTION_C: '' OPTION_D: '\n' #OPTION_E: '333' OPTION_F: ` func TestDotEnvYAML(t *testing.T) { env := dotenv.MustParse(TestYAMLEnv) 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 TestCommentOverrideEnv = ` VARIABLE=value #VARIABLE=disabled_value ` func TestCommentOverride(t *testing.T) { env := dotenv.MustParse(TestCommentOverrideEnv) shouldNotHaveEmptyKey(t, env) if env["VARIABLE"] != "value" { t.Error("VARIABLE should == value, not", env["VARIABLE"]) } } const TestVariableExpansionEnv = ` OPTION_A=$FOO OPTION_B="$FOO" OPTION_C=${FOO} OPTION_D="${FOO}" OPTION_E='$FOO' OPTION_F=$FOO/bar OPTION_G="$FOO/bar" OPTION_H=${FOO}/bar OPTION_I="${FOO}/bar" OPTION_J='$FOO/bar' OPTION_K=$BAR OPTION_L="$BAR" OPTION_M=${BAR} OPTION_N="${BAR}" OPTION_O='$BAR' OPTION_P=$BAR/baz OPTION_Q="$BAR/baz" OPTION_R=${BAR}/baz OPTION_S="${BAR}/baz" OPTION_T='$BAR/baz' OPTION_U="$OPTION_A/bar" OPTION_V=$OPTION_A/bar OPTION_W="$OPTION_A/bar" OPTION_X=${OPTION_A}/bar OPTION_Y="${OPTION_A}/bar" OPTION_Z='$OPTION_A/bar' OPTION_A1="$OPTION_A/bar/${OPTION_H}/$FOO" ` func TestVariableExpansion(t *testing.T) { err := os.Setenv("FOO", "foo") if err != nil { t.Fatalf("unable to set environment variable for testing: %s", err) } env := dotenv.MustParse(TestVariableExpansionEnv) shouldNotHaveEmptyKey(t, env) envShouldContain(t, env, "OPTION_A", "foo") envShouldContain(t, env, "OPTION_B", "foo") envShouldContain(t, env, "OPTION_C", "foo") envShouldContain(t, env, "OPTION_D", "foo") envShouldContain(t, env, "OPTION_E", "$FOO") envShouldContain(t, env, "OPTION_F", "foo/bar") envShouldContain(t, env, "OPTION_G", "foo/bar") envShouldContain(t, env, "OPTION_H", "foo/bar") envShouldContain(t, env, "OPTION_I", "foo/bar") envShouldContain(t, env, "OPTION_J", "$FOO/bar") envShouldContain(t, env, "OPTION_K", "") envShouldContain(t, env, "OPTION_L", "") envShouldContain(t, env, "OPTION_M", "") envShouldContain(t, env, "OPTION_N", "") envShouldContain(t, env, "OPTION_O", "$BAR") envShouldContain(t, env, "OPTION_P", "/baz") envShouldContain(t, env, "OPTION_Q", "/baz") envShouldContain(t, env, "OPTION_R", "/baz") envShouldContain(t, env, "OPTION_S", "/baz") envShouldContain(t, env, "OPTION_T", "$BAR/baz") envShouldContain(t, env, "OPTION_U", "foo/bar") envShouldContain(t, env, "OPTION_V", "foo/bar") envShouldContain(t, env, "OPTION_W", "foo/bar") envShouldContain(t, env, "OPTION_X", "foo/bar") envShouldContain(t, env, "OPTION_Y", "foo/bar") envShouldContain(t, env, "OPTION_Z", "$OPTION_A/bar") envShouldContain(t, env, "OPTION_A1", "foo/bar/foo/bar/foo") } const TestVariableExpansionWithDefaultsEnv = ` OPTION_A="${FOO:-}" OPTION_B="${FOO:-default}" OPTION_C='${FOO:-default}' OPTION_D="${FOO:-default}/bar" OPTION_E='${FOO:-default}/bar' OPTION_F="$FOO:-default" OPTION_G="$BAR:-default" OPTION_H="${BAR:-}" OPTION_I="${BAR:-default}" OPTION_J='${BAR:-default}' OPTION_K="${BAR:-default}/bar" OPTION_L='${BAR:-default}/bar' OPTION_M="${OPTION_A:-}" OPTION_N="${OPTION_A:-default}" OPTION_O='${OPTION_A:-default}' OPTION_P="${OPTION_A:-default}/bar" OPTION_Q='${OPTION_A:-default}/bar' OPTION_R="${:-}" OPTION_S="${BAR:-:-}" ` func TestVariableExpansionWithDefaults(t *testing.T) { err := os.Setenv("FOO", "foo") if err != nil { t.Fatalf("unable to set environment variable for testing: %s", err) } env := dotenv.MustParse(TestVariableExpansionWithDefaultsEnv) shouldNotHaveEmptyKey(t, env) envShouldContain(t, env, "OPTION_A", "foo") envShouldContain(t, env, "OPTION_B", "foo") envShouldContain(t, env, "OPTION_C", "${FOO:-default}") envShouldContain(t, env, "OPTION_D", "foo/bar") envShouldContain(t, env, "OPTION_E", "${FOO:-default}/bar") envShouldContain(t, env, "OPTION_F", "foo:-default") envShouldContain(t, env, "OPTION_G", ":-default") envShouldContain(t, env, "OPTION_H", "") envShouldContain(t, env, "OPTION_I", "default") envShouldContain(t, env, "OPTION_J", "${BAR:-default}") envShouldContain(t, env, "OPTION_K", "default/bar") envShouldContain(t, env, "OPTION_L", "${BAR:-default}/bar") envShouldContain(t, env, "OPTION_M", "foo") envShouldContain(t, env, "OPTION_N", "foo") envShouldContain(t, env, "OPTION_O", "${OPTION_A:-default}") envShouldContain(t, env, "OPTION_P", "foo/bar") envShouldContain(t, env, "OPTION_Q", "${OPTION_A:-default}/bar") envShouldContain(t, env, "OPTION_R", "") // this is actually invalid in bash, but what to do here? envShouldContain(t, env, "OPTION_S", ":-") } direnv-2.32.1/pkg/sri/000077500000000000000000000000001425437440700144565ustar00rootroot00000000000000direnv-2.32.1/pkg/sri/parse.go000066400000000000000000000012631425437440700161210ustar00rootroot00000000000000package sri import ( "fmt" "strings" ) // Parse a SRI hash func Parse(sriHash string) (*Hash, error) { elems := strings.SplitN(sriHash, "-", 2) if len(elems) != 2 { return nil, fmt.Errorf("sri: not a hash %v", sriHash) } // Get the algo var algo Algo switch elems[0] { case string(SHA256): algo = SHA256 case string(SHA384): algo = SHA384 case string(SHA512): algo = SHA512 default: return nil, fmt.Errorf("sri: unsupported algo %s", elems[0]) } // Get the hash dbuf := make([]byte, b64Enc.DecodedLen(len(elems[1]))) n, err := b64Enc.Decode(dbuf, []byte(elems[1])) if err != nil { return nil, err } sum := dbuf[:n] return &Hash{string(algo), sum}, nil } direnv-2.32.1/pkg/sri/sri.go000066400000000000000000000014461425437440700156070ustar00rootroot00000000000000// Package sri implements helper functions to calculate SubResource Integrity // hashes. // https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity package sri import ( b64 "encoding/base64" "encoding/hex" ) // Algo is a supported hashing algorithm type Algo string const ( // SHA256 algo SHA256 = Algo("sha256") // SHA384 algo SHA384 = Algo("sha384") // SHA512 algo SHA512 = Algo("sha512") ) // Base64 encoding to use var b64Enc = b64.StdEncoding // Hash represents a SRI-hash type Hash struct { algo string sum []byte } // String returns a SRI-encoded string func (h *Hash) String() string { return h.algo + "-" + b64Enc.EncodeToString(h.sum) } // Hex return a hex-encoded representation of the sum func (h *Hash) Hex() string { return hex.EncodeToString(h.sum) } direnv-2.32.1/pkg/sri/sri_test.go000066400000000000000000000017041425437440700166430ustar00rootroot00000000000000package sri import ( "strings" "testing" ) func TestWriter(t *testing.T) { var b strings.Builder s := "testdata" // Generated with: // `echo -n "testdata" | openssl dgst -sha256 -binary - | // openssl base64 -A` expectedHash := "sha256-gQ/y+yQqXe5CIPLLDmpRmJH7Z/L4KKbKtO+IlGM7H1A=" w := NewWriter(&b, SHA256) // Check the writer n, err := w.Write([]byte(s)) if err != nil { t.Fatalf("write error: %s", err) } if n != len(s) { t.Fatalf("expected len %d but got %d", len(s), n) } if b.String() != s { t.Fatal("data has not been forwarded") } // Check that the hash has been calculated properly x := w.Sum().String() if x != expectedHash { t.Fatal("hash mismatch") } } func TestParser(t *testing.T) { expectedHash := "sha256-gQ/y+yQqXe5CIPLLDmpRmJH7Z/L4KKbKtO+IlGM7H1A=" hash, err := Parse(expectedHash) if err != nil { t.Fatalf("parse error: %v", err) } if hash.String() != expectedHash { t.Fatal("hash mismatch") } } direnv-2.32.1/pkg/sri/writer.go000066400000000000000000000015511425437440700163230ustar00rootroot00000000000000package sri import ( "crypto/sha256" "crypto/sha512" "hash" "io" ) // Writer is like a hash.Hash with a Sum function type Writer struct { w io.Writer algo Algo h hash.Hash } // NewWriter returns a SRI writer that forwards the write while calculating // the SRI hash. func NewWriter(w io.Writer, algo Algo) Writer { var h hash.Hash switch algo { case SHA256: h = sha256.New() case SHA384: h = sha512.New384() case SHA512: h = sha512.New() default: panic("unsupported SRI algo") } return Writer{w, algo, h} } func (w Writer) Write(b []byte) (int, error) { // First write to the underlying storage n, err := w.w.Write(b) if err == nil { // This should always succeed _, _ = w.h.Write(b) } return n, err } // Sum returns the calculated SRI hash func (w Writer) Sum() *Hash { sum := w.h.Sum(nil) return &Hash{string(w.algo), sum} } direnv-2.32.1/script/000077500000000000000000000000001425437440700144045ustar00rootroot00000000000000direnv-2.32.1/script/dist-push000077500000000000000000000041741425437440700162600ustar00rootroot00000000000000#!/usr/bin/env bash # # Upload binary artifacts when a new release is made. # # Usage: ./script/dist-push [] # # Depends on: bash, coreutils, jq, curl set -euo pipefail # Ensure that the GITHUB_TOKEN secret is included if [[ -z "${GITHUB_TOKEN:-}" ]]; then echo "Set the GITHUB_TOKEN env variable." exit 1 fi # Prepare the headers for our curl-command. AUTH_HEADER="Authorization: token ${GITHUB_TOKEN}" # Set the github repository in CI : "${GITHUB_REPOSITORY:=direnv/direnv}" # Create the correct Upload URL. if [[ -n "${1:-}" ]]; then RELEASE_ID=$(curl -sfL \ -H "${AUTH_HEADER}" \ "https://api.github.com/repos/$GITHUB_REPOSITORY/releases/tags/$1" \ | jq .id) else # if not tag is given, assume we are in CI RELEASE_ID=$(jq --raw-output '.release.id' "$GITHUB_EVENT_PATH") fi # start from the project root cd "$(dirname "$0")/.." # make sure we have all the dist files make dist # For each matching file.. for file in dist/*; do echo "Processing '${file}'" filename=$(basename "${file}") upload_url="https://uploads.github.com/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets?name=${filename}" echo "Upload URL is '${upload_url}'" # Generate a temporary file. tmp=$(mktemp) # Upload the artifact - capturing HTTP response-code in our output file. if ! response=$( curl \ -sSL \ -XPOST \ -H "${AUTH_HEADER}" \ --upload-file "${file}" \ --header "Content-Type:application/octet-stream" \ --write-out "%{http_code}" \ --output "$tmp" \ "${upload_url}" ); then echo "**********************************" echo " curl command did not return zero." echo " Aborting" echo "**********************************" cat "$tmp" rm "$tmp" exit 1 fi # If upload is not successful, we must abort if [[ $response -ge 400 ]]; then echo "***************************" echo " upload was not successful." echo " Aborting" echo " HTTP status is $response" echo "**********************************" cat "$tmp" rm "$tmp" exit 1 fi # Show pretty output, since we already have jq jq . <"$tmp" rm "$tmp" done direnv-2.32.1/script/issue-command/000077500000000000000000000000001425437440700171505ustar00rootroot00000000000000direnv-2.32.1/script/issue-command/main.go000066400000000000000000000023131425437440700204220ustar00rootroot00000000000000package main import ( "fmt" "os" "strings" ) func escapeData(data string) string { data = strings.ReplaceAll(data, "%", "%25") data = strings.ReplaceAll(data, "\r", "%0D") data = strings.ReplaceAll(data, "\n", "%0A") return data } func escapeProperty(prop string) string { prop = escapeData(prop) prop = strings.ReplaceAll(prop, ":", "%3A") prop = strings.ReplaceAll(prop, ",", "%2C") return prop } // Go implementation of // https://github.com/actions/toolkit/blob/master/packages/core/src/command.ts func main() { var remain []string var props []string for _, arg := range os.Args[1:] { if arg == "--" { continue } if strings.HasPrefix(arg, "--") { kv := strings.SplitN(arg[2:], "=", 2) if len(kv) != 2 { panic(fmt.Sprintf("expected %s to be of form --key=value", arg[2:])) } props = append(props, fmt.Sprintf("%s=%s", kv[0], escapeProperty(kv[1]))) } else { remain = append(remain, arg) } } if len(remain) != 2 { panic(fmt.Sprintf("expected 2 remaining arguments, go %v", remain)) } cmd := remain[0] msg := escapeData(remain[1]) var propStr string if len(props) > 0 { propStr = " " + strings.Join(props, ",") } fmt.Printf("::%s%s::%s", cmd, propStr, msg) } direnv-2.32.1/script/release-changelog/000077500000000000000000000000001425437440700177515ustar00rootroot00000000000000direnv-2.32.1/script/release-changelog/main.go000066400000000000000000000010261425437440700212230ustar00rootroot00000000000000package main import ( "bufio" "os" "strings" ) func run() error { headers := 0 f, err := os.Open("CHANGELOG.md") if err != nil { return err } r := bufio.NewReader(f) prev, err := r.ReadString('\n') if err != nil { return err } for { line, err := r.ReadString('\n') if err != nil { return err } if strings.HasPrefix(line, "======") { headers++ } if headers > 1 { return nil } os.Stdout.WriteString(prev) prev = line } } func main() { err := run() if err != nil { panic(err) } } direnv-2.32.1/shell.nix000066400000000000000000000007371425437440700147360ustar00rootroot00000000000000{ pkgs ? import ./nix {} }: with pkgs; mkShell { buildInputs = [ # Build gitAndTools.git gitAndTools.git-extras # for git-changelog gnumake go go-md2man gox # Shells bashInteractive elvish fish tcsh zsh # Test dependencies golangci-lint ruby shellcheck shfmt ]; shellHook = '' unset GOPATH GOROOT export GO111MODULE=on export SSL_CERT_FILE=${cacert}/etc/ssl/certs/ca-bundle.crt ''; } direnv-2.32.1/stdlib.sh000077500000000000000000001061551425437440700147300ustar00rootroot00000000000000#!/usr/bin/env bash # # These are the commands available in an .envrc context # # ShellCheck exceptions: # # SC1090: Can't follow non-constant source. Use a directive to specify location. # SC1091: Not following: (file missing) # SC1117: Backslash is literal in "\n". Prefer explicit escaping: "\\n". # SC2059: Don't use variables in the printf format string. Use printf "..%s.." "$foo". shopt -s gnu_errfmt shopt -s nullglob shopt -s extglob # NOTE: don't touch the RHS, it gets replaced at runtime direnv="$(command -v direnv)" # Config, change in the direnvrc DIRENV_LOG_FORMAT="${DIRENV_LOG_FORMAT-direnv: %s}" # Where direnv configuration should be stored direnv_config_dir="${DIRENV_CONFIG:-${XDG_CONFIG_HOME:-$HOME/.config}/direnv}" # This variable can be used by programs to detect when they are running inside # of a .envrc evaluation context. It is ignored by the direnv diffing # algorithm and so it won't be re-exported. export DIRENV_IN_ENVRC=1 __env_strictness() { local mode tmpfile old_shell_options local -i res tmpfile="$(mktemp)" res=0 mode="$1" shift set +o | grep 'pipefail\|nounset\|errexit' > "$tmpfile" old_shell_options=$(< "$tmpfile") rm -f "$tmpfile" case "$mode" in strict) set -o errexit -o nounset -o pipefail ;; unstrict) set +o errexit +o nounset +o pipefail ;; *) log_error "Unknown strictness mode '${mode}'." exit 1 ;; esac if (($#)); then "${@}" res=$? eval "$old_shell_options" fi # Force failure if the inner script has failed and the mode is strict if [[ $mode = strict && $res -gt 0 ]]; then exit 1 fi return $res } # Usage: strict_env [ ...] # # Turns on shell execution strictness. This will force the .envrc # evaluation context to exit immediately if: # # - any command in a pipeline returns a non-zero exit status that is # not otherwise handled as part of `if`, `while`, or `until` tests, # return value negation (`!`), or part of a boolean (`&&` or `||`) # chain. # - any variable that has not explicitly been set or declared (with # either `declare` or `local`) is referenced. # # If followed by a command-line, the strictness applies for the duration # of the command. # # Example: # # strict_env # has curl # # strict_env has curl strict_env() { __env_strictness strict "$@" } # Usage: unstrict_env [ ...] # # Turns off shell execution strictness. If followed by a command-line, the # strictness applies for the duration of the command. # # Example: # # unstrict_env # has curl # # unstrict_env has curl unstrict_env() { if (($#)); then __env_strictness unstrict "$@" else set +o errexit +o nounset +o pipefail fi } # 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=$* local color_normal="\e[m" # shellcheck disable=SC2059,SC1117 printf "${color_normal}${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() { if [[ -n $DIRENV_LOG_FORMAT ]]; then local msg=$* local color_normal="\e[m" local color_error="\e[38;5;1m" # shellcheck disable=SC2059,SC1117 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: join_args [args...] # # Joins all the passed arguments into a single string that can be evaluated by bash # # This is useful when one has to serialize an array of arguments back into a string join_args() { printf '%q ' "$@" } # 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() { local REPLY; realpath.absolute "${2+"$2"}" "${1+"$1"}"; echo "$REPLY" } # --- vendored from https://github.com/bashup/realpaths realpath.dirname() { REPLY=.; ! [[ $1 =~ /+[^/]+/*$|^//$ ]] || REPLY="${1%${BASH_REMATCH[0]}}"; REPLY=${REPLY:-/}; } realpath.basename(){ REPLY=/; ! [[ $1 =~ /*([^/]+)/*$ ]] || REPLY="${BASH_REMATCH[1]}"; } realpath.absolute() { REPLY=$PWD; local eg=extglob; ! shopt -q $eg || eg=; ${eg:+shopt -s $eg} while (($#)); do case $1 in //|//[^/]*) REPLY=//; set -- "${1:2}" "${@:2}" ;; /*) REPLY=/; set -- "${1##+(/)}" "${@:2}" ;; */*) set -- "${1%%/*}" "${1##${1%%/*}+(/)}" "${@:2}" ;; ''|.) shift ;; ..) realpath.dirname "$REPLY"; shift ;; *) REPLY="${REPLY%/}/$1"; shift ;; esac; done; ${eg:+shopt -u $eg} } # --- # 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 watch_file "$path" if ! [[ -f $path ]]; then log_error ".env at $path not found" return 1 fi eval "$("$direnv" dotenv bash "$@")" } # Usage: dotenv_if_exists [] # # Loads a ".env" file into the current environment, but only if it exists. # dotenv_if_exists() { local path=${1:-} if [[ -z $path ]]; then path=$PWD/.env elif [[ -d $path ]]; then path=$path/.env fi watch_file "$path" if ! [[ -f $path ]]; then return fi eval "$("$direnv" dotenv bash "$@")" } # 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} if has cygpath ; then rcpath=$(cygpath -u "$rcpath") fi local REPLY if [[ -d $rcpath ]]; then rcpath=$rcpath/.envrc fi if [[ ! -e $rcpath ]]; then log_status "referenced $rcpath does not exist" return 1 fi realpath.dirname "$rcpath" local rcpath_dir=$REPLY realpath.basename "$rcpath" local rcpath_base=$REPLY local rcfile rcfile=$(user_rel_path "$rcpath") watch_file "$rcpath" pushd "$(pwd 2>/dev/null)" >/dev/null || return 1 pushd "$rcpath_dir" >/dev/null || return 1 if [[ -f ./$rcpath_base ]]; then log_status "loading $(user_rel_path "$(expand_path "$rcpath")")" # shellcheck disable=SC1090 . "./$rcpath_base" else log_status "referenced $rcfile does not exist" fi popd >/dev/null || return 1 popd >/dev/null || return 1 } # Usage: source_env_if_exists # # Loads another ".envrc", but only if it exists. # # NOTE: contrary to source_env, this only works when passing a path to a file, # not a directory. # # Example: # # source_env_if_exists .envrc.private # source_env_if_exists() { watch_file "$1" if [[ -f "$1" ]]; then source_env "$1"; fi } # Usage: env_vars_required [ ...] # # Logs error for every variable not present in the environment or having an empty value. # Typically this is used in combination with source_env and source_env_if_exists. # # Example: # # # expect .envrc.private to provide tokens # source_env .envrc.private # # check presence of tokens # env_vars_required GITHUB_TOKEN OTHER_TOKEN # env_vars_required() { local environment local -i ret environment=$(env) ret=0 for var in "$@"; do if [[ "$environment" != *"$var="* || -z ${!var:-} ]]; then log_error "env var $var is required but missing/empty" ret=1 fi done return "$ret" } # Usage: watch_file [ ...] # # Adds each 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() { eval "$("$direnv" watch bash "$@")" } # Usage: watch_dir # # Adds to the list of dirs that direnv will recursively watch for changes watch_dir() { eval "$("$direnv" watch-dir bash "$1")" } # Usage: _source_up [] [true|false] # # Private helper function for source_up and source_up_if_exists. The second # parameter determines if it's an error for the file we're searching for to # not exist. _source_up() { local envrc file=${1:-.envrc} local ok_if_not_exist=${2} envrc=$(cd .. && (find_up "$file" || true)) if [[ -n $envrc ]]; then source_env "$envrc" elif $ok_if_not_exist; then return 0 else log_error "No ancestor $file found" return 1 fi } # Usage: source_up [] # # Loads another ".envrc" if found with the find_up command. Returns 1 if no # file is found. # # NOTE: the other ".envrc" is not checked by the security framework. source_up() { _source_up "${1:-}" false } # Usage: source_up_if_exists [] # # Loads another ".envrc" if found with the find_up command. If one is not # found, nothing happens. # # NOTE: the other ".envrc" is not checked by the security framework. source_up_if_exists() { _source_up "${1:-}" true } # Usage: fetchurl [] # # Fetches a URL and outputs a file with its content. If the # is given it will also validate the content of the file before returning it. fetchurl() { "$direnv" fetchurl "$@" } # Usage: source_url # # Fetches a URL and evalutes its content. source_url() { local url=$1 integrity_hash=${2:-} path if [[ -z $url ]]; then log_error "source_url: argument missing" return 1 fi if [[ -z $integrity_hash ]]; then log_error "source_url: argument missing. Use \`direnv fetchurl $url\` to find out the hash." return 1 fi log_status "loading $url ($integrity_hash)" path=$(fetchurl "$url" "$integrity_hash") # shellcheck disable=SC1090 source "$path" } # 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. # # shellcheck disable=SC1090 direnv_load() { # Backup watches in case of `nix-shell --pure` local prev_watches=$DIRENV_WATCHES local temp_dir output_file script_file exit_code old_direnv_dump_file_path # Prepare a temporary place for dumps and such. temp_dir=$(mktemp -dt direnv.XXXXXX) || { log_error "Could not create temporary directory." return 1 } output_file="$temp_dir/output" script_file="$temp_dir/script" old_direnv_dump_file_path=${DIRENV_DUMP_FILE_PATH:-} # Chain the following commands explicitly so that we can capture the exit code # of the whole chain. Crucially this ensures that we don't return early (via # `set -e`, for example) and hence always remove the temporary directory. touch "$output_file" && DIRENV_DUMP_FILE_PATH="$output_file" "$@" && { test -s "$output_file" || { log_error "Environment not dumped; did you invoke 'direnv dump'?" false } } && "$direnv" apply_dump "$output_file" > "$script_file" && source "$script_file" || exit_code=$? # Scrub temporary directory rm -rf "$temp_dir" # Restore watches if the dump wiped them if [[ -z "${DIRENV_WATCHES:-}" ]]; then export DIRENV_WATCHES=$prev_watches fi # Restore DIRENV_DUMP_FILE_PATH if needed if [[ -n "$old_direnv_dump_file_path" ]]; then export DIRENV_DUMP_FILE_PATH=$old_direnv_dump_file_path else unset DIRENV_DUMP_FILE_PATH fi # Exit accordingly return ${exit_code:-0} } # Usage: direnv_apply_dump # # Loads the output of `direnv dump` that was stored in a file. direnv_apply_dump() { local path=$1 eval "$("$direnv" apply_dump "$path")" } # 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 path i 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[@]+"${path_array[@]}"}) done # join back all the paths 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: PATH_rm [ ...] # Removes directories that match any of the given shell patterns from # the PATH environment variable. Order of the remaining directories is # preserved in the resulting PATH. # # Bash pattern syntax: # https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html # # Example: # # echo $PATH # # output: /dontremove/me:/remove/me:/usr/local/bin/:... # PATH_rm '/remove/*' # echo $PATH # # output: /dontremove/me:/usr/local/bin/:... # PATH_rm() { path_rm PATH "$@" } # Usage: path_rm [ ...] # # Works like PATH_rm except that it's for an arbitrary . path_rm() { local path i discard var_name="$1" # split existing paths into an array declare -a path_array IFS=: read -ra path_array <<<"${!1}" shift patterns=("$@") results=() # iterate over path entries, discard entries that match any of the patterns # shellcheck disable=SC2068 for path in ${path_array[@]+"${path_array[@]}"}; do discard=false # shellcheck disable=SC2068 for pattern in ${patterns[@]+"${patterns[@]}"}; do if [[ "$path" == +($pattern) ]]; then discard=true break fi done if ! $discard; then results+=("$path") fi done # join the result paths result=$( IFS=: echo "${results[*]}" ) # and finally export back the result to the original variable export "$var_name=$result" } # 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 REPLY realpath.absolute "$1" MANPATH_add "$REPLY/man" MANPATH_add "$REPLY/share/man" path_add CPATH "$REPLY/include" path_add LD_LIBRARY_PATH "$REPLY/lib" path_add LIBRARY_PATH "$REPLY/lib" path_add PATH "$REPLY/bin" path_add PKG_CONFIG_PATH "$REPLY/lib/pkgconfig" } # Usage: semver_search # # Search a directory for the highest version number in SemVer format (X.Y.Z). # # Examples: # # $ tree . # . # |-- dir # |-- program-1.4.0 # |-- program-1.4.1 # |-- program-1.5.0 # $ semver_search "dir" "program-" "1.4.0" # 1.4.0 # $ semver_search "dir" "program-" "1.4" # 1.4.1 # $ semver_search "dir" "program-" "1" # 1.5.0 # semver_search() { local version_dir=${1:-} local prefix=${2:-} local partial_version=${3:-} # Look for matching versions in $version_dir path # Strip possible "/" suffix from $version_dir, then use that to # strip $version_dir/$prefix prefix from line. # Sort by version: split by "." then reverse numeric sort for each piece of the version string # The first one is the highest find "$version_dir" -maxdepth 1 -mindepth 1 -type d -name "${prefix}${partial_version}*" \ | while IFS= read -r line; do echo "${line#${version_dir%/}/${prefix}}"; done \ | sort -t . -k 1,1rn -k 2,2rn -k 3,3rn \ | head -1 } # Usage: layout # # A semantic dispatch used to describe common project layouts. # layout() { local name=$1 shift eval "layout_$name" "$@" } # Usage: layout go # # Adds "$(direnv_layout_dir)/go" to the GOPATH environment variable. # And also adds "$PWD/bin" to the PATH environment variable. # layout_go() { path_add GOPATH "$(direnv_layout_dir)/go" PATH_add "$(direnv_layout_dir)/go/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 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 php # # Adds "$PWD/vendor/bin" to the PATH environment variable layout_php() { PATH_add vendor/bin } # Usage: layout python # # Creates and loads a virtual environment. # You can specify the path of the virtual environment through VIRTUAL_ENV # environment variable, otherwise it will be set to # "$direnv_layout_dir/python-$python_version". # For python older then 3.3 this requires virtualenv to be installed. # # It's possible to specify the python executable if you want to use different # versions of python. # layout_python() { local old_env local python=${1:-python} [[ $# -gt 0 ]] && shift old_env=$(direnv_layout_dir)/virtualenv unset PYTHONHOME if [[ -d $old_env && $python == python ]]; then VIRTUAL_ENV=$old_env else local python_version ve # shellcheck disable=SC2046 read -r python_version ve <<<$($python -c "import pkgutil as u, platform as p;ve='venv' if u.find_loader('venv') else ('virtualenv' if u.find_loader('virtualenv') else '');print(p.python_version()+' '+ve)") if [[ -z $python_version ]]; then log_error "Could not find python's version" return 1 fi if [[ -n "${VIRTUAL_ENV:-}" ]]; then local REPLY realpath.absolute "$VIRTUAL_ENV" VIRTUAL_ENV=$REPLY else VIRTUAL_ENV=$(direnv_layout_dir)/python-$python_version fi case $ve in "venv") if [[ ! -d $VIRTUAL_ENV ]]; then $python -m venv "$@" "$VIRTUAL_ENV" fi ;; "virtualenv") if [[ ! -d $VIRTUAL_ENV ]]; then $python -m virtualenv "$@" "$VIRTUAL_ENV" fi ;; *) log_error "Error: neither venv nor virtualenv are available." return 1 ;; esac fi export VIRTUAL_ENV 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 or prefix. 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_or_prefix=$1 local env_name local env_loc local conda local REPLY if [[ $# -gt 1 ]]; then conda=${2} else conda=$(command -v conda) fi realpath.dirname "$conda" PATH_add "$REPLY" if [[ "${env_name_or_prefix%%/*}" == "." ]]; then # "./foo" relative prefix realpath.absolute "$env_name_or_prefix" env_loc="$REPLY" elif [[ ! "$env_name_or_prefix" == "${env_name_or_prefix#/}" ]]; then # "/foo" absolute prefix env_loc="$env_name_or_prefix" else # "foo" name # if no name was passed, try to parse it from local environment.yml if [[ -n "$env_name_or_prefix" ]]; then env_name="$env_name_or_prefix" elif [[ -e environment.yml ]]; then env_name_grep_match="$(grep -- '^name:' environment.yml)" env_name="${env_name_grep_match/#name:*([[:space:]])}" fi if [[ -z "$env_name" ]]; then log_error "Could not determine conda env name (set in environment.yml or pass explicitly)" return 1 fi env_loc=$("$conda" env list | grep -- '^'"$env_name"'\s') env_loc="${env_loc##* }" fi if [[ ! -d "$env_loc" ]]; then if [[ -e environment.yml ]]; then log_status "creating conda environment" if [[ -n "$env_name" ]]; then "$conda" env create --name "$env_name" env_loc=$("$conda" env list | grep -- '^'"$env_name"'\s') env_loc="/${env_loc##* /}" else "$conda" env create --prefix "$env_loc" fi else log_error "Could not find environment.yml" return 1 fi fi eval "$( "$conda" shell.bash activate "$env_loc" )" } # Usage: layout pipenv # # Similar to layout_python, but uses Pipenv to build a # virtualenv from the Pipfile located in the same directory. # layout_pipenv() { PIPENV_PIPFILE="${PIPENV_PIPFILE:-Pipfile}" if [[ ! -f "$PIPENV_PIPFILE" ]]; then log_error "No Pipfile found. Use \`pipenv\` to create a \`$PIPENV_PIPFILE\` first." exit 2 fi VIRTUAL_ENV=$(pipenv --venv 2>/dev/null ; true) if [[ -z $VIRTUAL_ENV || ! -d $VIRTUAL_ENV ]]; then pipenv install --dev VIRTUAL_ENV=$(pipenv --venv) fi PATH_add "$VIRTUAL_ENV/bin" export PIPENV_ACTIVE=1 export VIRTUAL_ENV } # Usage: layout pyenv [ ...] # # Example: # # layout pyenv 3.6.7 # # Uses pyenv and layout_python to create and load a virtual environment. # You can specify the path of the virtual environment through VIRTUAL_ENV # environment variable, otherwise it will be set to # "$direnv_layout_dir/python-$python_version". # layout_pyenv() { unset PYENV_VERSION # layout_python prepends each python version to the PATH, so we add each # version in reverse order so that the first listed version ends up # first in the path local i for ((i = $#; i > 0; i--)); do local python_version=${!i} local pyenv_python pyenv_python=$(pyenv root)/versions/${python_version}/bin/python if [[ -x "$pyenv_python" ]]; then if layout_python "$pyenv_python"; then # e.g. Given "use pyenv 3.6.9 2.7.16", PYENV_VERSION becomes "3.6.9:2.7.16" PYENV_VERSION=${python_version}${PYENV_VERSION:+:$PYENV_VERSION} fi else log_error "pyenv: version '$python_version' not installed" return 1 fi done [[ -n "$PYENV_VERSION" ]] && export PYENV_VERSION } # 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() { BUNDLE_BIN=$(direnv_layout_dir)/bin if ruby -e "exit Gem::VERSION > '2.2.0'" 2>/dev/null; then GEM_HOME=$(direnv_layout_dir)/ruby else local ruby_version ruby_version=$(ruby -e"puts (defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby') + '-' + RUBY_VERSION") GEM_HOME=$(direnv_layout_dir)/ruby-${ruby_version} fi export BUNDLE_BIN export GEM_HOME PATH_add "$GEM_HOME/bin" PATH_add "$BUNDLE_BIN" } # Usage: layout julia # # Sets the JULIA_PROJECT environment variable to the current directory. layout_julia() { export JULIA_PROJECT=$PWD } # 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 julia [] # Loads specified Julia version. # # Environment Variables: # # - $JULIA_VERSIONS (required) # You must specify a path to your installed Julia versions with the `$JULIA_VERSIONS` variable. # # - $JULIA_VERSION_PREFIX (optional) [default="julia-"] # Overrides the default version prefix. # use_julia() { local version=${1:-} local julia_version_prefix=${JULIA_VERSION_PREFIX-julia-} local search_version local julia_prefix if [[ -z ${JULIA_VERSIONS:-} || -z $version ]]; then log_error "Must specify the \$JULIA_VERSIONS environment variable and a Julia version!" return 1 fi julia_prefix="${JULIA_VERSIONS}/${julia_version_prefix}${version}" if [[ ! -d ${julia_prefix} ]]; then search_version=$(semver_search "${JULIA_VERSIONS}" "${julia_version_prefix}" "${version}") julia_prefix="${JULIA_VERSIONS}/${julia_version_prefix}${search_version}" fi if [[ ! -d $julia_prefix ]]; then log_error "Unable to find Julia version ($version) in ($JULIA_VERSIONS)!" return 1 fi if [[ ! -x $julia_prefix/bin/julia ]]; then log_error "Unable to load Julia binary (julia) for version ($version) in ($JULIA_VERSIONS)!" return 1 fi load_prefix "$julia_prefix" log_status "Successfully loaded $(julia --version), from prefix ($julia_prefix)" } # 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 disable=SC1090,SC1091 source "${rvm_scripts_path}/rvm" elif [[ -n ${rvm_path:-} ]]; then # shellcheck disable=SC1090,SC1091 source "${rvm_path}/scripts/rvm" else # shellcheck disable=SC1090,SC1091 source "$HOME/.rvm/scripts/rvm" fi rvm "$@" } # Usage: use node [] # # Loads the specified NodeJS version into the environment. # # If a partial NodeJS version is passed (i.e. `4.2`), a fuzzy match # is performed and the highest matching version installed is selected. # # If no version is passed, it will look at the '.nvmrc' or '.node-version' # files in the current directory if they exist. # # Environment Variables: # # - $NODE_VERSIONS (required) # Points to a folder that contains all the installed Node versions. That # folder must exist. # # - $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 search_version 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 # Search for the highest version matchin $version in the folder search_version=$(semver_search "$NODE_VERSIONS" "${node_version_prefix}" "${version}") node_prefix="${NODE_VERSIONS}/${node_version_prefix}${search_version}" 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 nodenv # # Example: # # use nodenv 15.2.1 # # Uses nodenv, use_node and layout_node to add the chosen node version and # "$PWD/node_modules/.bin" to the PATH # use_nodenv() { local node_version="${1}" local node_versions_dir local nodenv_version node_versions_dir="$(nodenv root)/versions" nodenv_version="${node_versions_dir}/${node_version}" if [[ -e "$nodenv_version" ]]; then # Put the selected node version in the PATH NODE_VERSIONS="${node_versions_dir}" NODE_VERSION_PREFIX="" use_node "${node_version}" # Add $PWD/node_modules/.bin to the PATH layout_node else log_error "nodenv: version '$node_version' not installed. Use \`nodenv install ${node_version}\` to install it first." return 1 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() { direnv_load nix-shell --show-trace "$@" --run "$(join_args "$direnv" dump)" if [[ $# == 0 ]]; then watch_file default.nix shell.nix fi } # Usage: use_flake [] # # Load the build environment of a derivation similar to `nix develop`. # # By default it will load the current folder flake.nix devShell attribute. Or # pass an "installable" like "nixpkgs#hello" to load all the build # dependencies of the hello package from the latest nixpkgs. # # Note that the flakes feature is hidden behind an experimental flag, which # you will have to enable on your own. Flakes is not considered stable yet. use_flake() { watch_file flake.nix watch_file flake.lock mkdir -p "$(direnv_layout_dir)" eval "$(nix print-dev-env --profile "$(direnv_layout_dir)/flake-profile" "$@")" } # 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)" } # Usage: use_vim [] # # Prepends the specified vim script (or .vimrc.local by default) to the # `DIRENV_EXTRA_VIMRC` environment variable. # # This variable is understood by the direnv/direnv.vim extension. When found, # it will source it after opening files in the directory. use_vim() { local extra_vimrc=${1:-.vimrc.local} path_add DIRENV_EXTRA_VIMRC "$extra_vimrc" } # Usage: direnv_version # # Checks that the direnv version is at least old as . direnv_version() { "$direnv" version "$@" } # Usage: on_git_branch [] OR on_git_branch -r [] # # Returns 0 if within a git repository with given `branch_name`. If no branch # name is provided, then returns 0 when within _any_ branch. Requires the git # command to be installed. Returns 1 otherwise. # # When the `-r` flag is specified, then the second argument is interpreted as a # regexp pattern for matching a branch name. # # Regardless, when a branch is specified, then `.git/HEAD` is watched so that # entering/exiting a branch triggers a reload. # # Example (.envrc): # # if on_git_branch; then # echo "Thanks for contributing to a GitHub project!" # fi # # if on_git_branch child_changes; then # export MERGE_BASE_BRANCH=parent_changes # fi # # if on_git_branch -r '.*py2'; then # layout python2 # else # layout python # fi on_git_branch() { local git_dir if ! has git; then log_error "on_git_branch needs git, which could not be found on your system" return 1 elif ! git_dir=$(git rev-parse --absolute-git-dir 2> /dev/null); then log_error "on_git_branch could not locate the .git directory corresponding to the current working directory" return 1 elif [ -z "$1" ]; then return 0 elif [[ "$1" = "-r" && -z "$2" ]]; then log_error "missing regexp pattern after \`-r\` flag" return 1 fi watch_file "$git_dir/HEAD" local git_branch git_branch=$(git branch --show-current) if [ "$1" = '-r' ]; then [[ "$git_branch" =~ $2 ]] else [ "$1" = "$git_branch" ] fi } # Usage: __main__ [...] # # Used by rc.go __main__() { # reserve stdout for dumping exec 3>&1 exec 1>&2 __dump_at_exit() { local ret=$? "$direnv" dump json "" >&3 trap - EXIT exit "$ret" } trap __dump_at_exit EXIT # load direnv libraries for lib in "$direnv_config_dir/lib/"*.sh; do # shellcheck disable=SC1090 source "$lib" done # load the global ~/.direnvrc if present if [[ -f $direnv_config_dir/direnvrc ]]; then # shellcheck disable=SC1090,SC1091 source "$direnv_config_dir/direnvrc" >&2 elif [[ -f $HOME/.direnvrc ]]; then # shellcheck disable=SC1090,SC1091 source "$HOME/.direnvrc" >&2 fi # and finally load the .envrc "$@" } direnv-2.32.1/test/000077500000000000000000000000001425437440700140575ustar00rootroot00000000000000direnv-2.32.1/test/.envrc000066400000000000000000000000001425437440700151630ustar00rootroot00000000000000direnv-2.32.1/test/config/000077500000000000000000000000001425437440700153245ustar00rootroot00000000000000direnv-2.32.1/test/config/direnv/000077500000000000000000000000001425437440700166135ustar00rootroot00000000000000direnv-2.32.1/test/config/direnv/direnvrc000066400000000000000000000000001425437440700203400ustar00rootroot00000000000000direnv-2.32.1/test/direnv-test-common.sh000077500000000000000000000137711425437440700201610ustar00rootroot00000000000000# Test script for Bourne-shell extensions. Set TARGET_SHELL # to the shell to be tested (bash, zsh, etc) before sourcing it. if [[ -z "$TARGET_SHELL" ]]; then echo "TARGET_SHELL variable not set" exit 1 fi set -e cd "$(dirname "$0")" TEST_DIR=$PWD export XDG_CONFIG_HOME=${TEST_DIR}/config export XDG_DATA_HOME=${TEST_DIR}/data PATH=$(dirname "$TEST_DIR"):$PATH export PATH # Reset the direnv loading if any export DIRENV_CONFIG=$PWD unset DIRENV_BASH unset DIRENV_DIR unset DIRENV_FILE unset DIRENV_MTIME unset DIRENV_WATCHES unset DIRENV_DIFF mkdir -p "${XDG_CONFIG_HOME}/direnv" touch "${XDG_CONFIG_HOME}/direnv/direnvrc" has() { type -P "$1" &>/dev/null } direnv_eval() { eval "$(direnv export "$TARGET_SHELL")" } 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() { rm -f "${XDG_CONFIG_HOME}/direnv/direnv.toml" cd / 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}" unset WATCHES 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 if has ruby; then test_start "ruby-layout" direnv_eval test_neq "$GEM_HOME" "" test_stop fi # 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=$(command -v 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 "in-envrc" direnv_eval set +e ./test-in-envrc es=$? set -e test_eq "$es" "1" test_stop test_start "missing-file-source-env" direnv_eval test_stop test_start "symlink-changed" # when using a symlink, reload if the symlink changes, or if the # target file changes. ln -fs ./state-A ./symlink direnv_eval test_eq "${STATE}" "A" sleep 1 ln -fs ./state-B ./symlink direnv_eval test_eq "${STATE}" "B" test_stop test_start "symlink-dir" # we can allow and deny the target direnv allow foo direnv deny foo # we can allow and deny the symlink direnv allow bar direnv deny bar test_stop test_start "utf-8" direnv_eval test_eq "${UTFSTUFF}" "♀♂" test_stop test_start "failure" # Test that DIRENV_DIFF and DIRENV_WATCHES are set even after a failure. # # This is needed so that direnv doesn't go into a loop when the loading # fails. test_eq "${DIRENV_DIFF:-}" "" test_eq "${DIRENV_WATCHES:-}" "" direnv_eval test_neq "${DIRENV_DIFF:-}" "" test_neq "${DIRENV_WATCHES:-}" "" test_stop test_start "watch-dir" echo "No watches by default" test_eq "${DIRENV_WATCHES}" "${WATCHES}" direnv_eval if ! direnv show_dump "${DIRENV_WATCHES}" | grep -q "testfile"; then echo "FAILED: testfile not added to DIRENV_WATCHES" exit 1 fi echo "After eval, watches have changed" test_neq "${DIRENV_WATCHES}" "${WATCHES}" test_stop test_start "load-envrc-before-env" direnv_eval test_eq "${HELLO}" "bar" test_stop test_start "load-env" echo "[global] load_dotenv = true" > "${XDG_CONFIG_HOME}/direnv/direnv.toml" direnv allow direnv_eval test_eq "${HELLO}" "world" test_stop test_start "skip-env" direnv_eval test -z "${SKIPPED}" test_stop if has python; then test_start "python-layout" rm -rf .direnv direnv_eval test -n "${VIRTUAL_ENV:-}" if [[ ":$PATH:" != *":${VIRTUAL_ENV}/bin:"* ]]; then echo "FAILED: VIRTUAL_ENV/bin not added to PATH" exit 1 fi test_stop test_start "python-custom-virtual-env" direnv_eval test "${VIRTUAL_ENV:-}" -ef ./foo if [[ ":$PATH:" != *":${PWD}/foo/bin:"* ]]; then echo "FAILED: VIRTUAL_ENV/bin not added to PATH" exit 1 fi test_stop fi test_start "aliases" direnv deny # check that allow/deny aliases work direnv permit && direnv_eval && test -n "${HELLO}" direnv block && direnv_eval && test -z "${HELLO}" direnv grant && direnv_eval && test -n "${HELLO}" direnv revoke && direnv_eval && test -z "${HELLO}" 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.32.1/test/direnv-test.bash000066400000000000000000000001701425437440700171600ustar00rootroot00000000000000#!/usr/bin/env bash export TARGET_SHELL=bash # shellcheck disable=SC1091 source "$(dirname "$0")/direnv-test-common.sh" direnv-2.32.1/test/direnv-test.elv000077500000000000000000000044001425437440700170340ustar00rootroot00000000000000#!/usr/bin/env elvish use path E:TEST_DIR = (path:dir (src)[name]) set-env XDG_CONFIG_HOME $E:TEST_DIR/config set-env XDG_DATA_HOME $E:TEST_DIR/data E:PATH = (path:dir $E:TEST_DIR):$E:PATH cd $E:TEST_DIR ## reset the direnv loading if any set-env DIRENV_CONFIG $pwd unset-env DIRENV_BASH unset-env DIRENV_DIR unset-env DIRENV_FILE unset-env DIRENV_MTIME unset-env DIRENV_WATCHES unset-env DIRENV_DIFF mkdir -p $E:XDG_CONFIG_HOME/direnv touch $E:XDG_CONFIG_HOME/direnv/direnvrc fn direnv-eval { try { m = (direnv export elvish | from-json) keys $m | each [k]{ if $m[$k] { set-env $k $m[$k] } else { unset-env $k } } } except e { nop } } fn test-debug { if (==s $E:DIRENV_DEBUG "1") { echo } } fn test-eq [a b]{ if (!=s $a $b) { fail "FAILED: '"$a"' == '"$b"'" } } fn test-neq [a b]{ if (==s $a $b) { fail "FAILED: '"$a"' != '"$b"'" } } fn test-scenario [name fct]{ cd $E:TEST_DIR/scenarios/$name direnv allow test-debug echo "\n## Testing "$name" ##" test-debug $fct cd $E:TEST_DIR direnv-eval } ### RUN ### try { direnv allow } except e { nop } direnv-eval test-scenario base { echo "Setting up" direnv-eval test-eq $E:HELLO "world" set E:WATCHES = $E:DIRENV_WATCHES echo "Reloading (should be no-op)" direnv-eval test-eq $E:WATCHES $E:DIRENV_WATCHES sleep 1 echo "Updating envrc and reloading (should reload)" touch .envrc direnv-eval test-neq $E:WATCHES $E:DIRENV_WATCHES echo "Leaving dir (should clear env set by dir's envrc)" cd .. direnv-eval test-eq $E:HELLO "" } test-scenario inherit { cp ../base/.envrc ../inherited/.envrc direnv-eval echo "HELLO should be world:"$E:HELLO test-eq $E:HELLO "world" sleep 1 echo "export HELLO=goodbye" > ../inherited/.envrc direnv-eval test-eq $E:HELLO "goodbye" } test-scenario "ruby-layout" { direnv-eval test-neq $E:GEM_HOME "" } test-scenario "space dir" { direnv-eval test-eq $E:SPACE_DIR "true" } test-scenario "child-env" { direnv-eval test-eq $E:PARENT_PRE "1" test-eq $E:CHILD "1" test-eq $E:PARENT_POST "1" test-eq $E:REMOVE_ME "" } test-scenario "utf-8" { direnv-eval test-eq $E:UTFSTUFF "♀♂" } ## TODO: special-vars ## TODO: dump ## TODO: empty-var ## TODO: empty-var-unset test-scenario "missing-file-source-env" { direnv-eval } direnv-2.32.1/test/direnv-test.fish000077500000000000000000000106411425437440700172030ustar00rootroot00000000000000#!/usr/bin/env fish function test_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 function test_neq --argument-names a b if not test (count $argv) = 2 echo "Error: " (count $argv) " arguments passed to `neq`: $argv" exit 1 end if test $a = $b printf "Error:\n - expected: %s\n - got: %s\n" "$a" "$b" exit 1 end end function has type -q $argv[1] end cd (dirname (status -f)) set TEST_DIR $PWD set XDG_CONFIG_HOME $TEST_DIR/config set XDG_DATA_HOME $TEST_DIR/data 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_FILE set -e DIRENV_WATCHES set -e DIRENV_MTIME set -e DIRENV_DIFF function direnv_eval #direnv export fish # for debugging direnv export fish | source end function test_start -a name cd "$TEST_DIR/scenarios/$name" direnv allow echo "## Testing $name ##" end function test_stop cd / direnv_eval end ### RUN ### direnv allow direnv_eval test_start base begin echo "Setting up" direnv_eval test_eq "$HELLO" world set 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" || exit 1 set -e WATCHES end test_stop test_start inherit begin 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 end test_stop if has ruby test_start ruby-layout begin direnv_eval test_neq "$GEM_HOME" "" end test_stop end # Make sure directories with spaces are fine test_start "space dir" begin direnv_eval test_eq "$SPACE_DIR" true end test_stop test_start child-env begin direnv_eval test_eq "$PARENT_PRE" 1 test_eq "$CHILD" 1 test_eq "$PARENT_POST" 1 test -z "$REMOVE_ME" || exit 1 end test_stop test_start special-vars begin set -x DIRENV_BASH (command -s bash) set -x DIRENV_CONFIG foobar direnv_eval || true test -n "$DIRENV_BASH" || exit 1 test_eq "$DIRENV_CONFIG" foobar set -e DIRENV_BASH set -e DIRENV_CONFIG end test_stop test_start dump begin set -e LS_COLORS direnv_eval test_eq "$LS_COLORS" "*.ogg=38;5;45:*.wav=38;5;45" test_eq "$LESSOPEN" "||/usr/bin/lesspipe.sh %s" test_eq "$THREE_BACKSLASHES" "\\\\\\" end test_stop test_start empty-var begin direnv_eval set -q FOO || exit 1 test_eq "$FOO" "" end test_stop test_start empty-var-unset begin set -x FOO "" direnv_eval set -q FOO && exit 1 set -e FOO end test_stop test_start in-envrc begin direnv_eval ./test-in-envrc test_eq $status 1 end test_stop test_start missing-file-source-env begin direnv_eval end test_stop test_start symlink-changed begin # when using a symlink, reload if the symlink changes, or if the # target file changes. ln -fs ./state-A ./symlink direnv_eval test_eq "$STATE" A sleep 1 ln -fs ./state-B ./symlink direnv_eval test_eq "$STATE" B end test_stop # Currently broken # test_start utf-8 # begin # direnv_eval # test_eq "$UTFSTUFF" "♀♂" # end # test_stop test_start failure begin # Test that DIRENV_DIFF and DIRENV_WATCHES are set even after a failure. # # This is needed so that direnv doesn't go into a loop when the loading # fails. test_eq "$DIRENV_DIFF" "" test_eq "$DIRENV_WATCHES" "" direnv_eval test_neq "$DIRENV_DIFF" "" test_neq "$DIRENV_WATCHES" "" end test_stop test_start watch-dir begin echo "No watches by default" test_eq "$DIRENV_WATCHES" "$WATCHES" direnv_eval if ! direnv show_dump $DIRENV_WATCHES | grep -q testfile echo "FAILED: testfile not added to DIRENV_WATCHES" exit 1 end echo "After eval, watches have changed" test_neq "$DIRENV_WATCHES" "$WATCHES" end test_stop direnv-2.32.1/test/direnv-test.tcsh000077500000000000000000000065771425437440700172300ustar00rootroot00000000000000#!/usr/bin/env tcsh -e cd `dirname $0` setenv TEST_DIR $PWD setenv PATH `dirname $TEST_DIR`:$PATH setenv XDG_CONFIG_HOME $TEST_DIR/config setenv XDG_DATA_HOME $TEST_DIR/data # Reset the direnv loading if any setenv DIRENV_CONFIG $PWD unsetenv DIRENV_BASH unsetenv DIRENV_DIR unsetenv DIRENV_FILE unsetenv DIRENV_MTIME unsetenv DIRENV_WATCHES unsetenv DIRENV_DIFF 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 test 0 -eq "$?HELLO" cd $TEST_DIR ; direnv_eval cd $TEST_DIR/scenarios/inherit cp ../base/.envrc ../inherited/.envrc direnv allow echo "Testing inherit" direnv_eval test "$HELLO" = "world" sleep 1 echo "export HELLO=goodbye" > ../inherited/.envrc direnv_eval test "$HELLO" = "goodbye" 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 cd $TEST_DIR/scenarios/"parenthesis" direnv allow echo "Testing parenthesis" direnv_eval test "$FOO" = "aaa(bbb)ccc" unsetenv FOO cd $TEST_DIR ; direnv_eval # Currently broken # cd $TEST_DIR/scenarios/"utf-8" # direnv allow # echo "Testing utf-8" # direnv_eval # test "$UTFSTUFF" -eq '♀♂' # 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.32.1/test/direnv-test.zsh000077500000000000000000000001301425437440700170460ustar00rootroot00000000000000#!/usr/bin/env zsh export TARGET_SHELL=zsh source "$(dirname $0)/direnv-test-common.sh" direnv-2.32.1/test/scenarios/000077500000000000000000000000001425437440700160455ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/aliases/000077500000000000000000000000001425437440700174665ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/aliases/.envrc000066400000000000000000000000231425437440700205770ustar00rootroot00000000000000export HELLO=world direnv-2.32.1/test/scenarios/base/000077500000000000000000000000001425437440700167575ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/base/.envrc000066400000000000000000000000231425437440700200700ustar00rootroot00000000000000export HELLO=world direnv-2.32.1/test/scenarios/child-env/000077500000000000000000000000001425437440700177165ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/child-env/.envrc000066400000000000000000000002061425437440700210320ustar00rootroot00000000000000set -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.32.1/test/scenarios/dump/000077500000000000000000000000001425437440700170125ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/dump/.envrc000066400000000000000000000006561425437440700201370ustar00rootroot00000000000000direnv_load env \ LS_COLORS='*.ogg=38;5;45:*.wav=38;5;45' \ LESSOPEN='||/usr/bin/lesspipe.sh %s' \ THREE_BACKSLASHES='\\\' \ bash -c "echo to stdout && echo to stderr >&2 && direnv dump" log_status "direnv_load would previously hang if DIRENV_DUMP_FILE_PATH was not opened." log_status "Expect the following to emit an error (which we suppress)." log_status "As long as it doesn't hang, we're okay." direnv_load true || true direnv-2.32.1/test/scenarios/empty-var-unset/000077500000000000000000000000001425437440700211255ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/empty-var-unset/.envrc000066400000000000000000000000111425437440700222330ustar00rootroot00000000000000unset FOOdirenv-2.32.1/test/scenarios/empty-var/000077500000000000000000000000001425437440700177715ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/empty-var/.envrc000066400000000000000000000000151425437440700211030ustar00rootroot00000000000000export FOO=""direnv-2.32.1/test/scenarios/failure/000077500000000000000000000000001425437440700174745ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/failure/.envrc000066400000000000000000000000071425437440700206070ustar00rootroot00000000000000exit 5 direnv-2.32.1/test/scenarios/github-actions/000077500000000000000000000000001425437440700207655ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/github-actions/.envrc000066400000000000000000000002601425437440700221010ustar00rootroot00000000000000export TEST_EXPORT_DIRENV_GITHUB_ACTIONS="${GITHUB_SHA:-MISSING_GITHUB_SHA}"$'\n'"${GITHUB_RUN_ID:MISSING_GITHUB_RUN_ID}"$'\n'"${GITHUB_RUN_NUMBER:-MISSING_GITHUB_RUN_NUMBER}" direnv-2.32.1/test/scenarios/in-envrc/000077500000000000000000000000001425437440700175665ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/in-envrc/test-in-envrc000077500000000000000000000000701425437440700222070ustar00rootroot00000000000000#!/bin/sh test -n "$DIRENV_IN_ENVRC" && echo "in envrc" direnv-2.32.1/test/scenarios/inherit/000077500000000000000000000000001425437440700175075ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/inherit/.envrc000066400000000000000000000000531425437440700206230ustar00rootroot00000000000000source_env ../inherited/.envrc echo $HELLO direnv-2.32.1/test/scenarios/inherited/000077500000000000000000000000001425437440700200205ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/inherited/.gitkeep000066400000000000000000000000001425437440700214370ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/load-env/000077500000000000000000000000001425437440700175525ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/load-env/.env000066400000000000000000000000141425437440700203360ustar00rootroot00000000000000HELLO=world direnv-2.32.1/test/scenarios/load-envrc-before-env/000077500000000000000000000000001425437440700221255ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/load-envrc-before-env/.env000066400000000000000000000000121425437440700227070ustar00rootroot00000000000000HELLO=foo direnv-2.32.1/test/scenarios/load-envrc-before-env/.envrc000066400000000000000000000000211425437440700232340ustar00rootroot00000000000000export HELLO=bar direnv-2.32.1/test/scenarios/missing-file-source-env/000077500000000000000000000000001425437440700225175ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/missing-file-source-env/.envrc000066400000000000000000000000561425437440700236360ustar00rootroot00000000000000source_env "$(mktemp -d -t $RANDOM.XXXXXXXX)" direnv-2.32.1/test/scenarios/parenthesis/000077500000000000000000000000001425437440700203725ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/parenthesis/.envrc000066400000000000000000000000311425437440700215020ustar00rootroot00000000000000export FOO="aaa(bbb)ccc" direnv-2.32.1/test/scenarios/python-custom-virtual-env/000077500000000000000000000000001425437440700231505ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/python-custom-virtual-env/.envrc000066400000000000000000000000451425437440700242650ustar00rootroot00000000000000export VIRTUAL_ENV=foo layout python direnv-2.32.1/test/scenarios/python-custom-virtual-env/foo/000077500000000000000000000000001425437440700237335ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/python-custom-virtual-env/foo/bin/000077500000000000000000000000001425437440700245035ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/python-custom-virtual-env/foo/bin/.keep000066400000000000000000000000001425437440700254160ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/python-layout/000077500000000000000000000000001425437440700207015ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/python-layout/.envrc000066400000000000000000000000161425437440700220140ustar00rootroot00000000000000layout python direnv-2.32.1/test/scenarios/ruby-layout.env000066400000000000000000000001731425437440700210540ustar00rootroot00000000000000export PATH=`pwd`/ruby-layout/bin:$PATH export RUBYLIB=`pwd`/ruby-layout/lib export GEM_HOME=`pwd`/ruby-layout/vendor/gems direnv-2.32.1/test/scenarios/ruby-layout/000077500000000000000000000000001425437440700203415ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/ruby-layout/.envrc000066400000000000000000000000161425437440700214540ustar00rootroot00000000000000layout "ruby" direnv-2.32.1/test/scenarios/skip-env/000077500000000000000000000000001425437440700176015ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/skip-env/.env000066400000000000000000000000171425437440700203700ustar00rootroot00000000000000SKIPPED=dotenv direnv-2.32.1/test/scenarios/space dir/000077500000000000000000000000001425437440700176775ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/space dir/.envrc000066400000000000000000000000451425437440700210140ustar00rootroot00000000000000PATH_add "bin" export SPACE_DIR=true direnv-2.32.1/test/scenarios/special-vars/000077500000000000000000000000001425437440700204365ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/special-vars/.envrc000066400000000000000000000000001425437440700215420ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/symlink-bug/000077500000000000000000000000001425437440700203065ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/symlink-bug/baz/000077500000000000000000000000001425437440700210625ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/symlink-bug/baz/.keep000066400000000000000000000000001425437440700217750ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/symlink-bug/foo/000077500000000000000000000000001425437440700210715ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/symlink-bug/foo/.envrc000066400000000000000000000000001425437440700221750ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/symlink-bug/foo/bar000077700000000000000000000000001425437440700217112..ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/symlink-changed/000077500000000000000000000000001425437440700211225ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/symlink-changed/.envrc000066400000000000000000000000411425437440700222330ustar00rootroot00000000000000watch_file ./symlink . ./symlink direnv-2.32.1/test/scenarios/symlink-changed/.gitignore000066400000000000000000000000101425437440700231010ustar00rootroot00000000000000symlink direnv-2.32.1/test/scenarios/symlink-changed/state-A000066400000000000000000000000171425437440700223410ustar00rootroot00000000000000export STATE=A direnv-2.32.1/test/scenarios/symlink-changed/state-B000066400000000000000000000000171425437440700223420ustar00rootroot00000000000000export STATE=B direnv-2.32.1/test/scenarios/symlink-dir/000077500000000000000000000000001425437440700203075ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/symlink-dir/bar000077700000000000000000000000001425437440700214772fooustar00rootroot00000000000000direnv-2.32.1/test/scenarios/symlink-dir/foo/000077500000000000000000000000001425437440700210725ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/symlink-dir/foo/.envrc000066400000000000000000000000001425437440700221760ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/use-rvm/000077500000000000000000000000001425437440700174435ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/use-rvm/.envrc000066400000000000000000000000161425437440700205560ustar00rootroot00000000000000rvm use 1.8.7 direnv-2.32.1/test/scenarios/utf-8/000077500000000000000000000000001425437440700170105ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/utf-8/.envrc000066400000000000000000000000271425437440700201250ustar00rootroot00000000000000export UTFSTUFF=♀♂ direnv-2.32.1/test/scenarios/utils/000077500000000000000000000000001425437440700172055ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/utils/link-to-file000077700000000000000000000000001425437440700231432somefileustar00rootroot00000000000000direnv-2.32.1/test/scenarios/utils/somefile000066400000000000000000000000001425437440700207210ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/watch-dir/000077500000000000000000000000001425437440700177275ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/watch-dir/.envrc000066400000000000000000000000221425437440700210370ustar00rootroot00000000000000watch_dir testdir direnv-2.32.1/test/scenarios/watch-dir/testdir/000077500000000000000000000000001425437440700214055ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/watch-dir/testdir/subdir/000077500000000000000000000000001425437440700226755ustar00rootroot00000000000000direnv-2.32.1/test/scenarios/watch-dir/testdir/subdir/testfile000066400000000000000000000000001425437440700244250ustar00rootroot00000000000000direnv-2.32.1/test/show-direnv-diff.sh000077500000000000000000000003341425437440700175710ustar00rootroot00000000000000#!/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.32.1/test/stdlib.bash000077500000000000000000000112401425437440700162000ustar00rootroot00000000000000#!/usr/bin/env bash set -euo pipefail # always execute relative to here cd "$(dirname "$0")" # add the built direnv to the path root=$(cd .. && pwd -P) export PATH=$root:$PATH load_stdlib() { # shellcheck disable=SC1090,SC1091 source "$root/stdlib.sh" } assert_eq() { if [[ $1 != "$2" ]]; then echo "expected '$1' to equal '$2'" return 1 fi } test_name() { echo "--- $*" } test_name dotenv ( load_stdlib workdir=$(mktemp -d) trap 'rm -rf "$workdir"' EXIT cd "$workdir" # Try to source a file that doesn't exist - should not succeed dotenv .env.non_existing_file && return 1 # Try to source a file that exists echo "export FOO=bar" > .env dotenv .env [[ $FOO = bar ]] ) test_name dotenv_if_exists ( load_stdlib workdir=$(mktemp -d) trap 'rm -rf "$workdir"' EXIT cd "$workdir" # Try to source a file that doesn't exist - should succeed dotenv_if_exists .env.non_existing_file || return 1 # Try to source a file that exists echo "export FOO=bar" > .env dotenv_if_exists .env [[ $FOO = bar ]] ) test_name find_up ( load_stdlib path=$(find_up "README.md") assert_eq "$path" "$root/README.md" ) test_name source_up ( load_stdlib cd scenarios/inherited source_up ) test_name direnv_apply_dump ( tmpfile=$(mktemp) cleanup() { rm "$tmpfile"; } trap cleanup EXIT load_stdlib FOO=bar direnv dump > "$tmpfile" direnv_apply_dump "$tmpfile" assert_eq "$FOO" bar ) test_name PATH_rm ( load_stdlib export PATH=/usr/local/bin:/home/foo/bin:/usr/bin:/home/foo/.local/bin PATH_rm '/home/foo/*' assert_eq "$PATH" /usr/local/bin:/usr/bin ) test_name path_rm ( load_stdlib somevar=/usr/local/bin:/usr/bin:/home/foo/.local/bin path_rm somevar '/home/foo/*' assert_eq "$somevar" /usr/local/bin:/usr/bin ) test_name expand_path ( load_stdlib tmpdir=$(mktemp -d) trap 'rm -rf $tmpdir' EXIT cd "$tmpdir" ret=$(expand_path ./bar) assert_eq "$ret" "$tmpdir/bar" ) test_name semver_search ( load_stdlib versions=$(mktemp -d) trap 'rm -rf $versions' EXIT mkdir "$versions/program-1.4.0" mkdir "$versions/program-1.4.1" mkdir "$versions/program-1.5.0" mkdir "$versions/1.6.0" assert_eq "$(semver_search "$versions" "program-" "1.4.0")" "1.4.0" assert_eq "$(semver_search "$versions" "program-" "1.4")" "1.4.1" assert_eq "$(semver_search "$versions" "program-" "1")" "1.5.0" assert_eq "$(semver_search "$versions" "program-" "1.8")" "" assert_eq "$(semver_search "$versions" "" "1.6")" "1.6.0" assert_eq "$(semver_search "$versions" "program-" "")" "1.5.0" assert_eq "$(semver_search "$versions" "" "")" "1.6.0" ) test_name use_julia ( load_stdlib JULIA_VERSIONS=$(TMPDIR=. mktemp -d -t tmp.XXXXXXXXXX) trap 'rm -rf $JULIA_VERSIONS' EXIT test_julia() { version_prefix="$1" version="$2" # Fake the existence of a julia binary julia=$JULIA_VERSIONS/$version_prefix$version/bin/julia mkdir -p "$(dirname "$julia")" echo "#!/usr/bin/env bash echo \"test-julia $version\"" > "$julia" chmod +x "$julia" # Locally disable set -u (see https://github.com/direnv/direnv/pull/667) if ! [[ "$(set +u; use julia "$version" 2>&1)" =~ Successfully\ loaded\ test-julia\ $version ]]; then return 1 fi } # Default JULIA_VERSION_PREFIX unset JULIA_VERSION_PREFIX test_julia "julia-" "1.0.0" test_julia "julia-" "1.1" # Custom JULIA_VERSION_PREFIX JULIA_VERSION_PREFIX="jl-" test_julia "jl-" "1.2.0" test_julia "jl-" "1.3" # Empty JULIA_VERSION_PREFIX # shellcheck disable=SC2034 JULIA_VERSION_PREFIX= test_julia "" "1.4.0" test_julia "" "1.5" ) test_name source_env_if_exists ( load_stdlib workdir=$(mktemp -d) trap 'rm -rf "$workdir"' EXIT cd "$workdir" # Try to source a file that doesn't exist source_env_if_exists non_existing_file # Try to source a file that exists echo "export FOO=bar" > existing_file source_env_if_exists existing_file [[ $FOO = bar ]] # Expect correct path being logged export HOME=$workdir output="$(source_env_if_exists existing_file 2>&1 > /dev/null)" [[ "${output#*'loading ~/existing_file'}" != "$output" ]] ) test_name env_vars_required ( load_stdlib export FOO=1 env_vars_required FOO # these should all fail # shellcheck disable=SC2034 BAR=1 export BAZ= output="$(env_vars_required BAR BAZ MISSING 2>&1 > /dev/null || echo "--- result: $?")" [[ "${output#*'--- result: 1'}" != "$output" ]] [[ "${output#*'BAR is required'}" != "$output" ]] [[ "${output#*'BAZ is required'}" != "$output" ]] [[ "${output#*'MISSING is required'}" != "$output" ]] ) # test strict_env and unstrict_env ./strict_env_test.bash echo OK direnv-2.32.1/test/strict_env_test.bash000077500000000000000000000026361425437440700201470ustar00rootroot00000000000000#! /usr/bin/env bash # Note: this is _explicitly_ not setting `set -euo pipefail` # because we are testing functions that configure that. declare base expected actual base="${TMPDIR:-/tmp}/$(basename "$0").$$" expected="$base".expected actual="$base".actual declare -i success success=0 # always execute relative to here cd "$(dirname "$0")" || exit 1 # add the built direnv to the path root=$(cd .. && pwd -P) export PATH=$root:$PATH load_stdlib() { # shellcheck disable=SC1090 source "$root/stdlib.sh" } test_fail() { echo "FAILED $*: expected is not actual" exit 1 } test_strictness() { local step step="$1" echo "$2" > "$expected" set -o | grep 'errexit\|nounset\|pipefail' > "$actual" diff -u "$expected" "$actual" || test_fail "$step" (( success += 1 )) } load_stdlib test_strictness 'after source' $'errexit off nounset off pipefail off' strict_env test_strictness 'after strict_env' $'errexit on nounset on pipefail on' unstrict_env echo HELLO > /dev/null test_strictness "after unstrict_env with command" $'errexit on nounset on pipefail on' strict_env echo HELLO > /dev/null test_strictness "after strict_env with command" $'errexit on nounset on pipefail on' unstrict_env test_strictness 'after unstrict_env' $'errexit off nounset off pipefail off' echo "OK ($success tests)" direnv-2.32.1/version.txt000066400000000000000000000000071425437440700153230ustar00rootroot000000000000002.32.1 direnv-2.32.1/xdg/000077500000000000000000000000001425437440700136625ustar00rootroot00000000000000direnv-2.32.1/xdg/xdg.go000066400000000000000000000027511425437440700150000ustar00rootroot00000000000000// Package xdg is a minimal implementation of the XDG specification. // // https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html package xdg import ( "path/filepath" ) // DataDir returns the data folder for the application func DataDir(env map[string]string, programName string) string { if env["XDG_DATA_HOME"] != "" { return filepath.Join(env["XDG_DATA_HOME"], programName) } else if env["HOME"] != "" { return filepath.Join(env["HOME"], ".local", "share", programName) } // In theory we could also read /etc/passwd and look for the home based on // the process' UID return "" } // ConfigDir returns the config folder for the application // // The XDG_CONFIG_DIRS case is not being handled func ConfigDir(env map[string]string, 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 based on // the process' UID return "" } // CacheDir returns the cache directory for the application func CacheDir(env map[string]string, programName string) string { if env["XDG_CACHE_HOME"] != "" { return filepath.Join(env["XDG_CACHE_HOME"], programName) } else if env["HOME"] != "" { return filepath.Join(env["HOME"], ".cache", programName) } // In theory we could also read /etc/passwd and look for the home based on // the process' UID return "" }