@@ -80,6 +80,7 @@ module Text.Pandoc.Shared (
8080 fetchItem,
8181 fetchItem',
8282 openURL,
83+ collapseFilePath,
8384 -- * Error handling
8485 err,
8586 warn,
@@ -105,6 +106,7 @@ import Network.URI ( escapeURIString, isURI, nonStrictRelativeTo,
105106 unEscapeString, parseURIReference, isAllowedInURI )
106107import qualified Data.Set as Set
107108import System.Directory
109+import System.FilePath (joinPath, splitDirectories)
108110import Text.Pandoc.MIME (getMimeType)
109111import System.FilePath ( (</>), takeExtension, dropExtension)
110112import Data.Generics (Typeable, Data)
@@ -530,7 +532,7 @@ stringify = query go . walk deNote
530532 deNote x = x
531533
532534-- | Bring all regular text in a pandoc structure to uppercase.
533−--
535+--
534536-- This function correctly handles cases where a lowercase character doesn't
535537-- match to a single uppercase character – e.g. “Straße” would be converted
536538-- to “STRASSE”, not “STRAßE”.
@@ -854,6 +856,29 @@ warn msg = do
854856 name <- getProgName
855857 UTF8.hPutStrLn stderr $ name ++ ": " ++ msg
856858
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+
857882--
858883-- Safe read
859884--