-
Notifications
You must be signed in to change notification settings - Fork 0
/
documenter.pl
576 lines (437 loc) · 13.4 KB
/
documenter.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
#!/usr/bin/perl -w
=head1 Literate Programming Automatic Documenter
This is a tool to make source code more accessible and
automatically generate documentation for source code that
contains few comments.
It will recognize POD comments and some special markup.
The result is a pretty HTML version of your source file(s),
together with an outline.
=cut
use strict;
use warnings;
use feature "state";
## make sure this script also works when called from somewhere else
use FindBin qw($Bin);
use lib "$Bin";
## import HTML::Entities to escape stuff to HTML
use File::Spec qw(catfile catdir);
use File::Basename;
use File::Copy;
use HTML::Entities;
use Data::Dumper;
use Getopt::Long;
use Cwd;
use JSON;
use Template;
use Storable;
## These are our own tool libraries
use Tools::NamedTree;
use Tools::PerlParser;
use Tools::Output;
use Tools::Output::HTML;
=head2 Option parsing
=cut
## the input parameters
# input source file name
my $filename = 'documenter.pl';
# output directory to write to
my $outputdirectory = "./docs";
# directory with images and additional source files.
my $sourcedirectory = $Bin;
## output parameters:
# true when only printing usage message
my $usage = 0;
# true to prevent copying js/images/etc.
my $nohelpercopy = 0;
# output format
my $format = 'html';
# make an index file
my $mkindex = 1;
my $verbose = 0;
GetOptions(
'outputdirectory|o=s' => \$outputdirectory,
'sourcedirectory|s=s' => \$sourcedirectory,
'help|h!' => \$usage,
'nohelpercopy|n!' => \$nohelpercopy,
'index|i!' => \$mkindex,
'format|f=s' => \$format,
'verbose|v!' => \$verbose,
);
if ($usage) {
print <<'END';
Code Documenter usage:
documenter.pl [options] <filename>
Where [options] can be
--outputdirectory <dirname> : set an output directory for the
generated HTML files.
Default value: "./"
--sourcedirectory <dirname> : set an source directory to copy
styles, images, etc. from
This directory will default to the
location of documenter.pl.
--format <html/md> : specify the output format
--index : make an index file, too.
END
exit 0;
}
$filename = $ARGV[$#ARGV]
if scalar @ARGV > 0;
if ( !-f $filename ) {
die "Input file '$filename' does not exist.";
}
if ( !-d $outputdirectory ) {
die "Output directory $outputdirectory does not exist.";
}
if ( !-d $sourcedirectory ) {
die "Output directory $outputdirectory does not exist.";
}
if ($format ne 'html' && $format ne 'md') {
die "Unknown output format $format";
}
my $outputclass = 'Tools::Output';
my $templatefile = "template.$format";
# md is the default format.
if ($format ne 'md') {
$outputclass = 'Tools::Output::' . uc ($format);
}
eval {
# test creating this class here. dies if we don't have it
$outputclass->new;
};
if($@) {
die "Cannot output to format $format ($@)";
}
my $templatedir = File::Spec->catdir($Bin, 'templates', $format);
if(-d $templatedir) {
my $templatefiles = File::Spec->catfile($templatedir, "*");
unless ($nohelpercopy) {
# this won't work on Windows.
if ($^O eq 'MSWin32') {
print STDERR qx(xcopy /E /Q /Y /C "$templatedir\\*" "$outputdirectory");
unlink File::Spec->catfile($outputdirectory, "template.$format");
} else {
print STDERR qx(cp -r $templatedir/* $outputdirectory);
unlink File::Spec->catfile($outputdirectory, "template.$format");
}
}
$templatefile = File::Spec->catfile($templatedir, $templatefile);
} else {
die "Unknown template $format"
}
print STDERR "Template directory: $templatedir\n"
if $verbose;
=head2 File parsing and index generation
=cut
## index item formatting options
our %index_options = (
"sub" => "show_type",
"method" => "show_type",
"package" => "show_type",
"class" => "show_type",
"role" => "show_type",
"has" => "show_type",
"type" => "show_type",
"subtype" => "show_type",
"enum" => "show_type",
"global" => "show_type",
);
## index of line numbers
our @line_index = ();
## global print options, set via comment markup
our %doc_options = ();
## create various output file names.
# windows-safety. This implies you can't have backslashes
# as filenames. Which you shouldn't anyway.
$filename =~ s/\\/\//g;
# the title: remove leading "./" and make subfolders into packages
my $titlefilename = $filename;
$titlefilename =~ s/^\.\///;
$titlefilename =~ s/\//::/g;
# the HTML file needs to go into the same folder as all the other HTML code.
our $htmlfilename = $filename . ".$format";
$htmlfilename =~ s/^\.\///;
$htmlfilename =~ s/\//_/g;
print STDERR "Reading package index\n"
if $verbose;
## get the index tree for all files
## append index tree to package index
my $pindexfile = File::Spec->catfile($outputdirectory, "index.json");
my $packageindex = Tools::NamedTree->new (name => 'documenter_root');
$packageindex->value({
title => 'Documentation Index',
type => 'book',
location => 0,
anchor => "#",
style => "h1",
link => "index.html",
});
if (-e $pindexfile . ".storable") {
# local $/ = undef;
# local *FILE;
# open FILE, "<$pindexfile" and do {
# my $pindex = <FILE>;
# close FILE;
# eval {
# $pindex = from_json($pindex);
# $packageindex->FROM_JSON($pindex);
# };
# if ($@) {
# print "[W] Invalid index.json file: $@\n";
# }
# }
$packageindex = retrieve($pindexfile . ".storable");
};
print STDERR "Updating package index\n"
if $verbose;
my @mypath = split /\:\:/, $titlefilename;
unshift @mypath, 'documenter_root';
my $this_node = $packageindex->has_path(\@mypath);
if(!defined $this_node) {
$this_node = $packageindex->make_path(\@mypath, {
title => $mypath[$#mypath],
type => 'file',
location => 0,
anchor => "#",
style => "h1",
link => $htmlfilename,
});
}
for (my $i = 1; $i <= $#mypath; $i++) {
my @subpath = @mypath[0..($i-1)];
my $path_node = $packageindex->has_path(\@subpath)
or die "Tree node creation failed for @subpath";
if(!defined ($path_node->value) || $path_node->value eq "") {
$path_node->value({
title => $mypath[$i-1],
style => 'h1',
type => 'folder',
});
}
}
print STDERR "Starting to parse\n"
if $verbose;
## set up parsing
our $documentation = $outputclass->new;
## check if it's perl
if ($filename =~ m/\.pl$/i
|| $filename =~ m/\.pm$/i) {
# setup print handlers.
Tools::PerlParser::setHandler( 'code', \&perl_code_handler );
Tools::PerlParser::setHandler( 'comment', \&comment_handler );
Tools::PerlParser::setHandler( 'pod', \&pod_handler );
Tools::PerlParser::setHandler( 'end', \&pod_handler );
## start parsing. Print handlers above will add to documentation string
Tools::PerlParser::parse($filename);
## update index
my $index_top = Tools::PerlParser::get_contents_tree();
$index_top->traverse_update(\&index_item_info);
$this_node->children($index_top->children);
## check if it is markdown or other stuff we can handle directly
} elsif ($filename =~ m/\.md$/
|| $filename =~ m/\.markdown$/
|| $filename =~ m/\.pod$/
|| $filename =~ m/\.js$/
|| $filename =~ m/\.html$/
|| $filename =~ m/README$/
|| $filename =~ m/LICENSE$/
) {
my $md = '';
{ local $/ = undef; local *FILE; open FILE, "<", $filename
or die "Unable to open $filename"; $md = <FILE>; close FILE }
my $type = 'text';
if($filename =~ m/\.([a-z0-9]+)$/i) {
$type = lc $1;
}
if($type eq 'markdown') {
$type = 'md';
}
# print "Documenting $filename as $type\n";
$documentation->code($md, $type);
} else {
die "Unknown file format for $filename";
}
## remove temp files
unlink ('pod2htmd.tmp');
unlink ('pod2htmi.tmp');
print STDERR "Processing output template\n"
if $verbose;
## process template
my $template = Template->new({
INCLUDE_PATH => $Bin,
ABSOLUTE => 1,
EVAL_PERL => 1,
OUTPUT => File::Spec->catfile($outputdirectory, $htmlfilename),
ENCODING => 'utf8',
});
my $vars = {
doc => {
TITLE => $titlefilename,
CONTENT => $documentation->result,
}
};
$template->process(
$templatefile,
$vars,
File::Spec->catfile($outputdirectory, $htmlfilename),
{binmode=>'utf8'} )
|| die $template->error();
## finally, write updated index
print STDERR "Writing package index\n"
if $verbose;
open OUT_INDEX, ">:utf8", $pindexfile
or die "Cannot write to $pindexfile";
print OUT_INDEX to_json($packageindex->TO_JSON, {pretty=>1, allow_blessed=>1});
close OUT_INDEX;
store($packageindex, $pindexfile . ".storable");
print STDERR "Done.\n"
if $verbose;
## all done
0;
=head1 Helper functions
Here are some helper functions for this tool.
=cut
=head2 Handler function to print source code
Parameters:
$current : the perl code
$currentline : starting source line number
=cut
sub perl_code_handler {
our $documentation;
my $current = shift;
my $currentline = shift;
# hide source
if (defined $doc_options{'hide_source'}
&& $doc_options{'hide_source'}) {
return;
}
set_current_line($currentline);
# ignore shell env...
$current =~ s/\#\!.*?\n//;
# ignore stuff that only consists of whitespace.
return if $current =~ m/^\W*$/;
# remove trailing empty lines
$current =~ s/(.*)\n+$/$1/g;
# print the code
$documentation->code($current, 'perl', $currentline);
}
=head2 Handler function to print and format PerlPod code
Parameters:
$current : the code
=cut
sub pod_handler {
our $documentation;
my $current = shift;
my $currentline = shift;
set_current_line($currentline);
$documentation->code($current, 'pod', $currentline);
}
=head2 Handler function to print and format comments
Parameters:
$current : the code
=cut
sub comment_handler {
our $documentation;
my $current = encode_entities(shift);
my $currentline = shift;
set_current_line($currentline);
## here we process special markup comments.
if ($current =~ m/^\s*hide\s+source/) {
$doc_options{hide_source} = 1;
} elsif ($current =~ m/^\s*show\s+source/) {
$doc_options{hide_source} = 0;
} else {
$current =~ s/\n/ /g;
$current = $documentation->b('## ') . $documentation->tt(
$documentation->x($current) );
$documentation->t($current);
}
}
=head2 get the line anchor closest to the given line
Parameters:
$lineno : the line number
Returns:
An anchor that is close to that line number.
=cut
sub get_closest_line_anchor {
my $lineno = shift;
our @line_index;
my $closest_line_dist = -1;
my $closest_line_anchor = "#";
foreach (@line_index) {
my $line_dist = abs( $lineno - $_->[0] );
my $anchor = $_->[1];
if ( $closest_line_dist < 0
|| $line_dist < $closest_line_dist )
{
$closest_line_dist = $line_dist;
$closest_line_anchor = "#" . $anchor;
if ( $line_dist == 0 ) {
last;
}
}
}
return $closest_line_anchor;
}
=head2 Function to add location info to index items.
Parameters:
$item : an index tree item
Returns:
A string with a formatted, hyperlinked item.
=cut
sub index_item_info {
my $item = $_->[0];
my $closest_line_anchor = get_closest_line_anchor( $item->{'location'} || 0 );
my $options = $index_options{ $item->{'type'} };
$options = "" if !defined($options);
our $htmlfilename;
my $link = $htmlfilename . $closest_line_anchor;
$item->{anchor} = $closest_line_anchor;
$item->{options} = $options;
$item->{link} = $link;
return $item;
}
=head2 Function to create line anchors.
Parameters:
$line : the current line
=cut
sub set_current_line {
our $documentation;
my $line = shift;
our @line_index;
$documentation->a("line_$line");
push @line_index, [ $line, "line_$line" ];
}
__END__
=head1 Tool usage
=head2 Commenting guidelines
The documenter recognizes standard Perl comments, POD comments, and some
extra markup.
Here is a list of the extra rules that apply.
=over
=item *
Double comment lines: Code lines starting with ## will be added to the outline and separate
code blocks.
=item *
Function parameter descriptions: before sub's or Moose method's, pod comments may be
specified as follows:
Parameters:
$parameter1 : what $parameter1 does
$parameter2 : what $parameter2 does
...
Returns:
What is returned.
Of course, you could also be more verbose.
=back
=head2 Command line usage
Code Documenter options:
documenter.pl [options] <filename>
Where [options] can be
--outputdirectory <dirname> : set an output directory for the
generated HTML files.
Default value: "./"
--sourcedirectory <dirname> : set an source directory to copy
styles, images, etc. from
This directory will default to the
location of documenter.pl.
--format <html/md> : specify the output format
--index : make an index file, too.