PageRenderTime 12ms CodeModel.GetById 1ms app.highlight 5ms RepoModel.GetById 2ms app.codeStats 0ms

/Angel/Files.hs

http://github.com/jamwt/Angel
Haskell | 33 lines | 29 code | 4 blank | 0 comment | 0 complexity | e3a0168b4f6ad3b1168a761f0f4bc6e2 MD5 | raw file
 1module Angel.Files (getFile, startFileManager) where
 2
 3import Control.Concurrent.STM
 4import Control.Concurrent.STM.TChan (readTChan, writeTChan, TChan, newTChan, newTChanIO)
 5import Control.Monad (forever)
 6import System.IO (Handle, hClose, openFile, IOMode(..), hIsClosed)
 7import GHC.IO.Handle (hDuplicate)
 8import Debug.Trace (trace)
 9import Angel.Data (GroupConfig(..), FileRequest)
10
11startFileManager req = forever $ fileManager req
12
13fileManager :: TChan FileRequest -> IO ()
14fileManager req = do 
15    (path, resp) <- atomically $ readTChan req
16    mh <- catch  (openFile path AppendMode >>= \h-> return $ Just h) (\e-> return Nothing)
17    case mh of
18        Just hand -> do
19            hand' <- hDuplicate hand
20            hClose hand
21            atomically $ writeTChan resp (Just hand')
22        Nothing -> atomically $ writeTChan resp Nothing
23    fileManager req
24
25getFile :: String -> GroupConfig -> IO Handle
26getFile path cfg = do
27    resp <- newTChanIO
28    atomically $ writeTChan (fileRequest cfg) (path, resp)
29    mh <- atomically $ readTChan resp
30    hand <- case mh of
31        Just hand -> return hand
32        Nothing -> error $ "could not open stdout/stderr file " ++ path
33    return hand