| 1 | package App::Pfind; | ||
| 2 | |||
| 3 | use 5.022; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | |||
| 7 | use Data::Dumper; | ||
| 8 | use Fcntl ':mode'; | ||
| 9 | use File::Find; | ||
| 10 | use File::Path qw(make_path remove_tree); | ||
| 11 | use Getopt::Long qw(GetOptionsFromArray :config auto_abbrev no_ignore_case | ||
| 12 | permute auto_version); | ||
| 13 | use Pod::Usage; | ||
| 14 | use Safe; | ||
| 15 | |||
| 16 | our $VERSION = '1.05'; | ||
| 17 | |||
| 18 | $Data::Dumper::Terse = 1; # Don't output variable names. | ||
| 19 | $Data::Dumper::Sortkeys = 1; # Sort the content of the hash variables. | ||
| 20 | $Data::Dumper::Useqq = 1; # Use double quote for string (better escaping). | ||
| 21 | |||
| 22 | { | ||
| 23 | # A simple way to make a scalar be read-only. | ||
| 24 | package App::Pfind::ReadOnlyVar; | ||
| 25 | sub TIESCALAR { | ||
| 26 | my ($class, $value) = @_; | ||
| 27 | return bless \$value, $class; | ||
| 28 | } | ||
| 29 | sub FETCH { | ||
| 30 | my ($self) = @_; | ||
| 31 | return $$self; | ||
| 32 | } | ||
| 33 | # Does nothing. We could warn_or_die, but it does not play well with the fact | ||
| 34 | # that we are inside the safe. | ||
| 35 | sub STORE {} | ||
| 36 | # Secret hidden methods for our usage only. These methods can't be used | ||
| 37 | # through the tie-ed variable, but only through the object returned by the | ||
| 38 | # call to tie. | ||
| 39 | sub set { | ||
| 40 | my ($self, $value) = @_; | ||
| 41 | $$self = $value; | ||
| 42 | } | ||
| 43 | } | ||
| 44 | |||
| 45 | # These two variables are shared with the user code. They have this name as a | ||
| 46 | # localized copy is passed to the code. | ||
| 47 | our ($internal_pfind_dir, $internal_pfind_name); | ||
| 48 | my $dir_setter = tie $internal_pfind_dir, 'App::Pfind::ReadOnlyVar'; | ||
| 49 | my $name_setter = tie $internal_pfind_name, 'App::Pfind::ReadOnlyVar'; | ||
| 50 | |||
| 51 | # A Safe object, created in reset_options. | ||
| 52 | my $safe; | ||
| 53 | |||
| 54 | # This hash contains options that are global for the whole program. | ||
| 55 | my %options; | ||
| 56 | |||
| 57 | # Methods that are shared with the safe: | ||
| 58 | |||
| 59 | sub prune { | ||
| 60 | die "The prune command cannot be used when --depth-first is set.\n" if $options{depth_first}; | ||
| 61 | $File::Find::prune = 1; | ||
| 62 | } | ||
| 63 | # The prototype means that $_ will be used if nothing else is passed. | ||
| 64 | sub mkdir(_;@) { | ||
| 65 | my $err; | ||
| 66 | make_path(@_, { error => \$err }); | ||
| 67 | # make_path sets $! on success (as it test the existance of the file). | ||
| 68 | undef $!; | ||
| 69 | $! = join(', ', @$err) if @$err; | ||
| 70 | } | ||
| 71 | sub rmdir(_;@) { | ||
| 72 | for my $d (@_) { | ||
| 73 | CORE::rmdir($d); | ||
| 74 | } | ||
| 75 | } | ||
| 76 | # A safe 'rm' that does not recurse into directories. | ||
| 77 | sub rm(_;@) { | ||
| 78 | for my $f (@_) { | ||
| 79 | if (-d $f) { | ||
| 80 | CORE::rmdir($f); | ||
| 81 | return if $!; | ||
| 82 | } else { | ||
| 83 | my $err; | ||
| 84 | remove_tree($f, { error => \$err }); | ||
| 85 | undef $!; | ||
| 86 | $! = join(', ', @$err) if @$err; | ||
| 87 | } | ||
| 88 | } | ||
| 89 | } | ||
| 90 | sub rmtree(_;@) { | ||
| 91 | my $err; | ||
| 92 | remove_tree(@_, { error => \$err }); | ||
| 93 | undef $!; | ||
| 94 | $! = join(', ', @$err) if @$err; | ||
| 95 | } | ||
| 96 | |||
| 97 | sub reset_options { | ||
| 98 | $safe = Safe->new(); | ||
| 99 | $safe->deny_only(':ownprocess', ':others', ':dangerous'); | ||
| 100 | $safe->reval('use File::Spec::Functions qw(:ALL);'); | ||
| 101 | $safe->reval('use File::Copy qw(cp mv)'); | ||
| 102 | $safe->share('$internal_pfind_dir', '$internal_pfind_name', 'prune', 'mkdir', | ||
| 103 | 'rmdir', 'rm', 'rmtree'); | ||
| 104 | $safe->share_from('main', ['*STDERR']); | ||
| 105 | |||
| 106 | # Whether to process the content of a directory before the directory itself. | ||
| 107 | $options{depth_first} = 0; | ||
| 108 | # Whether to follow the symlinks. | ||
| 109 | $options{follow} = 0; | ||
| 110 | # Whether to follow the symlinks using a fast method that may process some files twice. | ||
| 111 | $options{follow_fast} = 0; | ||
| 112 | # Whether to recurse in directories. | ||
| 113 | $options{recurse} = 1; | ||
| 114 | # Blocks of code to execute before the main loop | ||
| 115 | $options{begin} = []; | ||
| 116 | # Blocks of code to execute after the main loop | ||
| 117 | $options{end} = []; | ||
| 118 | # Blocks of code to execute for each file and directory encountered | ||
| 119 | $options{exec} = []; | ||
| 120 | # Blocks of code to execute at the beginning of the processing of each directory | ||
| 121 | $options{pre} = []; | ||
| 122 | # Blocks of code to execute at the end of the processing of each directory | ||
| 123 | $options{post} = []; | ||
| 124 | # Type of files that are processed. Note that after the reading of the option, this is concatenated in a string. | ||
| 125 | $options{type} = []; | ||
| 126 | # Whether to chdir in the crawled directories | ||
| 127 | $options{chdir} = 1; | ||
| 128 | # Whether to catch errors returned in $! in user code | ||
| 129 | $options{catch_errors} = 1; # non-modifiable for now. | ||
| 130 | # Add this string after each print statement | ||
| 131 | $options{print} = "\n"; | ||
| 132 | # If true, debug message are printed on STDERR | ||
| 133 | $options{verbose} = 0; | ||
| 134 | } | ||
| 135 | |||
| 136 | sub all_options {( | ||
| 137 | 'help|h' => sub { pod2usage(-exitval => 0, -verbose => 2) }, | ||
| 138 | 'depth-first|depth|d!' => \$options{depth_first}, | ||
| 139 | 'follow|f!' => \$options{follow}, | ||
| 140 | 'follow-fast|ff!' => \$options{follow_fast}, | ||
| 141 | 'recurse|r!' => \$options{recurse}, | ||
| 142 | 'type|t=s@' => $options{type}, | ||
| 143 | 'chdir!' => \$options{chdir}, | ||
| 144 | 'print|p=s' => \$options{print}, | ||
| 145 | 'begin|BEGIN|B=s@' => $options{begin}, | ||
| 146 | 'end|END|E=s@' => $options{end}, | ||
| 147 | 'pre|pre-process=s@' => $options{pre}, | ||
| 148 | 'post|post-process=s@' => $options{post}, | ||
| 149 | 'exec|e=s@' => $options{exec}, | ||
| 150 | 'verbose|v|V+' => \$options{verbose}, | ||
| 151 | )} | ||
| 152 | |||
| 153 | sub eval_code { | ||
| 154 | my ($code, $flag) = @_; | ||
| 155 | my $r = $safe->reval($code); | ||
| 156 | if ($@) { | ||
| 157 | die "Failure in the code given to --${flag}: ${@}\n"; | ||
| 158 | } | ||
| 159 | return $r; | ||
| 160 | } | ||
| 161 | |||
| 162 | sub wrap_code_blocks { | ||
| 163 | my ($code_blocks, $default_variable_value, $flag) = @_; | ||
| 164 | # We're building a sub that will execute each given piece of code in a block. | ||
| 165 | # That way we can evaluate this code in the safe once and get the sub | ||
| 166 | # reference (so that it does not need to be recompiled for each file). In | ||
| 167 | # addition, control flow keywords (mainly next, redo and return) can be used | ||
| 168 | # in each block. | ||
| 169 | my $block_start = '{ my $tmp_pfind_default = '.$default_variable_value.'; '; | ||
| 170 | $block_start .= "print { *STDERR } 'Executing code $flag:'.\$internal_pfind_block_count++;" if $options{verbose}; | ||
| 171 | $block_start .= 'local $_ = $tmp_pfind_default;' | ||
| 172 | .'local $dir = $internal_pfind_dir;' | ||
| 173 | .'local $name = $internal_pfind_name;'; | ||
| 174 | my $block_end = $options{catch_errors} ? '} die "$!\n" if $!;' : '} '; | ||
| 175 | my $all_exec_code = 'sub { my $internal_pfind_block_count = 1;' | ||
| 176 | .${block_start}.join("${block_end} \n ${block_start}", @$code_blocks).${block_end} | ||
| 177 | .' }'; | ||
| 178 | print STDERR $all_exec_code if $options{verbose} > 2; | ||
| 179 | return eval_code($all_exec_code, 'exec'); | ||
| 180 | } | ||
| 181 | |||
| 182 | sub run_wrapped_sub { | ||
| 183 | my ($wrapped_code, $flag) = @_; | ||
| 184 | # Instead of using our local variables, we could share the real one here: | ||
| 185 | # $safe->share_from('File::Find', ['$dir', '$name']); | ||
| 186 | # They have to be shared inside the sub as they are 'localized' each time. | ||
| 187 | # That approach would be slower by a small factor though. | ||
| 188 | $dir_setter->set($File::Find::dir); | ||
| 189 | $name_setter->set($File::Find::name); | ||
| 190 | undef $!; | ||
| 191 | $wrapped_code->(); | ||
| 192 | die "Failure in the code given to --${flag}: $!\n" if $!; | ||
| 193 | } | ||
| 194 | |||
| 195 | # Perform a real-stat or just reads the result from the previous stat. Returns | ||
| 196 | # just the mode part of the stat. | ||
| 197 | my $last_stated_file = ''; | ||
| 198 | sub cheap_stat { | ||
| 199 | my ($relative_file_name, $full_file_name) = @_; | ||
| 200 | return (stat(_))[2] if $full_file_name eq $last_stated_file; | ||
| 201 | $last_stated_file = $full_file_name; | ||
| 202 | # When executing find in follow mode, the current file has already been | ||
| 203 | # stat-ed (this is guaranteed by find), so we can re-use the value using `_`. | ||
| 204 | return (stat(_))[2] if $options{follow} || $options{follow_fast}; | ||
| 205 | return (stat($relative_file_name))[2]; | ||
| 206 | } | ||
| 207 | |||
| 208 | my %file_mode = ( | ||
| 209 | f => S_IFREG, # regular file | ||
| 210 | d => S_IFDIR, # directory | ||
| 211 | l => S_IFLNK, # symbolic link | ||
| 212 | b => S_IFBLK, # block special file | ||
| 213 | c => S_IFCHR, # character special file | ||
| 214 | p => S_IFIFO, # fifo (pipe) | ||
| 215 | s => S_IFSOCK, # socket | ||
| 216 | # S_IFWHT and S_ENFMT are not supported (they're Sys-V specific features) | ||
| 217 | ); | ||
| 218 | |||
| 219 | sub should_skip_file { | ||
| 220 | my ($relative_file_name, $full_file_name) = @_; | ||
| 221 | return 0 unless %{$options{type}}; | ||
| 222 | my $mode = cheap_stat($relative_file_name, $full_file_name); | ||
| 223 | for my $m (keys(%{$options{type}})) { | ||
| 224 | if (($mode & $file_mode{$m}) xor $options{type}{$m}) { | ||
| 225 | print STDERR "Skipping '$full_file_name' due to '$m' type" if $options{verbose}; | ||
| 226 | return 1; | ||
| 227 | } | ||
| 228 | } | ||
| 229 | return 0; | ||
| 230 | } | ||
| 231 | |||
| 232 | sub Run { | ||
| 233 | my ($argv) = @_; | ||
| 234 | |||
| 235 | reset_options(); | ||
| 236 | # After the GetOptions call this will contain the input directories. | ||
| 237 | my @inputs = @$argv; | ||
| 238 | GetOptionsFromArray(\@inputs, all_options()) | ||
| 239 | or pod2usage(-exitval => 2, -verbose => 0); | ||
| 240 | |||
| 241 | # With this the -v option (--verbose) will still trigger the behavior of the | ||
| 242 | # --version option (although it won't stop the execution). | ||
| 243 | Getopt::Long::VersionMessage({-exitval => 'NOEXIT', -output => \*STDERR}) if $options{verbose}; | ||
| 244 | |||
| 245 | if (not @{$options{exec}}) { | ||
| 246 | $options{exec} = ['print $name']; | ||
| 247 | } | ||
| 248 | |||
| 249 | $options{type} = { map { lc() => ($_ eq lc()) } split(//, join('', @{$options{type}})) }; | ||
| 250 | |||
| 251 | print STDERR "options = ".Dumper({%options}) if $options{verbose} > 1; | ||
| 252 | |||
| 253 | if ($options{follow} && $options{follow_fast}) { | ||
| 254 | die "The --follow and --follow-fast options cannot be used together.\n"; | ||
| 255 | } | ||
| 256 | my $follow_mode = $options{follow} || $options{follow_fast}; | ||
| 257 | if (@{$options{pre}} && $follow_mode) { | ||
| 258 | die "The --pre-process option cannot be used with --follow or --follow-fast.\n"; | ||
| 259 | } | ||
| 260 | if (@{$options{post}} && $follow_mode) { | ||
| 261 | die "The --post-process option cannot be used with --follow or --follow-fast.\n"; | ||
| 262 | } | ||
| 263 | if (not $options{recurse} and $options{depth_first}) { | ||
| 264 | die "The --no-recurse option cannot be used with --depth-first.\n"; | ||
| 265 | } | ||
| 266 | if (join('', keys %{$options{type}}) !~ /^[fdlpsbc]*$/) { | ||
| 267 | die "Unsupported value for the --type option.\n"; | ||
| 268 | } | ||
| 269 | if (not @inputs) { | ||
| 270 | print STDERR "No input given on the command-line. Exiting without doing any work."; | ||
| 271 | exit 1; | ||
| 272 | } | ||
| 273 | |||
| 274 | $\ = $options{print}; | ||
| 275 | |||
| 276 | for my $c (@{$options{begin}}) { | ||
| 277 | eval_code($c, 'BEGIN'); | ||
| 278 | } | ||
| 279 | |||
| 280 | my $wrapped_exec = wrap_code_blocks($options{exec}, '$_', 'exec'); | ||
| 281 | # The $_ variable inside these method will be set to $File::Find::dir (as the | ||
| 282 | # real $_ does not contain anything useful in that case). | ||
| 283 | my $wrapped_pre; | ||
| 284 | if (@{$options{pre}}) { | ||
| 285 | $wrapped_pre = wrap_code_blocks($options{pre}, '$internal_pfind_dir', 'pre'); | ||
| 286 | } | ||
| 287 | my $wrapped_post; | ||
| 288 | if (@{$options{post}}) { | ||
| 289 | $wrapped_post = wrap_code_blocks($options{post}, '$internal_pfind_dir', 'post'); | ||
| 290 | } | ||
| 291 | |||
| 292 | find({ | ||
| 293 | bydepth => $options{depth_first}, | ||
| 294 | follow => $options{follow}, | ||
| 295 | follow_fast => $options{follow_fast}, | ||
| 296 | no_chdir => !$options{chdir}, | ||
| 297 | wanted => sub { | ||
| 298 | if (not $options{recurse} and cheap_stat($_, $File::Find::name) & S_IFDIR) { | ||
| 299 | print "Will not recurse into $File::Find::name" if $options{verbose}; | ||
| 300 | $File::Find::prune = 1; | ||
| 301 | } | ||
| 302 | print STDERR "Looking at file: $File::Find::name" if $options{verbose}; | ||
| 303 | return if should_skip_file($_, $File::Find::name); | ||
| 304 | run_wrapped_sub($wrapped_exec, 'exec'); | ||
| 305 | }, | ||
| 306 | preprocess => sub { | ||
| 307 | print STDERR "Entering: $File::Find::dir" if $options{verbose}; | ||
| 308 | run_wrapped_sub($wrapped_pre, 'pre-process') if $wrapped_pre; | ||
| 309 | return @_; # Needed by find(). | ||
| 310 | }, | ||
| 311 | postprocess => sub { | ||
| 312 | print STDERR "Exiting: $File::Find::dir" if $options{verbose}; | ||
| 313 | run_wrapped_sub($wrapped_post, 'post-process') if $wrapped_post; | ||
| 314 | } | ||
| 315 | }, @inputs); | ||
| 316 | |||
| 317 | for my $c (@{$options{end}}) { | ||
| 318 | eval_code($c, 'BEGIN'); | ||
| 319 | } | ||
| 320 | } | ||
| 321 | |||
| 322 | 1; |