set >=tls-2.0 lower bound
[diohsc.git] / Mundanities.hs
blob0424c00e75d26f0fe4a750b8d3c1ef971a6dd79d
1 -- This file is part of Diohsc
2 -- Copyright (C) 2020 Martin Bays <mbays@sdf.org>
3 --
4 -- This program is free software: you can redistribute it and/or modify
5 -- it under the terms of version 3 of the GNU General Public License as
6 -- published by the Free Software Foundation, or any later version.
7 --
8 -- You should have received a copy of the GNU General Public License
9 -- along with this program. If not, see http://www.gnu.org/licenses/.
11 module Mundanities where
13 import Control.Applicative (Alternative, empty)
14 import Control.Monad.Catch (MonadMask, handle)
15 import Control.Monad.IO.Class (MonadIO, liftIO)
16 import Safe
17 import System.Directory
18 import System.FilePath
20 import qualified Data.ByteString as BS
21 import qualified Data.ByteString.Lazy as BL
22 import qualified Data.Text as TS
23 import qualified Data.Text.IO as TS
24 import qualified Data.Text.Lazy as T
25 import qualified Data.Text.Lazy.Encoding as T
27 mkdirhierto :: FilePath -> IO ()
28 mkdirhierto = mkdirhier . takeDirectory
29 mkdirhier :: FilePath -> IO ()
30 mkdirhier = createDirectoryIfMissing True
32 -- |returns true iff path is contained within the directory dir
33 isSubPath :: FilePath -> FilePath -> IO Bool
34 isSubPath dir path = isRelative . makeRelative dir <$> canonicalizePath path
36 ignoreIOErr :: (MonadIO m, MonadMask m, Monoid a) => m a -> m a
37 ignoreIOErr = handle ((\_ -> return mempty) :: (Monad m, Monoid a) => IOError -> m a)
39 warnIOErr :: (MonadIO m, MonadMask m, Monoid a) => m a -> m a
40 warnIOErr = handle ((\e -> liftIO (print e) >> return mempty) :: (MonadIO m, Monoid a) => IOError -> m a)
42 ignoreIOErrAlt :: (MonadIO m, MonadMask m, Alternative f) => m (f a) -> m (f a)
43 ignoreIOErrAlt = handle ((\_ -> return empty) :: (Monad m, Alternative f) => IOError -> m (f a))
45 warnIOErrAlt :: (MonadIO m, MonadMask m, Alternative f) => m (f a) -> m (f a)
46 warnIOErrAlt = handle ((\e -> liftIO (print e) >> return empty) :: (MonadIO m, Alternative f) => IOError -> m (f a))
48 readFileLines :: FilePath -> IO [T.Text]
49 readFileLines path = ignoreIOErr $
50 map T.strip . T.lines . T.decodeUtf8 . BL.fromStrict <$> BS.readFile path
52 writeReadFile :: (Show a) => FilePath -> a -> IO ()
53 writeReadFile path = BL.writeFile path . T.encodeUtf8 . T.pack . show
55 readReadFile :: (Read a) => FilePath -> IO (Maybe a)
56 readReadFile path = ignoreIOErrAlt $
57 readMay . T.unpack . T.decodeUtf8 . BL.fromStrict <$> BS.readFile path
59 -- delete all but last n lines of file
60 truncateToEnd :: Int -> FilePath -> IO ()
61 truncateToEnd n path =
62 TS.readFile path >>= TS.writeFile path . TS.unlines . dropAllBut n . TS.lines
63 where dropAllBut m as = drop (length as - m) as