Coder Social home page Coder Social logo

laravel-directory-cleanup's Introduction

Delete old files in Laravel apps

Latest Version on Packagist Software License run-tests Total Downloads

This package will delete old files from directories. You can use a configuration file to specify the maximum age of a file in a certain directory.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-directory-cleanup

In Laravel 5.5 the service provider will automatically get registered. In older versions of the framework just add the service provider in config/app.php file:

'providers' => [
    ...
    Spatie\DirectoryCleanup\DirectoryCleanupServiceProvider::class,

];

Next, you must publish the config file:

php artisan vendor:publish --provider="Spatie\DirectoryCleanup\DirectoryCleanupServiceProvider"

This is the content of the published config file laravel-directory-cleanup

return [

    'directories' => [

        /*
         * Here you can specify which directories need to be cleanup. All files older than
         * the specified amount of minutes will be deleted.
         */

        /*
        'path/to/a/directory' => [
            'deleteAllOlderThanMinutes' => 60 * 24,
        ],
        */
    ],

    /*
     * If a file is older than the amount of minutes specified, a cleanup policy will decide if that file
     * should be deleted. By default every file that is older than the specified amount of minutes
     * will be deleted.
     *
     * You can customize this behaviour by writing your own clean up policy.  A valid policy
     * is any class that implements `Spatie\DirectoryCleanup\Policies\CleanupPolicy`.
     */
    'cleanup_policy' => \Spatie\DirectoryCleanup\Policies\DeleteEverything::class,
];

Usage

Specify the directories that need cleaning in the config file.

When running the console command clean:directories all files in the specified directories older than deleteAllOlderThanMinutes will be deleted. Empty subdirectories will also be deleted.

This command can be scheduled in Laravel's console kernel.

// app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
   $schedule->command('clean:directories')->daily();
}

Writing a custom clean up policy

If you want to apply additional conditional logic before a file is deleted, you can replace the default cleanup_policy with a custom one. Create a class which implements Spatie\DirectoryCleanup\Policies\CleanupPolicy and add your logic to the shouldDelete method.

// app/CleanupPolicies/MyPolicy.php

namespace App\CleanupPolicies;

use Symfony\Component\Finder\SplFileInfo;
use Spatie\DirectoryCleanup\Policies\CleanupPolicy;

class MyPolicy implements CleanupPolicy
{
    public function shouldDelete(SplFileInfo $file) : bool
    {
        $filesToKeep = ['robots.txt'];

        return ! in_array($file->getFilename(), $filesToKeep);
    }
}

Changelog

Please see CHANGELOG for more information on what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-directory-cleanup's People

Contributors

adrianmrn avatar akoepcke avatar alexbowers avatar alexvanderbist avatar andreasnij avatar bluec avatar chapeupreto avatar freekmurze avatar gsi-luis avatar laravel-shift avatar lasserafn avatar m1guelpf avatar mariavilaro avatar neochief avatar patinthehat avatar peter279k avatar poldixd avatar schnoop avatar sebastiandedeyne avatar stefanzweifel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-directory-cleanup's Issues

Hidden files are not deleted

Any hidden files in the specified directory are not deleted, even with the default DeleteEverything policy. In fact it's currently impossible to write a policy that does delete hidden files.

Note that hidden files in any subdirectory are deleted so this is inconsistent behaviour (see #26)

Possibility of recursive delete?

Can we make it so it will delete the directories and files as well? i.e. if we use a temporary directory to store files and directories there and want to clean that temporary directory, then this deletes only files as of now. Is there a way to delete the directories as well? Thanks for your great tools.

Files are not deleted

I am simply trying to use this to delete old files from the storage directory. I am on Laravel 5.6. I run clean:directories and get a successful message:
$ php artisan clean:directories Cleaning directories... All done!
however no files in the storage directory are modified.

my config is as follows:

'/home/vagrant/code/myApp/storage' => [
            'deleteAllOlderThanMinutes' => 60,
        ],

I have also tried using just 'storage' as the folder key name.

no files are deleted. (my storage folder contains many files older than 60 minutes)

Use Storage facade in configuration?

Hi,

First, as with all your projects, great work!

My question : is it be possible to use the Storage facade to target (local) directories? Such as

Storage::disk('local_disk') => [
    'deleteAllOlderThanMinutes' => 60 * 24 * 7
]

As is, when running php artisan clean:directories, I get

In laravel-directory-cleanup.php line 21:
  Class 'Storage' not found 

If I add Use \Illuminate\Support\Facades\Storage as Storage; I get

In Facade.php line 218:
  A facade root has not been set.

The filename, directory name, or volume label syntax is incorrect.

I'm running laravel 7.20

this is my config

'directories' => [

    /*
     * Here you can specify which directories need to be cleanup. All files older than
     * the specified amount of minutes will be deleted.
     */


    'storage/app/public/' => [
        'deleteAllOlderThanMinutes' => 1,
    ],

],

After running clean:directories
I get The filename, directory name, or volume label syntax is incorrect.

is this compatible with laravel 7.2?

Thank you

Wrong console output if no files are deleted

When no files are deleted the console says
Cleaning directories...
Deleted 30 file(s) from storage/app/public/tmp/uploads.
Deleted 0 directory(ies) from storage/app/public/tmp/uploads.
All done!

<?php

use Spatie\DirectoryCleanup\Policies\DeleteEverything;

return [

    'directories' => [

        /*
         * Here you can specify which directories need to be cleanup. All files older than
         * the specified amount of minutes will be deleted.
         */


        'storage/app/public/tmp/uploads' => [
            'deleteAllOlderThanMinutes' => 30,
        ],

    ],

    /*
     * If a file is older than the amount of minutes specified, a cleanup policy will decide if that file
     * should be deleted. By default every file that is older that the specified amount of minutes
     * will be deleted.
     *
     * You can customize this behaviour by writing your own clean up policy.  A valid policy
     * is any class that implements `Spatie\DirectoryCleanup\Policies\CleanupPolicy`.
     */
    'cleanup_policy' => DeleteEverything::class,
];

If i put 'deleteAllOlderThanMinutes' => 60, then the same is said only saying deleted 60 files

I don't need the console output so is no big issue for me but just wanted to let you know

Different paths based on local / staging / production

We have some files stored in a temporary directory and the paths change depending whether we're on local, staging or production (the relative paths are the same, but the absolute paths change).

Is there a way to handle this using this package?

Stat failed - filemtime error

From time to time i am getting errors related to filemtime function used in directory cleanup.

[2019-11-10 03:47:52] NNTmux.ERROR: filemtime(): stat failed for /var/www/nntmux/resources/tmp/unrar/0/b38bf0fd-aa79-490d-b131-b9cae84dfe67/unrar/9a3b5665ffcb4b07ac08c500843b8c10.mkv {"exception":"[object] (ErrorException(code: 0): filemtime(): stat failed for /var/www/nntmux/resources/tmp/unrar/0/b38bf0fd-aa79-490d-b131-b9cae84dfe67/unrar/9a3b5665ffcb4b07ac08c500843b8c10.mkv at /var/www/nntmux/vendor/spatie/laravel-directory-cleanup/src/DirectoryCleaner.php:36)
[stacktrace]
#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(2, 'filemtime(): st...', '/var/www/nntmux...', 36, Array)
#1 /var/www/nntmux/vendor/spatie/laravel-directory-cleanup/src/DirectoryCleaner.php(36): filemtime('/var/www/nntmux...')
#2 [internal function]: Spatie\\DirectoryCleanup\\DirectoryCleaner->Spatie\\DirectoryCleanup\\{closure}(Object(Symfony\\Component\\Finder\\SplFileInfo), 240)
#3 /var/www/nntmux/vendor/laravel/framework/src/Illuminate/Support/Arr.php(611): array_filter(Array, Object(Closure), 1)
#4 /var/www/nntmux/vendor/laravel/framework/src/Illuminate/Support/Collection.php(352): Illuminate\\Support\\Arr::where(Array, Object(Closure))
#5 /var/www/nntmux/vendor/spatie/laravel-directory-cleanup/src/DirectoryCleaner.php(38): Illuminate\\Support\\Collection->filter(Object(Closure))
#6 /var/www/nntmux/vendor/spatie/laravel-directory-cleanup/src/DirectoryCleanupCommand.php(34): Spatie\\DirectoryCleanup\\DirectoryCleaner->deleteFilesOlderThanMinutes(240)
#7 /var/www/nntmux/vendor/spatie/laravel-directory-cleanup/src/DirectoryCleanupCommand.php(22): Spatie\\DirectoryCleanup\\DirectoryCleanupCommand->deleteFilesIfOlderThanMinutes('/var/www/nntmux...', 240)
#8 /var/www/nntmux/vendor/laravel/framework/src/Illuminate/Support/Traits/EnumeratesValues.php(176): Spatie\\DirectoryCleanup\\DirectoryCleanupCommand->Spatie\\DirectoryCleanup\\{closure}(Array, '/var/www/nntmux...')
#9 /var/www/nntmux/vendor/spatie/laravel-directory-cleanup/src/DirectoryCleanupCommand.php(25): Illuminate\\Support\\Collection->each(Object(Closure))
#10 [internal function]: Spatie\\DirectoryCleanup\\DirectoryCleanupCommand->handle()
#11 /var/www/nntmux/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(32): call_user_func_array(Array, Array)
#12 /var/www/nntmux/vendor/laravel/framework/src/Illuminate/Support/helpers.php(520): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#13 /var/www/nntmux/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(90): value(Object(Closure))
#14 /var/www/nntmux/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(34): Illuminate\\Container\\BoundMethod::callBoundMethod(Object(Illuminate\\Foundation\\Application), Array, Object(Closure))
#15 /var/www/nntmux/vendor/laravel/framework/src/Illuminate/Container/Container.php(591): Illuminate\\Container\\BoundMethod::call(Object(Illuminate\\Foundation\\Application), Array, Array, NULL)
#16 /var/www/nntmux/vendor/laravel/framework/src/Illuminate/Console/Command.php(202): Illuminate\\Container\\Container->call(Array)
#17 /var/www/nntmux/vendor/symfony/console/Command/Command.php(255): Illuminate\\Console\\Command->execute(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Illuminate\\Console\\OutputStyle))
#18 /var/www/nntmux/vendor/laravel/framework/src/Illuminate/Console/Command.php(189): Symfony\\Component\\Console\\Command\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Illuminate\\Console\\OutputStyle))
#19 /var/www/nntmux/vendor/symfony/console/Application.php(934): Illuminate\\Console\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#20 /var/www/nntmux/vendor/symfony/console/Application.php(273): Symfony\\Component\\Console\\Application->doRunCommand(Object(Spatie\\DirectoryCleanup\\DirectoryCleanupCommand), Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#21 /var/www/nntmux/vendor/symfony/console/Application.php(149): Symfony\\Component\\Console\\Application->doRun(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#22 /var/www/nntmux/vendor/laravel/framework/src/Illuminate/Console/Application.php(90): Symfony\\Component\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#23 /var/www/nntmux/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(131): Illuminate\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#24 /var/www/nntmux/artisan(35): Illuminate\\Foundation\\Console\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#25 {main}
"}

If i run clean:directories couple of times it will do the job eventually.

Allow to specify a Policy for each path

Would you be open to allow to specify a Policy for each path?

My use case is that I have some files to be kept in different directories that could be deleted from others.

For example, in a directory that preprocess bulk inserts to a SQL Server database I need to keep .fmt files which hold the format configuration to be used by the bcp CLI tool. But in a directory that accepts temporary uploads it is fine to delete such files.

I can workaround now by adding if clauses to my custom policy to check for the file path, but it would be cleaner to have a custom policy for such folders and defer to a standard one if not specified.

I could try sending a PR if that would be desirable.

Thanks!

Installation Error from Composer

I am a little new when it comes to maintaining composer packages, so I apologize if this seems obvious, but I want to make sure I understand the problem. When I try and install this package with composer it returns the following error:

Problem 1 - Installation request for spatie/laravel-directory-cleanup ^1.3 -> satisfiable by spatie/laravel-directory-cleanup[1.3.0]. - Conclusion: remove laravel/framework v5.7.28 - Conclusion: don't install laravel/framework v5.7.28 - spatie/laravel-directory-cleanup 1.3.0 requires illuminate/support ~5.8.0 -> satisfiable by illuminate/support[v5.8.0, v5.8.2]. - don't install illuminate/support v5.8.0|don't install laravel/framework v5.7.28 - don't install illuminate/support v5.8.2|don't install laravel/framework v5.7.28 - Installation request for laravel/framework (locked at v5.7.28, required as 5.7.*) -> satisfiable by laravel/framework[v5.7.28].

So if I'm reading this correctly, does it mean that the illuminate/support package I have isn't a high enough version? At this time I have laravel ^5.7 listed in composer json file, but I don't have illuminate/support listed at all. Doesn't laravel require it? Shouldn't it be listed based on that? When pacakges have requirements, don't those get "pulled in" automatically? Again, I know this seems like basic stuff but I'm trying to understand these concepts so any clarification would be appreciated!

Tag new release

It would be nice if you could tag a new release of this package, so that we get the merged package auto-discovery functionality (already mentioned in the readme).

Thanks!

how to use it with amazon s3 ?

am trying to clean up the old db backups, so i tried to use something like

Storage::disk('s3db') => [
    'deleteAllOlderThanMinutes' => 60 * 24 * 7
],
's3db' => [
    'driver' => 's3',
    'key'    => env('S3_KEY'),
    'secret' => env('S3_SECRET'),
    'region' => env('S3_REGION'),
    'bucket' => env('S3_DB_BUCKET'),
],

in the bucket i have a sub dir for each year, like 2015,2016,etc.. so how to access those folders ?

Empty folders is not deleted

I have tried the package on 3 environments, my local environment, a dev server and the production server. On all three old files were removed, but only my local environment manage to actually delete the empty folders. Do you have any idea why this is?

I can't manage to find any errors, but that could be a miss I guess.

I'm using version 1.2.4 since I haven't been able to update laravel yet.

'directories' => [
    'storage/app/temp' => [
        'deleteAllOlderThanMinutes' => 60 * 24 * 7,
    ],
],

Laravel 5.7

Failed to install with Laravel 5.7.* . Can we have a quick update please?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.