{-| Module  : FiniteCategories
Description : Write into a file, create directories if necessary.
Copyright   : Guillaume Sabbagh 2021
License     : GPL-3
Maintainer  : guillaumesabbagh@protonmail.com
Stability   : experimental
Portability : portable

Write lazy text to a file specified by a path, if the path leads to non existing directories, it creates the directories.
Credits to wisn : https://stackoverflow.com/a/58685979
-}

module IO.CreateAndWriteFile
(
    createAndWriteFile
)
where
    import System.Directory (createDirectoryIfMissing)
    import System.FilePath.Posix (takeDirectory)
    import qualified    Data.Text.Lazy as L                 (Text)
    import qualified    Data.Text.Lazy.IO as LIO             (writeFile)

    -- | Write lazy text to a file specified by a path, if the path leads to non existing directories, it creates the directories.

    createAndWriteFile :: FilePath -> L.Text -> IO ()
    createAndWriteFile :: FilePath -> Text -> IO ()
createAndWriteFile FilePath
path Text
content = do
        Bool -> FilePath -> IO ()
createDirectoryIfMissing Bool
True (FilePath -> IO ()) -> FilePath -> IO ()
forall a b. (a -> b) -> a -> b
$ FilePath -> FilePath
takeDirectory FilePath
path

        FilePath -> Text -> IO ()
LIO.writeFile FilePath
path Text
content