module Manatee.Toolkit.General.FilePath where
import Data.Array
import Data.List
import Manatee.Toolkit.General.List
import System.FilePath
import System.Process
import Text.Regex.TDFA
fileIntersectEnd :: FilePath -> FilePath -> FilePath
fileIntersectEnd xs ys =
case findIndex (== pathSeparator) zs of
Just i -> drop (succ i) zs
Nothing -> zs
where zs = intersectEnd xs ys
getUpperDirectoryName :: FilePath -> FilePath
getUpperDirectoryName = takeFileName . dropTrailingPathSeparator . dropFileName
getUpperDirectory :: FilePath -> FilePath
getUpperDirectory = dropFileName . dropTrailingPathSeparator
expandBacktickFilePath :: FilePath -> IO FilePath
expandBacktickFilePath filepath
| filepath =~ "^~.*" :: Bool
= expandFilePath filepath
| otherwise
= return filepath
expandFileName :: FilePath -> IO FilePath
expandFileName = expandBacktickFilePath . fillFilePathBlank
expandFilePath :: FilePath -> IO FilePath
expandFilePath filepath = fmap (head . lines) (readProcess "bash" ["-c", "echo " ++ filepath] [])
fillFilePathBlank :: FilePath -> FilePath
fillFilePathBlank filepath = replaceRegex filepath "[^\\][ ]+" "\\ "
where
replaceRegex string regex target = do
let matchTextList = string =~ regex :: [MatchText String]
if null matchTextList
then
string
else do
let indexList = map (snd . head . elems) matchTextList
replaceMatchText indexList target string
replaceMatchText indexList target string
| null indexList
= string
| otherwise
= matchBefore ++ newMatch ++ replaceMatchText newList target matchAfter
where
(matchOffset, matchLength) = head indexList
(matchBefore, afterString) = splitAt matchOffset string
(match, matchAfter) = splitAt matchLength afterString
newMatch = head match : target
adjust = matchOffset + matchLength
newList = map (\(a,b) -> (a adjust, b)) $ tail indexList
filterDotDirectory :: [FilePath] -> [FilePath]
filterDotDirectory = filter notDotDirectory
filterDotDirectoryApply :: (a -> FilePath) -> [a] -> [a]
filterDotDirectoryApply =
filter . (notDotDirectory .)
notDotDirectory :: FilePath -> Bool
notDotDirectory = (`notElem` [".", ".."])
takeFileNameExceptRoot :: FilePath -> FilePath
takeFileNameExceptRoot filepath
| filepath == "/"
= filepath
| otherwise
= takeFileName filepath