4

我想创建一个函数来~user使用该用户的主目录(通常/home/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

我的理解是,getHomeDirectory从环境变量中读取HOME,以及其他主目录将更难获得,但我希望不是不可能或非常困难。

笔记

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

4

1 回答 1

4

看起来这可以在unix包中使用getUserEntryForName然后homeDirectory使用UserEntry.

import System.Posix.User

main :: IO ()
main = do entry <- getUserEntryForName "djf"
          putStrLn (homeDirectory entry)
于 2017-07-19T14:02:58.510 回答