Haskell 获取特定用户的主目录路径

Haskell get a specific user's home directory path

我想创建一个函数,用该用户的主目录(通常是 /home/user/)扩展 ~user 形式的名称,包括 ~root,通常是 /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

我的理解是 getHomeDirectoryHOME 环境变量中读取,其他主目录将很难获得,但我希望并非不可能或非常困难。

备注

目前我只对 linux 系统感兴趣;我知道 Windows 和 Mac 的风格完全不同。

看起来这在 unix package using getUserEntryForNameUserEntryhomeDirectory 字段中可用。

import System.Posix.User

main :: IO ()
main = do entry <- getUserEntryForName "djf"
          putStrLn (homeDirectory entry)