Last active
January 23, 2017 16:01
-
-
Save schoettl/312467a7fb6ad27c0ab74cbebbc30aac to your computer and use it in GitHub Desktop.
Write stdin to a file and rewrite the file after a timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- See http://jakob.keramik-schoettl.de/blog/ | |
-- usage: rewrite-after-timeout SECONDS FILENAME | |
import Prelude | |
import System.IO | |
import System.Timeout | |
import System.Environment | |
import Data.Time | |
import Data.Maybe | |
import Control.Monad | |
main :: IO () | |
main = do | |
pause <- read . head <$> getArgs :: IO Integer | |
filename <- head . tail <$> getArgs :: IO String | |
start <- getCurrentTime | |
getLineAndAppendOrReplace pause filename start | |
getLineAndAppendOrReplace :: Integer -> FilePath -> UTCTime -> IO () | |
getLineAndAppendOrReplace pause filename lastAppend = do | |
maybeLine <- timeout 100000 getLine -- timeout in microseconds | |
time <- case maybeLine of | |
Just line -> appendLine pause filename lastAppend line | |
Nothing -> pure lastAppend | |
getLineAndAppendOrReplace pause filename time | |
appendLine :: Integer -> FilePath -> UTCTime -> String -> IO UTCTime | |
appendLine pause filename lastAppend line = do | |
now <- getCurrentTime | |
let mode = if diffUTCTime now lastAppend > realToFrac pause | |
then WriteMode | |
else AppendMode | |
file <- openFile filename mode | |
hPutStrLn file line | |
hClose file | |
pure now |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment