Data-Section-Writer

 view release on metacpan or  search on metacpan

lib/Data/Section/Writer.pm  view on Meta::CPAN

use warnings;
use 5.020;
use experimental qw( signatures );
use stable qw( postderef );
use true;

package Data::Section::Writer 0.05 {

  # ABSTRACT: Write __DATA__ section files for Data::Section, Data::Section::Simple or Mojo::Loader::data_section


  use Path::Tiny ();
  use Carp ();
  use Class::Tiny qw( perl_filename _files _same _formats );
  use Ref::Util qw( is_coderef is_blessed_ref is_plain_arrayref );
  use MIME::Base64 qw(encode_base64);
  use File::Temp ();

  sub BUILD ($self, $) {

    # use the callers filename if not provided.
    unless(defined $self->perl_filename) {
      my(undef, $fn) = caller 2;
      $self->perl_filename($fn);
    }

    # upgrade to Path::Tiny if it is not already
    unless(is_blessed_ref $self->perl_filename && $self->isa('Path::Tiny')) {
      $self->perl_filename(Path::Tiny->new($self->perl_filename));
    }

    $self->_files({});
    $self->_formats({});

  }


  sub add_file ($self, $filename, $content, $encoding=undef) {
    Carp::croak("Unknown encoding $encoding") if defined $encoding && $encoding ne 'base64';
    $self->_files->{"$filename"} = [ $content, $encoding ];
    return $self;
  }

  sub _render_file ($self, $filename, $data) {
    my $text = "@@ $filename";
    $text .= " (" . $data->[1] . ")" if defined $data->[1];
    $text .= "\n";

    my $content = $data->[0];

    if($filename =~ /\.(.*?)\z/ && ($self->_formats->{$1} // [])->@*) {
        my $ext = $1;
        $content = $_->($self, $content) for $self->_formats->{$ext}->@*;
    }

    if(defined $data->[1] && $data->[1] eq 'base64') {
        $text .= encode_base64($data->[0]);
    } else {
        $text .= $content;
    }
    chomp $text;
    return $text;
  }


  sub render_section ($self) {
    my $files = $self->_files;
    return "__DATA__\n" unless %$files;
    return join("\n",
      "__DATA__",
      (map { $self->_render_file($_, $files->{$_}) } sort keys $files->%*),
      ''
    );
  }



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