@@ -2,12 +2,16 @@
22--
33module Hakyll.Web.Util.String
44 ( trim
5+ , replaceAll
6+ , toUrl
57 , toSiteRoot
68 ) where
79
810import Data.Char (isSpace)
11+import Data.Maybe (listToMaybe)
912
1013import System.FilePath (splitPath, takeDirectory, joinPath)
14+import Text.Regex.PCRE ((=~~))
1115
1216-- | Trim a string (drop spaces, tabs and newlines at both sides).
1317--
@@ -16,9 +20,37 @@ trim = reverse . trim' . reverse . trim'
1620 where
1721 trim' = dropWhile isSpace
1822
23+-- | A simple (but inefficient) regex replace funcion
24+--
25+replaceAll :: String -- ^ Pattern
26+ -> (String -> String) -- ^ Replacement (called on capture)
27+ -> String -- ^ Source string
28+ -> String -- ^ Result
29+replaceAll pattern f source = replaceAll' source
30+ where
31+ replaceAll' src = case listToMaybe (src =~~ pattern) of
32+ Nothing -> src
33+ Just (o, l) ->
34+ let (before, tmp) = splitAt o src
35+ (capture, after) = splitAt l tmp
36+ in before ++ f capture ++ replaceAll' after
37+
38+-- | Convert a filepath to an URL starting from the site root
39+--
40+-- Example:
41+--
42+-- > toUrl "foo/bar.html"
43+--
44+-- Result:
45+--
46+-- > "/foo/bar.html"
47+--
48+toUrl :: FilePath -> String
49+toUrl = ('/' :)
50+
1951-- | Get the relative url to the site root, for a given (absolute) url
2052--
21−toSiteRoot :: FilePath -> FilePath
53+toSiteRoot :: String -> String
2254toSiteRoot = emptyException . joinPath . map parent . splitPath . takeDirectory
2355 where
2456 parent = const ".."