Skip to content

[12.x] Add storage:clear Artisan command to delete files or folders on a configured disk #55719

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: 12.x
Choose a base branch
from
Open
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
109 changes: 109 additions & 0 deletions src/Illuminate/Foundation/Console/StorageClearCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
<?php

namespace Illuminate\Foundation\Console;

use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
use Illuminate\Contracts\Filesystem\Factory as FilesystemFactory;
use Illuminate\Contracts\Filesystem\Filesystem;
use InvalidArgumentException;
use Symfony\Component\Console\Attribute\AsCommand;

#[AsCommand(name: 'storage:clear')]
class StorageClearCommand extends Command
{
use ConfirmableTrait;

/**
* The console command signature.
*
* @var string
*/
protected $signature = 'storage:clear
{--disk=local : The storage disk to clear}
Copy link
Contributor

@MrPunyapal MrPunyapal May 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will be better to have disk as a argument at the place of option!

{--folder= : The specific folder within the disk}
{--force : Force the operation to run when in production}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Clear a specific folder or all contents of a given storage disk (e.g., local, public, s3)';

/**
* Execute the console command.
*
* @return void
*/
public function handle(FilesystemFactory $filesystem)
{
if (! $this->confirmToProceed()) {
return;
}

$diskName = $this->option('disk');
$folder = $this->option('folder');
$folder = $folder ? trim($folder, '/') : null;

try {
$disk = $filesystem->disk($diskName);
} catch (InvalidArgumentException $e) {
$availableDisks = implode(', ', array_keys(config('filesystems.disks')));
$this->error("Disk [{$diskName}] is not configured. Available disks: {$availableDisks}");

return;
}

try {
if ($folder) {
if (! $disk->exists($folder)) {
$this->error("The folder [{$folder}] does not exist on the [{$diskName}] disk.");

return;
}

$this->clearFolder($disk, $folder);
$this->line("Cleared folder [{$folder}] on disk [{$diskName}].");
} else {
$this->clearDisk($disk, $diskName);
$this->line("Cleared all contents on disk [{$diskName}].");
}
} catch (\Throwable $e) {
Comment on lines +58 to +72
Copy link

@5baddi 5baddi May 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactored the logic to make it cleaner and easier to follow. Now, if a folder is provided but doesn’t exist, it exits early with an error. If the folder exists, it gets cleared, otherwise the entire disk is cleared.
This avoids deep nesting and keeps each action clearly separated.

Suggested change
try {
if ($folder) {
if (! $disk->exists($folder)) {
$this->error("The folder [{$folder}] does not exist on the [{$diskName}] disk.");
return;
}
$this->clearFolder($disk, $folder);
$this->line("Cleared folder [{$folder}] on disk [{$diskName}].");
} else {
$this->clearDisk($disk, $diskName);
$this->line("Cleared all contents on disk [{$diskName}].");
}
} catch (\Throwable $e) {
try {
if ($folder && ! $disk->exists($folder)) {
$this->error("The folder [{$folder}] does not exist on the [{$diskName}] disk.");
return;
}
if ($folder) {
$this->clearFolder($disk, $folder);
$this->line("Cleared folder [{$folder}] on disk [{$diskName}].");
return;
}
$this->clearDisk($disk, $diskName);
$this->line("Cleared all contents on disk [{$diskName}].");
} catch (\Throwable $e) {

$this->error("An error occurred while clearing storage: {$e->getMessage()}");
}
}

protected function clearDisk(Filesystem $disk, string $diskName): void
{
$files = $disk->files();
$directories = $disk->directories();

foreach ($files as $file) {
if ($diskName === 'local' && basename($file) === '.gitignore') {
$this->line("Skipping [.gitignore] on [{$diskName}] disk.");
continue;
}

$disk->delete($file);
}

foreach ($directories as $directory) {
$disk->deleteDirectory($directory);
}
}

protected function clearFolder(Filesystem $disk, string $folder): void
{
$files = $disk->allFiles($folder);
$directories = $disk->allDirectories($folder);

foreach ($files as $file) {
$disk->delete($file);
}

foreach (array_reverse($directories) as $directory) {
$disk->deleteDirectory($directory);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
use Illuminate\Foundation\Console\RuleMakeCommand;
use Illuminate\Foundation\Console\ScopeMakeCommand;
use Illuminate\Foundation\Console\ServeCommand;
use Illuminate\Foundation\Console\StorageClearCommand;
use Illuminate\Foundation\Console\StorageLinkCommand;
use Illuminate\Foundation\Console\StorageUnlinkCommand;
use Illuminate\Foundation\Console\StubPublishCommand;
Expand Down Expand Up @@ -169,6 +170,7 @@ class ArtisanServiceProvider extends ServiceProvider implements DeferrableProvid
'ScheduleInterrupt' => ScheduleInterruptCommand::class,
'ShowModel' => ShowModelCommand::class,
'StorageLink' => StorageLinkCommand::class,
'StorageClear' => StorageClearCommand::class,
'StorageUnlink' => StorageUnlinkCommand::class,
'Up' => UpCommand::class,
'ViewCache' => ViewCacheCommand::class,
Expand Down
117 changes: 117 additions & 0 deletions tests/Integration/Console/StorageClearCommandTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?php

namespace Illuminate\Tests\Foundation\Console;

use Illuminate\Support\Facades\Storage;
use Orchestra\Testbench\TestCase;

class StorageClearCommandTest extends TestCase
{
public function testClearAllFilesFromDisk()
{
Storage::fake('local');

Storage::disk('local')->put('file1.txt', 'test');
Storage::disk('local')->put('file2.txt', 'test');

$this->artisan('storage:clear')
->assertExitCode(0)
->expectsOutput('Cleared all contents on disk [local].');

Storage::disk('local')->assertMissing('file1.txt');
Storage::disk('local')->assertMissing('file2.txt');
}

public function testClearSpecificFolderFromDisk()
{
Storage::fake('local');

Storage::disk('local')->put('folder1/file1.txt', 'test');
Storage::disk('local')->put('folder1/subfolder/file2.txt', 'test');
Storage::disk('local')->put('folder2/keep.txt', 'test');

$this->artisan('storage:clear', [
'--disk' => 'local',
'--folder' => 'folder1',
])
->assertExitCode(0)
->expectsOutput('Cleared folder [folder1] on disk [local].');

Storage::disk('local')->assertMissing('folder1/file1.txt');
Storage::disk('local')->assertMissing('folder1/subfolder/file2.txt');
Storage::disk('local')->assertExists('folder2/keep.txt');
}

public function testThrowsErrorForInvalidDisk()
{
$invalidDisk = 'invalidDisk';
$availableDisks = implode(', ', array_keys(config('filesystems.disks', [])));

$this->artisan('storage:clear', [
'--disk' => $invalidDisk,
])
->assertExitCode(0)
->expectsOutput("Disk [{$invalidDisk}] is not configured. Available disks: {$availableDisks}");
}

public function testSkipsIfUserDoesNotConfirm()
{
$this->app['env'] = 'production';
Storage::fake('local');
Storage::disk('local')->put('file.txt', 'test');

$this->artisan('storage:clear', [
'--disk' => 'local',
])
->expectsConfirmation('Are you sure you want to run this command?', 'no')
->assertExitCode(0);

Storage::disk('local')->assertExists('file.txt');
}

public function testForceOptionBypassesConfirmationInProduction()
{
$this->app['env'] = 'production';

Storage::fake('local');
Storage::disk('local')->put('file.txt', 'test');

$this->artisan('storage:clear', [
'--disk' => 'local',
'--force' => true,
])
->assertExitCode(0)
->expectsOutput('Cleared all contents on disk [local].');

Storage::disk('local')->assertMissing('file.txt');
}

public function testGitignoreIsSkippedWhenClearingLocalDisk()
{
Storage::fake('local');
Storage::disk('local')->put('.gitignore', 'content');
Storage::disk('local')->put('delete-me.txt', 'content');

$this->artisan('storage:clear', [
'--disk' => 'local',
])
->assertExitCode(0)
->expectsOutput('Skipping [.gitignore] on [local] disk.')
->expectsOutput('Cleared all contents on disk [local].');

Storage::disk('local')->assertExists('.gitignore');
Storage::disk('local')->assertMissing('delete-me.txt');
}

public function testFolderNotFoundShowsError()
{
Storage::fake('local');

$this->artisan('storage:clear', [
'--disk' => 'local',
'--folder' => 'nonexistent',
])
->assertExitCode(0)
->expectsOutput('The folder [nonexistent] does not exist on the [local] disk.');
}
}