package Test::MooseX::Compiler;

use strict;
use warnings;
use autodie;

use Exporter qw( import );
use File::Temp qw( tempdir );
use Module::Runtime qw( module_notional_filename );
use Path::Class qw( dir );
use Test::More;

our @EXPORT_OK = qw(
    code_compiles_ok
    save_class
    save_fragment
);

my $Dir = dir( tempdir( CLEANUP => 1 ) );

sub save_fragment {
    my $class = shift;
    my $code  = shift;

    my $full_code = <<"EOF";
package $class;

use strict;
use warnings;

$code

1;
EOF

    save_class($class, $full_code);
}

sub save_class {
    my $class = shift;
    my $code  = shift;

    {
        local $@;
        eval $code;
        die $@ if $@;
    }

    my $pm_file = module_notional_filename($class);
    my $path    = $Dir->file($pm_file);
    $path->dir()->mkpath( 0, 0755 );

    open my $fh, '>', $path;
    print {$fh} $code;
    close $fh;

    $INC{$pm_file} = $path;

    return $pm_file;
}

sub code_compiles_ok {
    my $code = shift;

    local $Test::Builder::Level = $Test::Builder::Level + 1;

    my $e;
    {
        local $@;
        local $SIG{__DIE__};
        eval $code;
        $e = $@;
    }

    is( $e, q{}, 'code compiled ok' );
}

1;
