瀏覽代碼

Write files atomically using rename to avoid some minor glitches

Jordi Boggiano 5 年之前
父節點
當前提交
7abdab2e99
共有 1 個文件被更改,包括 13 次插入11 次删除
  1. 13 11
      src/Packagist/WebBundle/Package/SymlinkDumper.php

+ 13 - 11
src/Packagist/WebBundle/Package/SymlinkDumper.php

@@ -306,7 +306,7 @@ class SymlinkDumper
 
                     // store affected files to clean up properly in the next update
                     $this->fs->mkdir(dirname($buildDir.'/'.$name));
-                    $this->writeFile($buildDir.'/'.$name.'.files', json_encode(array_keys($affectedFiles)));
+                    $this->writeFileNonAtomic($buildDir.'/'.$name.'.files', json_encode(array_keys($affectedFiles)));
 
                     $dumpTimeUpdates[$dumpTime->format('Y-m-d H:i:s')][] = $package->getId();
                 }
@@ -613,14 +613,6 @@ class SymlinkDumper
             ksort($this->rootFile['packages'][$package]);
         }
 
-        if (file_exists($file)) {
-            $timedFile = $file.'-'.time();
-            rename($file, $timedFile);
-            if (file_exists($file.'.gz')) {
-                rename($file.'.gz', $timedFile.'.gz');
-            }
-        }
-
         $json = json_encode($this->rootFile, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
         $time = time();
 
@@ -860,10 +852,20 @@ class SymlinkDumper
 
     private function writeFile($path, $contents, $mtime = null)
     {
-        file_put_contents($path, $contents);
+        file_put_contents($path.'.tmp', $contents);
         if ($mtime !== null) {
-            touch($path, $mtime);
+            touch($path.'.tmp', $mtime);
+        }
+        rename($path.'.tmp', $path);
+
+        if (is_array($this->writeLog)) {
+            $this->writeLog[$path] = array($contents, $mtime);
         }
+    }
+
+    private function writeFileNonAtomic($path, $contents)
+    {
+        file_put_contents($path, $contents);
 
         if (is_array($this->writeLog)) {
             $this->writeLog[$path] = array($contents, $mtime);