split more
[diohsc.git] / Mundanities.hs
bloba8c83f2554bdf4a379ed50459115fc2731617932
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 {-# LANGUAGE Safe #-}
13 module Mundanities where
15 import Control.Applicative (Alternative, empty)
16 import Control.Monad.Catch (MonadMask, handle)
17 import Control.Monad.IO.Class (MonadIO, liftIO)
18 import Safe
19 import System.Directory
20 import System.FilePath
22 import qualified Data.ByteString as BS
23 import qualified Data.ByteString.Lazy as BL
24 import qualified Data.Text as TS
25 import qualified Data.Text.IO as TS
26 import qualified Data.Text.Lazy as T
27 import qualified Data.Text.Lazy.Encoding as T
29 mkdirhierto :: FilePath -> IO ()
30 mkdirhierto = mkdirhier . takeDirectory
31 mkdirhier :: FilePath -> IO ()
32 mkdirhier = createDirectoryIfMissing True
34 -- |returns true iff path is contained within the directory dir
35 isSubPath :: FilePath -> FilePath -> IO Bool
36 isSubPath dir path = isRelative . makeRelative dir <$> canonicalizePath path
38 ignoreIOErr :: (MonadIO m, MonadMask m, Monoid a) => m a -> m a
39 ignoreIOErr = handle ((\_ -> return mempty) :: (Monad m, Monoid a) => IOError -> m a)
41 warnIOErr :: (MonadIO m, MonadMask m, Monoid a) => m a -> m a
42 warnIOErr = handle ((\e -> liftIO (print e) >> return mempty) :: (MonadIO m, Monoid a) => IOError -> m a)
44 ignoreIOErrAlt :: (MonadIO m, MonadMask m, Alternative f) => m (f a) -> m (f a)
45 ignoreIOErrAlt = handle ((\_ -> return empty) :: (Monad m, Alternative f) => IOError -> m (f a))
47 warnIOErrAlt :: (MonadIO m, MonadMask m, Alternative f) => m (f a) -> m (f a)
48 warnIOErrAlt = handle ((\e -> liftIO (print e) >> return empty) :: (MonadIO m, Alternative f) => IOError -> m (f a))
50 readFileLines :: FilePath -> IO [T.Text]
51 readFileLines path = ignoreIOErr $
52 map T.strip . T.lines . T.decodeUtf8 . BL.fromStrict <$> BS.readFile path
54 writeReadFile :: (Show a) => FilePath -> a -> IO ()
55 writeReadFile path = BL.writeFile path . T.encodeUtf8 . T.pack . show
57 readReadFile :: (Read a) => FilePath -> IO (Maybe a)
58 readReadFile path = ignoreIOErrAlt $
59 readMay . T.unpack . T.decodeUtf8 . BL.fromStrict <$> BS.readFile path
61 -- delete all but last n lines of file
62 truncateToEnd :: Int -> FilePath -> IO ()
63 truncateToEnd n path =
64 TS.readFile path >>= TS.writeFile path . TS.unlines . dropAllBut n . TS.lines
65 where dropAllBut m as = drop (length as - m) as