December 19, 2009

Directory Copy Hack

Snow Leopard cunningly disabled VPN access during my upgrade from Tiger last month, so I am forced to do schema and large business object updates on weekends. While updating today I realized I had not written a script to bulk copy attachments from the old directory structure to the new directory structure, so I cobbled this together in perl:

#
# Check if the Account uploaded Attachments to the old structure (existence of directory).
#
if (opendir(DIR, $oldpath))
{
 #
 # Add the new Attachments folder if it does not yet exist.
 #
 if (!(-d $newpath)) { mkdir $newpath or die; }

 #
 # Grab a list of files in the directory sans current(.) and parent(..).
 #
 @files = grep(/\.\w+$/, readdir(DIR));

 foreach (@files) {
  $oldfile = $oldpath . $_;
  $newfile = $newpath . $_;
 
  #
  # If the old file exists and the new file doesn't, copy it.
  #
  if ((-e $oldfile) && !(-e $newfile)) {
   copy($oldfile, $newfile) or die;
  
   #
   # If the new file copied, delete the old file.
   #
   if (-e $newfile) {
    unlink $oldfile or die;
   }
  }
  #
  # If both the new file and the old file exist, delete the old file.
  #
  elsif ((-e $oldfile) && (-e $newfile)) {
   unlink $oldfile or die;
  }
 }

 #
 # Close the old path.
 #
 closedir(DIR);
}

Obviously, this is only the portion of the script that handles the actual file copying. I am sure there are a ton of ways to improve upon it (say, spend more than 20 minutes writing it), but it got the job done. I'll need to use it again to copy files from our archive server, so I may refine it to delete empty directories and use an actual error log.

No comments: