| 1 |
-- | |
| 2 |
-- Module : System.AtomicWrite.Writer.ByteStringBuilder |
| 3 |
-- Copyright : © 2015-2019 Stack Builders Inc. |
| 4 |
-- License : MIT |
| 5 |
-- |
| 6 |
-- Maintainer : Stack Builders <[email protected]> |
| 7 |
-- Stability : experimental |
| 8 |
-- Portability : portable |
| 9 |
-- |
| 10 |
-- Provides functionality to dump the contents of a ByteStringBuilder |
| 11 |
-- to a file. |
| 12 |
|
| 13 |
module System.AtomicWrite.Writer.ByteStringBuilder (atomicWriteFile, atomicWriteFileWithMode) where |
| 14 |
|
| 15 |
import System.AtomicWrite.Internal (closeAndRename, maybeSetFileMode, |
| 16 |
tempFileFor) |
| 17 |
|
| 18 |
import Data.ByteString.Builder (Builder, hPutBuilder) |
| 19 |
|
| 20 |
import GHC.IO.Handle (BufferMode (BlockBuffering), |
| 21 |
hSetBinaryMode, hSetBuffering) |
| 22 |
|
| 23 |
import System.Posix.Types (FileMode) |
| 24 |
|
| 25 |
-- | Creates or modifies a file atomically on POSIX-compliant |
| 26 |
-- systems while preserving permissions. |
| 27 |
atomicWriteFile :: |
| 28 |
FilePath -- ^ The path where the file will be updated or created |
| 29 |
-> Builder -- ^ The content to write to the file |
| 30 |
-> IO () |
| 31 |
atomicWriteFile = |
| 32 |
atomicWriteFileMaybeMode Nothing |
| 33 |
|
| 34 |
-- | Creates or modifies a file atomically on POSIX-compliant |
| 35 |
-- systems and updates permissions. |
| 36 |
atomicWriteFileWithMode :: |
| 37 |
FileMode |
| 38 |
-> FilePath -- ^ The path where the file will be updated or created |
| 39 |
-> Builder -- ^ The content to write to the file |
| 40 |
-> IO () |
| 41 |
atomicWriteFileWithMode mode = |
| 42 |
atomicWriteFileMaybeMode $ Just mode |
| 43 |
|
| 44 |
-- Helper function |
| 45 |
atomicWriteFileMaybeMode :: |
| 46 |
Maybe FileMode |
| 47 |
-> FilePath -- ^ The path where the file will be updated or created |
| 48 |
-> Builder -- ^ The content to write to the file |
| 49 |
-> IO () |
| 50 |
atomicWriteFileMaybeMode mmode path builder = do |
| 51 |
(temppath, h) <- tempFileFor path |
| 52 |
|
| 53 |
-- Recommendations for binary and buffering are from the |
| 54 |
-- Data.ByteString.Builder docs: |
| 55 |
-- http://hackage.haskell.org/package/bytestring-0.10.2.0/docs/Data-ByteString-Builder.html#v:hPutBuilder |
| 56 |
hSetBinaryMode h True |
| 57 |
hSetBuffering h (BlockBuffering Nothing) |
| 58 |
|
| 59 |
hPutBuilder h builder |
| 60 |
|
| 61 |
closeAndRename h temppath path |
| 62 |
|
| 63 |
-- set new permissions if a FileMode was provided |
| 64 |
maybeSetFileMode path mmode |