cautious-file-1.0.2/0000755000000000000000000000000012070652744012460 5ustar0000000000000000cautious-file-1.0.2/cautious-file.cabal0000644000000000000000000000244012070652744016215 0ustar0000000000000000name: cautious-file version: 1.0.2 Cabal-Version: >= 1.6 synopsis: Ways to write a file cautiously, to reduce the chances of problems such as data loss due to crashes or power failures description: On non-Windows systems, posix-specific functions are used to reduce the chance of data loss further category: System license: BSD3 license-file: LICENSE copyright: Copyright (C) Robin Green 2009, 2011 author: Robin Green maintainer: Robin Green build-type: Custom stability: experimental bug-reports: mailto:greenrd@greenrd.org tested-with: GHC == 7.0.2 extra-source-files: Test.hs source-repository head type: darcs location: http://patch-tag.com/r/greenrd/cautious-file Flag posix description: Use POSIX-specific features default: True Library hs-source-dirs: src build-Depends: base >= 4, base < 5, directory >= 1.1, directory < 1.3, filepath >= 1.2, filepath < 1.4, bytestring >= 0.9, bytestring < 0.11 if flag(posix) && !os(Windows) cpp-options: -D_POSIX build-Depends: unix exposed-modules: System.Posix.ByteLevel, System.Posix.Fsync exposed-modules: System.IO.Cautious ghc-options: -Wall cautious-file-1.0.2/LICENSE0000644000000000000000000000273212070652744013471 0ustar0000000000000000 Copyright (c) 2009 Robin Green Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Robin Green nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. cautious-file-1.0.2/Setup.lhs0000644000000000000000000000044112070652744014267 0ustar0000000000000000#!/usr/bin/env runhaskell > import Distribution.Simple > import System.Process (rawSystem) > import System.Exit (ExitCode(..)) > main = defaultMainWithHooks $ simpleUserHooks { runTests = \args _ _ _ -> do > ExitSuccess <- rawSystem "runhaskell" ("Test.hs" : args) > return () > } cautious-file-1.0.2/Test.hs0000644000000000000000000000433312070652744013736 0ustar0000000000000000{-# LANGUAGE CPP #-} module Main where import System.IO.Cautious (writeFile) import Prelude hiding (writeFile) import Control.Monad (replicateM, zipWithM_, unless) import System.Directory (removeFile) import System.Environment (getArgs) #ifdef _POSIX import System.Posix.Files (createSymbolicLink, readSymbolicLink) #endif import System.Random (mkStdGen, randomRIO, setStdGen) -- Remember that because we are using zipWithM_ below, the lengths of testLengths and outputFilePaths need to be the same! testLengths :: [Int] testLengths = [ 0 -- Extreme value , 1 -- Extreme value , 65530 -- Normal value below split limit , 65536 -- Split limit , 128000 -- Normal value above split limit ] outputFilePaths :: [FilePath] outputFilePaths = ["foo", "foo.txt", "./bar.txt", ".dotfile", "./.dot.dot"] defaultSeed :: Int defaultSeed = 1234 stdTestCase :: Int -> FilePath -> IO () stdTestCase dataLen outputFile = do testData <- replicateM dataLen $ randomRIO ('\0', '\127') writeFile outputFile testData testData' <- readFile outputFile unless (testData == testData') . fail $ "stdTestCase: failed with " ++ show dataLen ++ " " ++ show outputFile removeFile outputFile #ifdef _POSIX symlinkTestCase :: IO () symlinkTestCase = do let linkTarget = "link-dest" linkSrc = "link" testData = "hi" writeFile linkTarget "" createSymbolicLink linkTarget linkSrc writeFile linkSrc testData newTarget <- readSymbolicLink linkSrc testData' <- readFile linkTarget unless (testData == testData') $ fail "symlinkTestCase failed: data read back not the same as data written out!" unless (newTarget == linkTarget) $ fail "symlinkTestCase failed: symlink clobbered" mapM_ removeFile [linkSrc, linkTarget] #endif main :: IO () main = do args <- getArgs setStdGen . mkStdGen $ if null args then defaultSeed else read (head args) zipWithM_ stdTestCase testLengths outputFilePaths #ifdef _POSIX symlinkTestCase #else putStrLn "Warning: POSIX tests not run! If you are on a POSIX platform, then to run them type 'runhaskell -D_POSIX Test.hs'" #endif putStrLn "All cautious-file tests completed successfully!"cautious-file-1.0.2/src/0000755000000000000000000000000012070652744013247 5ustar0000000000000000cautious-file-1.0.2/src/System/0000755000000000000000000000000012070652744014533 5ustar0000000000000000cautious-file-1.0.2/src/System/Posix/0000755000000000000000000000000012070652744015635 5ustar0000000000000000cautious-file-1.0.2/src/System/Posix/ByteLevel.hsc0000644000000000000000000000246212070652744020233 0ustar0000000000000000{-# LANGUAGE ForeignFunctionInterface #-} module System.Posix.ByteLevel (fdWrite, fdWriteB, writeAllB, writeAllL) where import Control.Applicative ((<$>)) import Control.Monad (unless) import qualified Data.ByteString as Strict import Data.ByteString.Lazy (ByteString, toChunks) import Data.ByteString.Unsafe (unsafeUseAsCStringLen) import Data.Function (fix) import Foreign.C.Error (throwErrnoIfMinus1Retry) import Foreign.C.String (CString, CStringLen) import Foreign.C.Types (CInt(..), CSize(..)) import System.Posix.Types (ByteCount, Fd(..)) #include foreign import ccall "write" c_write :: CInt -> CString -> CSize -> IO CSize fdWrite :: Fd -> CStringLen -> IO ByteCount fdWrite (Fd fd) (cs, l) = throwErrnoIfMinus1Retry "write" . c_write fd cs $ fromIntegral l fdWriteB :: Fd -> Strict.ByteString -> IO Int fdWriteB fd bs = fromIntegral <$> unsafeUseAsCStringLen bs (fdWrite fd) -- | Write the entire contents of the strict bytestring. Assumes blocking mode. writeAllB :: Fd -> Strict.ByteString -> IO () writeAllB fd = fix $ \me s -> unless (Strict.null s) $ do count <- fdWriteB fd s me $ Strict.drop (fromIntegral count) s -- | Write the entire contents of the lazy bytestring. Assumes blocking mode. writeAllL :: Fd -> ByteString -> IO () writeAllL fd = mapM_ (writeAllB fd) . toChunks cautious-file-1.0.2/src/System/Posix/Fsync.hsc0000644000000000000000000000055212070652744017420 0ustar0000000000000000{-# LANGUAGE ForeignFunctionInterface #-} module System.Posix.Fsync (fsync) where import Foreign.C.Error (throwErrnoIfMinus1_) import Foreign.C.Types (CInt(..)) import System.Posix.Types (Fd(..)) #include foreign import ccall "fsync" c_fsync :: CInt -> IO CInt fsync :: Fd -> IO () fsync (Fd fd) = throwErrnoIfMinus1_ "fsync" $ c_fsync fd cautious-file-1.0.2/src/System/IO/0000755000000000000000000000000012070652744015042 5ustar0000000000000000cautious-file-1.0.2/src/System/IO/Cautious.hs0000644000000000000000000000370312070652744017175 0ustar0000000000000000{-# LANGUAGE CPP #-} -- | It is recommended to write -- -- import Prelude hiding (writeFile) -- -- when importing this module. module System.IO.Cautious ( writeFile , writeFileL , writeFileWithBackup , writeFileWithBackupL ) where import Prelude hiding (writeFile) import Control.Exception (tryJust) import Control.Monad (guard) import Data.ByteString.Lazy.Char8 (ByteString, pack) import System.Directory (canonicalizePath, renameFile) import System.FilePath (splitFileName) import System.IO (openTempFile) import System.IO.Error (isDoesNotExistError) #ifdef _POSIX import System.Posix.ByteLevel (writeAllL) import System.Posix.Files (fileMode, getFileStatus, setFdMode) import System.Posix.Fsync (fsync) import System.Posix.IO (closeFd, handleToFd) #else import Data.ByteString.Lazy (hPut) import System.IO (hClose) #endif writeFile :: FilePath -> String -> IO () writeFile = writeFileWithBackup $ return () writeFileL :: FilePath -> ByteString -> IO () writeFileL = writeFileWithBackupL $ return () -- | Backs up the old version of the file with "backup". "backup" must not fail if there is no -- old version of the file. writeFileWithBackup :: IO () -> FilePath -> String -> IO () writeFileWithBackup backup fp = writeFileWithBackupL backup fp . pack ignoreNotFound :: IO a -> IO (Either () a) ignoreNotFound = tryJust (guard . isDoesNotExistError) -- | Backs up the old version of the file with "backup". "backup" must not fail if there is no -- old version of the file. writeFileWithBackupL :: IO () -> FilePath -> ByteString -> IO () writeFileWithBackupL backup fp bs = do cfp <- either (const fp) id `fmap` ignoreNotFound (canonicalizePath fp) (tempFP, handle) <- uncurry openTempFile $ splitFileName cfp #ifdef _POSIX fd <- handleToFd handle writeAllL fd bs _ <- ignoreNotFound $ setFdMode fd . fileMode =<< getFileStatus cfp fsync fd closeFd fd #else hPut handle bs hClose handle #endif backup renameFile tempFP cfp