我想创建一个函数,用该用户的主目录(通常是~user
)扩展表单/home/user/
的名称,包括~root
,通常是{{ 1}}。我知道/root/
方法,以获取当前用户的家,但我不知道确定给定用户的主目录的任何功能。
我有以下功能,用任意文件路径中的前导getHomeDirectory
替换用户的主目录
~
我的理解是-- join path with '/', except at root
-- opposite of breakPath
rejoinPath :: [FilePath] -> FilePath
rejoinPath [] = ""
rejoinPath (p:ps)
| p == "/" = p ++ go ps
| otherwise = go (p:ps)
where
go :: [FilePath] -> FilePath
go [] = ""
go [p] = p
go (p:ps) = p ++ "/" ++ go ps
-- split path on '/', erasing separator except at root
-- opposite of rejoinPath
breakPath :: FilePath -> [FilePath]
breakPath [] = []
breakPath (c:cs)
| c == '/' = "/" : go "" cs
| otherwise = go [c] cs
where
go :: FilePath -> FilePath -> [FilePath]
go z [] = [z]
go z (c:cs)
| c == '/' = z : go "" cs
| otherwise = go (z ++ [c]) cs
expandHome :: FilePath -> IO FilePath
expandHome p = rejoinPath <$> (go $ breakPath p)
where
go [] = pure []
go (p:ps)
| p == "~" = do
home <- getHomeDirectory
pure $ home : ps
| otherwise = pure $ p : ps
从getHomeDirectory
环境变量中读取,并且其他主目录将更难以获得,但我希望不是不可能或非常困难。
我目前只对linux系统感兴趣;我知道Windows和Mac有完全不同的风格。