file_updater.pl 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 04 November 2012
  5. # https://github.com/trizen
  6. # Update files in a directory, with files from other dirs.
  7. # Example: perl file_updater.pl -o /tmp /root
  8. # /tmp/dir/file.txt is updated with /root/dir/file.txt
  9. # if the file from the /root dir is newer than the file from the /tmp dir.
  10. use 5.010;
  11. use strict;
  12. use warnings;
  13. use File::Copy qw(copy);
  14. use File::Find qw(find);
  15. use Getopt::Std qw(getopts);
  16. use File::Compare qw(compare);
  17. use File::Spec::Functions qw(rel2abs catfile);
  18. my %opts;
  19. getopts('o:', \%opts);
  20. sub usage {
  21. die <<"EOH";
  22. usage: $0 [options] [dirs]
  23. options:
  24. -o <output_dir> : update files in this directory
  25. example: $0 -o /my/path/out /my/path/input
  26. EOH
  27. }
  28. my $output_dir = $opts{o};
  29. if ( not defined $output_dir
  30. or not -d $output_dir
  31. or not @ARGV) {
  32. usage();
  33. }
  34. $output_dir = rel2abs($output_dir);
  35. my @dirs;
  36. foreach my $dir (@ARGV) {
  37. if (not -d -r $dir) {
  38. warn "[!] Invalid dir '$dir': $!\n";
  39. next;
  40. }
  41. push @dirs, rel2abs($dir);
  42. }
  43. sub update_files {
  44. return if $_ eq $output_dir;
  45. return unless -f;
  46. my $filename = substr($_, length($output_dir) + 1);
  47. my $mdays = -M _;
  48. foreach my $dir (@dirs) {
  49. my $file = catfile($dir, $filename);
  50. if (-e $file and -M (_) < $mdays and compare($file, $_) == 1) {
  51. say "Updating: $file -> $_";
  52. copy($file, $_) or do { warn "[!] Copy failed: $!\n" };
  53. }
  54. }
  55. }
  56. find {
  57. no_chdir => 1,
  58. wanted => \&update_files,
  59. } => $output_dir;