Catmandu

 view release on metacpan or  search on metacpan

lib/Catmandu/Util.pm  view on Meta::CPAN

        $io = $arg;
        defined($io) && binmode $io, $binmode;
    }
    else {
        Catmandu::BadArg->throw("can't make io from argument");
    }

    $io;
}

# Deprecated use tools like File::Slurp::Tiny
sub read_file {
    my ($path) = @_;
    local $/;
    open my $fh, "<:encoding(UTF-8)", $path
        or Catmandu::Error->throw(qq(can't open "$path" for reading));
    my $str = <$fh>;
    close $fh;
    $str;
}

sub read_io {
    my ($io) = @_;
    $io->binmode("encoding(UTF-8)") if ($io->can('binmode'));
    my @lines = ();
    while (<$io>) {
        push @lines, $_;
    }
    $io->close();
    join "", @lines;
}

# Deprecated use tools like File::Slurp::Tiny
sub write_file {
    my ($path, $str) = @_;
    open my $fh, ">:encoding(UTF-8)", $path
        or Catmandu::Error->throw(qq(can't open "$path" for writing));
    print $fh $str;
    close $fh;
    $path;
}

sub read_yaml {

    # dies on error
    YAML::XS::LoadFile($_[0]);
}

sub read_json {
    my $text = read_file($_[0]);

    # dies on error
    Cpanel::JSON::XS->new->decode($text);
}

##
# Split a path on . or /, but not on \/ or \.
sub split_path {
    my ($path) = @_;
    $path = trim($path);
    $path =~ s/^\$[\.\/]//;
    return [map {s/\\(?=[\.\/])//g; $_} split /(?<!\\)[\.\/]/, $path];
}

sub join_path {
    my $path = File::Spec->catfile(@_);
    $path =~ s!/\./!/!g;
    while ($path =~ s![^/]*/\.\./!!) { }
    $path;
}

sub normalize_path {    # taken from Dancer::FileUtils
    my ($path) = @_;
    $path =~ s!/\./!/!g;
    while ($path =~ s![^/]*/\.\./!!) { }
    File::Spec->catfile($path);
}

sub segmented_path {
    my ($id, %opts) = @_;
    my $segment_size = $opts{segment_size} || 3;
    my $base_path    = $opts{base_path};
    $id =~ s/[^0-9a-zA-Z]+//g;
    my @path = unpack "(A$segment_size)*", $id;
    defined $base_path
        ? File::Spec->catdir($base_path, @path)
        : File::Spec->catdir(@path);
}

my $MIME_TYPES;

sub content_type {
    my ($filename) = @_;

    $MIME_TYPES ||= MIME::Types->new(only_complete => 1);

    return undef unless $filename;

    my ($ext) = $filename =~ /\.(.+?)$/;

    my $type = 'application/octet-stream';

    my $mime = $MIME_TYPES->mimeTypeOf($ext);

    # Require explicit stringification!
    $type = sprintf "%s", $mime->type if $mime;

    $type;
}

sub parse_data_path {
    my ($path) = @_;
    check_string($path);
    $path = split_path($path);
    my $key = pop @$path;
    return $path, $key;
}

sub get_data {
    my ($data, $key) = @_;
    if (is_array_ref($data)) {



( run in 0.888 second using v1.01-cache-2.11-cpan-5c0b1e786e0 )