1#!./perl -Ilib -w
2
3# This file should really be extracted from a .PL file
4
5$| = 1;
6use strict;
7use Config;		# for config options in the makefile
8use File::Path qw(remove_tree);
9use File::Spec::Functions qw(rel2abs no_upwards);
10use Getopt::Long;	# for command-line parsing
11use Cwd;
12use Pod::Html 1.32;
13use Pod::Html::Util 1.32 qw(anchorify relativize_url);
14
15=head1 NAME
16
17installhtml - converts a collection of POD pages to HTML format.
18
19=head1 SYNOPSIS
20
21  installhtml  [--help] [--podpath=<name>:...:<name>] [--podroot=<name>]
22       [--htmldir=<name>] [--htmlroot=<name>]  [--norecurse] [--recurse]
23       [--splithead=<name>,...,<name>]   [--splititem=<name>,...,<name>]
24       [--ignore=<name>,...,<name>]  [--verbose]
25
26=head1 DESCRIPTION
27
28I<installhtml> converts a collection of POD pages to a corresponding
29collection of HTML pages.  This is used to convert the pod pages found in the
30perl distribution.  (It is not intended as a general-purpose
31converter/installer of POD pages in HTML format.  See L<Pod::Html>.)
32
33=head1 OPTIONS
34
35=over 4
36
37=item B<--help> help
38
39Displays the usage.
40
41=item B<--podroot> POD search path base directory
42
43The base directory to search for all .pod and .pm files to be converted.
44Default is current directory.
45
46=item B<--podpath> POD search path
47
48The list of directories to search for .pod and .pm files to be converted.
49Default is 'podroot/lib'.
50
51=item B<--recurse> recurse on subdirectories
52
53Whether or not to convert all .pm and .pod files found in subdirectories
54too.  Default is to not recurse.
55
56=item B<--htmldir> HTML destination directory
57
58The base directory which all HTML files will be written to.  This should
59be a path relative to the filesystem, not the resulting URL.
60
61=item B<--htmlroot> URL base directory
62
63The base directory which all resulting HTML files will be visible at in
64a URL.  The default is '/'.
65
66=item B<--splithead> POD files to split on =head directive
67
68Comma-separated list of pod files to split by the =head directive.  The
69.pod suffix is optional. These files should have names specified
70relative to podroot.
71
72=item B<--splititem> POD files to split on =item directive
73
74Comma-separated list of all pod files to split by the =item directive.  The
75.pod suffix is optional.  I<installhtml> does not do the actual split, rather
76it invokes I<splitpod>, a separate program in the Perl 5 core distribution,
77to do the dirty work.  As with --splithead, these files should have names
78specified relative to podroot.
79
80=item B<--splitpod> Directory containing the splitpod program
81
82The directory containing the splitpod program. The default is 'podroot/pod'.
83
84=item B<--ignore> files to be ignored
85
86Comma-separated of files that shouldn't be installed, given relative
87to podroot.
88
89=item B<--verbose> verbose output
90
91Self-explanatory.
92
93=back
94
95=head1 EXAMPLE
96
97The following command-line is an example of the one we use to convert
98perl documentation:
99
100    ./installhtml --podpath=lib:ext:pod:vms   \
101			--podroot=/usr/src/perl     \
102			--htmldir=/perl/nmanual     \
103			--htmlroot=/perl/nmanual    \
104			--splithead=pod/perlipc     \
105			--splititem=pod/perlfunc    \
106			--recurse \
107			--verbose
108
109=head1 AUTHOR
110
111Chris Hall E<lt>hallc@cs.colorado.eduE<gt>
112
113=cut
114
115my $usage;
116
117$usage =<<END_OF_USAGE;
118Usage: $0 --help --podpath=<name>:...:<name> --podroot=<name>
119         --htmldir=<name> --htmlroot=<name> --norecurse --recurse
120         --splithead=<name>,...,<name> --splititem=<name>,...,<name>
121         --ignore=<name>,...,<name> --verbose
122
123    --help      - this message
124    --podpath   - colon-separated list of directories containing .pod and
125                  .pm files to be converted ('lib/' by default).
126    --podroot   - filesystem base directory from which all relative paths in
127                  podpath stem (default is .).
128    --htmldir   - directory to store resulting html files in relative
129                  to the filesystem (\$podroot/html by default).
130    --htmlroot  - http-server base directory from which all relative paths
131                  in podpath stem (default is /).
132    --norecurse - don't recurse on those subdirectories listed in podpath.
133                  (default behavior).
134    --recurse   - recurse on those subdirectories listed in podpath
135    --splithead - comma-separated list of .pod or .pm files to split.  will
136                  split each file into several smaller files at every occurrence
137                  of a pod =head[1-6] directive.
138    --splititem - comma-separated list of .pod or .pm files to split using
139                  splitpod.
140    --splitpod  - directory where the program splitpod can be found
141                  (\$podroot/pod by default).
142    --ignore    - comma-separated list of files that shouldn't be installed.
143    --verbose   - self-explanatory.
144
145END_OF_USAGE
146
147my (@podpath, $podroot, $htmldir, $htmlroot, $recurse, @splithead,
148    @splititem, $splitpod, $verbose, $pod2html, @ignore);
149
150@podpath = ( "lib" );	# colon-separated list of directories containing .pod
151			# and .pm files to be converted.
152$podroot = ".";		# assume the pods we want are here
153$htmldir = "";		# nothing for now...
154$htmlroot = "/";	# default value
155$recurse = 0;		# default behavior
156@splithead = ();	# don't split any files by default
157@splititem = ();	# don't split any files by default
158$splitpod = "";		# nothing for now.
159
160$verbose = 0;		# whether or not to print debugging info
161
162$pod2html = "pod/pod2html";
163
164usage("") unless @ARGV;
165
166# Overcome shell's p1,..,p8 limitation.
167# See vms/descrip_mms.template -> descrip.mms for invocation.
168if ( $^O eq 'VMS' ) { @ARGV = split(/\s+/,$ARGV[0]); }
169
170our %Options;
171
172# parse the command-line
173my $result = GetOptions( \%Options, qw(
174	help
175	podpath=s
176	podroot=s
177	htmldir=s
178	htmlroot=s
179	ignore=s
180	recurse!
181	splithead=s
182	splititem=s
183	splitpod=s
184	verbose
185));
186usage("invalid parameters") unless $result;
187parse_command_line();
188
189
190# set these variables to appropriate values if the user didn't specify
191#  values for them.
192$htmldir = "$htmlroot/html" unless $htmldir;
193$splitpod = "$podroot/pod" unless $splitpod;
194
195
196# make sure that the destination directory exists
197(mkdir($htmldir, 0755) ||
198	die "$0: cannot make directory $htmldir: $!\n") if ! -d $htmldir;
199
200
201# the following array will eventually contain files that are to be
202# ignored in the conversion process.  these are files that have been
203# process by splititem or splithead and should not be converted as a
204# result.
205my @splitdirs;
206
207# split pods. It's important to do this before convert ANY pods because
208# it may affect some of the links
209@splitdirs = ();    # files in these directories won't get an index
210split_on_head($podroot, $htmldir, \@splitdirs, \@ignore, @splithead);
211split_on_item($podroot,           \@splitdirs, \@ignore, @splititem);
212
213
214# convert the pod pages found in @poddirs
215#warn "converting files\n" if $verbose;
216#warn "\@ignore\t= @ignore\n" if $verbose;
217foreach my $dir (@podpath) {
218    installdir($dir, $recurse, $podroot, \@splitdirs, \@ignore);
219}
220
221
222# now go through and create master indices for each pod we split
223foreach my $dir (@splititem) {
224    print "creating index $htmldir/$dir.html\n" if $verbose;
225    create_index("$htmldir/$dir.html", "$htmldir/$dir");
226}
227
228foreach my $dir (@splithead) {
229    (my $pod = $dir) =~ s,^.*/,,;
230    $dir .= ".pod" unless $dir =~ /(\.pod|\.pm)$/;
231    # let pod2html create the file
232    runpod2html($dir, 1);
233
234    # now go through and truncate after the index
235    $dir =~ /^(.*?)(\.pod|\.pm)?$/sm;
236    my $file = "$htmldir/$1";
237    print "creating index $file.html\n" if $verbose;
238
239    # read in everything until what would have been the first =head
240    # directive, patching the index as we go.
241    open(H, '<', "$file.html") ||
242	die "$0: error opening $file.html for input: $!\n";
243    $/ = "";
244    my @data = ();
245    while (<H>) {
246	last if m!<h1 id="NAME">NAME</h1>!;
247	$_ =~ s{href="#(.*)">}{
248	    my $url = "$file/@{[anchorify(qq($1))]}.html" ;
249	    $url = relativize_url( $url, "$file.html" )
250	    if ( ! defined $Options{htmlroot} || $Options{htmlroot} eq '' );
251	    "href=\"$url\">" ;
252	}egi;
253	push @data, $_;
254    }
255    close(H);
256
257    # now rewrite the file
258    open(H, '>', "$file.html") ||
259	die "$0: error opening $file.html for output: $!\n";
260    print H @data, "</body>\n\n</html>\n\n\n";
261    close(H);
262}
263
264remove_tree(@splitdirs, {safe=>1});
265
266##############################################################################
267
268
269sub usage {
270    warn "$0: @_\n" if @_;
271    die $usage;
272}
273
274
275sub parse_command_line {
276    usage() if defined $Options{help};
277    $Options{help} = ""; 	    	    # make -w shut up
278
279    # list of directories
280    @podpath   = split(":", $Options{podpath}) if defined $Options{podpath};
281
282    # lists of files
283    @splithead = split(",", $Options{splithead}) if defined $Options{splithead};
284    @splititem = split(",", $Options{splititem}) if defined $Options{splititem};
285
286    $htmldir  = $Options{htmldir}	    if defined $Options{htmldir};
287    $htmlroot = $Options{htmlroot}	    if defined $Options{htmlroot};
288    $podroot  = $Options{podroot}	    if defined $Options{podroot};
289    $splitpod = $Options{splitpod}	    if defined $Options{splitpod};
290
291    $recurse  = $Options{recurse}	    if defined $Options{recurse};
292    $verbose  = $Options{verbose}	    if defined $Options{verbose};
293
294    @ignore = map "$podroot/$_", split(",", $Options{ignore}) if defined $Options{ignore};
295}
296
297
298sub create_index {
299    my($html, $dir) = @_;
300    (my $pod = $dir) =~ s,^.*/,,;
301
302    # get the list of .html files in this directory
303    opendir(DIR, $dir) ||
304	die "$0: error opening directory $dir for reading: $!\n";
305    my @files = sort(grep(/\.html?$/, readdir(DIR)));
306    closedir(DIR);
307
308    open(HTML, '>', $html) ||
309	die "$0: error opening $html for output: $!\n";
310
311    # for each .html file in the directory, extract the index
312    #	embedded in the file and throw it into the big index.
313    print HTML "<DL COMPACT>\n";
314    foreach my $file (@files) {
315
316	my $filedata = do {
317	    open(my $in, '<', "$dir/$file") ||
318		die "$0: error opening $dir/$file for input: $!\n";
319	    local $/ = undef;
320	    <$in>;
321	};
322
323	# pull out the NAME section
324	my($lcp1, $lcp2) =
325	    ($filedata =~
326		m#<h1 id="NAME">NAME</h1>\s*<p>\s*(\S+)\s+-\s+(\S.*?\S)</p>#);
327	defined $lcp1 or die "$0: can't find NAME section in $dir/$file\n";
328
329	my $url= "$dir/$file" ;
330	if ( ! defined $Options{htmlroot} || $Options{htmlroot} eq '' ) {
331	    $url = relativize_url( $url, $html ) ;
332	}
333
334	print HTML qq(<DT><A HREF="$url">);
335	print HTML "$lcp1</A></DT><DD>$lcp2</DD>\n";
336    }
337    print HTML "</DL>\n";
338
339    close(HTML);
340}
341
342
343sub split_on_head {
344    my($podroot, $htmldir, $splitdirs, $ignore, @splithead) = @_;
345    my($pod, $dirname, $filename);
346
347    # split the files specified in @splithead on =head[1-6] pod directives
348    print "splitting files by head.\n" if $verbose && $#splithead >= 0;
349    foreach $pod (@splithead) {
350	# figure out the directory name and filename
351	$pod      =~ s,^([^/]*)$,/$1,;
352	$pod      =~ m,(.*)/(.*?)(\.pod)?$,;
353	$dirname  = $1;
354	$filename = "$2.pod";
355
356	# since we are splitting this file it shouldn't be converted.
357	push(@$ignore, "$podroot/$dirname/$filename");
358
359	# split the pod
360	splitpod("$podroot/$dirname/$filename", "$podroot/$dirname", $htmldir,
361	    $splitdirs);
362    }
363}
364
365
366sub split_on_item {
367    my($podroot, $splitdirs, $ignore, @splititem) = @_;
368    my($pwd, $dirname, $filename);
369
370    print "splitting files by item.\n" if $verbose && $#splititem >= 0;
371    $pwd = getcwd();
372    my $splitter = rel2abs("$splitpod/splitpod", $pwd);
373    my $perl = rel2abs($^X, $pwd);
374    foreach my $pod (@splititem) {
375	# figure out the directory to split into
376	$pod      =~ s,^([^/]*)$,/$1,;
377	$pod      =~ m,(.*)/(.*?)(\.pod)?$,;
378	$dirname  = "$1/$2";
379	$filename = "$2.pod";
380
381	# since we are splitting this file it shouldn't be converted.
382	push(@$ignore, "$podroot/$dirname.pod");
383
384	# split the pod
385	push(@$splitdirs, "$podroot/$dirname");
386	-d "$podroot/$dirname" and remove_tree("$podroot/$dirname", {safe=>1});
387	mkdir("$podroot/$dirname", 0755) ||
388		    die "$0: error creating directory $podroot/$dirname: $!\n";
389	chdir("$podroot/$dirname") ||
390	    die "$0: error changing to directory $podroot/$dirname: $!\n";
391	die "$splitter not found. Use '-splitpod dir' option.\n"
392	    unless -f $splitter;
393	system($perl, $splitter, "../$filename") &&
394	    warn "$0: error running '$splitter ../$filename'"
395		 ." from $podroot/$dirname";
396    }
397    chdir($pwd);
398}
399
400
401#
402# splitpod - splits a .pod file into several smaller .pod files
403#  where a new file is started each time a =head[1-6] pod directive
404#  is encountered in the input file.
405#
406sub splitpod {
407    my($pod, $poddir, $htmldir, $splitdirs) = @_;
408    my(@poddata, @filedata, @heads);
409    my($file, $i, $j, $prevsec, $section, $nextsec);
410
411    print "splitting $pod\n" if $verbose;
412
413    # read the file in paragraphs
414    $/ = "";
415    open(SPLITIN, '<', $pod) ||
416	die "$0: error opening $pod for input: $!\n";
417    @filedata = <SPLITIN>;
418    close(SPLITIN) ||
419	die "$0: error closing $pod: $!\n";
420
421    # restore the file internally by =head[1-6] sections
422    @poddata = ();
423    for ($i = 0, $j = -1; $i <= $#filedata; $i++) {
424	$j++ if ($filedata[$i] =~ /^\s*=head[1-6]/);
425	if ($j >= 0) {
426	    $poddata[$j]  = "" unless defined $poddata[$j];
427	    $poddata[$j] .= "\n$filedata[$i]" if $j >= 0;
428	}
429    }
430
431    # create list of =head[1-6] sections so that we can rewrite
432    #  L<> links as necessary.
433    my %heads = ();
434    foreach $i (0..$#poddata) {
435	$heads{anchorify($1)} = 1 if $poddata[$i] =~ /=head[1-6]\s+(.*)/;
436    }
437
438    # create a directory of a similar name and store all the
439    #  files in there
440    $pod =~ s,.*/(.*),$1,;	# get the last part of the name
441    my $dir = $pod;
442    $dir =~ s/\.pod//g;
443    push(@$splitdirs, "$poddir/$dir");
444    -d "$poddir/$dir" and remove_tree("$poddir/$dir", {safe=>1});
445    mkdir("$poddir/$dir", 0755) ||
446	die "$0: could not create directory $poddir/$dir: $!\n";
447
448    $poddata[0] =~ /^\s*=head[1-6]\s+(.*)/;
449    $section    = "";
450    $nextsec    = $1;
451
452    # for each section of the file create a separate pod file
453    for ($i = 0; $i <= $#poddata; $i++) {
454	# determine the "prev" and "next" links
455	$prevsec = $section;
456	$section = $nextsec;
457	if ($i < $#poddata) {
458	    $poddata[$i+1] =~ /^\s*=head[1-6]\s+(.*)/;
459	    $nextsec       = $1;
460	} else {
461	    $nextsec = "";
462	}
463
464	# determine an appropriate filename (this must correspond with
465	#  what pod2html will try and guess)
466	# $poddata[$i] =~ /^\s*=head[1-6]\s+(.*)/;
467	$file = "$dir/" . anchorify($section) . ".pod";
468
469	# create the new .pod file
470	print "\tcreating $poddir/$file\n" if $verbose;
471	open(SPLITOUT, '>', "$poddir/$file") ||
472	    die "$0: error opening $poddir/$file for output: $!\n";
473	$poddata[$i] =~ s,L<([^<>]*)>,
474			defined $heads{anchorify($1)} ? "L<$dir/$1>" : "L<$1>"
475		     ,ge;
476	print SPLITOUT $poddata[$i]."\n\n";
477	print SPLITOUT "=over 4\n\n";
478	print SPLITOUT "=item *\n\nBack to L<$dir/\"$prevsec\">\n\n" if $prevsec;
479	print SPLITOUT "=item *\n\nForward to L<$dir/\"$nextsec\">\n\n" if $nextsec;
480	print SPLITOUT "=item *\n\nUp to L<$dir>\n\n";
481	print SPLITOUT "=back\n\n";
482	close(SPLITOUT) ||
483	    die "$0: error closing $poddir/$file: $!\n";
484    }
485}
486
487
488#
489# installdir - takes care of converting the .pod and .pm files in the
490#  current directory to .html files and then installing those.
491#
492sub installdir {
493    my($dir, $recurse, $podroot, $splitdirs, $ignore) = @_;
494
495    my @dirlist; # directories to recurse on
496    my @podlist; # .pod files to install
497    my @pmlist;  # .pm files to install
498
499    # should files in this directory get an index?
500    my $doindex = (grep($_ eq "$podroot/$dir", @$splitdirs) ? 0 : 1);
501
502    opendir(DIR, "$podroot/$dir")
503	|| die "$0: error opening directory $podroot/$dir: $!\n";
504
505    while(readdir DIR) {
506	no_upwards($_) or next;
507	my $is_dir = -d "$podroot/$dir/$_";
508	next if $is_dir and not $recurse;
509	my $target
510	    = $is_dir    ? \@dirlist
511	    : s/\.pod$// ? \@podlist
512	    : s/\.pm$//  ? \@pmlist
513	    : undef
514	    ;
515	push @$target, "$dir/$_" if $target;
516    }
517
518    closedir(DIR);
519
520    if ($^O eq 'VMS') { s/\.dir$//i for @dirlist }
521
522    # recurse on all subdirectories we kept track of
523    foreach $dir (@dirlist) {
524	installdir($dir, $recurse, $podroot, $splitdirs, $ignore);
525    }
526
527    # install all the pods we found
528    foreach my $pod (@podlist) {
529	# check if we should ignore it.
530	next if $pod =~ m(/t/); # comes from a test file
531	next if grep($_ eq "$pod.pod", @$ignore);
532
533	# check if a .pm files exists too
534	if (grep($_ eq $pod, @pmlist)) {
535	    print  "$0: Warning both '$podroot/$pod.pod' and "
536		. "'$podroot/$pod.pm' exist, using pod\n";
537	    push(@ignore, "$pod.pm");
538	}
539	runpod2html("$pod.pod", $doindex);
540    }
541
542    # install all the .pm files we found
543    foreach my $pm (@pmlist) {
544	# check if we should ignore it.
545	next if $pm =~ m(/t/); # comes from a test file
546	next if grep($_ eq "$pm.pm", @ignore);
547
548	runpod2html("$pm.pm", $doindex);
549    }
550}
551
552
553#
554# runpod2html - invokes pod2html to convert a .pod or .pm file to a .html
555#  file.
556#
557sub runpod2html {
558    my($pod, $doindex) = @_;
559    my($html, $i, $dir, @dirs);
560
561    $html = $pod;
562    $html =~ s/\.(pod|pm)$/.html/g;
563
564    # make sure the destination directories exist
565    @dirs = split("/", $html);
566    $dir  = "$htmldir/";
567    for ($i = 0; $i < $#dirs; $i++) {
568	if (! -d "$dir$dirs[$i]") {
569	    mkdir("$dir$dirs[$i]", 0755) ||
570		die "$0: error creating directory $dir$dirs[$i]: $!\n";
571	}
572	$dir .= "$dirs[$i]/";
573    }
574
575    # invoke pod2html
576    print "$podroot/$pod => $htmldir/$html\n" if $verbose;
577    Pod::Html::pod2html(
578        "--htmldir=$htmldir",
579	"--htmlroot=$htmlroot",
580	"--podpath=".join(":", @podpath),
581	"--podroot=$podroot",
582	"--header",
583	($doindex ? "--index" : "--noindex"),
584	"--" . ($recurse ? "" : "no") . "recurse",
585	"--infile=$podroot/$pod", "--outfile=$htmldir/$html");
586    die "$0: error running $pod2html: $!\n" if $?;
587}
588