Mojolicious
view release on metacpan or search on metacpan
lib/Mojo/File.pm view on Meta::CPAN
package Mojo::File;
use Mojo::Base -strict;
use overload '@{}' => sub { shift->to_array }, bool => sub {1}, '""' => sub { ${$_[0]} }, fallback => 1;
use Carp qw(croak);
use Cwd qw(getcwd);
use Exporter qw(import);
use File::Basename ();
use File::Copy qw(copy move);
use File::Path ();
use File::Spec::Functions qw(abs2rel canonpath catfile file_name_is_absolute rel2abs splitdir);
use File::stat ();
use File::Temp ();
use IO::File ();
use Mojo::Collection;
use Mojo::Util qw(decode encode);
our @EXPORT_OK = ('curfile', 'path', 'tempdir', 'tempfile');
sub basename { File::Basename::basename ${shift()}, @_ }
sub child { $_[0]->new(${shift()}, @_) }
sub chmod {
my ($self, $mode) = @_;
chmod $mode, $$self or croak qq{Can't chmod file "$$self": $!};
return $self;
}
sub copy_to {
my ($self, $to) = @_;
copy($$self, $to) or croak qq{Can't copy file "$$self" to "$to": $!};
return $self->new(-d $to ? ($to, File::Basename::basename $self) : $to);
}
sub curfile { __PACKAGE__->new(Cwd::realpath((caller)[1])) }
sub dirname { $_[0]->new(scalar File::Basename::dirname ${$_[0]}) }
sub download {
my ($self, $url, $options) = (shift, shift, shift // {});
my $ua = $options->{ua}
|| do { require Mojo::UserAgent; Mojo::UserAgent->new(max_redirects => 10, max_response_size => 0) };
my $tx = _download_error($ua->transactor->download($ua->head($url => $options->{headers} // {}), $$self));
return $tx ? !!_download_error($ua->start($tx)) : 1;
}
sub extname { shift->basename =~ /.+\.([^.]+)$/ ? $1 : '' }
sub is_abs { file_name_is_absolute ${shift()} }
sub list {
my ($self, $options) = (shift, shift // {});
return Mojo::Collection->new unless -d $$self;
opendir(my $dir, $$self) or croak qq{Can't open directory "$$self": $!};
my @files = grep { $_ ne '.' && $_ ne '..' } readdir $dir;
@files = grep { !/^\./ } @files unless $options->{hidden};
@files = map { catfile $$self, $_ } @files;
@files = grep { !-d } @files unless $options->{dir};
return Mojo::Collection->new(map { $self->new($_) } sort @files);
}
sub list_tree {
my ($self, $options) = (shift, shift // {});
return Mojo::Collection->new unless -d $$self;
my (@results, $walk);
$walk = sub {
my ($path, $depth) = @_;
opendir my $dh, $path or return;
my @names = sort grep { $_ ne '.' && $_ ne '..' } readdir $dh;
@names = grep { !/^\./ } @names unless $options->{hidden};
for my $name (@names) {
my $child = $self->new($path, $name);
my $is_dir = -d $$child;
push @results, $child if $options->{dir} || !$is_dir;
__SUB__->($$child, $depth + 1)
if $is_dir && !-l $$child && (!$options->{max_depth} || $depth + 1 < $options->{max_depth});
}
};
$walk->($$self, 0);
return Mojo::Collection->new(@results);
}
sub lstat { File::stat::lstat(${shift()}) }
sub make_path {
my $self = shift;
File::Path::make_path $$self, @_;
return $self;
}
sub move_to {
( run in 0.984 second using v1.01-cache-2.11-cpan-364913b4093 )