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