improvements to generate command
[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/^${only}/;
29     @all_paths = grep /$re/, @all_paths;
30   }
31   my @fail;
32   foreach my $path (@all_paths) {
33     warn "Generating ${path}\n";
34     my $res = $self->app->web->run_test_request(GET => "${prefix}${path}");
35
36     unless ($res->is_success) {
37       warn "ERROR on ${path}\n";
38       push @fail, [ $path, $res ];
39       next;
40     }
41
42     my $dir = $dir->catdir($path);
43     $dir->mkpath;
44     # text/html -> html
45     # application/atom+xml -> atom
46     my ($ext) = $res->content_type =~ m{\/(\w+)}
47       or die "Couldn't parse extension"
48             ." from content type ${\$res->content_type}"
49             ." for path ${path}";
50     $dir->catfile("index.${ext}")->print($res->content);
51   }
52   warn "\nERRORS GENERATING PAGES:\n";
53   foreach my $fail (@fail) {
54     my ($path, $res) = @$fail;
55     warn "\nFailed to generate ${path}:\n";
56     my $error = $res->content||'';
57     $error =~ s/^/  /mg;
58     $error .= "\n" unless $error =~ /\n\Z/;
59     warn $error;
60   }
61 }
62
63 sub run_command_staticserver {
64   my ($self, $env) = @_;
65   my @args = @{$env->{argv}};
66   my $opt = $env->{options};
67   my $dir = io->dir($opt->{dir} || $self->dir);
68   my $s = use_module('App::SCS::Plugin::Generate::StaticServer')->new(
69     dir => $dir, app => $self->app,
70   )->run_server($env);
71 }
72
73 1;