{-# LANGUAGE LambdaCase #-}

module Stack.DefaultColorWhen
  ( defaultColorWhen
  ) where

import           Stack.Prelude ( stdout )
import           Stack.Types.ColorWhen ( ColorWhen (..) )
import           System.Console.ANSI ( hSupportsANSI )
import           System.Environment ( lookupEnv )

-- | The default adopts the standard proposed at http://no-color.org/, that

-- color should not be added by default if the @NO_COLOR@ environment variable

-- is present.

defaultColorWhen :: IO ColorWhen
defaultColorWhen :: IO ColorWhen
defaultColorWhen = String -> IO (Maybe String)
lookupEnv String
"NO_COLOR" IO (Maybe String) -> (Maybe String -> IO ColorWhen) -> IO ColorWhen
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
  Just String
_ -> ColorWhen -> IO ColorWhen
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ColorWhen
ColorNever
  Maybe String
_ -> Handle -> IO Bool
hSupportsANSI Handle
stdout IO Bool -> (Bool -> IO ColorWhen) -> IO ColorWhen
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
    Bool
False -> ColorWhen -> IO ColorWhen
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ColorWhen
ColorNever
    Bool
_ -> ColorWhen -> IO ColorWhen
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ColorWhen
ColorAuto