prepare to fix spark distribution
[barcat.git] / reformat-podusage
1 #!/usr/bin/env perl
2 use 5.014;
3 use warnings;
4 use utf8;
5 use open qw( :std :utf8 );
6 use re '/msx';
7
8 our $VERSION = '1.00';
9
10 local $/ = undef;  # slurp
11 my $source = readline;
12 my $pod = $source;
13 $pod =~ s/^=over\K/ 25/;  # indent options list
14 $pod =~ s{
15         ^=item \h \N*\n\n \N*\n \K  # first line
16         (?: (?: ^=over .*? ^=back\n )? (?!=) \N*\n )*
17 }{\n}g;  # abbreviate options
18 $pod =~ s/[.,](?=\n)//g;  # trailing punctuation
19 $pod =~ s/^=item\ \K(?=--)/____/g;  # align long options
20 # abbreviate <variable> indicators
21 $pod =~ s/\Q>.../s>/g;
22 $pod =~ s/<(?:number|count|seconds)>/N/g;
23 $pod =~ s/<character(s?)>/\Uchar$1/g;
24 $pod =~ s/\Q | /|/g;
25 $pod =~ s/(?<!\w)<([a-z]+)>/\U$1/g;  # uppercase
26
27 require Pod::Usage;
28 my $parser = Pod::Usage->new(USAGE_OPTIONS => {
29         -indent => 2, -width => 78,
30 });
31 $parser->select('SYNOPSIS', 'OPTIONS');
32 $parser->output_string(\my $usage);
33 $parser->parse_string_document($pod);
34
35 $usage =~ s/\n(?=\n\h)//msg;  # strip space between items
36 $usage =~ s/^\ \ \K____/    /g;  # nbsp substitute
37
38 if (open my $logo, '<', 'mascot.txt') {
39         # append logo lines to top usage lines
40         my @ll = split /\n/, readline $logo;
41         my @ul = split /\n/, $usage, @ll + 1;
42         # centered in empty space on the second (longest) line
43         my $pad = (78 - 1 + length($ul[1]) - length($ll[0])) >> 1;
44         $ul[$_] .= (' ' x ($pad - length($ul[$_]))) . $ll[$_] for 0..$#ll;
45         $usage = join "\n", @ul;
46 }
47
48 if ($ARGV eq '-') {
49         # custom formatted minimal usage text from pod document
50         print $usage;
51 }
52 elsif (open my $rewrite, '>', $ARGV) {
53         # replace perl code between program end and pod start
54         $source =~ s/^__END__\n \K .*? (?=^=)/$usage/;
55         print {$rewrite} $source;
56 }