provide diohsc.bundle
[diohsc.git] / Mundanities.hs
blob5133f2d0f0f54321e39d5cc2bd075ff978c8990d
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 System.Directory
19 import System.FilePath
21 import qualified Data.ByteString as BS
22 import qualified Data.ByteString.Lazy as BL
23 import qualified Data.Text as TS
24 import qualified Data.Text.IO as TS
25 import qualified Data.Text.Lazy as T
26 import qualified Data.Text.Lazy.Encoding as T
28 mkdirhierto :: FilePath -> IO ()
29 mkdirhierto = mkdirhier . takeDirectory
30 mkdirhier :: FilePath -> IO ()
31 mkdirhier = createDirectoryIfMissing True
33 -- |returns true iff path is contained within the directory dir
34 isSubPath :: FilePath -> FilePath -> IO Bool
35 isSubPath dir path = isRelative . makeRelative dir <$> canonicalizePath path
37 ignoreIOErr :: (MonadIO m, MonadMask m, Monoid a) => m a -> m a
38 ignoreIOErr = handle ((\_ -> return mempty) :: (Monad m, Monoid a) => IOError -> m a)
40 warnIOErr :: (MonadIO m, MonadMask m, Monoid a) => m a -> m a
41 warnIOErr = handle ((\e -> liftIO (print e) >> return mempty) :: (MonadIO m, Monoid a) => IOError -> m a)
43 ignoreIOErrAlt :: (MonadIO m, MonadMask m, Alternative f) => m (f a) -> m (f a)
44 ignoreIOErrAlt = handle ((\_ -> return empty) :: (Monad m, Alternative f) => IOError -> m (f a))
46 warnIOErrAlt :: (MonadIO m, MonadMask m, Alternative f) => m (f a) -> m (f a)
47 warnIOErrAlt = handle ((\e -> liftIO (print e) >> return empty) :: (MonadIO m, Alternative f) => IOError -> m (f a))
49 readFileLines :: FilePath -> IO [T.Text]
50 readFileLines path = ignoreIOErr $
51 map T.strip . T.lines . T.decodeUtf8 . BL.fromStrict <$> BS.readFile path
53 -- delete all but last n lines of file
54 truncateToEnd :: Int -> FilePath -> IO ()
55 truncateToEnd n path =
56 TS.readFile path >>= TS.writeFile path . TS.unlines . dropAllBut n . TS.lines
57 where dropAllBut m as = drop (length as - m) as