packages feed

hwm-0.1.2 / src / HWM / Core / Formatting.hs

{-# LANGUAGE FlexibleInstances #-}{-# LANGUAGE OverloadedStrings #-}{-# LANGUAGE NoImplicitPrelude #-}{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}{-# HLINT ignore "Eta reduce" #-}module HWM.Core.Formatting  ( Color (..),    chalk,    formatStatus,    Status (..),    padDots,    genMaxLen,    separator,    deriveStatus,    statusFromSeverity,    statusIcon,    isOk,    displayStatus,    Format (..),    availableOptions,    renderSummaryStatus,    subPathSign,    slugify,    commonPrefix,    indentBlockNum,    indentBlock,    formatTable,    formatList,    monadStatus,    formatTemplate,  )whereimport Data.Aeson (Value, encode)import Data.ByteString.Lazy.Char8 (unpack)import Data.Foldable (maximum)import qualified Data.List as Listimport Data.Text (pack)import qualified Data.Text as Timport HWM.Core.Result (MonadIssue (catchIssues), Severity (..))import Reludedata Color  = Red  | Green  | Yellow  | Gray  | Magenta  | Cyan  | Dim  | Bold  | White  | None  | RedBackground  | GreenBackground  | YellowBackground  | BrightRed  | BrightGreen  | BrightYellowtoColor :: Color -> TexttoColor c = "\x1b[" <> T.pack (show (colorCode c)) <> "m"colorCode :: Color -> IntcolorCode Red = 31colorCode Green = 32colorCode Yellow = 33colorCode Cyan = 36colorCode Magenta = 95colorCode Gray = 90colorCode Dim = 2colorCode None = 0colorCode Bold = 1colorCode RedBackground = 41colorCode GreenBackground = 42colorCode YellowBackground = 43colorCode BrightRed = 91colorCode BrightGreen = 92colorCode BrightYellow = 93colorCode White = 37chalk :: Color -> Text -> Textchalk c x = toColor c <> x <> toColor Nonedata Status = Checked | Updated | Warning | Invalid  deriving (Show, Eq, Ord)deriveStatus :: [Status] -> StatusderiveStatus [] = CheckedderiveStatus statuses = maximum statuses-- | Convert issue severity to statusstatusFromSeverity :: Maybe Severity -> StatusstatusFromSeverity (Just SeverityError) = InvalidstatusFromSeverity (Just SeverityWarning) = WarningstatusFromSeverity Nothing = CheckedmonadStatus :: (Functor m, MonadIssue m) => m b -> m StatusmonadStatus x = statusFromSeverity . fst <$> catchIssues xdisplayStatus :: [(Text, Status)] -> TextdisplayStatus ls =  let status = deriveStatus (map snd ls)   in if isOk status then statusIcon status else formatStatus lsformatTemplate :: [(Text, Text)] -> Text -> TextformatTemplate vars template =  foldl' applyVar template vars  where    applyVar current (key, val) =      T.replace ("{{" <> key <> "}}") val currentpadDots :: Int -> Text -> TextpadDots width s = s <> " " <> chalk Dim (T.replicate (max 0 (width - T.length s)) ".") <> " "isOk :: Status -> BoolisOk Checked = TrueisOk Updated = TrueisOk _ = FalselabelColor :: Status -> ColorlabelColor Checked = DimlabelColor Updated = DimlabelColor Warning = YellowlabelColor Invalid = RedstatusIcon :: Status -> TextstatusIcon s = case s of  Checked -> chalk Green "✓"  Updated -> chalk Cyan "⟳"  Invalid -> chalk Red "✖"  Warning -> chalk Yellow "!"formatStatus :: [(Text, Status)] -> TextformatStatus = T.intercalate (chalk Dim " ") . map formatItem . sortBy (comparing (Down . snd)) . filter ((/= Checked) . snd)  where    formatItem (label, s) = statusIcon s <> " " <> chalk (labelColor s) labelgenMaxLen :: [Text] -> IntgenMaxLen names = if null names then 16 else maximum (map T.length names) + 4separator :: Int -> Textseparator size = chalk Gray $ T.replicate size "─"class Format a where  format :: a -> Textinstance Format Int where  format = showinstance Format String where  format = packinstance Format Text where  format = idinstance Format Value where  format = format . unpack . encodeavailableOptions :: (Format a) => [a] -> TextavailableOptions xs = "Available options: " <> T.intercalate ", " (map format xs)boxed :: Color -> Text -> Textboxed color text = chalk Bold "• " <> block <> " " <> chalk color text <> " " <> block  where    block = chalk color "▌"renderSummaryStatus :: Status -> TextrenderSummaryStatus Warning = boxed BrightYellow "warning"renderSummaryStatus Invalid = boxed Red "errors"renderSummaryStatus _ = boxed BrightGreen "success"subPathSign :: TextsubPathSign = chalk Dim "└─- "slugify :: Text -> Textslugify = T.map replaceChar . T.toLower  where    replaceChar c      | c == ' ' = '-'      | c == '_' = '-'      | c == '.' = '-'      | otherwise = ccommonPrefix :: [Text] -> (Maybe Text, [Text])commonPrefix [] = (Nothing, [])commonPrefix [name] = (Nothing, [name])commonPrefix names =  refine names (T.dropWhileEnd (== '-') (List.foldl1' pairwisePrefix names))  where    pairwisePrefix a b = maybe "" (\(prefix, _, _) -> prefix) (T.commonPrefixes a b)    refine _ candidate | T.null candidate = (Nothing, names)    refine sources candidate      | all (matches candidate) sources = (Just candidate, map (dropPrefix candidate) sources)      | otherwise = refine sources (shrink candidate)    matches prefix name      | prefix == name = True      | prefix `T.isPrefixOf` name = startsWithHyphen (T.drop (T.length prefix) name)      | otherwise = False    startsWithHyphen remainder =      case T.uncons remainder of        Nothing -> True        Just ('-', _) -> True        _ -> False    shrink prefix =      case T.breakOnEnd "-" prefix of        (rest, _) | T.null rest -> ""        (rest, _) -> T.dropWhileEnd (== '-') rest    dropPrefix prefix text =      let name = fromMaybe "" (T.stripPrefix prefix text)       in if T.null name            then "."            else fromMaybe name (T.stripPrefix "-" name)indentBlockNum :: Int -> Text -> TextindentBlockNum i = indentBlock (T.replicate (i * 2) " ")indentBlock :: Text -> Text -> TextindentBlock prefix text  | T.null text = text  | otherwise =      let linesList = T.lines text          indented = map (prefix <>) linesList          joined = T.intercalate "\n" indented       in if T.isSuffixOf "\n" text            then joined <> "\n"            else joinedtype Table = [Row]type Row = [Text]getSizes :: Table -> [Int]getSizes xs = map size (transpose xs)  where    size :: Row -> Int    size = maximum . map T.lengthprintRow :: [Int] -> Row -> TextprintRow sizes ls =  T.strip    $ T.intercalate "  "    $ zipWith (\item s -> T.justifyLeft s ' ' item) ls sizesformatTable :: [Text] -> [Text]formatTable deps = sort $ map (printRow (getSizes table)) table  where    table = map words depsformatList :: (Format a) => Text -> [a] -> TextformatList x = T.intercalate x . map format