Generate toc_url entry into XML
[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( 'toc_url', ( $type eq 'filter' ? 'filter' : 'index' ) . '.html' );
159             $chapter->appendTextChild(
160                 'canonical_url',
161                 sprintf(
162                     'http://www.exim.org/exim-html-current/doc/html/spec_html/%sch%02d.html',
163                     $prepend_chapter, $counter
164                 )
165             );
166             if ( $version ne $opt{latest} ) {
167                 $chapter->appendTextChild(
168                     'current_url',
169                     sprintf(
170                         '../../../../exim-html-current/doc/html/spec_html/%sch%02d.html',
171                         $prepend_chapter, $counter
172                     )
173                 );
174             }
175         }
176
177         ## Create an XML document from the chapter
178         my $doc = XML::LibXML::Document->createDocument( '1.0', 'UTF-8' );
179         $doc->setDocumentElement($chapter);
180
181         ## Transform the chapter into html
182         {
183             my $path = sprintf( 'exim-html-%s/doc/html/spec_html/%sch%02d.html', $version, $prepend_chapter, $counter );
184             print "Generating  : docroot:/$path\n" if ( $opt{verbose} );
185             transform( $doc, "$opt{tmpl}/doc/chapter.xsl", "$opt{docroot}/$path", );
186         }
187     }
188 }
189
190 ## Fixup xref tags
191 sub xref_fixup {
192     my ( $xml, $prepend_chapter ) = @_;
193
194     my %index = ();
195
196     ## Add the "prepend_chapter" info
197     ( $xml->findnodes('/book') )[0]->appendTextChild( 'prepend_chapter', $prepend_chapter );
198
199     ## Iterate over each chapter
200     my $chapter_counter = 0;
201     foreach my $chapter ( $xml->findnodes('/book/chapter') ) {
202         ++$chapter_counter;
203
204         my $chapter_id = $chapter->getAttribute('id');
205         unless ($chapter_id) {    # synthesise missing id
206             $chapter_id = sprintf( 'chapter_noid_%04d', $chapter_counter );
207             $chapter->setAttribute( 'id', $chapter_id );
208         }
209         my $chapter_title = $chapter->findvalue('title');
210
211         $index{$chapter_id} = { chapter_id => $chapter_counter, chapter_title => $chapter_title };
212
213         ## Iterate over each section
214         my $section_counter = 0;
215         foreach my $section ( $chapter->findnodes('section') ) {
216             ++$section_counter;
217
218             my $section_id = $section->getAttribute('id');
219             unless ($section_id) {    # synthesise missing id
220                 $section_id = sprintf( 'section_noid_%04d_%04d', $chapter_counter, $section_counter );
221                 $section->setAttribute( 'id', $section_id );
222             }
223             my $section_title = $section->findvalue('title');
224
225             $index{$section_id} = {
226                 chapter_id    => $chapter_counter,
227                 chapter_title => $chapter_title,
228                 section_id    => $section_counter,
229                 section_title => $section_title
230             };
231         }
232     }
233     ## Build indexes as new chapters
234     build_indexes( $xml, $prepend_chapter, \%index );
235
236     ## Replace all of the xrefs in the XML
237     foreach my $xref ( $xml->findnodes('//xref') ) {
238         my $linkend = $xref->getAttribute('linkend');
239         if ( exists $index{$linkend} ) {
240             $xref->setAttribute( 'chapter_id',    $index{$linkend}{'chapter_id'} );
241             $xref->setAttribute( 'chapter_title', $index{$linkend}{'chapter_title'} );
242             $xref->setAttribute( 'section_id', $index{$linkend}{'section_id'} ) if ( $index{$linkend}{'section_id'} );
243             $xref->setAttribute( 'section_title', $index{$linkend}{'section_title'} )
244                 if ( $index{$linkend}{'section_title'} );
245             $xref->setAttribute( 'url',
246                 sprintf( '%sch%02d.html', $prepend_chapter, $index{$linkend}{'chapter_id'} )
247                     . ( $index{$linkend}{'section_id'} ? '#' . $linkend : '' ) );
248         }
249     }
250 }
251
252 ## Build indexes
253 sub build_indexes {
254     my ( $xml, $prepend_chapter, $xref ) = @_;
255
256     my $index_hash = {};
257     my $current_id;
258     foreach my $node ( $xml->findnodes('//section | //chapter | //indexterm') ) {
259         if ( $node->nodeName eq 'indexterm' ) {
260             my $role      = $node->getAttribute('role') || 'concept';
261             my $primary   = $node->findvalue('child::primary');
262             my $first     = ( $primary =~ /^[A-Za-z]/ ) ? uc( substr( $primary, 0, 1 ) ) : '';  # first letter or marker
263             my $secondary = $node->findvalue('child::secondary') || '';
264             next unless ( $primary || $secondary );    # skip blank entries for now...
265             $index_hash->{$role}{$first}{$primary}{$secondary} ||= [];
266             push @{ $index_hash->{$role}{$first}{$primary}{$secondary} }, $current_id;
267         }
268         else {
269             $current_id = $node->getAttribute('id');
270         }
271     }
272
273     # now we build a set of new chapters with the index data in
274     my $book = ( $xml->findnodes('/book') )[0];
275     foreach my $role ( sort { $a cmp $b } keys %{$index_hash} ) {
276         my $chapter = XML::LibXML::Element->new('chapter');
277         $book->appendChild($chapter);
278         $chapter->setAttribute( 'id', join( '_', 'index', $role ) );
279         $chapter->setAttribute( 'class', 'index' );
280         $chapter->appendTextChild( 'title', ( ucfirst($role) . ' Index' ) );
281         foreach my $first ( sort { $a cmp $b } keys %{ $index_hash->{$role} } ) {
282             my $section = XML::LibXML::Element->new('section');
283             my $list    = XML::LibXML::Element->new('variablelist');
284             $chapter->appendChild($section);
285             $section->setAttribute( 'id', join( '_', 'index', $role, $first ) );
286             $section->setAttribute( 'class', 'index' );
287             $section->appendTextChild( 'title', $first ? $first : 'Symbols' );
288             $section->appendChild($list);
289             foreach my $primary ( sort { $a cmp $b } keys %{ $index_hash->{$role}{$first} } ) {
290                 my $entry = XML::LibXML::Element->new('varlistentry');
291                 my $item  = XML::LibXML::Element->new('listitem');
292                 $list->appendChild($entry)->appendTextChild( 'term', $primary );
293                 $entry->appendChild($item);
294                 my $slist;
295                 foreach my $secondary ( sort { $a cmp $b } keys %{ $index_hash->{$role}{$first}{$primary} } ) {
296                     my $para = XML::LibXML::Element->new('para');
297                     if ( $secondary eq '' ) {
298                         $item->appendChild($para);    # skip having extra layer of heirarchy
299                     }
300                     else {
301                         unless ($slist) {
302                             $slist = XML::LibXML::Element->new('variablelist');
303                             $item->appendChild($slist);
304                         }
305                         my $sentry = XML::LibXML::Element->new('varlistentry');
306                         my $sitem  = XML::LibXML::Element->new('listitem');
307                         $slist->appendChild($sentry)->appendTextChild( 'term', $secondary );
308                         $sentry->appendChild($sitem)->appendChild($para);
309                     }
310                     my $count = 0;
311                     foreach my $ref ( @{ $index_hash->{$role}{$first}{$primary}{$secondary} } ) {
312                         $para->appendText(', ')
313                             if ( $count++ );
314                         my $xrefel = XML::LibXML::Element->new('xref');
315                         $xrefel->setAttribute( linkend => $ref );
316                         $xrefel->setAttribute( longref => 1 );
317                         $para->appendChild($xrefel);
318                     }
319                 }
320             }
321         }
322     }
323 }
324
325 ## Handle the transformation
326 sub transform {
327     my ( $xml, $xsl_path, $out_path ) = @_;
328
329     ## Build an empty XML structure if an undefined $xml was passed
330     unless ( defined $xml ) {
331         $xml = XML::LibXML::Document->createDocument( '1.0', 'UTF-8' );
332         $xml->setDocumentElement( $xml->createElement('content') );
333     }
334
335     ## Add the current version of Exim to the XML
336     $xml->documentElement()->appendTextChild( 'current_version', $opt{latest} );
337
338     ## Add the old versions of Exim to the XML
339     $xml->documentElement()->appendTextChild( 'old_versions', $_ ) foreach old_docs_versions();
340
341     ## Parse the ".xsl" file as XML
342     my $xsl = XML::LibXML->new()->parse_file($xsl_path) or die $!;
343
344     ## Generate a stylesheet from the ".xsl" XML.
345     my $stylesheet = XML::LibXSLT->new()->parse_stylesheet($xsl);
346
347     ## Generate a doc from the XML transformed with the XSL
348     my $doc = $stylesheet->transform($xml);
349
350     ## Make the containing directory if it doesn't exist
351     make_path( ( $out_path =~ /^(.+)\/.+$/ )[0], { verbose => 1 } );
352
353     ## Write out the document
354     open my $out, '>', $out_path or die "Unable to write $out_path - $!";
355     print $out $stylesheet->output_as_bytes($doc);
356     close $out;
357 }
358
359 ## Look in the docroot for old versions of the documentation
360 sub old_docs_versions {
361     if ( !exists $cache{old_docs_versions} ) {
362         my @versions;
363         foreach ( glob("$opt{docroot}/exim-html-*") ) {
364             push @versions, $1 if /-(\d+(?:\.\d+)?)$/ && $1 < $opt{latest} && -d $_;
365         }
366         $cache{old_docs_versions} = [ reverse sort { $a <=> $b } @versions ];
367     }
368     return @{ $cache{old_docs_versions} };
369 }
370
371 ## error_help
372 sub error_help {
373     my $msg = shift;
374
375     warn $msg;
376     pod2usage( -exitval => 1, -verbose => 0 );
377 }
378
379 ## Parse arguments
380 sub parse_arguments {
381
382     my %opt = ( spec => [], filter => [], help => 0, man => 0, web => 0, minify => 1, verbose => 0 );
383     GetOptions(
384         \%opt,      'help|h!', 'man!',      'web!',    'spec=s{1,}', 'filter=s{1,}',
385         'latest=s', 'tmpl=s',  'docroot=s', 'minify!', 'verbose!'
386     ) || pod2usage( -exitval => 1, -verbose => 0 );
387
388     ## --help
389     pod2usage(0) if ( $opt{help} );
390     pod2usage( -verbose => 2 ) if ( $opt{man} );
391
392     ## --spec and --filter lists
393     foreach my $set (qw[spec filter]) {
394         $opt{$set} =
395             [ map { my $f = File::Spec->rel2abs($_); help( 1, 'No such file: ' . $_ ) unless -f $f; $f }
396                 @{ $opt{$set} } ];
397     }
398     ## --latest
399     error_help('Missing value for latest') unless ( exists( $opt{latest} ) && defined( $opt{latest} ) );
400     error_help('Invalid value for latest') unless $opt{latest} =~ /^\d+(?:\.\d+)*$/;
401
402     ## --tmpl and --docroot
403     foreach my $set (qw[tmpl docroot]) {
404         error_help( 'Missing value for ' . $set ) unless ( exists( $opt{$set} ) && defined( $opt{$set} ) );
405         my $f = File::Spec->rel2abs( $opt{$set} );
406         error_help( 'No such directory: ' . $opt{$set} ) unless -d $f;
407         $opt{$set} = $f;
408     }
409     error_help('Excess arguments') if ( scalar(@ARGV) );
410
411     error_help('Must include at least one of --web, --spec or --filter')
412         unless ( $opt{web} || scalar( @{ $opt{spec} || [] } ) || scalar( @{ $opt{filter} || [] } ) );
413
414     return %opt;
415 }
416
417 1;
418
419 __END__
420
421 =head1 NAME
422
423 gen.pl - Generate exim html documentation and website
424
425 =head1 SYNOPSIS
426
427 gen.pl [options]
428
429  Options:
430    --help              display this help and exits
431    --man               displays man page
432    --spec file...      spec docbook/XML source files
433    --filter file...    filter docbook/XML source files
434    --web               Generate the general website pages
435    --latest VERSION    Required. Specify the latest stable version of Exim.
436    --tmpl PATH         Required. Path to the templates directory
437    --docroot PATH      Required. Path to the website document root
438    --[no-]minify       [Don't] minify CSS and Javascript    
439
440 =head1 OPTIONS
441
442 =over 4
443
444 =item B<--help>
445
446 Display help and exits
447
448 =item B<--man>
449
450 Display man page
451
452 =item B<--spec> I<file...>
453
454 List of files that make up the specification documentation
455 docbook/XML source files.
456
457 =item B<--filter> I<file...>
458
459 List of files that make up the filter documentation docbook/XML
460 source files.
461
462 =item B<--web>
463
464 Generate the website from the template files.
465
466 =item B<--latest> I<version>
467
468 Specify the current exim version. This is used to create links to
469 the current documentation.
470
471 This option is I<required>
472
473 =item B<--tmpl> I<directory>
474
475 Specify the directory that the templates are kept in.
476
477 This option is I<required>
478
479 =item B<--docroot> I<directory>
480
481 Specify the directory that the output should be generated into.
482 This is the website C<docroot> directory.
483
484 This option is I<required>
485
486 =item B<--minify>
487
488 If this option is set then both the CSS and Javascript files
489 processed are minified using L<CSS::Minifier::XS> and
490 L<JavaScript::Minifier::XS> respectively.
491
492 This option is set by default - to disable it specify C<--no-minify>
493
494 =back
495
496 =head1 DESCRIPTION
497
498 Generates the exim website and HTML documentation.
499
500 =head1 EXAMPLE
501
502     script/gen.pl \
503       --web \
504       --spec docbook/*/spec.xml \
505       --filter  docbook/*/filter.xml \
506       --latest 4.72 \
507       --tmpl templates \
508       --docroot /tmp/website
509
510 =head1 AUTHOR
511
512 Mike Cardwell
513
514 Nigel Metheringham <nigel@exim.org> - mostly broke the framework
515 Mike produced.
516
517 =head1 COPYRIGHT
518
519 Copyright 2010-2011 Exim Maintainers. All rights reserved.
520
521 =cut