]> khamidou — GitHub mirrors - vcrpy.git/commitdiff
add back the secure write
authorKevin McCarthy <me@kevinmccarthy.org>
Wed, 7 Aug 2013 05:06:55 +0000 (19:06 -1000)
committerKevin McCarthy <me@kevinmccarthy.org>
Mon, 12 Aug 2013 01:05:40 +0000 (15:05 -1000)
vcr/files.py

index 59ac42854b62f62babcb508e9657e17d1c6bd360..6850dd1d150b98df7264f4a27f9711a6a4f2980a 100644 (file)
@@ -1,3 +1,4 @@
+import tempfile
 import os
 import yaml
 
@@ -7,13 +8,22 @@ try:
 except ImportError:
     from yaml import Loader, Dumper
 
+def _secure_write(path, contents):
+    """
+    We'll overwrite the old version securely by writing out a temporary
+    version and then moving it to replace the old version
+    """
+    dirname, filename = os.path.split(path)
+    fd, name = tempfile.mkstemp(dir=dirname, prefix=filename)
+    with os.fdopen(fd, 'w') as fout:
+        fout.write(contents)
+        os.rename(name, path)
+
 def load_cassette(cassette_path):
     return yaml.load(open(cassette_path), Loader=Loader)
 
 def save_cassette(cassette_path, data):
-    #TODO: safe overwrite using tmpfile
     dirname, filename = os.path.split(cassette_path)
     if not os.path.exists(dirname):
         os.makedirs(dirname)
-    with open(cassette_path, 'w') as cassette_file:
-        cassette_file.write(yaml.dump(data, Dumper=Dumper))
+    _secure_write(cassette_path, yaml.dump(data, Dumper=Dumper))