-- |
-- Module      :  System.AtomicWrite.Writer.Text
-- Copyright   :  © 2015-2019 Stack Builders Inc.
-- License     :  MIT
--
-- Maintainer  :  Stack Builders <hackage@stackbuilders.com>
-- Stability   :  experimental
-- Portability :  portable
--
-- Provides functionality to dump the contents of a Text
-- to a file.

module System.AtomicWrite.Writer.Text (atomicWriteFile, atomicWriteFileWithMode) where

import           System.AtomicWrite.Internal (atomicWriteFileMaybeModeText)

import           Data.Text                   (Text)

import           Data.Text.IO                (hPutStr)

import           System.Posix.Types          (FileMode)

-- | Creates a file atomically on POSIX-compliant
-- systems while preserving permissions.
atomicWriteFile ::
  FilePath   -- ^ The path where the file will be updated or created
  -> Text    -- ^ The content to write to the file
  -> IO ()
atomicWriteFile :: FilePath -> Text -> IO ()
atomicWriteFile =
  Maybe FileMode -> FilePath -> Text -> IO ()
atomicWriteFileMaybeMode Maybe FileMode
forall a. Maybe a
Nothing

-- | Creates or modifies a file atomically on
-- POSIX-compliant systems and updates permissions
atomicWriteFileWithMode ::
  FileMode      -- ^ The mode to set the file to
  -> FilePath   -- ^ The path where the file will be updated or created
  -> Text       -- ^ The content to write to the file
  -> IO ()
atomicWriteFileWithMode :: FileMode -> FilePath -> Text -> IO ()
atomicWriteFileWithMode =
  Maybe FileMode -> FilePath -> Text -> IO ()
atomicWriteFileMaybeMode (Maybe FileMode -> FilePath -> Text -> IO ())
-> (FileMode -> Maybe FileMode)
-> FileMode
-> FilePath
-> Text
-> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FileMode -> Maybe FileMode
forall a. a -> Maybe a
Just

-- Helper Function
atomicWriteFileMaybeMode ::
  Maybe FileMode -- ^ The mode to set the file to
  -> FilePath    -- ^ The path where the file will be updated or created
  -> Text        -- ^ The content to write to the file
  -> IO ()
atomicWriteFileMaybeMode :: Maybe FileMode -> FilePath -> Text -> IO ()
atomicWriteFileMaybeMode Maybe FileMode
mmode FilePath
path = Maybe FileMode
-> FilePath -> (Handle -> Text -> IO ()) -> Text -> IO ()
forall a.
Maybe FileMode -> FilePath -> (Handle -> a -> IO ()) -> a -> IO ()
atomicWriteFileMaybeModeText Maybe FileMode
mmode FilePath
path Handle -> Text -> IO ()
hPutStr