insomnimus / ps-dotenv

A feature complete and unintrusive direnv for Powershell Core
MIT License
65 stars 3 forks source link

`$Dotenv.Quiet = $true` does not disable the prompt: dotenv info: .env is not authorized, authorize it with `Approve-DotenvFile` or disable the safe mode #4

Closed brian6932 closed 1 year ago

brian6932 commented 1 year ago

Neither does $Dotenv.SafeMode = $false, both are in $profile

insomnimus commented 1 year ago

I'm not able to reproduce the problem. Are you on the latest version?

PS T:\> mkdir foo; "" > foo/.env

foo

PS T:\> $dotenv.Enabled = $false
PS T:\> cd foo
PS T:\foo> cd ..
PS T:\> $dotenv.Enabled = $true
PS T:\> cd foo/
PS T:\foo> dotenv info: T:\foo\.env is not authorized, authorize it with `Approve-DotenvFile` or disable the safe mode
You can turn this message off by setting `$Dotenv.Quiet = $true`
PS T:\foo> cd ..
PS T:\> $dotenv.Quiet = $true
PS T:\> cd foo
PS T:\foo>
brian6932 commented 1 year ago

Yea I'm on 1.0.0, I have:

$Dotenv.SafeMode = $false
$Dotenv.Quiet = $true

in my $profile, and I still get that message

Now to be clear, the env vars are loaded in from the .env file, just that warning doesn't go away for me.

insomnimus commented 1 year ago

This is very odd... I'm still not able to reproduce the issue on my end.

Can you show your prompt function and how you import Dotenv?

brian6932 commented 1 year ago
  1. I open explorer to the path I want which contains a .env file. Note, this doesn't happen when the path doesn't contain a .env file
  2. I alt + d then type alacritty, using pwsh directly shows the same dialogue tho
  3. I get the top text image
insomnimus commented 1 year ago

Uhm I'm actually visually impaired and can't read images without OCR (I use a screen reader). Could you provide text?

insomnimus commented 1 year ago

Actually if you can provide me with a sample profile script that reproduces the problem, that will be the best way to go about it.

brian6932 commented 1 year ago

Uhm I'm actually visually impaired and can't read images without OCR (I use a screen reader). Could you provide text?

oh sry, here you go:

dotenv info: .env is not authorized, authorize it with `Approve-DotenvFile` or disable the safe mode
You can turn this message off by setting `$Dotenv.Quiet = $true`
❯ $Dotenv.SafeMode
False
❯ $Dotenv.Quiet
True

Actually if you can provide me with a sample profile script that reproduces the problem, that will be the best way to go about it.

Regarding dotenv, this is all I have in my $profile

Enable-Dotenv
$Dotenv.SafeMode = $false
$Dotenv.Quiet = $true
insomnimus commented 1 year ago

What's your prompt function like?

brian6932 commented 1 year ago

It's set by oh-my-posh, a slightly modified version of their Pure theme, with transient_prompt removed.

Brian ~ 
❯ ]0;(Admin) ~
oh-my-posh --init --shell pwsh --config ~\pureCustom.omp.json | Invoke-Expression
insomnimus commented 1 year ago

You can post the output of "$function:prompt"

That will print the function body, which is enough.

brian6932 commented 1 year ago

        # store the orignal last command execution status
        if ($global:NVS_ORIGINAL_LASTEXECUTIONSTATUS -is [bool]) {
            # make it compatible with NVS auto-switching, if enabled
            $script:OriginalLastExecutionStatus = $global:NVS_ORIGINAL_LASTEXECUTIONSTATUS
        } else {
            $script:OriginalLastExecutionStatus = $?
        }
        # store the orignal last exit code
        $script:OriginalLastExitCode = $global:LASTEXITCODE

        Set-PoshPromptType
        if ($script:PromptType -ne 'transient') {
            Update-PoshErrorCode
        }
        $cleanPSWD = Get-CleanPSWD
        $stackCount = global:Get-PoshStackCount
        Set-PoshContext
        $terminalWidth = $Host.UI.RawUI.WindowSize.Width
        # set a sane default when the value can't be retrieved
        if (-not $terminalWidth) {
            $terminalWidth = 0
        }
        $standardOut = @(Start-Utf8Process $script:OMPExecutable @("print", $script:PromptType, "--error=$script:ErrorCode", "--pswd=$cleanPSWD", "--execution-time=$script:ExecutionTime", "--stack-count=$stackCount", "--config=$env:POSH_THEME", "--shell-version=$script:PSVersion", "--terminal-width=$terminalWidth", "--shell=$script:ShellName"))
        # make sure PSReadLine knows if we have a multiline prompt
        Set-PSReadLineOption -ExtraPromptLineCount (($standardOut | Measure-Object -Line).Lines - 1)
        # the output can be multiline, joining these ensures proper rendering by adding line breaks with `n
        $standardOut -join "`n"

        # remove any posh-git status
        $env:POSH_GIT_STATUS = $null

        # restore the orignal last exit code
        $global:LASTEXITCODE = $script:OriginalLastExitCode
insomnimus commented 1 year ago

Hmm... This is interesting because as far as I can tell, this does not call Update-Dotenv.

Could you execute every line below one by one (interactively; not in a script) and paste the output?

mkdir foo; "BAR=42" > foo/.env
$dotenv.quiet = $dotenv.enabled = $true
$dotenv.safemode = $false
cd foo
$env:BAR
brian6932 commented 1 year ago
Brian ~\test
❯ mkdir foo

        Directory: ~\test

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d----        12/23/2022   9:57 AM                  foo

Brian ~\test
❯ "BAR=42" > foo/.env
Brian ~\test
❯ $dotenv.quiet = $dotenv.enabled = $true
Brian ~\test
❯ $dotenv.safemode = $false
Brian ~\test
❯ cd foo
Brian ~\test\foo
❯ $env:BAR
Brian ~\test\foo
❯
insomnimus commented 1 year ago

So as I suspected your prompt does not call Update-Dotenv.

I don't use oh-my-psoh but I'd guess they preserve the old prompt somehow. So, before importing oh-my-posh, define your prompt function as shown in the readme

Then try the same test as you did in the comment above.

Inside the foo directory, $env:BAR should be 42.

brian6932 commented 1 year ago

Ok I added this Using this doesn't seem to work at all However, it doesn't show in $function:prompt, oh-my-posh just seems to overwrite it, even if I put place the function after oh-my-posh, it only results in the prompt theme going back to default. However, if the oh-my-posh line in $profile is commented out, it works (on cd).

I noticed, that the dialogue even after doing all this doesn't go away when launching the shell in a path with a .env file, but it does go away when cd-ing to the paths.

insomnimus commented 1 year ago

Aha! Yes, I can reproduce this. Thank you for your efforts, I'll try to figure out why this happens and fix it when I get the time to do so (probably in the first week of 2023).

insomnimus commented 1 year ago

I'm so sorry this took so long. I've been pretty busy and forgot about this issue along the way.

This commit fixes the issue.

brian6932 commented 1 year ago

This issue still seems to occur for me, even when I remove everything $function:prompt related, and just use DotEnv

dotenv info: .env is not authorized, authorize it with `Approve-DotenvFile` or disable the safe mode
You can turn this message off by setting `$Dotenv.Quiet = $true`
> $function:prompt

    # Print the built-in prompt:
    $(if (Test-Path variable:/PSDebugContext) { '[DBG]: ' }
        else { '' }) + 'PS ' + $(Get-Location) +
    $(if ($NestedPromptLevel -ge 1) { '>>' }) + '> '

    # We check if the command exists to not cause any errors.
    if(Test-Path function:/Update-Dotenv) { Dotenv\Update-Dotenv }

> $dotenv

LoggingPreference  : Dotenv.Logging.LoggingPreference
AuthorizedPatterns : {}
SafeMode           : False
Names              : {.env}
Sourced            : {.env, .env}
Logs               : {}
Enabled            : True
Async              : True
SkipErrors         : False
Quiet              : True
insomnimus commented 1 year ago

That's odd, does it at least load the environment variables?

insomnimus commented 1 year ago

Actually which installation method did you follow? Also could you post the output of (get-module Dotenv).version ? For reference, I'm not getting the problem with v1.0.1 from the releases page.

brian6932 commented 1 year ago
❯ (Get-Module Dotenv).Version

Major  Minor  Build  Revision
-----  -----  -----  --------
1      0      1      -1

That's odd, does it at least load the environment variables?

Yea

Actually which installation method did you follow?

I use scoop, I did verify that all the files and libraries were the same as the latest release

insomnimus commented 1 year ago

I'm trying to reproduce this but haven't been able to. Is there anything else you can think of that might be messing with it? Like say an older version in PSMODULEPATH?

You can also try manually applying the change, if it's somehow not applied:

# in Dotenv.psm1
[string]$lastdir = $PWD.ProviderPath
# ^ change above to
[string]$lastdir = ""
brian6932 commented 1 year ago
❯ cat "$(fd dotenv ($env:PSModulePath -split ';'))\Dotenv\Dotenv.psm1"
New-Variable -Option ReadOnly Dotenv ([Dotenv.Daemon]::new())

$ExecutionContext.SessionState.Module.OnRemove += {
        if($global:Dotenv.Enabled) {
                Write-Host "dotenv: unloading..."
                $global:Dotenv.Disable()
                remove-item -force -ea silentlyContinue variable:/Dotenv
        }
}

[string]$lastdir = ""
insomnimus commented 1 year ago

Alright after failing to reproduce on my machine I've decided to spin up a VM. Finally reproduced it. I think I fixed it. Try the latest release: Dotenv V1.0.2.

Thanks for your patience!

brian6932 commented 1 year ago

Hey sorry for the late response, I was on vacation. It is solved now, thank you.