| 1 | use v5.28; | ||
| 2 | use warnings; | ||
| 3 | use Object::Pad 0.73; | ||
| 4 | |||
| 5 | class Archive::SCS::DirIndex 1.12; | ||
| 6 | |||
| 7 | field $dirs :param = []; | ||
| 8 | field $files :param = []; | ||
| 9 | |||
| 10 | method dirs () { $dirs->@* } | ||
| 11 | method files () { $files->@* } | ||
| 12 | |||
| 13 | |||
| 14 | my $dirname_basename = qr{ | ||
| 15 | \A((?: # dirname components, starting from beginning of string | ||
| 16 | /? # beginning with a path separator, if any | ||
| 17 | .+? # minimal match | ||
| 18 | (?=/) # ending before the next separator | ||
| 19 | )*+) # stingy match of zero or more dirname components | ||
| 20 | /? # drop the last path separator, if any | ||
| 21 | (.*) # basename | ||
| 22 | }xx; | ||
| 23 | |||
| 24 | # Create DirIndex objects for the entire directory hierarchy described by | ||
| 25 | # the given list of file paths (and optional dir paths, for empty subdirs). | ||
| 26 | # Takes array refs, returns hash ref. | ||
| 27 | method auto_index :common ($files, $dirs = []) { | ||
| 28 | my %index; | ||
| 29 | my %dirs; | ||
| 30 | |||
| 31 | for my $file ($files->@*) { | ||
| 32 | my ($parent, $name) = $file =~ $dirname_basename; | ||
| 33 | |||
| 34 | $index{$parent}{files}{$name} = 1; | ||
| 35 | length $parent and $dirs{$parent} = 1; | ||
| 36 | } | ||
| 37 | |||
| 38 | # Performance optimization: Gather parent dirs above in hash instead of array | ||
| 39 | # because there is a very large amount of duplicates | ||
| 40 | my @dirs = ($dirs->@*, keys %dirs); | ||
| 41 | |||
| 42 | while (defined (my $dir = shift @dirs)) { | ||
| 43 | my ($parent, $name) = $dir =~ $dirname_basename; | ||
| 44 | |||
| 45 | # Performance optimization: Don't add dir to queue if we've got it already | ||
| 46 | exists $index{$dir} && exists $index{$parent}{dirs}{$name} and next; | ||
| 47 | |||
| 48 | # Add index for empty dirs | ||
| 49 | $index{$dir} //= {}; | ||
| 50 | |||
| 51 | $index{$parent}{dirs}{$name} = 1; | ||
| 52 | length $parent and push @dirs, $parent; | ||
| 53 | } | ||
| 54 | |||
| 55 | $index{$_} = Archive::SCS::DirIndex->new( | ||
| 56 | dirs => [ sort keys $index{$_}{dirs }->%* ], | ||
| 57 | files => [ sort keys $index{$_}{files}->%* ], | ||
| 58 | ) for keys %index; | ||
| 59 | |||
| 60 | return \%index; | ||
| 61 | } | ||
| 62 | |||
| 63 | 1; |