Fix cleaned up config files code
[scpubgit/App-SCS.git] / lib / App / SCS / PageSet.pm
1 package App::SCS::PageSet;
2
3 use Text::MultiMarkdown 'markdown';
4 use HTML::Zoom;
5 use Sub::Quote;
6 use Syntax::Keyword::Gather;
7 use App::SCS::Page;
8 use IO::All;
9 use Try::Tiny;
10 use List::Util qw(reduce max);
11 use Module::Runtime qw(use_module);
12 use JSON::MaybeXS;
13 use Moo;
14 use Hash::Merge qw(merge);
15 use Data::Pond qw(pond_read_datum pond_write_datum);
16 use JSONY;
17
18 with 'App::SCS::Role::PageChildren';
19
20 {
21   my $j = JSON->new;
22   sub _json { $j }
23 }
24
25 has top_dir => (is => 'ro', lazy => 1, builder => 'base_dir');
26 has base_dir => (is => 'ro', required => 1);
27 has plugin_config => (is => 'ro', required => 1);
28 has max_depth => (is => 'ro', default => quote_sub q{ 0 });
29 has min_depth => (is => 'ro', default => quote_sub q{ 1 });
30
31 has rel_path => (is => 'lazy');
32
33 sub _build_rel_path {
34   my ($self) = @_;
35   io->dir('/')
36     ->catdir(File::Spec->abs2rel($self->base_dir->name, $self->top_dir->name))
37 }
38
39 sub _page_set { $_[0] }
40 sub _page_set_class { ref($_[0]) }
41 sub _top_dir { shift->top_dir }
42 sub _my_path { shift->base_dir }
43
44 sub get {
45   my ($self, $spec) = @_;
46   $spec->{path} or die "path is required to get";
47   my ($dir, $file) = $spec->{path} =~ m{^(?:(.*)/)?([^/]+)$};
48   my $type;
49   my @poss = io->dir($self->base_dir)->${\sub {
50     my $io = shift;
51     defined($dir) ? $io->catdir($dir) : $io
52   }}->filter(sub {
53         $_->filename =~ /^\Q${file}\E${\$self->_types_re}$/ and $type = $1
54       })
55     ->${\sub { -e "$_[0]" ? $_[0]->all_files : () }};
56   die "multiple files found for ${\$spec->{path}}:\n".join "\n", @poss
57     if @poss > 1;
58   return undef unless @poss;
59   $self->_inflate(
60     $type, $self->rel_path->catdir($spec->{path}), $poss[0]
61   );
62 }
63
64 sub _config_files_for {
65   my ($self, $path) = @_;
66
67   my @dir_parts = io->dir($path)->splitdir;
68   my @dirs = map io->dir('')->catdir(@dir_parts[1..$_]), 1..($#dir_parts - 1);
69
70   return grep +($_->is_file and $_->exists and not $_->empty),
71            map $self->_top_dir->catfile("${_}.conf"), @dirs;
72 }
73
74 sub _inflate {
75   my ($self, $type, $path, $io) = @_;
76   (my $cache_name = $io->name) =~ s/\/([^\/]+)$/\/.htcache.$1.json/;
77   my $cache = io($cache_name);
78   my @config_files = $self->_config_files_for($path);
79   my $max_stat = max map $_->mtime, $io, @config_files;
80
81   if (-f $cache_name) {
82     if ($cache->mtime >= $max_stat) {
83       return try {
84         $self->_new_page($path, $self->_json->decode($cache->all));
85       } catch {
86         die "Error inflating ${path} from cache: $_\n";
87       }
88     }
89   }
90   my $raw = $io->all;
91   try {
92
93     my $extracted = $self->${\"_extract_from_${type}"}($raw);
94     my $jsony = JSONY->new;
95     my $config = reduce { merge($a, $jsony->load($b->all)) } [], @config_files;
96
97     $extracted->{plugins} = pond_read_datum('[' . $extracted->{plugins} . ']');
98
99     my $setup = $extracted;
100
101     $setup->{plugin_config} = merge($extracted->{plugins}, $config);
102
103     try {
104         my $tmp_cache = io($cache_name . ".tmp");
105         $tmp_cache->print($self->_json->encode($setup));
106         $tmp_cache->rename($cache_name);
107     };
108
109     $self->_new_page($path, $setup);
110   } catch {
111     die "Error inflating ${path} as ${type}: $_\n";
112   }
113 }
114
115 sub map {
116   my ($self, $mapper) = @_;
117   [ map $mapper->($_), $self->flatten ]
118 }
119
120 sub _depth_under_base {
121   my ($self, $path) = @_;
122   File::Spec->splitdir(File::Spec->abs2rel($path, $self->base_dir->name))
123 }
124
125 sub flatten {
126   my ($self) = @_;
127   my $slash = io->dir('/');
128   map {
129     my ($path, $type) = $_->name =~ /^(.*)${\$self->_types_re}$/;
130     $self->_inflate(
131       $type,
132       $slash->catdir(File::Spec->abs2rel($path, $self->top_dir->name)),
133       $_
134     );
135   } $self->_all_files;
136 }
137
138 sub all_paths {
139   my ($self) = @_;
140   my $slash = io->dir('/');
141   map {
142     my ($path, $type) = $_->name =~ /^(.*)${\$self->_types_re}$/;
143     $slash->catdir(File::Spec->abs2rel($path, $self->top_dir->name))->name,
144   } $self->_all_files;
145 }
146
147 sub _all_files {
148   my ($self) = @_;
149   return unless (my $base = $self->base_dir)->exists;
150   my %seen;
151   my $min = $self->min_depth;
152   map {
153     $_->filter(sub { $_->filename =~ /${\$self->_types_re}$/ })
154       ->all_files($self->max_depth - ($min-1))
155   } map
156       $min > 1
157         ? do {
158             # can't use ->all_dirs($min-1) since we only want the final level
159             my @x = ($_); @x = map $_->all_dirs, @x for 1..$min-1; @x
160           }
161         : $_,
162       $base;
163 }
164
165 sub latest {
166   my ($self, $max) = @_;
167   use_module('App::SCS::LatestPageSet')->new(
168     parent => $self,
169     max_entries => $max,
170   );
171 }
172
173 sub _new_page {
174   use_module('App::SCS::Page')->new(
175     path => $_[1], page_set => $_[0], %{$_[2]}
176   );
177 }
178
179 sub _types_re { qw/\.(html|md)/ }
180
181 sub _extract_from_html {
182   my ($self, $html) = @_;
183   my %meta;
184   HTML::Zoom->from_html($html)
185     ->select('title')->collect_content({ into => \my @title })
186     ->${\sub {
187         my $z = shift;
188         return reduce {
189           $a->collect("meta[name=${b}]", { into => ($meta{$b}=[]) })
190         } $z, qw(subtitle description keywords created plugins)
191       }}
192     ->run;
193   +{
194     title => $title[0]->{raw}||'',
195     (map +($_ => $meta{$_}[0]->{attrs}{content}||''), keys %meta),
196     html => $html,
197   }
198 }
199
200 sub _extract_from_md {
201   my ($self, $md) = @_;
202   $self->_extract_from_html(markdown($md, { document_format => 'complete' }));
203 }
204
205 1;