Catalyst-Controller-SimpleCAS

 view release on metacpan or  search on metacpan

lib/Catalyst/Controller/SimpleCAS/Store/File.pm  view on Meta::CPAN

package Catalyst::Controller::SimpleCAS::Store::File;

use warnings;
use Moose;

with qw(
  Catalyst::Controller::SimpleCAS::Store
);

use Data::Dumper;
use IO::File;
use Try::Tiny;
use File::Spec::Functions 'catdir', 'catfile';
use Path::Class qw( file dir );
use IO::All;
use File::Copy 'move';

has 'store_dir' => ( is => 'ro', isa => 'Str', required => 1 );

sub init_store_dir {
  my $self = shift;
  return if (-d $self->store_dir);
  mkdir $self->store_dir or die "Failed to create directory: " . $self->store_dir;
}

sub add_content {
  my $self = shift;
  my $data = shift;
  
  $self->init_store_dir;
  
  my $checksum = $self->calculate_checksum($data);
  return $checksum if ($self->content_exists($checksum));
  
  my $save_path = $self->checksum_to_path($checksum,1);
  my $fd= IO::File->new($save_path, '>:raw') or die $!;
  $fd->write($data);
  $fd->close;
  return $checksum;
}

sub add_content_file {
  my $self = shift;
  my $file = shift;
  
  $self->init_store_dir;
  
  my $checksum = $self->file_checksum($file);
  return $checksum if ($self->content_exists($checksum));
  
  my $save_path = $self->checksum_to_path($checksum,1);
  
  try {
    # This is cleaner, but will fail for various reasons like source/dest 
    # on different file systems:
    link $file, $save_path or die "Failed to create hard link: '$file' -> '$save_path'";
  }
  catch {
    move($file, $save_path)
      or die "SimpleCAS: Failed to move file '$file' -> '$save_path': $!";
  };
  
  return $checksum;
}

sub split_checksum {
  my $self = shift;
  my $checksum = shift;

  return ( substr($checksum,0,2), substr($checksum,2) );
}



( run in 0.726 second using v1.01-cache-2.11-cpan-39bf76dae61 )