| 1 | use Perlmazing qw(croak dir devnull); | ||
| 2 | use File::Path qw(); | ||
| 3 | use IPC::Cmd qw(); | ||
| 4 | |||
| 5 | my $checked; | ||
| 6 | my $can_run_rm; | ||
| 7 | my $on_win32; | ||
| 8 | |||
| 9 | sub main { | ||
| 10 | if (not $checked) { | ||
| 11 | $on_win32 = ($^O eq 'MSWin32' or $^O eq 'WinNT'); | ||
| 12 | $can_run_rm = IPC::Cmd::can_run('rm'); | ||
| 13 | $checked++; | ||
| 14 | } | ||
| 15 | my $path = shift || $_; | ||
| 16 | |||
| 17 | # Let's have it behave as expected when the directory doesn't exist | ||
| 18 | return CORE::rmdir($path) unless -d $path; | ||
| 19 | |||
| 20 | # Why am I doing this? After using a previous implementation for a while | ||
| 21 | # and trying many others from CPAN, all of them had a common problem: | ||
| 22 | # it takes them 20 or more times to delete a big directory, compared to | ||
| 23 | # the native OS tools to remove a dir. So, we try that first. | ||
| 24 | my $count = 0; | ||
| 25 | # Hide messages printed out to console from commands. Errors should stay in $! only. | ||
| 26 | my $devnull = devnull; | ||
| 27 | my $stderr = ''; | ||
| 28 | my $stdout = ''; | ||
| 29 | { | ||
| 30 | local *STDERR; | ||
| 31 | local *STDOUT; | ||
| 32 | open STDERR, '>>', \$stderr; | ||
| 33 | open STDOUT, '>>', \$stdout; | ||
| 34 | if ($on_win32 or $can_run_rm) { | ||
| 35 | # We can't return the actual number of deleted items (without verifying and taking time) this way. Just 1 for the directory. | ||
| 36 | if ($on_win32) { | ||
| 37 | unless (system qq[rmdir /S /Q "$path" >$devnull 2>&1]) { | ||
| 38 | $count = 1; | ||
| 39 | } | ||
| 40 | } | ||
| 41 | # Not win32, but can rm: | ||
| 42 | # Also, some times, rm is present on win32, and some times, it succeeds to delete files that for some reason rmdir fails to delete. | ||
| 43 | # In such case, this won't take a noticeable extra time to try: | ||
| 44 | if (!$count) { | ||
| 45 | unless (system qq[$can_run_rm -rf "$path" >$devnull 2>&1]) { | ||
| 46 | $count = 1; | ||
| 47 | } | ||
| 48 | } | ||
| 49 | } | ||
| 50 | # If the previous steps didn't seem to work, we try the portable but slow Perl solution: | ||
| 51 | unless ($count) { | ||
| 52 | $count += eval { | ||
| 53 | File::Path::remove_tree($path); | ||
| 54 | }; | ||
| 55 | } | ||
| 56 | } | ||
| 57 | # If the directory is gone, $count should never be 0 | ||
| 58 | if (!$count and not -d $path) { | ||
| 59 | $count++; | ||
| 60 | } | ||
| 61 | $count; | ||
| 62 | } | ||
| 63 | |||
| 64 | 1; |