Revamped option processing, added --minify
[exim-website.git] / script / gen.pl
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4 use CSS::Minifier::XS;
5 use File::Copy;
6 use File::Find;
7 use File::Slurp;
8 use File::Spec;
9 use Getopt::Long;
10 use JavaScript::Minifier::XS;
11 use XML::LibXML;
12 use XML::LibXSLT;
13
14 my $canonical_url = 'http://www.exim.org/';
15
16 ## Parse arguments
17 my %opt = parse_arguments();
18
19 ## Generate the pages
20 do_doc( 'spec',   $_ ) foreach @{ $opt{spec}   || [] };
21 do_doc( 'filter', $_ ) foreach @{ $opt{filter} || [] };
22 do_web() if exists $opt{web};
23
24 ## Add the exim-html-current symlink
25 print "Symlinking exim-html-current to exim-html-$opt{latest}\n";
26 symlink( "$opt{docroot}/exim-html-$opt{latest}", "$opt{docroot}/exim-html-current" );
27
28 ## Generate the website files
29 sub do_web {
30
31     ## Make sure the template web directory exists
32     die "No such directory: $opt{tmpl}/web\n" unless -d "$opt{tmpl}/web";
33
34     ## Scan the web templates
35     find(
36         sub {
37             my ($path) = substr( $File::Find::name, length("$opt{tmpl}/web"), length($File::Find::name) ) =~ m#^/*(.*)$#;
38
39             if ( -d "$opt{tmpl}/web/$path" ) {
40
41                 ## Create the directory in the doc root if it doesn't exist
42                 if ( !-d "$opt{docroot}/$path" ) {
43                     mkdir("$opt{docroot}/$path") or die "Unable to make $opt{docroot}/$path: $!\n";
44                 }
45
46             }
47             else {
48
49                 ## Build HTML from XSL files and simply copy static files which have changed
50                 if ( $path =~ /(.+)\.xsl$/ ) {
51                     print "Generating  : docroot:/$1.html\n";
52                     transform( undef, "$opt{tmpl}/web/$path", "$opt{docroot}/$1.html" );
53                 }
54                 elsif ( -f "$opt{tmpl}/web/$path" ) {
55
56                     ## Skip if the file hasn't changed (mtime based)
57                     return if -f "$opt{docroot}/$path" && ( stat("$opt{tmpl}/web/$path") )[9] == ( stat("$opt{docroot}/$path") )[9];
58
59                     if ( $path =~ /(.+)\.css$/ ) {
60                         print "CSS to  : docroot:/$path\n";
61                         my $content = read_file("$opt{tmpl}/web/$path");
62                         write_file( "$opt{docroot}/$path", $opt{minify} ? CSS::Minifier::XS::minify($content) : $content );
63                     }
64                     elsif ( $path =~ /(.+)\.js$/ ) {
65                         print "JS to  : docroot:/$path\n";
66                         my $content = read_file("$opt{tmpl}/web/$path");
67                         write_file( "$opt{docroot}/$path", $opt{minify} ? JavaScript::Minifier::XS::minify($content) : $content );
68                     }
69                     else {
70                         ## Copy
71                         print "Copying to  : docroot:/$path\n";
72                         copy( "$opt{tmpl}/web/$path", "$opt{docroot}/$path" ) or die "$path: $!";
73                     }
74                     ## Set mtime
75                     utime( time, ( stat("$opt{tmpl}/web/$path") )[9], "$opt{docroot}/$path" );
76                 }
77             }
78
79         },
80         "$opt{tmpl}/web"
81     );
82 }
83
84 ## Generate index/chapter files for a doc
85 sub do_doc {
86     my ( $type, $xml_path ) = @_;
87
88     ## Read and validate the XML file
89     my $xml = XML::LibXML->new()->parse_file($xml_path) or die $!;
90
91     ## Get the version number
92     my $version = $xml->findvalue('/book/bookinfo/revhistory/revision/revnumber');
93     die "Unable to get version number\n" unless defined $version && $version =~ /^\d+(\.\d+)*$/;
94
95     ## Prepend chapter filenames?
96     my $prepend_chapter = $type eq 'filter' ? 'filter_' : '';
97
98     ## Add the canonical url for this document
99     $xml->documentElement()
100       ->appendTextChild( 'canonical_url',
101         "${canonical_url}exim-html-current/doc/html/spec_html/" . ( $type eq 'spec' ? 'index' : 'filter' ) . ".html" );
102
103     ## Fixup the XML
104     xref_fixup( $xml, $prepend_chapter );
105
106     ## Generate the front page
107     {
108         my $path = "exim-html-$version/doc/html/spec_html/" . ( $type eq 'filter' ? $type : 'index' ) . ".html";
109         print "Generating  : docroot:/$path\n";
110         transform( $xml, "$opt{tmpl}/doc/index.xsl", "$opt{docroot}/$path", );
111     }
112
113     ## Generate a Table of Contents XML file
114     {
115         my $path = "exim-html-$version/doc/html/spec_html/" . ( $type eq 'filter' ? 'filter_toc' : 'index_toc' ) . ".xml";
116         print "Generating  : docroot:/$path\n";
117         transform( $xml, "$opt{tmpl}/doc/toc.xsl", "$opt{docroot}/$path", );
118     }
119
120     ## Generate the chapters
121     my $counter = 0;
122     foreach my $chapter ( map { $_->cloneNode(1) } $xml->findnodes('/book/chapter') ) {
123
124         ## Add a <chapter_id>N</chapter_id> node for the stylesheet to use
125         $chapter->appendTextChild( 'chapter_id', ++$counter );
126
127         ## Add previous/next/canonical urls for nav
128         {
129             $chapter->appendTextChild( 'prev_url',
130                   $counter == 1
131                 ? $type eq 'filter'
132                       ? 'filter.html'
133                       : 'index.html'
134                 : sprintf( '%sch%02d.html', $prepend_chapter, $counter - 1 ) );
135             $chapter->appendTextChild( 'next_url', sprintf( '%sch%02d.html', $prepend_chapter, $counter + 1 ) );
136             $chapter->appendTextChild( 'canonical_url',
137                 sprintf( 'http://www.exim.org/exim-html-current/doc/html/spec_html/%sch%02d.html', $prepend_chapter, $counter ) );
138         }
139
140         ## Create an XML document from the chapter
141         my $doc = XML::LibXML::Document->createDocument( '1.0', 'UTF-8' );
142         $doc->setDocumentElement($chapter);
143
144         ## Transform the chapter into html
145         {
146             my $path = sprintf( 'exim-html-%s/doc/html/spec_html/%sch%02d.html', $version, $prepend_chapter, $counter );
147             print "Generating  : docroot:/$path\n";
148             transform( $doc, "$opt{tmpl}/doc/chapter.xsl", "$opt{docroot}/$path", );
149         }
150     }
151 }
152
153 ## Fixup xref tags
154 sub xref_fixup {
155     my ( $xml, $prepend_chapter ) = @_;
156
157     my %index = ();
158
159     ## Add the "prepend_chapter" info
160     ( $xml->findnodes('/book') )[0]->appendTextChild( 'prepend_chapter', $prepend_chapter );
161
162     ## Iterate over each chapter
163     my $chapter_counter = 0;
164     foreach my $chapter ( $xml->findnodes('/book/chapter') ) {
165         ++$chapter_counter;
166
167         my $chapter_id = $chapter->getAttribute('id');
168         unless ($chapter_id) {    # synthesise missing id
169             $chapter_id = sprintf( 'chapter_noid_%04d', $chapter_counter );
170             $chapter->setAttribute( 'id', $chapter_id );
171         }
172         my $chapter_title = $chapter->findvalue('title');
173
174         $index{$chapter_id} = { chapter_id => $chapter_counter, chapter_title => $chapter_title };
175
176         ## Iterate over each section
177         my $section_counter = 0;
178         foreach my $section ( $chapter->findnodes('section') ) {
179             ++$section_counter;
180
181             my $section_id = $section->getAttribute('id');
182             unless ($section_id) {    # synthesise missing id
183                 $section_id = sprintf( 'section_noid_%04d_%04d', $chapter_counter, $section_counter );
184                 $section->setAttribute( 'id', $section_id );
185             }
186             my $section_title = $section->findvalue('title');
187
188             $index{$section_id} =
189               { chapter_id => $chapter_counter, chapter_title => $chapter_title, section_id => $section_counter };
190         }
191     }
192
193     ## Replace all of the xrefs in the XML
194     foreach my $xref ( $xml->findnodes('//xref') ) {
195         my $linkend = $xref->getAttribute('linkend');
196         if ( exists $index{$linkend} ) {
197             $xref->setAttribute( 'chapter_id',    $index{$linkend}{'chapter_id'} );
198             $xref->setAttribute( 'chapter_title', $index{$linkend}{'chapter_title'} );
199             $xref->setAttribute( 'section_id',    $index{$linkend}{'section_id'} ) if $index{$linkend}{'section_id'};
200             $xref->setAttribute( 'url',
201                 sprintf( '%sch%02d.html', $prepend_chapter, $index{$linkend}{'chapter_id'} )
202                   . ( $index{$linkend}{'section_id'} ? '#' . $linkend : '' ) );
203         }
204     }
205 }
206
207 ## Handle the transformation
208 sub transform {
209     my ( $xml, $xsl_path, $out_path ) = @_;
210
211     ## Build an empty XML structure if an undefined $xml was passed
212     unless ( defined $xml ) {
213         $xml = XML::LibXML::Document->createDocument( '1.0', 'UTF-8' );
214         $xml->setDocumentElement( $xml->createElement('content') );
215     }
216
217     ## Add the current version of Exim to the XML
218     $xml->documentElement()->appendTextChild( 'current_version', $opt{latest} );
219
220     ## Parse the ".xsl" file as XML
221     my $xsl = XML::LibXML->new()->parse_file($xsl_path) or die $!;
222
223     ## Generate a stylesheet from the ".xsl" XML.
224     my $stylesheet = XML::LibXSLT->new()->parse_stylesheet($xsl);
225
226     ## Generate a doc from the XML transformed with the XSL
227     my $doc = $stylesheet->transform($xml);
228
229     ## Make the containing directory if it doesn't exist
230     mkdirp( ( $out_path =~ /^(.+)\/.+$/ )[0] );
231
232     ## Write out the document
233     open my $out, '>', $out_path or die $!;
234     print $out $stylesheet->output_as_bytes($doc);
235     close $out;
236 }
237
238 ## "mkdir -p "
239 sub mkdirp {
240     my $path = shift;
241
242     my @parts = ();
243     foreach ( split( /\//, $path ) ) {
244         push @parts, $_;
245         my $make = join( '/', @parts );
246         next unless length($make);
247         next if -d $make;
248         mkdir($make) or die "Unable to mkdir $make: $!\n";
249     }
250 }
251
252 ## Parse arguments
253 sub parse_arguments {
254
255     my %opt = ( spec => [], filter => [], help => 0, web => 0, minify => 1 );
256     GetOptions( \%opt, 'help|h!', 'web!', 'spec=s{}', 'filter=s{}', 'latest=s', 'tmpl=s', 'docroot=s', 'minify!' )
257       || help( 1, 'Bad options' );
258
259     ## --help
260     help(0) if ( $opt{help} );
261
262     ## --spec and --filter lists
263     foreach my $set (qw[spec filter]) {
264         $opt{$set} = [ map { my $f = File::Spec->rel2abs($_); help( 1, 'No such file: ' . $_ ) unless -f $f; $f } @{ $opt{$set} } ];
265     }
266     ## --latest
267     help( 1, 'Missing value for latest' ) unless ( exists( $opt{latest} ) && defined( $opt{latest} ) );
268     help( 1, 'Invalid value for latest' ) unless $opt{latest} =~ /^\d+(?:\.\d+)*$/;
269
270     ## --tmpl and --docroot
271     foreach my $set (qw[tmpl docroot]) {
272         help( 1, 'Missing value for ' . $set ) unless ( exists( $opt{$set} ) && defined( $opt{$set} ) );
273         my $f = File::Spec->rel2abs( $opt{$set} );
274         help( 1, 'No such directory: ' . $opt{$set} ) unless -d $f;
275         $opt{$set} = $f;
276     }
277     help( 1, 'Excess arguments' ) if ( scalar(@ARGV) );
278
279     help( 1, 'Must include at least one of --web, --spec or --filter' )
280       unless ( defined $opt{web} || scalar( @{ $opt{spec} } ) || scalar( @{ $opt{web} } ) );
281
282     return %opt;
283 }
284
285 ## Help information
286 sub help {
287     my ( $exit_code, $msg ) = @_;
288
289     print "$msg\n\n" if defined $msg;
290
291     print << "END_HELP";
292 Options:
293    --help or -h  : Print this help information and then exit
294
295    --web         : Generate the general website pages
296    --spec PATH   : Generate the spec pages. PATH is the path to the spec.xml
297    --filter PATH : Generate the filter pages. PATH is the path to the filter.xml
298
299    One or more of the above three options are required. --spec and --filter can
300    take multiple values to generate different sets of documentation for
301    different versions at the same time.
302
303    --latest VERSION : Required. Specify the latest stable version of Exim.
304    --tmpl PATH      : Required. Path to the templates directory
305    --docroot PATH   : Required. Path to the website document root
306
307    If CSS::Minifier::XS is installed, then CSS will be minified.
308    If JavaScript::Minifier::XS is installed, then JavaScript will be minified.
309
310 Example:
311
312    ./gen.pl --latest 4.72
313             --web
314             --spec spec.xml 4.71/spec.xml
315             --filter filter.xml 4.71/filter.xml
316             --tmpl ~/www/templates
317             --docroot ~/www/docroot
318 END_HELP
319
320     exit($exit_code);
321 }