git.iko.soy/typeable/pandoc
on master help sign in
Shared: Added collapseFilePath function
2d95667Matthew Pickering
src/Text/Pandoc/Shared.hs+26−1
@@ -80,6 +80,7 @@ module Text.Pandoc.Shared (
80 fetchItem,
80 fetchItem,
81 fetchItem',
81 fetchItem',
82 openURL,
82 openURL,
83+ collapseFilePath,
83 -- * Error handling
84 -- * Error handling
84 err,
85 err,
85 warn,
86 warn,
@@ -105,6 +106,7 @@ import Network.URI ( escapeURIString, isURI, nonStrictRelativeTo,
105 unEscapeString, parseURIReference, isAllowedInURI )
106 unEscapeString, parseURIReference, isAllowedInURI )
106import qualified Data.Set as Set
107import qualified Data.Set as Set
107import System.Directory
108import System.Directory
109+import System.FilePath (joinPath, splitDirectories)
108import Text.Pandoc.MIME (getMimeType)
110import Text.Pandoc.MIME (getMimeType)
109import System.FilePath ( (</>), takeExtension, dropExtension)
111import System.FilePath ( (</>), takeExtension, dropExtension)
110import Data.Generics (Typeable, Data)
112import Data.Generics (Typeable, Data)
@@ -530,7 +532,7 @@ stringify = query go . walk deNote
530 deNote x = x
532 deNote x = x
531
533
532-- | Bring all regular text in a pandoc structure to uppercase.
534-- | Bring all regular text in a pandoc structure to uppercase.
533−--
535+--
534-- This function correctly handles cases where a lowercase character doesn't
536-- This function correctly handles cases where a lowercase character doesn't
535-- match to a single uppercase character – e.g. “Straße” would be converted
537-- match to a single uppercase character – e.g. “Straße” would be converted
536-- to “STRASSE”, not “STRAßE”.
538-- to “STRASSE”, not “STRAßE”.
@@ -854,6 +856,29 @@ warn msg = do
854 name <- getProgName
856 name <- getProgName
855 UTF8.hPutStrLn stderr $ name ++ ": " ++ msg
857 UTF8.hPutStrLn stderr $ name ++ ": " ++ msg
856
858
859+-- | Remove intermediate "." and ".." directories from a path.
860+--
861+-- @
862+-- collapseFilePath "./foo" == "foo"
863+-- collapseFilePath "/bar/../baz" == "/baz"
864+-- collapseFilePath "/../baz" == "/../baz"
865+-- collapseFilePath "parent/foo/baz/../bar" == "parent/foo/bar"
866+-- collapseFilePath "parent/foo/baz/../../bar" == "parent/bar"
867+-- collapseFilePath "parent/foo/.." == "parent"
868+-- collapseFilePath "/parent/foo/../../bar" == "/bar"
869+-- @
870+collapseFilePath :: FilePath -> FilePath
871+collapseFilePath = joinPath . reverse . foldl go [] . splitDirectories
872+ where
873+ go rs "." = rs
874+ go r@(p:rs) ".." = case p of
875+ ".." -> ("..":r)
876+ "/" -> ("..":r)
877+ _ -> rs
878+ go _ "/" = ["/"]
879+ go rs x = x:rs
880+
881+
857--
882--
858-- Safe read
883-- Safe read
859--
884--