haskell-scfg

[MIRROR] Haskell library for scfg

git clone git://git.marius.pm/haskell-scfg.git

 1{-# LANGUAGE OverloadedStrings #-}
 2
 3-- | Canonical formatter for scfg configurations.
 4module Data.Scfg.Formatter (format) where
 5
 6import Data.Scfg.Types
 7import Data.Text (Text)
 8import qualified Data.Text as T
 9
10{- | Format a 'Config' as canonical scfg text. All words are
11double-quoted and blocks are indented with tabs.
12-}
13format :: [Directive] -> Text
14format = foldMap (formatDirective 0)
15
16formatDirective :: Int -> Directive -> Text
17formatDirective depth d =
18  indent
19    <> quoteWord (directiveName d)
20    <> params
21    <> block
22    <> "\n"
23 where
24  indent = T.replicate depth "\t"
25  params = case directiveParams d of
26    [] -> ""
27    ps -> " " <> T.unwords (map quoteWord ps)
28  block = case directiveChildren d of
29    [] -> ""
30    cs ->
31      " {\n"
32        <> foldMap (formatDirective (depth + 1)) cs
33        <> indent
34        <> "}"
35
36quoteWord :: Text -> Text
37quoteWord t = "\"" <> T.concatMap escape t <> "\""
38 where
39  escape '"' = "\\\""
40  escape '\\' = "\\\\"
41  escape c = T.singleton c