blib/lib/Getopt/Auto/Long/Usage.pm

filter: Statementstmt 18.0% 18 / 100 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 31 MC/DCmcdc 0.0% 0 / 16 Subroutinesub 45.4% 5 / 11 Podpod 100% 3 / 3 totaltotal 13.6% 26 / 191 CC 33 SCAR 50.7
CC
33
Cov
11%
getoptlong2usage
342.0
opts2bash
56.0
bashgetopt
42.0
CRAP 159.7
↑ Summary
1 #!/usr/bin/env -S perl -CSDA
2  
3 # Copyright 2021 Alin Mr. <almr.oss@outlook.com>. Licensed under the MIT license (https://opensource.org/licenses/MIT).
4  
5 package Getopt::Auto::Long::Usage;
6 1 ▶use v5.28.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use strict; use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 =head1 NAME
12  
13 C<Getopt::Auto::Long::Usage> - generate usage strings from Getopt::Long specs
14  
15 =head1 VERSION
16  
17 Version 0.03
18  
19 =cut
20  
21 1 our $VERSION = '0.03';
22  
23 =head1 SYNOPSIS
24  
25 This is a pure perl module that generates simple usage / help messages by parsing L<Getopt::Long> argument specs (and optionally using provided descriptions).
26  
27 print getoptlong2usage( Getopt_Long => \@conf [, ...] )
28  
29 =head1 DESCRIPTION
30  
31 C<Getopt::Auto::Long::Usage> strives to be compatible with L<Getopt::LongUsage>. In particular, it does not require supplementing existing arglist specs with additional data (e.g. descriptions are optional). However, the goal is to provide maximum maintainability with the least amount of code, not to achieve complete L<Getopt::Long> coverage. So, there are some differences:
32  
33 =over 4
34  
35 =item * the generated usage clearly distinguishes boolean flags from arguments requiring an option, and prints type information for the latter. For negatable boolean options (C<longopt|s!>), it will print the corresponding C<--no-longopt> flag (but not C<--no-s>).
36  
37 =item * there are no dependencies; the main function can be copied directly into your source code, if necessary
38  
39 =item * it does not attempt to parse C<GetOptions()> abbreviated / case-insensitive options, and in fact recommends that you disable those when using C<Getopt::Long> for maintainability and predictability. One shortopt + one (or several) longopts, explicitly specified, will avoid nasty surprises (plus, suppose you decide to rewrite the code in some other language...)
40  
41 =back
42  
43 The following example should print the generated help message either to stdout, if requested (C<--help>) or to stderr, if argument parsing fails.
44  
45 use Getopt::Auto::Long::Usage;
46 use Getopt::Long;
47 my @getoptargs = qw{ help
48 delim:s
49 eval|e!
50 };
51 my %_O_; my @getoptconf = (\%_O_, @getoptargs);
52  
53 sub usage {
54 my ($rc) = @_;
55 my @dsc = ( delim => 'instead of newline' );
56 print getoptlong2usage(
57 Getopt_Long => \@getoptconf, # all others optional
58 cli_use => "Arguments: [OPTION]...\nOptions:";
59 footer => "No other arguments may be supplied"
60 descriptions => \@dsc
61 );
62 exit $rc if defined( $rc );
63 }
64  
65 Getopt::Long::Configure( qw(
66 no_ignore_case no_auto_abbrev no_getopt_compat
67 gnu_compat bundling
68 ));
69 unless( GetOptions( @getoptconf ) ) {
70 local *STDOUT = *STDERR; usage 1;
71 }
72 usage 0 if( $_O_{ help } );
73  
74 =head1 EXPORT
75  
76 =over 4
77  
78 =item * C<getoptlong2usage>
79  
80 =item * C<opts2bash> (import explicitly)
81  
82 =item * C<bashgetopt> (import explicitly; experimental -- see code)
83  
84 =back
85  
86 =cut
87  
88 1 ▶use Exporter qw( import );
Subroutine BEGIN: called CC=1 SCAR=0.0
89 1 our @EXPORT = qw( getoptlong2usage );
90 1 our @EXPORT_OK = qw( opts2bash bashgetopt );
91  
92 =head1 FUNCTIONS
93  
94 =head2 getoptlong2usage
95  
96 $usage = getoptlong2usage( Getopt_Long => \@getoptconf [,
97 descriptions => \@dsc, # this & all others: optional
98 cli_use => '',
99 footer => '',
100 colon => ': ',
101 indent => undef,
102 pfx => '' ] )
103  
104 C<@getoptconf> is an arrayref containing all the arguments you would supply to C<GetOptions()>, including the initial hashref in which C<GetOptions()> stores results (and which is ignored). It's easiest to define C<@getoptconf> separately and reuse it for both calls. See L</"DESCRIPTION"> for an example.
105  
106 All other arguments are optional and shown with their defaults. I<colon> separates flags from descriptions. I<pfx> is an arbitrary string (like C<'* '>). I<indent> sets I<pfx> to a number of spaces (don't use both). I<cli_use> goes at the top, I<footer> at the bottom, and both will have a newline appended if they don't end with one.
107  
108 =cut
109  
110 0 ▶sub getoptlong2usage {
Subroutine getoptlong2usage: not called CC=18 SCAR=58.3
Pod documented
111 0 ▶ my %_O_ = @_; $_O_{ descriptions } //= [];
Condition0%0/2
$_O_{"descriptions"} //= []
l!l
00
MC/DC0%0/1
$_O_{"descriptions"} //= []
$_O_{"descriptions"}
Truth table0%0/2
A
A= $_O_{"descriptions"}
Aresult
11
00
112 0 ▶ $_O_{ $_ } //= '' for qw{ pfx cli_use footer };
Condition0%0/2
$_O_{$_} //= ""
l!l
00
MC/DC0%0/1
$_O_{$_} //= ""
$_O_{$_}
Truth table0%0/2
A
A= $_O_{$_}
Aresult
11
00
113 0 ▶ $_O_{ colon } //= ': ';
Condition0%0/2
$_O_{"colon"} //= ": "
l!l
00
MC/DC0%0/1
$_O_{"colon"} //= ": "
$_O_{"colon"}
Truth table0%0/2
A
A= $_O_{"colon"}
Aresult
11
00
114 0 my ($conf, $pfx ) = @_O_{ qw{ Getopt_Long pfx }};
115 0 my %dsc = @{ $_O_{ descriptions } };
116  
117 0 ▶ my $opt2dash = sub { length $_ == 1 ? "-$_" : "--$_"; };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
length $_ == 1 ? : 0 0 0
118 0 ▶ my $finalnl = sub { my ($s) = @_; $s .= "\n" unless $s =~ /(^|\n)$/; $s; };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
unless $s =~ /(^|\n)$/u 0 0 0
119 # my $uniq = sub { my %cn; return grep { ! $cn{ $_ }++ } @_; }; # for auto_abbrev
120  
121 0 my $out = &$finalnl( $_O_{ cli_use } );
122 0 ▶ $pfx = (' ' x $_O_{ indent }) if defined( $_O_{ indent } );
Branch: 1 branch
BranchTrueFalseTotal
if defined $_O_{"indent"} 0 0 0
123  
124 0 my %t2p = (s => 'STR', i => 'INT', f => 'REAL', o => '[0[x|b]]INT', '+' => 'repeated...'); # TODO: :number, = t [desttype] [repeat]
125  
126 0 for( @{ $conf }[ 1..$#$conf ] ) {
127 0 my $a = $_; my $isneg = 0; my $t = ''; my $isopt = 0;
128 0 ▶ if (/(.*)!$/) { $a = $1; $isneg = 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (/(.*)!$/u) 0 0 0
129 0 ▶ if (/(.*)\+$/) { $a = $1; $t = '+'; $isopt = 1; }
Branch: 3 branches
BranchTrueFalseTotal
if (/(.*)\+$/u) { } 0 0 0
elsif (/(.*):(.*)/u) { } 0 0 0
elsif (/(.*)=(.*)/u) { } 0 0 0
130 0 elsif (/(.*):(.*)/) { $a = $1; $t = $2; $isopt = 1; }
131 0 elsif (/(.*)=(.*)/) { $a = $1; $t = $2; }
132  
133 0 $a =~ qr{ (^|\|) ( (?<long> [^|]{2,}) ($|\|) ) }x; my $along = $+{long};
134 0 my @aa = split( /\|/, $a );
135 # @aa = &$uniq( @aa, substr( $along, 0, 1 ) ) if length $along; # handle auto_abbrev
136 0 $out .= $pfx . join( ' | ', map( &$opt2dash, @aa ) );
137 0 ▶ my $d = ''; $d = (length $along and $dsc{ $along }) ? "$_O_{ colon }$dsc{ $along }" : '';
Branch: 1 branch
BranchTrueFalseTotal
length $along && $dsc{$along} ? : 0 0 0
Condition0%0/3
length $along and $dsc{$along}
!ll&&!rl&&r
000
MC/DC0%0/2
length $along and $dsc{$along}
length $along $dsc{$along}
Truth table0%0/3
A and B
A= length $alongB= $dsc{$along}
ABresult
0X0
100
111
138 0 ▶ if( length $t ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $t) { } 0 0 0
139 0 ▶ $t = $t2p{ $t } // "ARG:$t"; $t = "[$t]" if $isopt;
Branch: 1 branch
BranchTrueFalseTotal
if $isopt 0 0 0
Condition0%0/2
$t2p{$t} // "ARG:$t"
l!l
00
MC/DC0%0/1
$t2p{$t} // "ARG:$t"
$t2p{$t}
Truth table0%0/2
A
A= $t2p{$t}
Aresult
11
00
140 0 $out .= " $t$d";
141 } else {
142 0 $out .= $d;
143 0 ▶ if( $isneg ) { $out .= "\n$pfx--no-" . $along if length $along; }
Branch: 2 branches
BranchTrueFalseTotal
if ($isneg) 0 0 0
if length $along 0 0 0
144 }
145 0 $out .= "\n";
146 }
147 0 return $out . &$finalnl( $_O_{ footer } );
148 }
149  
150 =head2 opts2bash
151  
152 opts2bash( opts => {}, ARGV => [],
153 assoc => 0,
154 name => q(_O_),
155 bash => q/bash/,
156 underline => q/_/,
157 uc => 0
158 )
159  
160 Outputs a string that can be eval'd in bash to set bash variables to the corresponding values in perl. Bash variables are either prefixed by I<name>, or I<name> can be an associative array (I<assoc> = 1). Calls C<system('bash' ...)> underneath to quote perl values (I<bash> can override the interpreter and can contain flags, e.g. 'C<bash44 -x>').
161  
162 This function can export, in Bash format, parameters (including positional ones: I<ARGV>) parsed by perl. In fact, C<bashgetopt()> uses it just for that.
163  
164 =cut
165  
166 0 ▶sub opts2bash {
Subroutine opts2bash: not called CC=7 SCAR=40.3
Pod documented
167 0 my %_O_ = @_;
168 0 ▶ $_O_{ name } //= '_O_'; $_O_{ underline } //= '_'; $_O_{ opts } //= {}; $_O_{ ARGV } //= []; $_O_{ bash } //= '/bin/bash';
Condition0%0/10
$_O_{"name"} //= "_O_"
l!l
00
$_O_{"underline"} //= "_"
l!l
00
$_O_{"opts"} //= {}
l!l
00
$_O_{"ARGV"} //= []
l!l
00
$_O_{"bash"} //= "/bin/bash"
l!l
00
MC/DC0%0/1
$_O_{"name"} //= "_O_"
$_O_{"name"}
MC/DC0%0/1
$_O_{"underline"} //= "_"
$_O_{"underline"}
MC/DC0%0/1
$_O_{"opts"} //= {}
$_O_{"opts"}
MC/DC0%0/1
$_O_{"ARGV"} //= []
$_O_{"ARGV"}
MC/DC0%0/1
$_O_{"bash"} //= "/bin/bash"
$_O_{"bash"}
Truth table0%0/2
A
A= $_O_{"name"}
Aresult
11
00
Truth table0%0/2
A
A= $_O_{"underline"}
Aresult
11
00
Truth table0%0/2
A
A= $_O_{"opts"}
Aresult
11
00
Truth table0%0/2
A
A= $_O_{"ARGV"}
Aresult
11
00
Truth table0%0/2
A
A= $_O_{"bash"}
Aresult
11
00
169 0 my @bash = split / /, $_O_{ bash };
170 0 my %opts = %{ $_O_{ opts } };
171 0 ▶ my $xlatek = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
172 0 my ($k) = @_;
173 0 ▶ $k =~ s/-/$_O_{underline}/g unless $_O_{ assoc };
Branch: 1 branch
BranchTrueFalseTotal
unless $_O_{"assoc"} 0 0 0
174 0 ▶ $k = uc $k if $_O_{ uc };
Branch: 1 branch
BranchTrueFalseTotal
if $_O_{"uc"} 0 0 0
175 0 $k
176 0 };
177 0 my @kvkv = map { (&$xlatek( $_ ), $opts{ $_ }) } keys %opts;
178 0 my $cmd=q{$1};
179 0 ▶ $cmd = "[$cmd]" if $_O_{ assoc };
Branch: 1 branch
BranchTrueFalseTotal
if $_O_{"assoc"} 0 0 0
180 0 $cmd = q{
181 v=$1; shift
182 while test $# -gt 0; do
183 test "$1" != -- || { shift; break; }
184 printf '%s%s=%s\n' "$v" "} . qq{$cmd} . q{" "${2@Q}"; shift 2
185 done
186 printf 'set -- %s\n' "${*@Q}"; echo
187 };
188 0 system( @bash, '-euc', $cmd, 'bash', $_O_{ name }, @kvkv, '--', @{ $_O_{ ARGV }});
189 }
190  
191 =head2 bashgetopt
192  
193 bashgetopt( argspec => '',
194 descriptions => '',
195 cli_use => "Arguments: [OPTION]...\nOptions:\n",
196 footer => '',
197 assoc => 0
198 )
199  
200 Generates a bash stub script that imports C<Getopt::Long> and this module. The stub script contains a bash function C<__perl_parse_args> (not invoked by default) that call perl to parse its arguments according to the provided argspec. You can use the generated output as scaffolding, or C<eval> it in another bash script. Sample usage:
201  
202 perl -wE >x.sh '
203 use Getopt::Auto::Long::Usage qw( bashgetopt );
204 print bashgetopt( argspec => q(name|n=s help|h) )'
205 # edit x.sh, uncomment lines
206 chmod +x x.sh; x.sh --help
207 x.sh --name 'My name' arg1 arg2
208  
209 =cut
210  
211 0 ▶sub bashgetopt {
Subroutine bashgetopt: not called CC=6 SCAR=37.4
Pod documented
212 0 ▶ my %_O_ = @_; $_O_{ argspec } //= 'help|h'; $_O_{ footer } //= ''; $_O_{ descriptions } //= [];
Condition0%0/6
$_O_{"argspec"} //= "help|h"
l!l
00
$_O_{"footer"} //= ""
l!l
00
$_O_{"descriptions"} //= []
l!l
00
MC/DC0%0/1
$_O_{"argspec"} //= "help|h"
$_O_{"argspec"}
MC/DC0%0/1
$_O_{"footer"} //= ""
$_O_{"footer"}
MC/DC0%0/1
$_O_{"descriptions"} //= []
$_O_{"descriptions"}
Truth table0%0/2
A
A= $_O_{"argspec"}
Aresult
11
00
Truth table0%0/2
A
A= $_O_{"footer"}
Aresult
11
00
Truth table0%0/2
A
A= $_O_{"descriptions"}
Aresult
11
00
213 0 ▶ $_O_{ cli_use } //= qq{Arguments: [OPTION]...\nOptions:\n};
Condition0%0/2
$_O_{"cli_use"} //= "Arguments: [OPTION]...\nOptions:\n"
l!l
00
MC/DC0%0/1
$_O_{"cli_use"} //= "Arguments: [OPTION]...\nOptions:\n"
$_O_{"cli_use"}
Truth table0%0/2
A
A= $_O_{"cli_use"}
Aresult
11
00
214 0 ▶ $_O_{ assoc } //= 0;
Condition0%0/2
$_O_{"assoc"} //= 0
l!l
00
MC/DC0%0/1
$_O_{"assoc"} //= 0
$_O_{"assoc"}
Truth table0%0/2
A
A= $_O_{"assoc"}
Aresult
11
00
215 0 $_ = <<'EOSH';
216 #!/bin/bash
217 __perl_parse_args() {
218 local -; set -u
219 local out rc; IFS= read -r -d '' out <<'EOPL'
220 use strict; use warnings; use v5.28.0;
221 use Getopt::Long; use Getopt::Auto::Long::Usage qw( getoptlong2usage opts2bash );
222 my ($assoc, $argspec, $descriptions, $cli_use, $footer);
223 !!--parsercfg--
224 my @getoptargs = split ' ', $argspec;
225 my %_O_; my @getoptconf = (\%_O_, @getoptargs);
226 sub usage {
227 my ($rc) = @_; $rc //= 0;
228 print getoptlong2usage( Getopt_Long => \@getoptconf, cli_use => $cli_use, footer => $footer, descriptions => $descriptions );
229 exit $rc if defined( $rc );
230 }
231 Getopt::Long::Configure( qw(no_ignore_case no_auto_abbrev no_getopt_compat gnu_compat bundling));
232 unless( GetOptions( @getoptconf ) ) { usage 2; }
233 usage 1 if( $_O_{ help } );
234 opts2bash( opts => \%_O_, ARGV => \@ARGV, assoc => $assoc )
235 EOPL
236 out=$(perl 2>&1 -wE "$out" -- "$@"); rc=$?
237 #declare -p rc out
238 case $rc in
239 0) eval "$out" ;;
240 1) printf '%s\n' "$out"; exit 0 ;;
241 2) printf '%s\n' "$out" >&2; exit 1 ;;
242 esac
243 ARGV=( "$@" )
244 };
245 #declare -A _O_ # if $assoc
246 #__perl_parse_args "$@"
247 #declare -p ARGV # _O_
248 EOSH
249 0 my @dumps = qw( argspec cli_use footer descriptions assoc );
250 0 my $cfg = Data::Dumper->Dump( [@_O_{ @dumps }], \@dumps );
251 0 say STDERR Dumper( \$cfg );
252 0 s/!!--parsercfg--/$cfg/;
253 0 $_;
254 }
255  
256 1 1;
257  
258 __END__
↑ Summary