on f104f91 help sign in
hakyll/src/Hakyll/Web/Util/String.hs
73 lines 2.0 kB history raw
1-- | Miscellaneous string manipulation functions.
2--
3module Hakyll.Web.Util.String
4 ( trim
5 , replaceAll
6 , splitAll
7 , toUrl
8 , toSiteRoot
9 ) where
11import Data.Char (isSpace)
12import Data.Maybe (listToMaybe)
14import System.FilePath (splitPath, takeDirectory, joinPath)
15import Text.Regex.PCRE ((=~~))
17-- | Trim a string (drop spaces, tabs and newlines at both sides).
18--
19trim :: String -> String
20trim = reverse . trim' . reverse . trim'
21 where
22 trim' = dropWhile isSpace
24-- | A simple (but inefficient) regex replace funcion
25--
26replaceAll :: String -- ^ Pattern
27 -> (String -> String) -- ^ Replacement (called on capture)
28 -> String -- ^ Source string
29 -> String -- ^ Result
30replaceAll pattern f source = replaceAll' source
31 where
32 replaceAll' src = case listToMaybe (src =~~ pattern) of
33 Nothing -> src
34 Just (o, l) ->
35 let (before, tmp) = splitAt o src
36 (capture, after) = splitAt l tmp
37 in before ++ f capture ++ replaceAll' after
39-- | A simple regex split function. The resulting list will contain no empty
40-- strings.
41--
42splitAll :: String -- ^ Pattern
43 -> String -- ^ String to split
44 -> [String] -- ^ Result
45splitAll pattern = filter (not . null) . splitAll'
46 where
47 splitAll' src = case listToMaybe (src =~~ pattern) of
48 Nothing -> [src]
49 Just (o, l) ->
50 let (before, tmp) = splitAt o src
51 in before : splitAll' (drop l tmp)
53-- | Convert a filepath to an URL starting from the site root
54--
55-- Example:
56--
57-- > toUrl "foo/bar.html"
58--
59-- Result:
60--
61-- > "/foo/bar.html"
62--
63toUrl :: FilePath -> String
64toUrl = ('/' :)
66-- | Get the relative url to the site root, for a given (absolute) url
67--
68toSiteRoot :: String -> String
69toSiteRoot = emptyException . joinPath . map parent . splitPath . takeDirectory
70 where
71 parent = const ".."
72 emptyException [] = "."
73 emptyException x = x