Last active
September 25, 2017 13:57
-
-
Save webframp/4fe7ced899585228a1800e2cf41d3992 to your computer and use it in GitHub Desktop.
simplistic direnv for powershell in ~100 loc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Initialize-Direnv { | |
| if($env:DIRENV_AUTH_FILE){ | |
| if(-not (test-path $env:DIRENV_AUTH_FILE)) { return "Auth file unreadable: $env:DIRENV_AUTH_FILE" } | |
| # stole this stuff from https://github.com/lzybkr/PSReadLine/blob/master/PSReadLine/SamplePSReadlineProfile.ps1 | |
| $global:DIRENV = [System.Collections.ArrayList]@( | |
| $last = '' | |
| $lines = '' | |
| foreach ($line in [System.IO.File]::ReadLines($env:DIRENV_AUTH_FILE)) | |
| { | |
| if ($lines) | |
| { | |
| $line = "$lines`n$line" | |
| $lines = '' | |
| } | |
| if (($line -cne $last) -and (!$pattern -or ($line -match $pattern))) | |
| { | |
| $last = $line | |
| $line | |
| } | |
| } | |
| ) | |
| } | |
| } | |
| function Load-Direnv { | |
| if ($global:DIRENV){ | |
| # Direnv enabled | |
| $this_envrc = $pwd.path + "\.envrc" | |
| if ((test-path $this_envrc) -and | |
| ((gc -raw $this_envrc).Length -ne 0)){ | |
| # .envrc exists and is not empty | |
| if ($global:DIRENV -ccontains $pwd.path){ | |
| # this .envrc has been whitelisted | |
| try { | |
| # it's not empty, use it in a very unsafe way | |
| iex (gc -raw $this_envrc) | |
| } | |
| catch { | |
| Write-Warning "Invalid $this_envrc" | |
| } | |
| } else { | |
| # .envrc not whitelisted | |
| Write-Warning ".envrc found in current directory but not authorized. Ignoring" | |
| Write-Warning "use Add-Direnv $pwd.path to whitelist" | |
| } | |
| } | |
| } else { | |
| # no DIRENV var, thus uninitialized | |
| Initialize-Direnv | |
| } | |
| } | |
| function Add-Direnv($dir=$pwd.path) { | |
| Add-Content $env:DIRENV_AUTH_FILE $dir | |
| Initialize-direnv | |
| } | |
| function Remove-Direnv($dir=$pwd.path) { | |
| $global:DIRENV.Remove($dir) | |
| Set-Content $env:DIRENV_AUTH_FILE $global:DIRENV | |
| Initialize-Direnv | |
| } | |
| # Bash style: cd - | |
| function cd { | |
| if ($args[0] -eq '-') { | |
| $pwd=$OLDPWD; | |
| } else { | |
| $pwd=$args[0]; | |
| } | |
| $tmp=Get-Location; | |
| if ($pwd) { | |
| Set-Location $pwd; | |
| } | |
| Set-Variable -Name OLDPWD -Value $tmp -Scope global; | |
| if($global:DIRENV) { | |
| Load-Direnv | |
| } | |
| } | |
| if((get-command cd).CommandType -eq 'Alias'){ | |
| remove-item alias:cd | |
| } | |
| $env:DIRENV_AUTH_FILE=(join-path $env:HOME _direnv.txt) | |
| echo $null >> $env:DIRENV_AUTH_FILE | |
| Initialize-Direnv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment