From 68bda32d0646c22004a9f20c6ef980ae4849be99 Mon Sep 17 00:00:00 2001 From: Thomas Gerbet Date: Mon, 6 May 2019 21:47:51 +0200 Subject: [PATCH] Preserve file permissions when updating a file The change of permissions is not explicitely requested by the user and is not shown in the dry-run. It makes Rector harder to use when the sources of a project has some executable scripts. --- .../Printer/FormatPerservingPrinter.php | 2 +- .../Printer/FormatPerservingPrinterTest.php | 42 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 tests/PhpParser/Printer/FormatPerservingPrinterTest.php diff --git a/src/PhpParser/Printer/FormatPerservingPrinter.php b/src/PhpParser/Printer/FormatPerservingPrinter.php index 383d33b9a01c..a42852240231 100644 --- a/src/PhpParser/Printer/FormatPerservingPrinter.php +++ b/src/PhpParser/Printer/FormatPerservingPrinter.php @@ -28,7 +28,7 @@ public function printToFile(SmartFileInfo $fileInfo, array $newStmts, array $old { $newContent = $this->printToString($newStmts, $oldStmts, $oldTokens); - FileSystem::write($fileInfo->getRealPath(), $newContent); + FileSystem::write($fileInfo->getRealPath(), $newContent, $fileInfo->getPerms()); return $newContent; } diff --git a/tests/PhpParser/Printer/FormatPerservingPrinterTest.php b/tests/PhpParser/Printer/FormatPerservingPrinterTest.php new file mode 100644 index 000000000000..70e383d49580 --- /dev/null +++ b/tests/PhpParser/Printer/FormatPerservingPrinterTest.php @@ -0,0 +1,42 @@ +bootKernel(RectorKernel::class); + $this->formatPerservingPrinter = self::$container->get(FormatPerservingPrinter::class); + } + + protected function tearDown(): void + { + FileSystem::delete(__DIR__ . '/Fixture'); + } + + public function testFileModeIsPreserved(): void + { + mkdir(__DIR__ . '/Fixture'); + touch(__DIR__ . '/Fixture/file.php'); + $expectedFilemod = 0755; + chmod(__DIR__ . '/Fixture/file.php', $expectedFilemod); + + $fileInfo = new SmartFileInfo(__DIR__ . '/Fixture/file.php'); + + $this->formatPerservingPrinter->printToFile($fileInfo, [], [], []); + + $this->assertSame($expectedFilemod, fileperms(__DIR__ . '/Fixture/file.php') & 0777); + } +}