Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use bash from $SHELL when it makes sense #408

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions src/Options/Applicative/Builder/Completer.hs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ module Options.Applicative.Builder.Completer
import Control.Applicative
import Prelude
import Control.Exception (IOException, try)
import Data.List (isPrefixOf)
import Data.List (isPrefixOf, isSuffixOf)
import System.Process (readProcess)
import System.Environment (lookupEnv)

import Options.Applicative.Types

Expand All @@ -33,9 +34,23 @@ listCompleter = listIOCompleter . pure
bashCompleter :: String -> Completer
bashCompleter action = Completer $ \word -> do
let cmd = unwords ["compgen", "-A", action, "--", requote word]
result <- tryIO $ readProcess "bash" ["-c", cmd] ""
bash <- getBash
result <- tryIO $ readProcess bash ["-c", cmd] ""
return . lines . either (const []) id $ result

-- | Determines the bash executable. Ideally we'd invoke the same bash that
-- is currently active. If $SHELL does not seem to be set to a bash executable
-- we don't assume $SHELL is bash and we take bash from the $PATH.
-- This fixes file completion in cases where a virtual environment with a
-- non-interactive bash is loaded with direnv, nix-shell or similar.
getBash :: IO String
getBash = do
shellEnv <- lookupEnv "SHELL"
pure (case shellEnv of
Just exe | "/bash" `isSuffixOf` exe -> exe
_ -> "bash"
)

tryIO :: IO a -> IO (Either IOException a)
tryIO = try

Expand Down