shell-scripts/file_processing/lib/ProcessDirectories.pm
2023-09-11 20:01:15 -05:00

125 lines
No EOL
2.9 KiB
Perl

package ProcessDirectories;
use Modern::Perl;
# VERSION
# AUTHORITY
# ABSTRACT: Get current subdirectories in current year directory and copy to archive directory
use Carp qw( croak );
use File::Basename;
use File::Find::Rule;
use File::Copy::Recursive qw(dircopy);
use File::DirCompare;
use Pod::Usage;
# use Time::Piece qw/localtime/;
sub create_archive_dirs {
my ( $source_dir, $dest_dir ) = @_;
unless ( -d $source_dir ) {
die "Source directory '$source_dir' does not exist, please create it";
}
print("Copying current directories to archive folder\n");
print("From: $source_dir\n");
print("To: $dest_dir\n");
dircopy( $source_dir, $dest_dir )
or croak "Could not copy directories $!";
return;
}
sub compare_dirs {
my ( $dir1, $dir2 ) = @_;
my $same = 1;
print("Making sure all directories and files match between source and destination\n");
File::DirCompare->compare(
$dir1, $dir2,
sub {
my ( $a, $b ) = @_;
if ( !$b ) {
printf "Only in %s: %s\n", dirname($a), basename($a);
$same = 0;
}
elsif ( !$a ) {
printf "Only in %s: %s\n", dirname($b), basename($b);
$same = 0;
}
else {
print "Files $a and $b differ\n";
$same = 0;
}
}
);
return $same;
}
sub clean_dirs {
my ( $new_dir, $old_dir, $curr_year, $last_year ) = @_;
my @this_year_files =
File::Find::Rule->file()->name("*$curr_year*")->in($old_dir);
my @last_year_files =
File::Find::Rule->file()->name("*$last_year*")->in($new_dir);
unlink @this_year_files;
print("Deleted all files for $curr_year from the folder for $last_year\n");
unlink @last_year_files;
print("Deleted all files for $last_year from the folder for $curr_year\n");
return;
}
1;
=pod
=head1 NAME
ProcessDirectories
=head1 DESCRIPTION
Methods for copying and processing a directory of files for the past year and this year
=head1 SYNOPSIS
use ProcessDirectories
create_archive_dirs ( $source_dir, $dest_dir );
compare_dirs( $source_dir, $dest_dir );
clean_dirs( $source_dir, $dest_dir, $year, $lastyear );
=head1 METHODS
=head2
C<create_archive_dirs>: Copies the directory structure and contents of a source file to the archive / destination directory.
=head3
Usage:
create_archive_dirs( $source_dir, $destination_dir );
=head2
C<compare_dirs>: Compares the content of two specified directories. Provides feedback on the results. Returns 1 if the source and destination match, 0 otherwise.
=head3
Usage:
compare_dirs( $source_dir, $destination_dir );
=head2
C<clean_dirs>: This method accepts the following parameters:
=over 4
=item source_dir
=item destination_dir
=item this_year
=item last_year
=back
=head3
Usage:
clean_dirs( $source_dir, $destination_dir, 2023, 2022 );
=cut