{-# LANGUAGE Safe #-}
module Utils (checkMajorVersion
,cleanDoubleQuotes
,deEscapeSingleQuotes
,dot
,escapeSingleQuotes
,nolines
,replace
,strip
,stripUsing
,toDoubleQuotedStr
,toSingleQuotedStr
,wrap
,wrapUsing
)
where
import Data.Char (isSpace)
import Data.List (findIndices,intercalate)
import Data.List.Split (splitOn)
import Data.Maybe (fromMaybe)
import Safe (lastDef,readMay)
checkMajorVersion :: (Int -> t) -> String -> t
checkMajorVersion f s = f (fromMaybe 0 (readMay (takeWhile (/='.') s) :: Maybe Int))
strip :: String -> String
strip = stripUsing isSpace
wrap :: Int -> String -> [String]
wrap = wrapUsing isSpace
stripUsing :: (a -> Bool) -> [a] -> [a]
stripUsing p = dropWhile p . reverse . dropWhile p . reverse
wrapUsing :: (a -> Bool) -> Int -> [a] -> [[a]]
wrapUsing p l s =
if length s' < l || null is
then [s']
else hd:wrapUsing p l tl
where s' = stripUsing p s
is = findIndices p s'
(hd, tl) = splitAt i s'
i = (lastDef (head is) . takeWhile (<=l)) is
dot :: FilePath
dot = "."
toDoubleQuotedStr :: String -> String
toDoubleQuotedStr = replace "\"" "'" . stripUsing (=='\'') . replace "\\'" "\""
toSingleQuotedStr :: String -> String
toSingleQuotedStr s = "'" ++ escapeSingleQuotes s ++ "'"
deEscapeSingleQuotes :: String -> String
deEscapeSingleQuotes = replace "\\'" "'"
escapeSingleQuotes :: String -> String
escapeSingleQuotes = replace "'" "\\'"
nolines :: String -> String
nolines = replace "\n" " "
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace needle replacement haystack =
intercalate replacement (splitOn needle haystack)
cleanDoubleQuotes :: String -> String
cleanDoubleQuotes = replace "\"" "" . replace "\\\"" "'"