Debian Codegraph @

src/System/AtomicWrite/Writer/String.hs

raw
1 -- |
2 -- Module : System.AtomicWrite.Writer.String
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 String
11 -- to a file.
12
13 module System.AtomicWrite.Writer.String (atomicWriteFile, atomicWithFile, atomicWriteFileWithMode, atomicWithFileAndMode) where
14
15 import System.AtomicWrite.Internal (closeAndRename, maybeSetFileMode,
16 tempFileFor)
17
18 import System.IO (Handle, hPutStr)
19
20 import System.Posix.Types (FileMode)
21
22 -- | Creates or modifies a file atomically on POSIX-compliant
23 -- systems while preserving permissions.
24 atomicWriteFile ::
25 FilePath -- ^ The path where the file will be updated or created
26 -> String -- ^ The content to write to the file
27 -> IO ()
28 atomicWriteFile = (. flip hPutStr) . atomicWithFile
29
30
31 -- | Creates or modifies a file atomically on
32 -- POSIX-compliant systems and updates permissions
33 atomicWriteFileWithMode ::
34 FileMode -- ^ The mode to set the file to
35 -> FilePath -- ^ The path where the file will be updated or created
36 -> String -- ^ The content to write to the file
37 -> IO ()
38 atomicWriteFileWithMode mode = ( . flip hPutStr)
39 . atomicWithFileAndMode mode
40
41 -- | A general version of 'atomicWriteFile'
42 atomicWithFile :: FilePath -> (Handle -> IO ()) -> IO ()
43 atomicWithFile = atomicWithFileAndMaybeMode Nothing
44
45 -- | A general version of 'atomicWriteFileWithMode'
46 atomicWithFileAndMode :: FileMode
47 -> FilePath
48 -> (Handle -> IO ())
49 -> IO ()
50 atomicWithFileAndMode = atomicWithFileAndMaybeMode . Just
51
52 -- | Helper function
53 atomicWithFileAndMaybeMode :: Maybe FileMode
54 -> FilePath
55 -> (Handle -> IO ())
56 -> IO ()
57 atomicWithFileAndMaybeMode mmode path action =
58 tempFileFor path >>= \(tmpPath, h) -> action h
59 >> closeAndRename h tmpPath path
60 >> maybeSetFileMode path mmode