module System.FriendlyPath
( userToCanonPath
, expandTilda
, isAbsolute'
) where
import System.CanonicalizePath (canonicalizePath)
import System.Directory (getHomeDirectory)
import System.FilePath (isAbsolute, normalise, pathSeparator)
import System.PosixCompat.User (getUserEntryForName, homeDirectory)
userToCanonPath :: FilePath -> IO String
userToCanonPath f = canonicalizePath =<< expandTilda f
expandTilda :: String -> IO FilePath
expandTilda ('~':path)
| null path || (head path == pathSeparator) = (++ path) <$> getHomeDirectory
| otherwise = let username = takeWhile (/= pathSeparator) path
dirname = drop (length username) path
in (normalise . (++ dirname) . homeDirectory) <$> getUserEntryForName username
expandTilda path = return path
isAbsolute' :: String -> Bool
isAbsolute' ('~':_) = True
isAbsolute' p = isAbsolute p