on master help sign in
Add O_TRUNC when opening a file CC @Blaisorblade

Without this, when overwriting a preexisting file with encodeFile, if the new file is smaller, old content would still be kept at the end. To see this bug in practice, see: https://github.com/commercialhaskell/all-cabal-metadata/commit/fbc77b036a68b661341ebd0d7ef7ae204675c30b#diff-45fc817b365b94b2e1f375bbf374a81eR36

commit64bf8227f517d6bcd9ec37ac3e2bbb342e05e305 authorMichael Snoyman <michael@snoyman.com> dateMon 19 Sep 2016, 06:50 (10 years ago) parent56cc7ce
4 files changed+20−2
ChangeLog.md+4 Text/Libyaml.hs+1−1 test/Data/YamlSpec.hs+13 yaml.cabal+2−1
ChangeLog.md+4
@@ -1,3 +1,7 @@
1+## 0.8.18.7
2+
3+* Add `O_TRUNC` when opening files
4+
15## 0.8.18.6
26
37* s/fdopen/_fdopen on Windows [#96](https://github.com/snoyberg/yaml/issues/96)
Text/Libyaml.hs+1−1
@@ -511,7 +511,7 @@ decode bs =
511511-- XXX copied from GHC.IO.FD
512512std_flags, read_flags, output_flags, write_flags :: CInt
513513std_flags = Posix.o_NOCTTY
514−output_flags = std_flags .|. Posix.o_CREAT
514+output_flags = std_flags .|. Posix.o_CREAT .|. Posix.o_TRUNC
515515read_flags = std_flags .|. Posix.o_RDONLY
516516write_flags = output_flags .|. Posix.o_WRONLY
517517
test/Data/YamlSpec.hs+13
@@ -34,6 +34,8 @@ import Data.Vector (Vector)
3434import qualified Data.Vector as V
3535import Data.HashMap.Strict (HashMap)
3636import qualified Data.HashMap.Strict as HM
37+import System.IO (hClose)
38+import System.IO.Temp (withSystemTempFile)
3739
3840data TestJSON = TestJSON
3941 { string :: Text
@@ -152,6 +154,8 @@ spec = do
152154
153155 it "preserves Scientific precision" casePreservesScientificPrecision
154156
157+ it "truncates files" caseTruncatesFiles
158+
155159
156160specialStrings :: [T.Text]
157161specialStrings =
@@ -502,3 +506,12 @@ casePreservesScientificPrecision = do
502506 -- results, because of <https://github.com/bos/text/issues/34>.
503507 D.decodeEither "x: 9.78159610558926e-5" @?= Right (object
504508 [ "x" .= D.Number (read "9.78159610558926e-5") ])
509+
510+caseTruncatesFiles :: Assertion
511+caseTruncatesFiles = withSystemTempFile "truncate.yaml" $ \fp h -> do
512+ replicateM_ 500 $ B8.hPut h "HELLO WORLD!!!!!\n"
513+ hClose h
514+ let val = object ["hello" .= ("world" :: String)]
515+ D.encodeFile fp val
516+ res <- D.decodeFileEither fp
517+ either (Left . show) Right res `shouldBe` Right val
yaml.cabal+2−1
@@ -1,5 +1,5 @@
11name: yaml
2−version: 0.8.18.6
2+version: 0.8.18.7
33license: BSD3
44license-file: LICENSE
55author: Michael Snoyman <michael@snoyman.com>, Anton Ageev <antage@gmail.com>,Kirill Simonov
@@ -139,6 +139,7 @@ test-suite spec
139139 , aeson-qq
140140 , mockery
141141 , base-compat
142+ , temporary
142143 ghc-options: -Wall
143144
144145executable examples