Plack-App-Directory-Markdown
view release on metacpan or search on metacpan
lib/Plack/App/Directory/Markdown.pm view on Meta::CPAN
my($self, $env, $dir) = @_;
if (-f $dir) {
if ($self->is_markdown($dir)) {
my $content = do {local $/;open my $fh,'<:encoding(UTF-8)',$dir or die $!;<$fh>};
$content = $self->markdown($content);
if ($self->callback) {
$self->callback->(\$content, $env, $dir);
}
my $path = $self->remove_root_path($dir);
$path =~ s/\.(?:markdown|mk?dn?)$//;
my ($prev, $next) = $self->_search_prev_and_next($self->remove_root_path($dir));
my $page = $self->tx->render('md.tx', {
path => $path,
title => ($self->title || 'Markdown'),
content => $content,
prev => $prev,
next => $next,
});
$page = encode_utf8($page);
my @stat = stat $dir;
return [ 200, [
'Content-Type' => 'text/html; charset=utf-8',
'Last-Modified' => HTTP::Date::time2str( $stat[9] ),
], [ $page ] ];
}
else {
return $self->SUPER::serve_path($env, $dir);
}
}
my $dir_url = $env->{SCRIPT_NAME} . $env->{PATH_INFO};
if ($dir_url !~ m{/$}) {
return $self->return_dir_redirect($env);
}
my @files;
push @files, ({ link => "../", name => "Parent Directory" }) if $env->{PATH_INFO} ne '/';
my $dh = DirHandle->new($dir);
my @children;
while (defined(my $ent = $dh->read)) {
next if $ent eq '.' or $ent eq '..';
push @children, $ent;
}
for my $basename (sort { $a cmp $b } @children) {
my $file = "$dir/$basename";
my $url = $dir_url . $basename;
my $is_dir = -d $file;
next if !$is_dir && !$self->is_markdown($file);
my @stat = stat _;
$url = join '/', map {uri_escape($_)} split m{/}, $url;
if ($is_dir) {
$basename .= "/";
$url .= "/";
}
push @files, { link => $url, name => $basename, mtime => HTTP::Date::time2str($stat[9]) };
}
my $path = Plack::Util::encode_html( $env->{PATH_INFO} );
$path =~ s{^/}{};
my $page = $self->tx->render('index.tx', {
title => ($self->title || 'Markdown'),
files => \@files,
path => $path
});
$page = encode_utf8($page);
return [ 200, ['Content-Type' => 'text/html; charset=utf-8'], [ $page ] ];
}
sub is_markdown {
my ($self, $file) = @_;
if ($self->markdown_ext) {
my $ext = quotemeta $self->markdown_ext;
$file =~ /$ext$/;
}
else {
$file =~ /\.(?:markdown|mk?dn?)$/;
}
}
sub remove_root_path {
my ($self, $path) = @_;
$path =~ s!^\./?!!;
my $root = $self->root || '';
$root =~ s!^\./?!!;
$root .= '/' if $root && $root !~ m!/$!;
$root = quotemeta $root;
$path =~ s!^$root!!;
$path;
}
sub process_path {
my $path = shift;
my @out;
my $i = 0;
foreach my $part (reverse(split('/',$path))) {
my $link = '../' x $i;
push @out,
{
name => $part,
link => "${link}",
};
$i++;
}
$out[0]->{link} = ''; # Last element should link to itself
return [ reverse @out ];
( run in 2.487 seconds using v1.01-cache-2.11-cpan-71847e10f99 )