Source

perl-File-Find-Object / lib / File / Find / Object.pm

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
package File::Find::Object::PathComponent;

use strict;
use warnings;

use base 'File::Find::Object::Base';

use File::Spec;


sub new {
    my ($class, $top, $from, $index) = @_;

    my $self = {};
    bless $self, $class;

    $self->dir($top->current_path($from));
    $self->idx($index);

    $self->_last_dir_scanned(undef);

    $from->dir($self->dir());

    return $top->open_dir($top->_father($self)) ? $self : undef;
}

package File::Find::Object;

use strict;
use warnings;

use base 'File::Find::Object::Base';

__PACKAGE__->mk_accessors(qw(
    _current_idx
    _dir_stack
    item
    _targets
    _target_index
));

sub _get_options_ids
{
    my $class = shift;
    return [qw(
        callback
        depth
        filter
        followlink
        nocrossfs
    )];
}

__PACKAGE__->mk_accessors(@{__PACKAGE__->_get_options_ids()});

use Carp;

our $VERSION = '0.0.5';

sub new {
    my ($class, $options, @targets) = @_;

    my $tree = {
        
        _dir_stack => [],
    };

    bless($tree, $class);

    foreach my $opt (@{$tree->_get_options_ids()})
    {
        $tree->set($opt, $options->{$opt});
    }
    $tree->_targets([ @targets ]);
    $tree->_target_index(-1);
    $tree->_current_idx(-1);

    $tree->_last_dir_scanned(undef);

    return $tree;
}

sub DESTROY {
    my ($self) = @_;
#    print STDERR join(" ", caller)."\n";
#    printf STDERR "destroy `%s'\n", $self->dir() || "--";
}

sub _current
{
    my $self = shift;

    my $dir_stack = $self->_dir_stack();

    if ($self->_current_idx < 0)
    {
        return $self;
    }
    else
    {
        return $dir_stack->[$self->_current_idx];
    }
}

sub next {
    my ($self) = @_;
    while (1) {
        my $current = $self->_current();
        if ($self->_process_current($current))
        {
            return $self->item($self->current_path($current));
        }
        $current = $self->_current();
        if(!$self->movenext) {
            if ($self->me_die($current))
            {
                return $self->item(undef);
            }
        }
    }
}

sub _father
{
    my ($self, $current) = @_;

    if (!defined($current))
    {
        require Data::Dumper;
        print Data::Dumper->new([$self],['$self'])->Dump();
        confess "Current is undef";
    }

    if (!defined($current->idx()))
    {
        return undef;
    }
    elsif ($current->idx() >= 1)
    {
        return $self->_dir_stack()->[$current->idx()-1];
    }
    else
    {
        return $self;
    }
}

sub _movenext_with_current
{
    my $self = shift;
    if ($self->_current->_curr_file(
            shift(@{$self->_father($self->_current)->_traverse_to()})
       ))
    {
        $self->_current->_action({});
        return 1;
    } else {
        return 0;
    }
}

sub _increment_target_index
{
    my $self = shift;
    $self->_target_index(
        $self->_target_index() + 1
    );
}

sub _movenext_wo_current
{
    my $self = shift;

    if ($self->_target_index() > @{$self->_targets()})
    {
        return 0;
    }
    $self->_increment_target_index();

    $self->_curr_file($self->_targets()->[$self->_target_index()]);
    $self->_action({});
    1;
}

sub movenext {
    my ($self) = @_;
    if (@{$self->_dir_stack()})
    {
        return $self->_movenext_with_current();
    }
    else
    {
        return $self->_movenext_wo_current();
    }
}

sub me_die {
    if (@_ != 2)
    {
        confess "Hello";
    }
    my ($self, $current) = @_;

    if ($self eq $current)
    {
        return 1;
    }

    $self->become_default($self->_father($current));
    return 0;
}

sub become_default
{
    my ($self, $current) = @_;

    if ($self eq $current)
    {
        @{$self->_dir_stack()} = ();
        $self->_current_idx(-1);
    }
    else
    {
        while (scalar(@{$self->_dir_stack()}) != $current->idx() + 1)
        {
            pop(@{$self->_dir_stack()});
            $self->_current_idx($self->_current_idx()-1);
        }
    }

    return 0;
}

# Return true if there is somthing next
sub _process_current {
    my ($self, $current) = @_;
   
    $current->_curr_file() or return 0;

    $self->isdot($current) and return 0;
    $self->_filter_wrapper($current) or return 0;  

    foreach my $action ($self->depth() ? qw(b a) : qw(a b))
    {
        if ($current->_action->{$action}) {
            next;
        }
        $current->_action->{$action} = 1;
        if($action eq 'a') {
            if ($self->callback()) {
                $self->callback()->($self->current_path($current));
            }
            return 1;
        }
            
        if ($action eq 'b') {
            my $status = $self->_recurse($current);
            
            if ($status eq "SKIP")
            {
                next;
            }
            else
            {
                $self->_current_idx($self->_current_idx()+1);
                return $status;
            }
        }
    }
    return 0;
}

sub _recurse
{
    my ($self, $current) = @_;

    $self->check_subdir($current) or 
        return "SKIP";


    push @{$self->_dir_stack()}, 
        File::Find::Object::PathComponent->new(
            $self,
            $current,
            scalar(@{$self->_dir_stack()})
        );

    return 0;
}

sub isdot
{
    my ($self, $current) = @_;

    my $file = $current->_curr_file();

    return ($file eq ".." || $file eq ".");
}

sub _filter_wrapper {
    my ($self, $current) = @_;
    return defined($self->filter()) ?
        $self->filter()->($self->current_path($current)) :
        1;
}

sub check_subdir 
{
    my ($self, $current) = @_;

    if ($self eq $current)
    {
        return 1;
    }
    my @st = stat($self->current_path($current));
    if (!-d _)
    {
        return 0;
    }
    if (-l $self->current_path($current) && !$self->followlink())
    {
        return 0;
    }
    if ($st[0] != $self->_father($current)->dev() && $self->nocrossfs())
    {
        return 0;
    }
    my $ptr = $current; my $rc;
    while($self->_father($ptr)) {
        if($self->_father($ptr)->inode() == $st[1] && $self->_father($ptr) == $st[0]) {
            $rc = 1;
            last;
        }
        $ptr = $self->_father($ptr);
    }
    if ($rc) {
        printf(STDERR "Avoid loop " . $self->_father($ptr)->dir() . " => %s\n",
            $self->current_path($current));
        return 0;
    }
    return 1;
}

sub current_path {
    my ($self, $current) = @_;

    if ($self eq $current)
    {
        return $self->_curr_file;
    }

    my $p = $self->_father($current)->dir();
    
    return File::Spec->catfile($p, $current->_curr_file);
}

sub open_dir {
    my ($self, $current) = @_;

    if (defined($current->_last_dir_scanned()) &&
        ($current->_last_dir_scanned() eq $current->dir()
       )
    )
    {
        return $current->_open_dir_ret();
    }

    $current->_last_dir_scanned($current->dir());

    my $handle;
    if (!opendir($handle, $current->dir()))
    {
        return $current->_open_dir_ret(undef);
    }
    my @files = (sort { $a cmp $b } File::Spec->no_upwards(readdir($handle)));
    closedir($handle);

    $current->_files(
        [ @files ]
    );
    $current->_traverse_to(
        [ @files ]
    );

    
    my @st = stat($current->dir());
    $current->inode($st[1]);
    $current->dev($st[0]);


    return $current->_open_dir_ret(1);
}

sub set_traverse_to
{
    my ($self, $children) = @_;

    # Make sure we scan the current directory for sub-items first.
    $self->get_current_node_files_list();

    $self->_current->_traverse_to([@$children]);
}

sub get_traverse_to
{
    my $self = shift;

    return [ @{$self->_current->_traverse_to()} ];
}

sub get_current_node_files_list
{
    my $self = shift;

    # Remming out because it doesn't work.
    # $self->_father($self->_current)->dir($self->_current->dir());

    $self->_current->dir($self->current_path($self->_current()));

    # open_dir can return undef if $self->_current is not a directory.
    if ($self->open_dir($self->_current))
    {
        return [ @{$self->_current->_files()}];
    }
    else
    {
        return [];
    }
}

sub prune
{
    my $self = shift;

    return $self->set_traverse_to([]);
}

1;

__END__

=head1 NAME

File::Find::Object - An object oriented File::Find replacement

=head1 SYNOPSIS

    use File::Find::Object;
    my $tree = File::Find::Object->new({}, @dir);

    while (my $r = $tree->next()) {
        print $r ."\n";
    }

=head1 DESCRIPTION

File::Find::Object does same job as File::Find but works like an object and 
with an iterator. As File::Find is not object oriented, one cannot perform
multiple searches in the same application. The second problem of File::Find 
is its file processing: after starting its main loop, one cannot easilly wait 
for another event an so get the next result.

With File::Find::Object you can get the next file by calling the next() 
function, but setting a callback is still possible.

=head1 FUNCTIONS

=head2 new

    my $ffo = File::Find::Object->new( { options }, @targets);

Create a new File::Find::Object object. C<@targets> is the list of 
directories or files which the object should explore.

=head3 options

=over 4

=item depth

Boolean - returns the directory content before the directory itself.

=item nocrossfs

Boolean - doesn't continue on filesystems different than the parent.

=item followlink

Boolean - follow symlinks when they point to a directory.

You can safely set this option to true as File::Find::Object does not follow 
the link if it detects a loop.

=item filter

Function reference - should point to a function returning TRUE or FALSE. This 
function is called with the filename to filter, if the function return FALSE, 
the file is skipped.

=item callback

Function reference - should point to a function, which would be called each 
time a new file is returned. The function is called with the current filename 
as an argument.

=back

=head2 next

Returns the next file found by the File::Find::Object. It returns undef once
the scan is completed.

=head2 item

Returns the current filename found by the File::Find::Object object, i.e: the
last value returned by next().

=head2 $ff->set_traverse_to([@children])

Sets the children to traverse to from the current node. Useful for pruning
items to traverse.

=head2 $ff->prune()

Prunes the current directory. Equivalent to $ff->set_traverse_to([]).

=head2 [@children] = $ff->get_traverse_to()

Retrieves the children that will be traversed to.

=head2 [@files] = $ff->get_current_node_files_list()

Gets all the files that appear in the current directory. This value is
constant for every node, and is useful to use as the basis of the argument
for C<set_traverse_to()>.

=head1 BUGS

No bugs are known but it doesn't mean there aren't any.

=head1 SEE ALSO

L<File::Find>

=cut