f765f76bcf36226720f631550300e236e898cdd0
[scpubgit/App-SCS.git] / lib / App / SCS / Plugin / Generate.pm
1 package App::SCS::Plugin::Generate;
2
3 use IO::All;
4 use Moo;
5 use Module::Runtime qw(use_module);
6 no warnings::illegalproto;
7
8 with 'App::SCS::Role::Plugin';
9
10 has dir => (
11   is => 'ro',
12   default => sub { $_[0]->config->{dir} || 'out' }
13 );
14
15 has host => (
16   is => 'ro',
17   default => sub { $_[0]->config->{host} || 'www.example.com' }
18 );
19
20 sub run_command_generate (dir=s;host=s;only=s) {
21   my ($self, $env) = @_;
22   my $opt = $env->{options};
23   my @all_paths = map $_->provides_pages, @{$self->app->plugins};
24   my $dir = io->dir($opt->{dir} || $self->dir);
25   $dir->mkpath;
26   my $prefix = 'http://'.($opt->{host} || $self->host);
27   if (my $only = $opt->{only}) {
28     my $re = qr/^\Q${only}/;
29     @all_paths = grep /$re/, @all_paths;
30   }
31   foreach my $path (@all_paths) {
32     warn "Generating ${path}\n";
33     my $dir = $dir->catdir($path);
34     $dir->mkpath;
35     my $res = $self->app->web->run_test_request(GET => "${prefix}${path}");
36     # text/html -> html
37     # application/atom+xml -> atom
38     my ($ext) = $res->content_type =~ m{\/(\w+)}
39       or die "Couldn't parse extension"
40             ." from content type ${\$res->content_type}"
41             ." for path ${path}";
42     $dir->catfile("index.${ext}")->print($res->content);
43   }
44 }
45
46 sub run_command_staticserver {
47   my ($self, $env) = @_;
48   my @args = @{$env->{argv}};
49   my $opt = $env->{options};
50   my $dir = io->dir($opt->{dir} || $self->dir);
51   my $s = use_module('App::SCS::Plugin::Generate::StaticServer')->new(
52     dir => $dir, app => $self->app,
53   )->run_server($env);
54 }
55
56 1;