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

filter: Statementstmt 18.5% 18 / 97 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 29 MC/DCmcdc 0.0% 0 / 15 Subroutinesub 45.4% 5 / 11 Podpod 100% 3 / 3 totaltotal 14.0% 26 / 185 CC 32 SCAR 49.5
CC
32
Cov
12%
getoptlong2usage
306.0
opts2bash
56.0
bashgetopt
42.0
CRAP 140.7
↑ Summary Build »
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.02
18  
19 =cut
20  
21 1 our $VERSION = '0.02';
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 and all other optional
98 cli_use => '',
99 footer => '',
100 indent => undef,
101 pfx => '' ] )
102  
103 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.
104  
105 All other arguments are optional and shown with their defaults. 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 will have a newline appended if they don't end with one.
106  
107 =cut
108  
109 sub getoptlong2usage {
110 0 ▶ my %_O_ = @_; $_O_{ descriptions } //= [];
Subroutine getoptlong2usage: not called CC=17 SCAR=57.2
Pod documented
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
111 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
112 0 my ($conf, $pfx ) = @_O_{ qw{ Getopt_Long pfx }};
113 0 my %dsc = @{ $_O_{ descriptions } };
114  
115 0 ▶ my $opt2dash = sub { length $_ == 1 ? "-$_" : "--$_"; };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
length $_ == 1 ? : 0 0 0
116 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
117 # my $uniq = sub { my %cn; return grep { ! $cn{ $_ }++ } @_; }; # for auto_abbrev
118  
119 0 my $out = &$finalnl( $_O_{ cli_use } );
120 0 ▶ $pfx = (' ' x $_O_{ indent }) if defined( $_O_{ indent } );
Branch: 1 branch
BranchTrueFalseTotal
if defined $_O_{"indent"} 0 0 0
121  
122 0 my %t2p = (s => 'STR', i => 'INT', f => 'REAL', o => '[0[x|b]]INT', '+' => 'repeated...'); # TODO: :number, = t [desttype] [repeat]
123  
124 0 for( @{ $conf }[ 1..$#$conf ] ) {
125 0 my $a = $_; my $isneg = 0; my $t = ''; my $isopt = 0;
126 0 ▶ if (/(.*)!$/) { $a = $1; $isneg = 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (/(.*)!$/u) 0 0 0
127 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
128 0 elsif (/(.*):(.*)/) { $a = $1; $t = $2; $isopt = 1; }
129 0 elsif (/(.*)=(.*)/) { $a = $1; $t = $2; }
130  
131 0 $a =~ qr{ (^|\|) ( (?<long> [^|]{2,}) ($|\|) ) }x; my $along = $+{long};
132 0 my @aa = split( /\|/, $a );
133 # @aa = &$uniq( @aa, substr( $along, 0, 1 ) ) if length $along; # handle auto_abbrev
134 0 $out .= $pfx . join( ' | ', map( &$opt2dash, @aa ) );
135 0 ▶ if( length $t ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $t) { } 0 0 0
136 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
137 0 $out .= " $t";
138 } else {
139 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
140 }
141 0 ▶ $out .= ": $dsc{ $along }" if length $along and $dsc{ $along };
Branch: 1 branch
BranchTrueFalseTotal
if length $along and $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
142 0 $out .= "\n";
143 }
144 0 return $out . &$finalnl( $_O_{ footer } );
145 }
146  
147 =head2 opts2bash
148  
149 opts2bash( opts => {}, ARGV => [],
150 assoc => 0,
151 name => q(_O_),
152 bash => q/bash/,
153 underline => q/_/,
154 uc => 0
155 )
156  
157 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>').
158  
159 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.
160  
161 =cut
162  
163 sub opts2bash {
164 0 ▶ my %_O_ = @_;
Subroutine opts2bash: not called CC=7 SCAR=40.3
Pod documented
165 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
166 0 my @bash = split / /, $_O_{ bash };
167 0 my %opts = %{ $_O_{ opts } };
168 my $xlatek = sub {
169 0 ▶ my ($k) = @_;
Subroutine __ANON__: not called CC=3 SCAR=24.8
170 0 ▶ $k =~ s/-/$_O_{underline}/g unless $_O_{ assoc };
Branch: 1 branch
BranchTrueFalseTotal
unless $_O_{"assoc"} 0 0 0
171 0 ▶ $k = uc $k if $_O_{ uc };
Branch: 1 branch
BranchTrueFalseTotal
if $_O_{"uc"} 0 0 0
172 0 $k
173 0 };
174 0 my @kvkv = map { (&$xlatek( $_ ), $opts{ $_ }) } keys %opts;
175 0 my $cmd=q{$1};
176 0 ▶ $cmd = "[$cmd]" if $_O_{ assoc };
Branch: 1 branch
BranchTrueFalseTotal
if $_O_{"assoc"} 0 0 0
177 0 $cmd = q{
178 v=$1; shift
179 while test $# -gt 0; do
180 test "$1" != -- || { shift; break; }
181 printf '%s%s=%s\n' "$v" "} . qq{$cmd} . q{" "${2@Q}"; shift 2
182 done
183 printf 'set -- %s\n' "${*@Q}"; echo
184 };
185 0 system( @bash, '-euc', $cmd, 'bash', $_O_{ name }, @kvkv, '--', @{ $_O_{ ARGV }});
186 }
187  
188 =head2 bashgetopt
189  
190 bashgetopt( argspec => '',
191 descriptions => '',
192 cli_use => "Arguments: [OPTION]...\nOptions:\n",
193 footer => '',
194 assoc => 0
195 )
196  
197 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:
198  
199 perl -wE >x.sh '
200 use Getopt::Auto::Long::Usage qw( bashgetopt );
201 print bashgetopt( argspec => q(name|n=s help|h) )'
202 # edit x.sh, uncomment lines
203 chmod +x x.sh; x.sh --help
204 x.sh --name 'My name' arg1 arg2
205  
206 =cut
207  
208 sub bashgetopt {
209 0 ▶ my %_O_ = @_; $_O_{ argspec } //= 'help|h'; $_O_{ footer } //= ''; $_O_{ descriptions } //= [];
Subroutine bashgetopt: not called CC=6 SCAR=37.4
Pod documented
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
210 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
211 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
212 0 $_ = <<'EOSH';
213 #!/bin/bash
214 __perl_parse_args() {
215 local -; set -u
216 local out rc; IFS= read -r -d '' out <<'EOPL'
217 use strict; use warnings; use v5.28.0;
218 use Getopt::Long; use Getopt::Auto::Long::Usage qw( getoptlong2usage opts2bash );
219 my ($assoc, $argspec, $descriptions, $cli_use, $footer);
220 !!--parsercfg--
221 my @getoptargs = split ' ', $argspec;
222 my %_O_; my @getoptconf = (\%_O_, @getoptargs);
223 sub usage {
224 my ($rc) = @_; $rc //= 0;
225 print getoptlong2usage( Getopt_Long => \@getoptconf, cli_use => $cli_use, footer => $footer, descriptions => $descriptions );
226 exit $rc if defined( $rc );
227 }
228 Getopt::Long::Configure( qw(no_ignore_case no_auto_abbrev no_getopt_compat gnu_compat bundling));
229 unless( GetOptions( @getoptconf ) ) { usage 2; }
230 usage 1 if( $_O_{ help } );
231 opts2bash( opts => \%_O_, ARGV => \@ARGV, assoc => $assoc )
232 EOPL
233 out=$(perl 2>&1 -wE "$out" -- "$@"); rc=$?
234 #declare -p rc out
235 case $rc in
236 0) eval "$out" ;;
237 1) printf '%s\n' "$out"; exit 0 ;;
238 2) printf '%s\n' "$out" >&2; exit 1 ;;
239 esac
240 ARGV=( "$@" )
241 };
242 #declare -A _O_ # if $assoc
243 #__perl_parse_args "$@"
244 #declare -p ARGV # _O_
245 EOSH
246 0 my @dumps = qw( argspec cli_use footer descriptions assoc );
247 0 my $cfg = Data::Dumper->Dump( [@_O_{ @dumps }], \@dumps );
248 0 say STDERR Dumper( \$cfg );
249 0 s/!!--parsercfg--/$cfg/;
250 0 $_;
251 }
252  
253 1 1;
254  
255 __END__
↑ Summary Build »