Skip to content

Commit 2c18408

Browse files
committed
Make mergetool write to the result atomically
More resilient in case e.g. git merge-file fails in the middle
1 parent ea7f881 commit 2c18408

File tree

1 file changed

+8
-15
lines changed

1 file changed

+8
-15
lines changed

main/Main.hs

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,15 @@ import System.Console.CmdArgs (
3333
typ,
3434
(&=),
3535
)
36-
import System.Directory (doesDirectoryExist, listDirectory)
36+
import System.Directory (doesDirectoryExist, listDirectory, renameFile)
3737
import System.Exit (ExitCode (..), exitFailure, exitSuccess)
3838
import System.FilePath ((</>))
39-
import System.IO (IOMode (WriteMode), hPutStrLn, hSetEncoding, stderr, withFile)
39+
import System.IO (hPutStrLn, hSetEncoding, stderr)
4040
import System.IO.Atomic (withOutputFile)
4141
import System.IO.Utf8 (readFileUtf8, withUtf8StdHandles)
4242
import System.Posix.Process (exitImmediately)
4343
import System.Posix.Signals (Handler (..), installHandler, keyboardSignal)
44-
import System.Process (CreateProcess (std_out), StdStream (UseHandle), proc, waitForProcess, withCreateProcess)
44+
import System.Process (callProcess)
4545

4646
type Result = Either String ()
4747

@@ -221,20 +221,13 @@ mergeToolJob opts@Nixfmt{files = [base, local, remote, merged]} = runExceptT $ d
221221
<$> formatTarget formatter (fileTarget path)
222222
)
223223

224-
exitCode <- lift $ withFile merged WriteMode $ \out -> do
225-
withCreateProcess
226-
(proc "git" ["merge-file", "--stdout", local, base, remote])
227-
{ std_out = UseHandle out
228-
}
229-
$ \_ _ _ -> waitForProcess
224+
lift $ callProcess "git" ["merge-file", local, base, remote]
225+
-- git merge-file writes the result to the local version
230226

231-
case exitCode of
232-
ExitFailure code -> do
233-
output <- lift $ readFile merged
234-
throwE $ output <> "`git merge-file` failed with exit code " <> show code <> "\n"
235-
ExitSuccess -> return ()
227+
ExceptT $ formatTarget formatter (fileTarget local)
236228

237-
ExceptT $ formatTarget formatter (fileTarget merged)
229+
-- Atomic move at the end
230+
lift $ renameFile local merged
238231
mergeToolJob _ = return $ Left "--mergetool mode expects exactly 4 file arguments ($BASE, $LOCAL, $REMOTE, $MERGED)"
239232

240233
toJobs :: Nixfmt -> IO [IO Result]

0 commit comments

Comments
 (0)