Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 37 additions & 7 deletions src/Service/SymlinkCleaner.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,18 @@ public function cleanSymlinks(string $themePath, SymfonyStyle $io, bool $isVerbo
return true;
}

$realCssPath = $this->fileDriver->getRealPath($cssPath);
if (!is_string($realCssPath)) {
return true;
}
$realCssPath = rtrim($realCssPath, '/');

$items = $this->fileDriver->readDirectory($cssPath);
$deletedCount = 0;

foreach ($items as $item) {
// Check if item is a symlink
if ($this->isSymlink($item)) {
if ($this->isSymlink($item, $realCssPath)) {
$this->fileDriver->deleteFile($item);
$deletedCount++;

Expand All @@ -81,36 +87,60 @@ public function cleanSymlinks(string $themePath, SymfonyStyle $io, bool $isVerbo
}

/**
* Check if a path is a symlink using stat info.
* Check if a directory entry is a symlink by comparing its resolved path with its expected location.
*
* The file driver offers no lstat(), and stat() follows links, so the file mode cannot be used.
* An entry whose real path differs from "<real directory>/<name>" (or cannot be resolved,
* i.e. a broken link) is a symlink.
*
* @param string $path
* @param string $realDirectory Resolved path of the directory containing the entry
* @return bool
*/
private function isSymlink(string $path): bool
private function isSymlink(string $path, string $realDirectory): bool
{
try {
$stat = $this->fileDriver->stat($path);
$realPath = $this->fileDriver->getRealPath($path);
} catch (\Exception $e) {
return false;
}

return ((int) ($stat['mode'] ?? 0) & 0o12_0000) === 0o12_0000;
if (!is_string($realPath)) {
return true;
}

return (
$this->normalizeSeparators($realPath)
!== $this->normalizeSeparators($realDirectory) . '/' . $this->getBasename($path)
);
}

/**
* Get basename without using basename().
*
* A backslash only separates path segments on Windows; on other platforms it is a valid filename character.
*
* @param string $path
* @return string
*/
private function getBasename(string $path): string
{
$normalized = str_replace('\\', '/', $path);
$trimmed = rtrim($normalized, '/');
$trimmed = rtrim($this->normalizeSeparators($path), '/');
$pos = strrpos($trimmed, '/');
if ($pos === false) {
return $trimmed;
}
return substr($trimmed, $pos + 1);
}

/**
* Convert platform-specific directory separators to forward slashes
*
* @param string $path
* @return string
*/
private function normalizeSeparators(string $path): string
{
return DIRECTORY_SEPARATOR === '\\' ? str_replace('\\', '/', $path) : $path;
}
}
94 changes: 83 additions & 11 deletions tests/Unit/Service/SymlinkCleanerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@

class SymlinkCleanerTest extends TestCase
{
private const SYMLINK_MODE = 0o12_0777;
private const REGULAR_FILE_MODE = 0o10_0644;

/**
* @var File&Stub
*/
Expand Down Expand Up @@ -69,10 +66,11 @@ public function testDeletesOnlySymlinks(): void
->method('readDirectory')
->willReturn(['/theme/web/css/styles.css', '/theme/web/css/link.css']);
$fileDriver
->method('stat')
->method('getRealPath')
->willReturnMap([
['/theme/web/css/styles.css', ['mode' => self::REGULAR_FILE_MODE]],
['/theme/web/css/link.css', ['mode' => self::SYMLINK_MODE]],
['/theme/web/css', '/theme/web/css'],
['/theme/web/css/styles.css', '/theme/web/css/styles.css'],
['/theme/web/css/link.css', '/shared/link.css'],
]);
$fileDriver->expects($this->once())->method('deleteFile')->with('/theme/web/css/link.css');
$io = $this->createMock(SymfonyStyle::class);
Expand All @@ -87,31 +85,101 @@ public function testVerboseModeWithoutSymlinksPrintsNoSuccess(): void
$this->state->method('getMode')->willReturn(State::MODE_DEVELOPER);
$this->fileDriver->method('isDirectory')->willReturn(true);
$this->fileDriver->method('readDirectory')->willReturn(['/theme/web/css/styles.css']);
$this->fileDriver->method('stat')->willReturn(['mode' => self::REGULAR_FILE_MODE]);
$this->fileDriver->method('getRealPath')->willReturnArgument(0);
$io = $this->createMock(SymfonyStyle::class);
$io->expects($this->never())->method('success');

$this->assertTrue($this->cleaner->cleanSymlinks('/theme', $io, true));
}

public function testTreatsUnstatableItemsAsRegularFiles(): void
public function testDeletesBrokenSymlinks(): void
{
$this->state->method('getMode')->willReturn(State::MODE_DEVELOPER);
$fileDriver = $this->createMock(File::class);
$fileDriver->method('isDirectory')->willReturn(true);
$fileDriver->method('readDirectory')->willReturn(['/theme/web/css/broken.css']);
$fileDriver->method('stat')->willThrowException(new \RuntimeException('stat failed'));
$fileDriver
->method('getRealPath')
->willReturnMap([
['/theme/web/css', '/theme/web/css'],
['/theme/web/css/broken.css', false],
]);
$fileDriver->expects($this->once())->method('deleteFile')->with('/theme/web/css/broken.css');

$this->assertTrue($this->createCleaner(fileDriver: $fileDriver)->cleanSymlinks('/theme', $this->io, false));
}

public function testKeepsRegularFilesInsideSymlinkedThemeDirectory(): void
{
$this->state->method('getMode')->willReturn(State::MODE_DEVELOPER);
$fileDriver = $this->createMock(File::class);
$fileDriver->method('isDirectory')->willReturn(true);
$fileDriver->method('readDirectory')->willReturn(['/theme/web/css/styles.css']);
$fileDriver
->method('getRealPath')
->willReturnMap([
['/theme/web/css', '/real/theme/web/css'],
['/theme/web/css/styles.css', '/real/theme/web/css/styles.css'],
]);
$fileDriver->expects($this->never())->method('deleteFile');

$this->assertTrue($this->createCleaner(fileDriver: $fileDriver)->cleanSymlinks('/theme', $this->io, false));
}

public function testKeepsRegularFileWithBackslashInName(): void
{
if (DIRECTORY_SEPARATOR === '\\') {
$this->markTestSkipped('A backslash is a path separator on Windows.');
}

$this->state->method('getMode')->willReturn(State::MODE_DEVELOPER);
$fileDriver = $this->createMock(File::class);
$fileDriver->method('isDirectory')->willReturn(true);
$fileDriver->method('readDirectory')->willReturn(['/theme/web/css/vendor\\styles.css']);
$fileDriver->method('getRealPath')->willReturnArgument(0);
$fileDriver->expects($this->never())->method('deleteFile');

$this->assertTrue($this->createCleaner(fileDriver: $fileDriver)->cleanSymlinks('/theme', $this->io, false));
}

public function testRemovesRealSymlinksFromFilesystem(): void
{
$state = $this->createStub(State::class);
$state->method('getMode')->willReturn(State::MODE_DEVELOPER);
$themePath = sys_get_temp_dir() . '/mageforge-symlink-' . uniqid();
$cssPath = $themePath . '/web/css';
mkdir($cssPath, 0o777, true);
file_put_contents($cssPath . '/styles.css', 'a{}');
file_put_contents($themePath . '/target.css', 'b{}');
symlink($themePath . '/target.css', $cssPath . '/link.css');
symlink($themePath . '/missing.css', $cssPath . '/broken.css');

try {
$cleaner = $this->createCleaner(fileDriver: new File(), state: $state);
$this->assertTrue($cleaner->cleanSymlinks($themePath, $this->io, false));

$this->assertFileExists($cssPath . '/styles.css');
$this->assertFileExists($themePath . '/target.css');
$this->assertFalse(is_link($cssPath . '/link.css'));
$this->assertFalse(is_link($cssPath . '/broken.css'));
} finally {
array_map('unlink', glob($cssPath . '/*') ?: []);
unlink($themePath . '/target.css');
rmdir($cssPath);
rmdir($themePath . '/web');
rmdir($themePath);
}
}

public function testReportsRemovedSymlinksInVerboseMode(): void
{
$this->state->method('getMode')->willReturn(State::MODE_DEVELOPER);
$this->fileDriver->method('isDirectory')->willReturn(true);
$this->fileDriver->method('readDirectory')->willReturn(['/theme/web/css/link.css']);
$this->fileDriver->method('stat')->willReturn(['mode' => self::SYMLINK_MODE]);
$this->fileDriver->method('getRealPath')->willReturnMap([
['/theme/web/css', '/theme/web/css'],
['/theme/web/css/link.css', '/shared/link.css'],
]);
$io = $this->createMock(SymfonyStyle::class);
$io->expects($this->once())->method('writeln')->with(' <fg=yellow>⚠</> Removed symlink: link.css');
$io->expects($this->once())->method('success')->with('Removed 1 symlink(s) from web/css/');
Expand All @@ -123,6 +191,7 @@ public function testSucceedsWithWarningWhenDirectoryCannotBeRead(): void
{
$this->state->method('getMode')->willReturn(State::MODE_DEVELOPER);
$this->fileDriver->method('isDirectory')->willReturn(true);
$this->fileDriver->method('getRealPath')->willReturnArgument(0);
$this->fileDriver->method('readDirectory')->willThrowException(new \RuntimeException('permission denied'));
$io = $this->createMock(SymfonyStyle::class);
$io->expects($this->once())->method('warning')->with('Could not clean symlinks: permission denied');
Expand All @@ -135,7 +204,10 @@ public function testReportsBasenameForItemWithoutDirectorySeparator(): void
$this->state->method('getMode')->willReturn(State::MODE_DEVELOPER);
$this->fileDriver->method('isDirectory')->willReturn(true);
$this->fileDriver->method('readDirectory')->willReturn(['link.css']);
$this->fileDriver->method('stat')->willReturn(['mode' => self::SYMLINK_MODE]);
$this->fileDriver->method('getRealPath')->willReturnMap([
['/theme/web/css', '/theme/web/css'],
['link.css', '/shared/link.css'],
]);
$io = $this->createMock(SymfonyStyle::class);
$io->expects($this->once())->method('writeln')->with(' <fg=yellow>⚠</> Removed symlink: link.css');

Expand Down
Loading