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