685d0eb4f7a831101a7aeab9a261bbf29a8f0cf1
[exim-website.git] / script / gen.pl
1 #!/usr/bin/env perl
2 #
3 use strict;
4 use warnings;
5
6 use CSS::Minifier::XS 0.07;
7 use File::Copy;
8 use File::Find;
9 use File::Slurp;
10 use File::Spec;
11 use Getopt::Long;
12 use JavaScript::Minifier::XS;
13 use Pod::Usage;
14 use XML::LibXML;
15 use XML::LibXSLT;
16
17 my $canonical_url = 'http://www.exim.org/';
18
19 ## Parse arguments
20 my %opt = parse_arguments();
21
22 ## Generate the pages
23 do_doc( 'spec',   $_ ) foreach @{ $opt{spec}   || [] };
24 do_doc( 'filter', $_ ) foreach @{ $opt{filter} || [] };
25 do_web() if exists $opt{web};
26
27 ## Add the exim-html-current symlink
28 print "Symlinking exim-html-current to exim-html-$opt{latest}\n";
29 unlink("$opt{docroot}/exim-html-current") if ( -l "$opt{docroot}/exim-html-current" );
30 symlink( "exim-html-$opt{latest}", "$opt{docroot}/exim-html-current" )
31   || die "symlink to $opt{docroot}/exim-html-current failed";
32
33 ## Generate the website files
34 sub do_web {
35
36     ## Make sure the template web directory exists
37     die "No such directory: $opt{tmpl}/web\n" unless -d "$opt{tmpl}/web";
38
39     ## Scan the web templates
40     find(
41         sub {
42             my ($path) = substr( $File::Find::name, length("$opt{tmpl}/web"), length($File::Find::name) ) =~ m#^/*(.*)$#;
43
44             if ( -d "$opt{tmpl}/web/$path" ) {
45
46                 ## Create the directory in the doc root if it doesn't exist
47                 if ( !-d "$opt{docroot}/$path" ) {
48                     mkdir("$opt{docroot}/$path") or die "Unable to make $opt{docroot}/$path: $!\n";
49                 }
50
51             }
52             else {
53
54                 ## Build HTML from XSL files and simply copy static files which have changed
55                 if ( $path =~ /(.+)\.xsl$/ ) {
56                     print "Generating  : docroot:/$1.html\n" if ($opt{verbose});
57                     transform( undef, "$opt{tmpl}/web/$path", "$opt{docroot}/$1.html" );
58                 }
59                 elsif ( -f "$opt{tmpl}/web/$path" ) {
60
61                     ## Skip if the file hasn't changed (mtime based)
62                     return if -f "$opt{docroot}/$path" && ( stat("$opt{tmpl}/web/$path") )[9] == ( stat("$opt{docroot}/$path") )[9];
63
64                     if ( $path =~ /(.+)\.css$/ ) {
65                         print "CSS to  : docroot:/$path\n" if ($opt{verbose});
66                         my $content = read_file("$opt{tmpl}/web/$path");
67                         write_file( "$opt{docroot}/$path", $opt{minify} ? CSS::Minifier::XS::minify($content) : $content );
68                     }
69                     elsif ( $path =~ /(.+)\.js$/ ) {
70                         print "JS to  : docroot:/$path\n" if ($opt{verbose});
71                         my $content = read_file("$opt{tmpl}/web/$path");
72                         write_file( "$opt{docroot}/$path", $opt{minify} ? JavaScript::Minifier::XS::minify($content) : $content );
73                     }
74                     else {
75                         ## Copy
76                         print "Copying to  : docroot:/$path\n" if ($opt{verbose});
77                         copy( "$opt{tmpl}/web/$path", "$opt{docroot}/$path" ) or die "$path: $!";
78                     }
79                     ## Set mtime
80                     utime( time, ( stat("$opt{tmpl}/web/$path") )[9], "$opt{docroot}/$path" );
81                 }
82             }
83
84         },
85         "$opt{tmpl}/web"
86     );
87 }
88
89 ## Generate index/chapter files for a doc
90 sub do_doc {
91     my ( $type, $xml_path ) = @_;
92
93     ## Read and validate the XML file
94     my $xml = XML::LibXML->new()->parse_file($xml_path) or die $!;
95
96     ## Get the version number
97     my $version = $xml->findvalue('/book/bookinfo/revhistory/revision/revnumber');
98     die "Unable to get version number\n" unless defined $version && $version =~ /^\d+(\.\d+)*$/;
99
100     ## Prepend chapter filenames?
101     my $prepend_chapter = $type eq 'filter' ? 'filter_' : '';
102
103     ## Add the canonical url for this document
104     $xml->documentElement()
105       ->appendTextChild( 'canonical_url',
106         "${canonical_url}exim-html-current/doc/html/spec_html/" . ( $type eq 'spec' ? 'index' : 'filter' ) . ".html" );
107
108     ## Fixup the XML
109     xref_fixup( $xml, $prepend_chapter );
110
111     ## Generate the front page
112     {
113         my $path = "exim-html-$version/doc/html/spec_html/" . ( $type eq 'filter' ? $type : 'index' ) . ".html";
114         print "Generating  : docroot:/$path\n";
115         transform( $xml, "$opt{tmpl}/doc/index.xsl", "$opt{docroot}/$path", );
116     }
117
118     ## Generate a Table of Contents XML file
119     {
120         my $path = "exim-html-$version/doc/html/spec_html/" . ( $type eq 'filter' ? 'filter_toc' : 'index_toc' ) . ".xml";
121         print "Generating  : docroot:/$path\n" if ($opt{verbose});
122         transform( $xml, "$opt{tmpl}/doc/toc.xsl", "$opt{docroot}/$path", );
123     }
124
125     ## Generate the chapters
126     my $counter = 0;
127     foreach my $chapter ( map { $_->cloneNode(1) } $xml->findnodes('/book/chapter') ) {
128
129         ## Add a <chapter_id>N</chapter_id> node for the stylesheet to use
130         $chapter->appendTextChild( 'chapter_id', ++$counter );
131
132         ## Add previous/next/canonical urls for nav
133         {
134             $chapter->appendTextChild( 'prev_url',
135                   $counter == 1
136                 ? $type eq 'filter'
137                       ? 'filter.html'
138                       : 'index.html'
139                 : sprintf( '%sch%02d.html', $prepend_chapter, $counter - 1 ) );
140             $chapter->appendTextChild( 'next_url', sprintf( '%sch%02d.html', $prepend_chapter, $counter + 1 ) );
141             $chapter->appendTextChild( 'canonical_url',
142                 sprintf( 'http://www.exim.org/exim-html-current/doc/html/spec_html/%sch%02d.html', $prepend_chapter, $counter ) );
143         }
144
145         ## Create an XML document from the chapter
146         my $doc = XML::LibXML::Document->createDocument( '1.0', 'UTF-8' );
147         $doc->setDocumentElement($chapter);
148
149         ## Transform the chapter into html
150         {
151             my $path = sprintf( 'exim-html-%s/doc/html/spec_html/%sch%02d.html', $version, $prepend_chapter, $counter );
152             print "Generating  : docroot:/$path\n" if ($opt{verbose});
153             transform( $doc, "$opt{tmpl}/doc/chapter.xsl", "$opt{docroot}/$path", );
154         }
155     }
156 }
157
158 ## Fixup xref tags
159 sub xref_fixup {
160     my ( $xml, $prepend_chapter ) = @_;
161
162     my %index = ();
163
164     ## Add the "prepend_chapter" info
165     ( $xml->findnodes('/book') )[0]->appendTextChild( 'prepend_chapter', $prepend_chapter );
166
167     ## Iterate over each chapter
168     my $chapter_counter = 0;
169     foreach my $chapter ( $xml->findnodes('/book/chapter') ) {
170         ++$chapter_counter;
171
172         my $chapter_id = $chapter->getAttribute('id');
173         unless ($chapter_id) {    # synthesise missing id
174             $chapter_id = sprintf( 'chapter_noid_%04d', $chapter_counter );
175             $chapter->setAttribute( 'id', $chapter_id );
176         }
177         my $chapter_title = $chapter->findvalue('title');
178
179         $index{$chapter_id} = { chapter_id => $chapter_counter, chapter_title => $chapter_title };
180
181         ## Iterate over each section
182         my $section_counter = 0;
183         foreach my $section ( $chapter->findnodes('section') ) {
184             ++$section_counter;
185
186             my $section_id = $section->getAttribute('id');
187             unless ($section_id) {    # synthesise missing id
188                 $section_id = sprintf( 'section_noid_%04d_%04d', $chapter_counter, $section_counter );
189                 $section->setAttribute( 'id', $section_id );
190             }
191             my $section_title = $section->findvalue('title');
192
193             $index{$section_id} = {
194                 chapter_id    => $chapter_counter,
195                 chapter_title => $chapter_title,
196                 section_id    => $section_counter,
197                 section_title => $section_title
198             };
199         }
200     }
201     ## Build indexes as new chapters
202     build_indexes( $xml, $prepend_chapter, \%index );
203
204     ## Replace all of the xrefs in the XML
205     foreach my $xref ( $xml->findnodes('//xref') ) {
206         my $linkend = $xref->getAttribute('linkend');
207         if ( exists $index{$linkend} ) {
208             $xref->setAttribute( 'chapter_id',    $index{$linkend}{'chapter_id'} );
209             $xref->setAttribute( 'chapter_title', $index{$linkend}{'chapter_title'} );
210             $xref->setAttribute( 'section_id',    $index{$linkend}{'section_id'} ) if ( $index{$linkend}{'section_id'} );
211             $xref->setAttribute( 'section_title', $index{$linkend}{'section_title'} ) if ( $index{$linkend}{'section_title'} );
212             $xref->setAttribute( 'url',
213                 sprintf( '%sch%02d.html', $prepend_chapter, $index{$linkend}{'chapter_id'} )
214                   . ( $index{$linkend}{'section_id'} ? '#' . $linkend : '' ) );
215         }
216     }
217 }
218
219 ## Build indexes
220 sub build_indexes {
221     my ( $xml, $prepend_chapter, $xref ) = @_;
222
223     my $index_hash = {};
224     my $current_id;
225     foreach my $node ( $xml->findnodes('//section | //chapter | //indexterm') ) {
226         if ( $node->nodeName eq 'indexterm' ) {
227             my $role      = $node->getAttribute('role') || 'concept';
228             my $primary   = $node->findvalue('child::primary');
229             my $first     = ( $primary =~ /^[A-Za-z]/ ) ? uc( substr( $primary, 0, 1 ) ) : '';    # first letter or marker
230             my $secondary = $node->findvalue('child::secondary') || '';
231             next unless ( $primary || $secondary );                                               # skip blank entries for now...
232             $index_hash->{$role}{$first}{$primary}{$secondary} ||= [];
233             push @{ $index_hash->{$role}{$first}{$primary}{$secondary} }, $current_id;
234         }
235         else {
236             $current_id = $node->getAttribute('id');
237         }
238     }
239
240     # now we build a set of new chapters with the index data in
241     my $book = ( $xml->findnodes('/book') )[0];
242     foreach my $role ( sort { $a cmp $b } keys %{$index_hash} ) {
243         my $chapter = XML::LibXML::Element->new('chapter');
244         $book->appendChild($chapter);
245         $chapter->setAttribute( 'id', join( '_', 'index', $role ) );
246         $chapter->setAttribute( 'class', 'index' );
247         $chapter->appendTextChild( 'title', ( ucfirst($role) . ' Index' ) );
248         foreach my $first ( sort { $a cmp $b } keys %{ $index_hash->{$role} } ) {
249             my $section = XML::LibXML::Element->new('section');
250             my $list    = XML::LibXML::Element->new('variablelist');
251             $chapter->appendChild($section);
252             $section->setAttribute( 'id', join( '_', 'index', $role, $first ) );
253             $section->setAttribute( 'class', 'index' );
254             $section->appendTextChild( 'title', $first ? $first : 'Symbols' );
255             $section->appendChild($list);
256             foreach my $primary ( sort { $a cmp $b } keys %{ $index_hash->{$role}{$first} } ) {
257                 my $entry = XML::LibXML::Element->new('varlistentry');
258                 my $item  = XML::LibXML::Element->new('listitem');
259                 $list->appendChild($entry)->appendTextChild( 'term', $primary );
260                 $entry->appendChild($item);
261                 my $slist;
262                 foreach my $secondary ( sort { $a cmp $b } keys %{ $index_hash->{$role}{$first}{$primary} } ) {
263                     my $para = XML::LibXML::Element->new('para');
264                     if ( $secondary eq '' ) {
265                         $item->appendChild($para);    # skip having extra layer of heirarchy
266                     }
267                     else {
268                         unless ($slist) {
269                             $slist = XML::LibXML::Element->new('variablelist');
270                             $item->appendChild($slist);
271                         }
272                         my $sentry = XML::LibXML::Element->new('varlistentry');
273                         my $sitem  = XML::LibXML::Element->new('listitem');
274                         $slist->appendChild($sentry)->appendTextChild( 'term', $secondary );
275                         $sentry->appendChild($sitem)->appendChild($para);
276                     }
277                     my $count = 0;
278                     foreach my $ref ( @{ $index_hash->{$role}{$first}{$primary}{$secondary} } ) {
279                         $para->appendText(', ')
280                           if ( $count++ );
281                         my $xrefel = XML::LibXML::Element->new('xref');
282                         $xrefel->setAttribute( linkend => $ref );
283                         $xrefel->setAttribute( longref => 1 );
284                         $para->appendChild($xrefel);
285                     }
286                 }
287             }
288         }
289     }
290 }
291
292 ## Handle the transformation
293 sub transform {
294     my ( $xml, $xsl_path, $out_path ) = @_;
295
296     ## Build an empty XML structure if an undefined $xml was passed
297     unless ( defined $xml ) {
298         $xml = XML::LibXML::Document->createDocument( '1.0', 'UTF-8' );
299         $xml->setDocumentElement( $xml->createElement('content') );
300     }
301
302     ## Add the current version of Exim to the XML
303     $xml->documentElement()->appendTextChild( 'current_version', $opt{latest} );
304
305     ## Parse the ".xsl" file as XML
306     my $xsl = XML::LibXML->new()->parse_file($xsl_path) or die $!;
307
308     ## Generate a stylesheet from the ".xsl" XML.
309     my $stylesheet = XML::LibXSLT->new()->parse_stylesheet($xsl);
310
311     ## Generate a doc from the XML transformed with the XSL
312     my $doc = $stylesheet->transform($xml);
313
314     ## Make the containing directory if it doesn't exist
315     mkdirp( ( $out_path =~ /^(.+)\/.+$/ )[0] );
316
317     ## Write out the document
318     open my $out, '>', $out_path or die "Unable to write $out_path - $!";
319     print $out $stylesheet->output_as_bytes($doc);
320     close $out;
321 }
322
323 ## "mkdir -p "
324 sub mkdirp {
325     my $path = shift;
326
327     my @parts = ();
328     foreach ( split( /\//, $path ) ) {
329         push @parts, $_;
330         my $make = join( '/', @parts );
331         next unless length($make);
332         next if -d $make;
333         mkdir($make) or die "Unable to mkdir $make: $!\n";
334     }
335 }
336
337 ## error_help
338 sub error_help {
339     my $msg = shift;
340
341     warn $msg;
342     pod2usage( -exitval => 1, -verbose => 0 );
343 }
344
345 ## Parse arguments
346 sub parse_arguments {
347
348     my %opt = ( spec => [], filter => [], help => 0, man => 0, web => 0, minify => 1, verbose => 0 );
349     GetOptions( \%opt, 'help|h!', 'man!', 'web!', 'spec=s{1,}', 'filter=s{1,}', 'latest=s', 'tmpl=s', 'docroot=s', 'minify!', 'verbose!' )
350       || pod2usage( -exitval => 1, -verbose => 0 );
351
352     ## --help
353     pod2usage(0) if ( $opt{help} );
354     pod2usage( -verbose => 2 ) if ( $opt{man} );
355
356     ## --spec and --filter lists
357     foreach my $set (qw[spec filter]) {
358         $opt{$set} = [ map { my $f = File::Spec->rel2abs($_); help( 1, 'No such file: ' . $_ ) unless -f $f; $f } @{ $opt{$set} } ];
359     }
360     ## --latest
361     error_help('Missing value for latest') unless ( exists( $opt{latest} ) && defined( $opt{latest} ) );
362     error_help('Invalid value for latest') unless $opt{latest} =~ /^\d+(?:\.\d+)*$/;
363
364     ## --tmpl and --docroot
365     foreach my $set (qw[tmpl docroot]) {
366         error_help( 'Missing value for ' . $set ) unless ( exists( $opt{$set} ) && defined( $opt{$set} ) );
367         my $f = File::Spec->rel2abs( $opt{$set} );
368         error_help( 'No such directory: ' . $opt{$set} ) unless -d $f;
369         $opt{$set} = $f;
370     }
371     error_help('Excess arguments') if ( scalar(@ARGV) );
372
373     error_help('Must include at least one of --web, --spec or --filter')
374       unless ( $opt{web} || scalar( @{ $opt{spec} || [] } ) || scalar( @{ $opt{filter} || [] } ) );
375
376     return %opt;
377 }
378
379 1;
380
381 __END__
382
383 =head1 NAME
384
385 gen.pl - Generate exim html documentation and website
386
387 =head1 SYNOPSIS
388
389 gen.pl [options]
390
391  Options:
392    --help              display this help and exits
393    --man               displays man page
394    --spec file...      spec docbook/XML source files
395    --filter file...    filter docbook/XML source files
396    --web               Generate the general website pages
397    --latest VERSION    Required. Specify the latest stable version of Exim.
398    --tmpl PATH         Required. Path to the templates directory
399    --docroot PATH      Required. Path to the website document root
400    --[no-]minify       [Don't] minify CSS and Javascript    
401
402 =head1 OPTIONS
403
404 =over 4
405
406 =item B<--help>
407
408 Display help and exits
409
410 =item B<--man>
411
412 Display man page
413
414 =item B<--spec> I<file...>
415
416 List of files that make up the specification documentation
417 docbook/XML source files.
418
419 =item B<--filter> I<file...>
420
421 List of files that make up the filter documentation docbook/XML
422 source files.
423
424 =item B<--web>
425
426 Generate the website from the template files.
427
428 =item B<--latest> I<version>
429
430 Specify the current exim version. This is used to create links to
431 the current documentation.
432
433 This option is I<required>
434
435 =item B<--tmpl> I<directory>
436
437 Specify the directory that the templates are kept in.
438
439 This option is I<required>
440
441 =item B<--docroot> I<directory>
442
443 Specify the directory that the output should be generated into.
444 This is the website C<docroot> directory.
445
446 This option is I<required>
447
448 =item B<--minify>
449
450 If this option is set then both the CSS and Javascript files
451 processed are minified using L<CSS::Minifier::XS> and
452 L<JavaScript::Minifier::XS> respectively.
453
454 This option is set by default - to disable it specify C<--no-minify>
455
456 =back
457
458 =head1 DESCRIPTION
459
460 Generates the exim website and HTML documentation.
461
462 =head1 EXAMPLE
463
464     script/gen.pl \
465       --web \
466       --spec docbook/*/spec.xml \
467       --filter  docbook/*/filter.xml \
468       --latest 4.72 \
469       --tmpl templates \
470       --docroot /tmp/website
471
472 =head1 AUTHOR
473
474 Mike Cardwell
475
476 Nigel Metheringham <nigel@exim.org> - mostly broke the framework
477 Mike produced.
478
479 =head1 COPYRIGHT
480
481 Copyright 2010 Exim Maintainers. All rights reserved.
482
483 =cut
484