Utils.hs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. {-# LANGUAGE OverloadedStrings #-}
  2. module Collage.Utils
  3. ( cOutput
  4. , cDebug
  5. , cWarn
  6. , cError
  7. , cOpenFile
  8. , throw
  9. , F.format
  10. , (F.%)
  11. , F.stext
  12. , F.text
  13. , F.string
  14. , F.shown
  15. ) where
  16. import qualified Formatting as F
  17. import qualified Data.Text.Lazy as TL
  18. import qualified Data.Text.Lazy.Builder as TL
  19. import qualified Data.Text.Lazy.IO as TL
  20. import qualified System.Directory as Sys
  21. import qualified System.Exit as Sys
  22. import qualified System.IO as Sys
  23. import qualified System.Posix.IO as Posix
  24. import qualified System.Posix.Terminal as Posix
  25. import Prelude (FilePath, IO, Either(Left), ($))
  26. throw :: F.Format (Either TL.Text r) a -> a
  27. throw f =
  28. F.runFormat f (\ b -> Left (TL.toLazyText b))
  29. stderr :: TL.Text -> IO ()
  30. stderr = TL.hPutStr Sys.stderr
  31. -- | Write output to stdout
  32. cOutput :: TL.Text -> IO ()
  33. cOutput = TL.putStrLn
  34. -- | Write a debug message to stderr.
  35. cDebug :: F.Format (IO ()) a -> a
  36. cDebug msg = F.runFormat msg $ \ b ->
  37. TL.hPutStrLn Sys.stderr (TL.toLazyText b)
  38. -- | Write a warning message to stderr. If we are connected to a TTY,
  39. -- then this will write in an orange color.
  40. cWarn :: F.Format (IO ()) a -> a
  41. cWarn msg = F.runFormat msg $ \b -> do
  42. isTTY <- Posix.queryTerminal Posix.stdOutput
  43. if isTTY
  44. then do stderr "\x1b[93m"
  45. stderr (TL.toLazyText b)
  46. stderr "\x1b[39m\n"
  47. else TL.hPutStrLn Sys.stderr (TL.toLazyText b)
  48. -- | Write an error message to stderr and exit. If we are connected to
  49. -- a TTY, this message will be in red.
  50. cError :: F.Format (IO r) a -> a
  51. cError msg = F.runFormat msg $ \b -> do
  52. isTTY <- Posix.queryTerminal Posix.stdOutput
  53. if isTTY
  54. then do stderr "\x1b[91m"
  55. stderr (TL.toLazyText b)
  56. stderr "\x1b[39m\n"
  57. else TL.hPutStrLn Sys.stderr (TL.toLazyText b)
  58. Sys.exitFailure
  59. cOpenFile :: TL.Text -> FilePath -> IO TL.Text
  60. cOpenFile purpose path = do
  61. exists <- Sys.doesFileExist path
  62. if exists
  63. then TL.readFile path
  64. else cError ("Unable to open " F.% F.text F.%
  65. " file at " F.% F.string) purpose path