forked from commercialhaskell/stack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackT.hs
More file actions
420 lines (377 loc) · 15.2 KB
/
StackT.hs
File metadata and controls
420 lines (377 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
{-# LANGUAGE CPP #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | The monad used for the command-line executable @stack@.
module Stack.Types.StackT
(StackT
,StackLoggingT
,runStackT
,runStackTGlobal
,runStackLoggingT
,runStackLoggingTGlobal
,runInnerStackT
,runInnerStackLoggingT
,newTLSManager
,logSticky
,logStickyDone)
where
import Control.Applicative
import Control.Concurrent.MVar
import Control.Monad
import Control.Monad.Base
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader hiding (lift)
import Control.Monad.Trans.Control
import qualified Data.ByteString.Char8 as S8
import Data.Char
import Data.List (stripPrefix)
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import qualified Data.Text.IO as T
import Data.Time
import GHC.Foreign (withCString, peekCString)
import Language.Haskell.TH
import Language.Haskell.TH.Syntax (lift)
import Network.HTTP.Client.Conduit (HasHttpManager(..))
import Network.HTTP.Conduit
import Prelude -- Fix AMP warning
import System.FilePath
import Stack.Types.Config (GlobalOpts (..))
import Stack.Types.Internal
import System.Console.ANSI
import System.IO
import System.Log.FastLogger
#ifndef MIN_VERSION_time
#define MIN_VERSION_time(x, y, z) 0
#endif
#if !MIN_VERSION_time(1, 5, 0)
import System.Locale
#endif
--------------------------------------------------------------------------------
-- Main StackT monad transformer
-- | The monad used for the executable @stack@.
newtype StackT config m a =
StackT {unStackT :: ReaderT (Env config) m a}
deriving (Functor,Applicative,Monad,MonadIO,MonadReader (Env config),MonadThrow,MonadCatch,MonadMask,MonadTrans)
deriving instance (MonadBase b m) => MonadBase b (StackT config m)
instance MonadBaseControl b m => MonadBaseControl b (StackT config m) where
type StM (StackT config m) a = ComposeSt (StackT config) m a
liftBaseWith = defaultLiftBaseWith
restoreM = defaultRestoreM
instance MonadTransControl (StackT config) where
type StT (StackT config) a = StT (ReaderT (Env config)) a
liftWith = defaultLiftWith StackT unStackT
restoreT = defaultRestoreT StackT
-- | Takes the configured log level into account.
instance MonadIO m => MonadLogger (StackT config m) where
monadLoggerLog = stickyLoggerFunc
instance MonadIO m => MonadLoggerIO (StackT config m) where
askLoggerIO = getStickyLoggerFunc
-- | Run a Stack action, using global options.
runStackTGlobal :: (MonadIO m)
=> Manager -> config -> GlobalOpts -> StackT config m a -> m a
runStackTGlobal manager config GlobalOpts{..} =
runStackT manager globalLogLevel config globalTerminal (isJust globalReExecVersion)
-- | Run a Stack action.
runStackT :: (MonadIO m)
=> Manager -> LogLevel -> config -> Bool -> Bool -> StackT config m a -> m a
runStackT manager logLevel config terminal reExec m = do
ansiTerminal <- liftIO $ hSupportsANSI stderr
canUseUnicode <- liftIO getCanUseUnicode
withSticky
terminal
(\sticky ->
runReaderT
(unStackT m)
(Env config logLevel terminal ansiTerminal reExec manager sticky canUseUnicode))
-- | Taken from GHC: determine if we should use Unicode syntax
getCanUseUnicode :: IO Bool
getCanUseUnicode = do
let enc = localeEncoding
str = "\x2018\x2019"
test = withCString enc str $ \cstr -> do
str' <- peekCString enc cstr
return (str == str')
test `catchIOError` \_ -> return False
--------------------------------------------------------------------------------
-- Logging only StackLoggingT monad transformer
-- | Monadic environment for 'StackLoggingT'.
data LoggingEnv = LoggingEnv
{ lenvLogLevel :: !LogLevel
, lenvTerminal :: !Bool
, lenvAnsiTerminal :: !Bool
, lenvReExec :: !Bool
, lenvManager :: !Manager
, lenvSticky :: !Sticky
, lenvSupportsUnicode :: !Bool
}
-- | The monad used for logging in the executable @stack@ before
-- anything has been initialized.
newtype StackLoggingT m a = StackLoggingT
{ unStackLoggingT :: ReaderT LoggingEnv m a
} deriving (Functor,Applicative,Monad,MonadIO,MonadThrow,MonadReader LoggingEnv,MonadCatch,MonadMask,MonadTrans)
deriving instance (MonadBase b m) => MonadBase b (StackLoggingT m)
instance MonadBaseControl b m => MonadBaseControl b (StackLoggingT m) where
type StM (StackLoggingT m) a = ComposeSt StackLoggingT m a
liftBaseWith = defaultLiftBaseWith
restoreM = defaultRestoreM
instance MonadTransControl StackLoggingT where
type StT StackLoggingT a = StT (ReaderT LoggingEnv) a
liftWith = defaultLiftWith StackLoggingT unStackLoggingT
restoreT = defaultRestoreT StackLoggingT
-- | Takes the configured log level into account.
instance (MonadIO m) => MonadLogger (StackLoggingT m) where
monadLoggerLog = stickyLoggerFunc
instance HasSticky LoggingEnv where
getSticky = lenvSticky
instance HasLogLevel LoggingEnv where
getLogLevel = lenvLogLevel
instance HasHttpManager LoggingEnv where
getHttpManager = lenvManager
instance HasTerminal LoggingEnv where
getTerminal = lenvTerminal
getAnsiTerminal = lenvAnsiTerminal
instance HasReExec LoggingEnv where
getReExec = lenvReExec
instance HasSupportsUnicode LoggingEnv where
getSupportsUnicode = lenvSupportsUnicode
runInnerStackT :: (HasHttpManager r, HasLogLevel r, HasTerminal r, HasReExec r, MonadReader r m, MonadIO m)
=> config -> StackT config IO a -> m a
runInnerStackT config inner = do
manager <- asks getHttpManager
logLevel <- asks getLogLevel
terminal <- asks getTerminal
reExec <- asks getReExec
liftIO $ runStackT manager logLevel config terminal reExec inner
runInnerStackLoggingT :: (HasHttpManager r, HasLogLevel r, HasTerminal r, HasReExec r, MonadReader r m, MonadIO m)
=> StackLoggingT IO a -> m a
runInnerStackLoggingT inner = do
manager <- asks getHttpManager
logLevel <- asks getLogLevel
terminal <- asks getTerminal
reExec <- asks getReExec
liftIO $ runStackLoggingT manager logLevel terminal reExec inner
-- | Run the logging monad, using global options.
runStackLoggingTGlobal :: MonadIO m
=> Manager -> GlobalOpts -> StackLoggingT m a -> m a
runStackLoggingTGlobal manager GlobalOpts{..} =
runStackLoggingT manager globalLogLevel globalTerminal (isJust globalReExecVersion)
-- | Run the logging monad.
runStackLoggingT :: MonadIO m
=> Manager -> LogLevel -> Bool -> Bool -> StackLoggingT m a -> m a
runStackLoggingT manager logLevel terminal reExec m = do
ansiTerminal <- liftIO $ hSupportsANSI stderr
canUseUnicode <- liftIO getCanUseUnicode
withSticky
terminal
(\sticky ->
runReaderT
(unStackLoggingT m)
LoggingEnv
{ lenvLogLevel = logLevel
, lenvManager = manager
, lenvSticky = sticky
, lenvTerminal = terminal
, lenvAnsiTerminal = ansiTerminal
, lenvReExec = reExec
, lenvSupportsUnicode = canUseUnicode
})
-- | Convenience for getting a 'Manager'
newTLSManager :: MonadIO m => m Manager
newTLSManager = liftIO $ newManager tlsManagerSettings
--------------------------------------------------------------------------------
-- Logging functionality
stickyLoggerFunc
:: (HasSticky r, HasLogLevel r, HasSupportsUnicode r, HasTerminal r, ToLogStr msg, MonadReader r m, MonadIO m)
=> Loc -> LogSource -> LogLevel -> msg -> m ()
stickyLoggerFunc loc src level msg = do
func <- getStickyLoggerFunc
liftIO $ func loc src level msg
getStickyLoggerFunc
:: (HasSticky r, HasLogLevel r, HasSupportsUnicode r, HasTerminal r, ToLogStr msg, MonadReader r m)
=> m (Loc -> LogSource -> LogLevel -> msg -> IO ())
getStickyLoggerFunc = do
sticky <- asks getSticky
logLevel <- asks getLogLevel
supportsUnicode <- asks getSupportsUnicode
supportsAnsi <- asks getAnsiTerminal
return $ stickyLoggerFuncImpl sticky logLevel supportsUnicode supportsAnsi
stickyLoggerFuncImpl
:: ToLogStr msg
=> Sticky -> LogLevel -> Bool -> Bool
-> (Loc -> LogSource -> LogLevel -> msg -> IO ())
stickyLoggerFuncImpl (Sticky mref) maxLogLevel supportsUnicode supportsAnsi loc src level msg =
case mref of
Nothing ->
loggerFunc
supportsAnsi
maxLogLevel
out
loc
src
(case level of
LevelOther "sticky-done" -> LevelInfo
LevelOther "sticky" -> LevelInfo
_ -> level)
msg
Just ref -> do
sticky <- takeMVar ref
let backSpaceChar = '\8'
repeating = S8.replicate (maybe 0 T.length sticky)
clear = S8.hPutStr out
(repeating backSpaceChar <>
repeating ' ' <>
repeating backSpaceChar)
-- Convert some GHC-generated Unicode characters as necessary
let msgText
| supportsUnicode = msgTextRaw
| otherwise = T.map replaceUnicode msgTextRaw
newState <-
case level of
LevelOther "sticky-done" -> do
clear
T.hPutStrLn out msgText
hFlush out
return Nothing
LevelOther "sticky" -> do
clear
T.hPutStr out msgText
hFlush out
return (Just msgText)
_
| level >= maxLogLevel -> do
clear
loggerFunc supportsAnsi maxLogLevel out loc src level $ toLogStr msgText
case sticky of
Nothing ->
return Nothing
Just line -> do
T.hPutStr out line >> hFlush out
return sticky
| otherwise ->
return sticky
putMVar ref newState
where
out = stderr
msgTextRaw = T.decodeUtf8With T.lenientDecode msgBytes
msgBytes = fromLogStr (toLogStr msg)
-- | Replace Unicode characters with non-Unicode equivalents
replaceUnicode :: Char -> Char
replaceUnicode '\x2018' = '`'
replaceUnicode '\x2019' = '\''
replaceUnicode c = c
-- | Logging function takes the log level into account.
loggerFunc :: ToLogStr msg
=> Bool -> LogLevel -> Handle -> Loc -> Text -> LogLevel -> msg -> IO ()
loggerFunc supportsAnsi maxLogLevel outputChannel loc _src level msg =
when (level >= maxLogLevel)
(liftIO (do out <- getOutput
T.hPutStrLn outputChannel out))
where
getOutput = do
timestamp <- getTimestamp
l <- getLevel
lc <- getLoc
return $ T.concat
[ T.pack timestamp
, T.pack l
, T.pack (ansi [Reset])
, T.decodeUtf8 (fromLogStr (toLogStr msg))
, T.pack lc
, T.pack (ansi [Reset])
]
where
ansi xs | supportsAnsi = setSGRCode xs
| otherwise = ""
getTimestamp
| maxLogLevel <= LevelDebug =
do now <- getZonedTime
return $
ansi [SetColor Foreground Vivid Black]
++ formatTime' now ++ ": "
| otherwise = return ""
where
formatTime' =
take timestampLength . formatTime defaultTimeLocale "%F %T.%q"
getLevel
| maxLogLevel <= LevelDebug =
return ((case level of
LevelDebug -> ansi [SetColor Foreground Dull Green]
LevelInfo -> ansi [SetColor Foreground Dull Blue]
LevelWarn -> ansi [SetColor Foreground Dull Yellow]
LevelError -> ansi [SetColor Foreground Dull Red]
LevelOther _ -> ansi [SetColor Foreground Dull Magenta]) ++
"[" ++
map toLower (drop 5 (show level)) ++
"] ")
| otherwise = return ""
getLoc
| maxLogLevel <= LevelDebug =
return $
ansi [SetColor Foreground Vivid Black] ++
"\n@(" ++ fileLocStr ++ ")"
| otherwise = return ""
fileLocStr =
fromMaybe file (stripPrefix dirRoot file) ++
':' :
line loc ++
':' :
char loc
where
file = loc_filename loc
line = show . fst . loc_start
char = show . snd . loc_start
dirRoot = $(lift . T.unpack . fromJust . T.stripSuffix (T.pack $ "Stack" </> "Types" </> "StackT.hs") . T.pack . loc_filename =<< location)
-- | The length of a timestamp in the format "YYYY-MM-DD hh:mm:ss.μμμμμμ".
-- This definition is top-level in order to avoid multiple reevaluation at runtime.
timestampLength :: Int
timestampLength =
length (formatTime defaultTimeLocale "%F %T.000000" (UTCTime (ModifiedJulianDay 0) 0))
-- | With a sticky state, do the thing.
withSticky :: (MonadIO m)
=> Bool -> (Sticky -> m b) -> m b
withSticky terminal m =
if terminal
then do state <- liftIO (newMVar Nothing)
originalMode <- liftIO (hGetBuffering stdout)
liftIO (hSetBuffering stdout NoBuffering)
a <- m (Sticky (Just state))
state' <- liftIO (takeMVar state)
liftIO (when (isJust state') (S8.putStr "\n"))
liftIO (hSetBuffering stdout originalMode)
return a
else m (Sticky Nothing)
-- | Write a "sticky" line to the terminal. Any subsequent lines will
-- overwrite this one, and that same line will be repeated below
-- again. In other words, the line sticks at the bottom of the output
-- forever. Running this function again will replace the sticky line
-- with a new sticky line. When you want to get rid of the sticky
-- line, run 'logStickyDone'.
--
logSticky :: Q Exp
logSticky =
logOther "sticky"
-- | This will print out the given message with a newline and disable
-- any further stickiness of the line until a new call to 'logSticky'
-- happens.
--
-- It might be better at some point to have a 'runSticky' function
-- that encompasses the logSticky->logStickyDone pairing.
logStickyDone :: Q Exp
logStickyDone =
logOther "sticky-done"