script/optex

filter: Statementstmt 61.0% 183 / 300 Branchbran 37.5% 42 / 112 Conditioncond 53.3% 24 / 45 MC/DCmcdc 22.2% 6 / 27 Subroutinesub 80.0% 28 / 35 Podpod n/a totaltotal 54.5% 283 / 519 CC 54 SCAR 38.1
CC
54
Cov
54%
_symlink
156.0
_ls
93.7
_rc
76.4
CRAP 45.3
↑ Summary blib/lib/App/optex/util/argv.pm »
1 #!/usr/bin/env perl
2  
3 47 ▶use App::optex;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 47 my $version = $App::optex::VERSION;
5  
6  
7 =encoding utf8
8  
9 =head1 NAME
10  
11 optex - General purpose command option wrapper
12  
13 =head1 VERSION
14  
15 Version 1.07
16  
17 =head1 SYNOPSIS
18  
19 B<optex> I<command> [ B<-M>I<module> ] ...
20  
21 or I<command> -> B<optex> symlink, or
22  
23 B<optex> I<options> [ -l | -m ] ...
24  
25 --link, --ln create symlink
26 --unlink, --rm remove symlink
27 --ls list link files
28 --rc list rc files
29 --nop, -x disable option processing
30 --[no]module disable module option on arguments
31  
32 =cut
33  
34  
35 47 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 47 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
37  
38 47 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 47 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 47 ▶use open IO => ':utf8';
Subroutine BEGIN: called CC=1 SCAR=0.0
41  
42 47 ▶use Pod::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 47 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
44 47 $Data::Dumper::Sortkeys = 1;
45 47 ▶use Cwd qw(abs_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
46 47 ▶use List::Util qw(uniq max);
Subroutine BEGIN: called CC=1 SCAR=0.0
47 47 ▶use Text::ParseWords qw(shellwords);
Subroutine BEGIN: called CC=1 SCAR=0.0
48 47 ▶use IO::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
49 47 ▶use App::optex::Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
50  
51 47 binmode STDOUT, ":encoding(utf8)";
52 47 binmode STDERR, ":encoding(utf8)";
53  
54 47 our $rcloader;
55 47 ▶our $debug //= $ENV{DEBUG_OPTEX};
Condition33%1/3
our $debug //= $ENV{"DEBUG_OPTEX"}
l!l&&r!l&&!r
0047
MC/DC0%0/2
our $debug //= $ENV{"DEBUG_OPTEX"}
our $debug $ENV{"DEBUG_OPTEX"}
Truth table33%1/3
A //= B
A= our $debugB= $ENV{"DEBUG_OPTEX"}
ABresult
1X1
011
000
56 47 our $no_operation;
57 47 our $mod_opt = '-M';
58 47 our $mod_arg = 1; # Process -M option in target command
59 47 our $exit_code;
60  
61 47 ▶my $command_path = $ENV{OPTEX_INVOKED_AS} // $0;
Condition33%1/3
$ENV{"OPTEX_INVOKED_AS"} // $0
l!l&&r!l&&!r
0470
MC/DC0%0/2
$ENV{"OPTEX_INVOKED_AS"} // $0
$ENV{"OPTEX_INVOKED_AS"} $0
Truth table33%1/3
A // B
A= $ENV{"OPTEX_INVOKED_AS"}B= $0
ABresult
1X1
011
000
62 47 ▶my($cmd_dir, $cmd_name) = ($command_path =~ m{ (.*) / ([^/]+) $ }x) or die;
Branch: 1 branch
BranchTrueFalseTotal
() = $command_path =~ m[ (.*) / ([^/]+) $ ]ux or die 47 0 47
63 47 ▶my($abs_dir, $abs_name) = (abs_path($0) =~ m{ (.*) / ([^/]+) $ }x) or die;
Branch: 1 branch
BranchTrueFalseTotal
() = abs_path($0) =~ m[ (.*) / ([^/]+) $ ]ux or die 47 0 47
64 47 my $env_MODULE_PATH = sprintf '%s_MODULE_PATH', uc($abs_name);
65 47 my $env_ROOT = sprintf '%s_ROOT', uc($abs_name);
66 47 my $env_BINDIR = sprintf '%s_BINDIR', uc($abs_name);
67 47 my $env_CONFIG = sprintf '%s_CONFIG', uc($abs_name);
68  
69 47 ▶my $HOME = $ENV{HOME} or die "No \$HOME.\n";
Branch: 1 branch
BranchTrueFalseTotal
my $HOME = $ENV{"HOME"} or die "No \$HOME.\n" 47 0 47
70 47 ▶my $config_dir = $ENV{$env_ROOT} || "${HOME}/.${abs_name}.d";
Condition100%2/2
$ENV{$env_ROOT} || "$HOME/.$abs_name.d"
l!l
1730
MC/DC100%1/1
$ENV{$env_ROOT} || "$HOME/.$abs_name.d"
$ENV{$env_ROOT}
Truth table100%2/2
A
A= $ENV{$env_ROOT}
Aresult
11
00
71 47 my $module_dir = $config_dir;
72 47 ▶my $bin_dir = $ENV{$env_BINDIR} || "$config_dir/bin";
Condition50%1/2
$ENV{$env_BINDIR} || "$config_dir/bin"
l!l
047
MC/DC0%0/1
$ENV{$env_BINDIR} || "$config_dir/bin"
$ENV{$env_BINDIR}
Truth table50%1/2
A
A= $ENV{$env_BINDIR}
Aresult
11
00
73 47 ▶my $config_file = $ENV{$env_CONFIG} || "$config_dir/config.toml";
Condition50%1/2
$ENV{$env_CONFIG} || "$config_dir/config.toml"
l!l
047
MC/DC0%0/1
$ENV{$env_CONFIG} || "$config_dir/config.toml"
$ENV{$env_CONFIG}
Truth table50%1/2
A
A= $ENV{$env_CONFIG}
Aresult
11
00
74  
75 ##
76 ## decode @ARGV
77 ##
78 47 ▶@ARGV = map { utf8::is_utf8($_) ? $_ : decode('utf8', $_) } @ARGV;
Branch: 1 branch
BranchTrueFalseTotal
utf8::is_utf8($_) ? : 0 144 144
79  
80 ##
81 ## load config file
82 ##
83 47 my $config = App::optex::Config::load_config($config_file);
84 46 ▶my $alias = $config->{alias} //= {};
Condition100%2/2
$config->{"alias"} //= {}
l!l
1630
MC/DC100%1/1
$config->{"alias"} //= {}
$config->{"alias"}
Truth table100%2/2
A
A= $config->{"alias"}
Aresult
11
00
85 46 ▶my $nomodule = $config->{"no-module"} //= [];
Condition100%2/2
$config->{"no-module"} //= []
l!l
937
MC/DC100%1/1
$config->{"no-module"} //= []
$config->{"no-module"}
Truth table100%2/2
A
A= $config->{"no-module"}
Aresult
11
00
86 46 my %nomodule = do {
87 46 ▶ if (ref $nomodule eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $nomodule eq 'ARRAY') { } 46 0 46
elsif (ref $nomodule eq 'HASH') { } 0 0 0
88 46 map { $_ => 1 } @{$nomodule};
89 }
90 elsif (ref $nomodule eq 'HASH') {
91 0 %{$nomodule};
92 }
93 else {
94 0 ($nomodule => 1);
95 }
96 };
97  
98 ##
99 ## setup Getopt::EX
100 ##
101 46 require Getopt::EX::Loader;
102 46 $rcloader = Getopt::EX::Loader->new(
103 BASECLASS => [ '', 'App::optex', 'Getopt::EX' ],
104 IGNORE_NO_MODULE => 1,
105 );
106  
107 46 load_rc("$config_dir/default.rc");
108  
109 ##
110 ## setup module search path
111 ##
112 my @private_mod_path = (
113 46 do {
114 46 ▶ if (my $mod_path = $ENV{$env_MODULE_PATH}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $mod_path = $ENV{$env_MODULE_PATH}) { } 0 46 46
115 0 split /:/, $mod_path;
116 } else {
117 46 ();
118 }
119 },
120 $module_dir,
121 );
122  
123 46 prepend_path(@private_mod_path);
124  
125 ##
126 ## get target command name
127 ##
128 46 my $target_name = do {
129 46 ▶ if ($cmd_name ne $abs_name) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd_name ne $abs_name) { } 9 37 46
130 9 $cmd_name;
131 } else {
132 37 self_option(\@ARGV);
133 28 ▶ if (@ARGV) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ARGV) { } 27 1 28
134 27 shift @ARGV;
135 } else {
136 1 usage();
137 0 exit 1;
138 }
139 }
140 };
141  
142 ##
143 ## alias
144 ##
145 36 my $aliased_name;
146 36 ▶if (my $alias = $alias->{$target_name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $alias = $alias->{$target_name}) 9 27 36
147 9 my($name, @opts) = do {
148 9 ▶ if (ref $alias eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $alias eq 'ARRAY') { } 0 9 9
149 0 @{$alias};
150 } else {
151 9 shellwords $alias;
152 }
153 };
154 9 ▶ if ($name ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name ne "") 9 0 9
155 9 $aliased_name = $name;
156 9 unshift @ARGV, @opts;
157 }
158 }
159  
160 36 ▶if ($nomodule{$target_name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nomodule{$target_name}) 3 33 36
161 3 $mod_arg = 0;
162 }
163  
164 ##
165 ## prepare command specific module path
166 ##
167 my @command_mod_path =
168 36 grep { -d $_ } map { "$_/$target_name" } @private_mod_path;
169  
170 36 prepend_path(@command_mod_path, @private_mod_path);
171  
172 36 ▶if ($mod_arg and @ARGV > 0 and $ARGV[0] eq $mod_opt) {
Branch: 1 branch
BranchTrueFalseTotal
if ($main::mod_arg and @ARGV > 0 and $ARGV[0] eq $main::mod_opt) 0 36 36
Condition83%5/6
$main::mod_arg and @ARGV > 0 and $ARGV[0] eq $main::mod_opt
!ll&&!rl&&r
17190
$main::mod_arg and @ARGV > 0
!ll&&!rl&&r
31419
MC/DC0%0/3
$main::mod_arg and @ARGV > 0 and $ARGV[0] eq $main::mod_opt
$main::mod_arg @ARGV > 0 $ARGV[0] eq $main::mod_opt
Truth table75%3/4
A and B and C
A= $main::mod_argB= @ARGV > 0C= $ARGV[0] eq $main::mod_opt
ABCresult
0XX0
10X0
1100
1111
173 0 show_modules();
174 0 exit;
175 }
176  
177 ##
178 ## load command specific rc file
179 ##
180 36 ▶unless ($no_operation) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($main::no_operation) 36 0 36
181 36 load_rc("$config_dir/$target_name.rc");
182 36 $rcloader->configure(PARSE_MODULE_OPT => $mod_arg);
183 36 $rcloader->deal_with(\@ARGV);
184 }
185  
186 36 ▶my $exec_name = $aliased_name || search_path($target_name);
Condition100%3/3
$aliased_name || search_path($target_name)
l!l&&r!l&&!r
9261
MC/DC100%2/2
$aliased_name || search_path($target_name)
$aliased_name search_path($target_name)
Truth table100%3/3
A || B
A= $aliased_nameB= search_path($target_name)
ABresult
1X1
011
000
187 36 ▶unless (defined $exec_name) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $exec_name) 1 35 36
188 1 warn "$abs_name: $target_name: command not found\n";
189 1 exit 127;
190 }
191  
192 35 ▶warn "$abs_name: exec $exec_name @ARGV\n" if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $main::debug 1 34 35
193  
194 ##
195 ## execute target command
196 ##
197 35 my $status = system $exec_name, @ARGV;
198  
199 43 ▶END {
Subroutine END: called CC=3 SCAR=11.0
200 43 ▶ if (defined $exit_code) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $main::exit_code) { } 2 41 43
elsif (defined $status) { } 33 8 41
201 2 $? = $exit_code;
202 } elsif (defined $status) {
203 33 $? = $status >> 8;
204 }
205 43 close STDERR;
206 43 close STDOUT;
207 }
208  
209 ######################################################################
210  
211 82 ▶sub load_rc {
Subroutine load_rc: called CC=2 SCAR=6.9
212 82 my $rc = shift;
213 82 $rcloader->load(FILE => $rc);
214 82 ▶ warn "$abs_name: load $rc\n" if $debug;
Branch: 1 branch
BranchTrueFalseTotal
if $main::debug 1 81 82
215 }
216  
217 27 ▶sub search_path {
Subroutine search_path: called CC=10 SCAR=24.1
218 27 my $new = shift;
219 27 ▶ return $new if $new =~ m{/} && -x $new;
Branch: 1 branch
BranchTrueFalseTotal
if $new =~ m[/]u and -x $new 0 27 27
Condition33%1/3
$new =~ m[/]u and -x $new
!ll&&!rl&&r
2700
MC/DC0%0/2
$new =~ m[/]u and -x $new
$new =~ m[/]u -x $new
Truth table33%1/3
A and B
A= $new =~ m[/]uB= -x $new
ABresult
0X0
100
111
220  
221 # Scan PATH and return the first executable that is not the running
222 # optex binary itself (avoid re-entering the wrapper and looping).
223 27 my $self_abs = abs_path("$abs_dir/$abs_name");
224  
225 27 ▶ for my $path (split /:+/, $ENV{PATH} // '') {
Condition50%1/2
$ENV{"PATH"} // ""
l!l
270
MC/DC0%0/1
$ENV{"PATH"} // ""
$ENV{"PATH"}
Truth table50%1/2
A
A= $ENV{"PATH"}
Aresult
11
00
226 63 my $candidate = "$path/$new";
227 63 ▶ -x $candidate or next;
Branch: 1 branch
BranchTrueFalseTotal
-x $candidate or next 32 31 63
228 32 ▶ next if $path eq $cmd_dir and $new eq $cmd_name;
Branch: 1 branch
BranchTrueFalseTotal
if $path eq $cmd_dir and $new eq $cmd_name 5 27 32
Condition66%2/3
$path eq $cmd_dir and $new eq $cmd_name
!ll&&!rl&&r
2705
MC/DC50%1/2
$path eq $cmd_dir and $new eq $cmd_name
$path eq $cmd_dir $new eq $cmd_name
Truth table66%2/3
A and B
A= $path eq $cmd_dirB= $new eq $cmd_name
ABresult
0X0
100
111
229  
230 27 ▶ my $cand_abs = eval { abs_path($candidate) } || $candidate;
Condition33%1/3
eval { do { abs_path($candidate) } } || $candidate
l!l&&r!l&&!r
2700
MC/DC0%0/2
eval { do { abs_path($candidate) } } || $candidate
eval { do { abs_path($candidate) } } $candidate
Truth table33%1/3
A || B
A= eval { do { abs_path($candidate) } }B= $candidate
ABresult
1X1
011
000
231 27 ▶ next if $cand_abs eq $self_abs;
Branch: 1 branch
BranchTrueFalseTotal
if $cand_abs eq $self_abs 1 26 27
232 26 return $candidate;
233 }
234  
235 1 return;
236 }
237  
238 37 ▶sub self_option {
Subroutine self_option: called CC=9 SCAR=25.3
239 37 my $argv = shift;
240  
241 37 local $rcloader = Getopt::EX::Loader->new(
242 BASECLASS => [ '', 'App::optex', 'Getopt::EX' ],
243 );
244 37 $rcloader->load(FILE => "$config_dir/$abs_name.rc");
245 37 $rcloader->deal_with($argv);
246  
247 47 ▶ use Getopt::Long qw(GetOptionsFromArray);
Subroutine BEGIN: called CC=1 SCAR=0.0
248 28 Getopt::Long::Configure(qw"bundling require_order");
249 47 ▶ use Getopt::EX::Hashed qw(has); {
Subroutine BEGIN: called CC=1 SCAR=0.0
250 28 Getopt::EX::Hashed->configure(DEFAULT => [ is => 'ro' ]);
251 0 ▶ has debug => " ! d " , action => sub { $debug = $_[1] };
Subroutine __ANON__: not called CC=1 SCAR=1.2
252 28 has version => " v " ;
253 28 has man => " h " ;
254 28 has link => " ln " ;
255 28 has unlink => " rm " ;
256 28 has force => " f " ;
257 28 has ls => " " ;
258 28 has rc => " " ;
259 28 has long => " l " ;
260 28 has path => " p " ;
261 28 has cat => " m " ;
262 28 has M => " " ;
263 0 ▶ has module => " ! " , action => sub { $mod_arg = $_[1] };
Subroutine __ANON__: not called CC=1 SCAR=1.2
264 0 ▶ has nop => " ! x " , action => sub { $no_operation = $_[1] };
Subroutine __ANON__: not called CC=1 SCAR=1.2
265 28 ▶ has exit => " =i " , action => sub { $exit_code = $_[1] } ;
Subroutine __ANON__: called CC=1 SCAR=0.0
266 47 ▶ }; no Getopt::EX::Hashed;
Subroutine BEGIN: called CC=1 SCAR=0.0
267 28 my $opt = Getopt::EX::Hashed->new->reset();
268 28 ▶ GetOptionsFromArray($argv, $opt->optspec, $rcloader->builtins) or usage();
Branch: 1 branch
BranchTrueFalseTotal
&GetOptionsFromArray($argv, $opt->optspec, $rcloader->builtins) or usage() 28 0 28
269  
270 28 ▶ if ($opt->man) {
Branch: 6 branches
BranchTrueFalseTotal
if ($opt->man) { } 0 28 28
elsif ($opt->version) { } 0 28 28
elsif ($opt->link or $opt->unlink) { } 0 28 28
elsif ($opt->ls) { } 0 28 28
elsif ($opt->rc) { } 0 28 28
elsif ($opt->M) { } 0 28 28
271 0 exec "perldoc $abs_name";
272 0 die "exec: $!";
273 }
274 elsif ($opt->version) {
275 0 print $version, "\n";
276 0 exit;
277 }
278 ▶ elsif ($opt->link || $opt->unlink) {
Condition33%1/3
$opt->link or $opt->unlink
l!l&&r!l&&!r
0028
MC/DC0%0/2
$opt->link or $opt->unlink
$opt->link $opt->unlink
Truth table33%1/3
A or B
A= $opt->linkB= $opt->unlink
ABresult
1X1
011
000
279 0 _symlink($argv, $opt);
280 0 exit 0;
281 }
282 elsif ($opt->ls) {
283 0 _ls($argv, $opt);
284 0 exit 0;
285 }
286 elsif ($opt->rc) {
287 0 _rc($argv, $opt);
288 0 exit 0;
289 }
290 elsif ($opt->M) {
291 0 show_modules();
292 0 exit 0;
293 }
294  
295 28 return;
296 }
297  
298 0 ▶sub _symlink {
Subroutine _symlink: not called CC=12 SCAR=50.5
299 0 my($argv, $op) = @_;
300 0 ▶ -d $bin_dir or die "Directory $bin_dir does not exist.\n";
Branch: 1 branch
BranchTrueFalseTotal
-d $bin_dir or die "Directory $bin_dir does not exist.\n" 0 0 0
301  
302 0 ▶ my $script_path = $ENV{OPTEX_SCRIPT_PATH} // $0;
Condition0%0/3
$ENV{"OPTEX_SCRIPT_PATH"} // $0
l!l&&r!l&&!r
000
MC/DC0%0/2
$ENV{"OPTEX_SCRIPT_PATH"} // $0
$ENV{"OPTEX_SCRIPT_PATH"} $0
Truth table0%0/3
A // B
A= $ENV{"OPTEX_SCRIPT_PATH"}B= $0
ABresult
1X1
011
000
303 0 my @target = @$argv;
304 0 for my $target (@target) {
305 0 my $link = "$bin_dir/$target";
306 0 ▶ if ($op->{link}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($op->{'link'}) { } 0 0 0
elsif ($op->{'unlink'}) { } 0 0 0
307 0 ▶ -f $link and do { warn "$link already exists.\n"; next };
Branch: 1 branch
BranchTrueFalseTotal
-f $link and do { warn "$link already exists.\n"; next } 0 0 0
308 0 ▶ symlink $script_path, $link or die "$link: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
symlink $script_path, $link or die "${link}: $!\n" 0 0 0
309 0 print "$link -> $script_path\n";
310 }
311 elsif ($op->{unlink}) {
312 0 ▶ -l $link or do { warn "$link is not symlink\n"; next };
Branch: 1 branch
BranchTrueFalseTotal
-l $link or do { warn "$link is not symlink\n"; next } 0 0 0
313 0 ▶ if ((my $name = readlink $link) ne $script_path ) {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $name = readlink $link) ne $script_path) 0 0 0
314 0 ▶ if (not $op->{force}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($op->{"force"}) 0 0 0
315 0 warn
316 "$link has unexpected link: -> $name\n" .
317 "Use -f option to force unlink.\n" ;
318 0 next;
319 }
320 }
321 0 ▶ unlink $link or die "$link: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
unlink $link or die "${link}: $!\n" 0 0 0
322 0 print "$link removed.\n";
323 }
324 }
325 }
326  
327 47 ▶use Text::VisualWidth::PP 'vwidth';
Subroutine BEGIN: called CC=1 SCAR=0.0
328  
329 0 ▶sub _ls {
Subroutine _ls: not called CC=10 SCAR=45.4
330 0 my($argv, $op) = @_;
331  
332 47 ▶ use IO::Dir;
Subroutine BEGIN: called CC=1 SCAR=0.0
333 0 ▶ my $dir = IO::Dir->new($bin_dir) or die "$bin_dir: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
my $dir = "IO::Dir"->new($bin_dir) or die "${bin_dir}: $!\n" 0 0 0
334 0 my @dirent = do {
335 0 sort { $a cmp $b }
336 0 map { decode 'utf8', $_ }
337 0 grep { not /^\./ }
338 $dir->read;
339 };
340 0 $dir->close;
341  
342 0 my @aliases = sort keys %{$alias};
343  
344 0 my $max = max map { vwidth $_ } @dirent, @aliases;
345  
346 0 print "[link]\n";
347 0 for my $ent (@dirent) {
348 0 my $path = "$bin_dir/$ent";
349 0 ▶ if (-l $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (-l $path) 0 0 0
350 0 print "\t";
351 0 ▶ print $op->{path} ? $path : $ent;
Branch: 1 branch
BranchTrueFalseTotal
$op->{'path'} ? : 0 0 0
352 0 ▶ if ($op->{long}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op->{"long"}) 0 0 0
353 0 print ' ' x ($max - vwidth $ent);
354 0 my $target = do {
355 # if (my $val = $alias->{$ent}) {
356 # ref($val) eq 'ARRAY' ? join(' ', @$val) : $val;
357 # } else {
358 0 readlink $path;
359 # }
360 };
361 0 print " -> ", $target;
362 }
363 0 print "\n";
364 }
365 0 ▶ warn "$ent: not exist\n" unless -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path 0 0 0
366 }
367  
368 0 print "[alias]\n";
369 0 for my $key (@aliases) {
370 0 my $val = $alias->{$key};
371 0 ▶ my $command = ref($val) eq 'ARRAY' ? join(' ', @$val) : $val;
Branch: 1 branch
BranchTrueFalseTotal
ref $val eq 'ARRAY' ? : 0 0 0
372 0 print "\t";
373 0 print $key;
374 0 ▶ if ($op->{long}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op->{"long"}) 0 0 0
375 0 print ' ' x ($max - vwidth $key);
376 0 printf " => %s", $command;
377 }
378 0 print "\n";
379 }
380 }
381  
382 0 ▶sub _rc {
Subroutine _rc: not called CC=10 SCAR=43.4
383 0 my($argv, $op) = @_;
384 0 my @command = @$argv;
385 0 my @rc = map { s/(?<!\.rc)$/.rc/r } @command;
386 0 my %rc = map { ($_ => 1) } @rc;
387 47 ▶ use IO::Dir;
Subroutine BEGIN: called CC=1 SCAR=0.0
388 0 ▶ my $dir = IO::Dir->new($config_dir) or die "$config_dir: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
my $dir = "IO::Dir"->new($config_dir) or die "${config_dir}: $!\n" 0 0 0
389 0 my @dirent = do {
390 0 ▶ grep { %rc == 0 or $rc{$_} }
Condition0%0/3
%rc == 0 || $rc{$_}
l!l&&r!l&&!r
000
MC/DC0%0/2
%rc == 0 || $rc{$_}
%rc == 0 $rc{$_}
Truth table0%0/3
A || B
A= %rc == 0B= $rc{$_}
ABresult
1X1
011
000
391 0 ▶ grep { /\.rc$/ }
Branch: 1 branch
BranchTrueFalseTotal
@rc ? : 0 0 0
392 @rc ? @rc : sort $dir->read
393 };
394 0 $dir->close;
395  
396 0 for my $ent (@dirent) {
397 0 my $path = "$config_dir/$ent";
398 0 ▶ if ($op->{cat}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op->{'cat'}) { } 0 0 0
399 47 ▶ use IO::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
400 0 ▶ my $fh = IO::File->new($path) or do {
Branch: 1 branch
BranchTrueFalseTotal
my $fh = "IO::File"->new($path) or do { warn "${path}: $!\n"; next } 0 0 0
401 0 warn "$path: $!\n";
402 0 next;
403 };
404 0 ▶ while (<$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $fh)) 0 0 0
405 0 ▶ print "$ent:" if @dirent > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @dirent > 1 0 0 0
406 0 print;
407 }
408 0 $fh->close;
409 } else {
410 0 ▶ print $op->{long} ? $path : $ent;
Branch: 1 branch
BranchTrueFalseTotal
$op->{'long'} ? : 0 0 0
411 0 print "\n";
412 }
413 }
414 }
415  
416 ######################################################################
417  
418 1 ▶sub usage {
Subroutine usage: called CC=1 SCAR=0.0
419 1 pod2usage(-verbose => 0,
420 -message => <<" EOS" =~ s/^\s+//mgr
421 Use `perldoc $abs_name` for document.
422 Use `$abs_name [command] ${mod_opt}help` for available options.
423 EOS
424 );
425 }
426  
427 35 ▶my @ORIG_INC; BEGIN { @ORIG_INC = @INC }
Subroutine BEGIN: called CC=1 SCAR=0.0
428 35 my @mod_path;
429 82 ▶sub prepend_path {
Subroutine prepend_path: called CC=1 SCAR=0.0
430 82 @mod_path = uniq @_;
431 82 @INC = (@mod_path, @ORIG_INC);
432 }
433  
434 0 ▶sub show_modules {
Subroutine show_modules: not called CC=5 SCAR=34.0
435 my $path = @_ ? shift : [
436 @mod_path,
437 0 ▶ grep { -d } map { "$_/App/optex" } @INC,
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 0 0 0
438 ];
439 0 print "MODULES:\n";
440 0 for my $path (@$path) {
441 0 my($name) = $path =~ m:([^/]+)$:;
442 0 my @module = do {
443 # grep { not /\bdefault\.pm$/ }
444 0 glob "$path/[a-z0-9]*.pm";
445 };
446 0 ▶ next unless @module;
Branch: 1 branch
BranchTrueFalseTotal
unless @module 0 0 0
447 0 print " $path\n";
448 0 for my $mod (@module) {
449 0 printf " ${mod_opt}%s\n", $mod =~ /([^\/]*)\.pm/;
450 }
451 0 print "\n";
452 }
453 }
454  
455 =head1 DESCRIPTION
456  
457 B<optex> is a general purpose command option handling wrapper
458 utilizing Perl module L<Getopt::EX>. It enables user to define their
459 own option aliases for any commands on the system, and provide module
460 style extensibility.
461  
462 Target command is given as an argument:
463  
464 % optex command
465  
466 or as a symbolic linked file to B<optex>:
467  
468 command -> optex
469  
470 If the configuration file F<~/.optex.d/>I<command>F<.rc> exists, it is
471 evaluated before execution and command arguments are pre-processed
472 using it.
473  
474  
475 =head2 OPTION ALIASES
476  
477 Think of macOS's C<date> command, which does not have C<-I[TIMESPEC]>
478 option. Using B<optex>, these can be implemented by preparing
479 following setting in F<~/.optex.d/date.rc> file.
480  
481 option -I -Idate
482 option -Idate +%F
483 option -Iseconds +%FT%T%z
484 option -Iminutes +%FT%H:%M%z
485 option -Ihours +%FT%H%z
486  
487 option --iso-8601 -I
488 option --iso-8601=date -Idate
489 option --iso-8601=seconds -Iseconds
490 option --iso-8601=minutes -Iminutes
491 option --iso-8601=hours -Ihours
492  
493 Then next command will work as expected.
494  
495 % optex date -Iseconds
496  
497 If a symbolic link C<< date -> optex >> is found in command search
498 path, you can use it just same as standard command, but with
499 unsupported options.
500  
501 % date -Iseconds
502  
503 Common configuration is stored in F<~/.optex.d/default.rc> file, and
504 those rules are applied to all commands executed through B<optex>.
505  
506 Actually, C<--iso-8601> option can be defined simpler as this:
507  
508 option --iso-8601 -I$<shift>
509  
510 This works fine almost always, but fails with sole C<--iso-8601>
511 option preceding other option like this:
512  
513 % date --iso-8601 -u
514  
515 =head2 COMMAND ALIASES
516  
517 B<optex>'s command alias is no different from the alias function of
518 shell, but it is effective in that it can be executed as a command
519 from a tool or script, and can be managed collectively in a
520 configuration file.
521  
522 Command aliases can be set in the configuration file
523 (F<~/.optex.d/config.toml>) like this:
524  
525 [alias]
526 tc = "optex -Mtextconv"
527  
528 You can make symbolic link from C<tc> to C<optex> like this:
529  
530 % optex --ln tc
531  
532 And include F<$HOME/.optex.d/bin> in your C<PATH> evnironment.
533  
534 The C<textconv> module can be used to convert files given as arguments
535 to plain text. Defined in this way, Word files can be compared as
536 follows.
537  
538 % tc diff A.docx B.docx
539  
540 Alias name is used to find rc file and module directory. In the above
541 example, F<~/.optex.d/tc.rc> and F<~/.optex.d/tc/> will be referred.
542  
543 It is also possible to write shell scripts in the config file. The
544 following example implements the C-shell C<repeat> command.
545  
546 [alias]
547 repeat = [ 'bash', '-c', '''
548 while getopts 'c:i:' OPT; do
549 case $OPT in
550 c) count=$OPTARG;;
551 i) sleep=$OPTARG;;
552 esac
553 done; shift $((OPTIND - 1))
554 case $1 in
555 [0-9]*) count=$1; shift;;
556 esac
557 while ((count--)); do
558 eval "$*"
559 [ "$sleep" ] && (( count > 0 )) && sleep $sleep
560 done
561 ''', 'repeat' ]
562  
563 Read L<CONFIGURATION FILE> section.
564  
565 =head2 MACROS
566  
567 Complex string can be composed using macro C<define>. Next example is
568 an awk script to count vowels in the text, to be declared in file
569 F<~/.optex.d/awk.rc>.
570  
571 define __delete__ /[bcdfgkmnpsrtvwyz]e( |$)/
572 define __match__ /ey|y[aeiou]*|[aeiou]+/
573 define __count_vowels__ <<EOS
574 {
575 s = tolower($0);
576 gsub(__delete__, " ", s);
577 for (count=0; match(s, __match__); count++) {
578 s=substr(s, RSTART + RLENGTH);
579 }
580 print count " " $0;
581 }
582 EOS
583 option --vowels __count_vowels__
584  
585 This can be used like this:
586  
587 % awk --vowels /usr/share/dict/words
588  
589 When setting complex option, C<expand> directive is useful. C<expand>
590 works almost same as C<option>, but effective only within the file
591 scope, and not available for command line option.
592  
593 expand repository ( -name .git -o -name .svn -o -name RCS )
594 expand no_dots ! -name .*
595 expand no_version ! -name *,v
596 expand no_backup ! -name *~
597 expand no_image ! -iname *.jpg ! -iname *.jpeg \
598 ! -iname *.gif ! -iname *.png
599 expand no_archive ! -iname *.tar ! -iname *.tbz ! -iname *.tgz
600 expand no_pdf ! -iname *.pdf
601  
602 option --clean \
603 repository -prune -o \
604 -type f \
605 no_dots \
606 no_version no_backup \
607 no_image \
608 no_archive \
609 no_pdf
610  
611 % find . --clean -print
612  
613  
614 =head2 MODULES
615  
616 B<optex> also supports module extension. In the example of C<date>,
617 module file is found at F<~/.optex.d/date/> directory. If default
618 module, F<~/.optex.d/date/default.pm> exists, it is loaded
619 automatically on every execution.
620  
621 This is a normal Perl module, so package declaration and the final
622 true value is necessary. Between them, you can put any kind of Perl
623 code. For example, next program set environment variable C<LANG> to
624 C<C> before executing C<date> command.
625  
626 package default;
627 $ENV{LANG} = 'C';
628 1;
629  
630 % /bin/date
631 2017年 10月22日 日曜日 18時00分00秒 JST
632  
633 % date
634 Sun Oct 22 18:00:00 JST 2017
635  
636 Other modules are loaded using C<-M> option. Unlike other options,
637 C<-M> have to be placed at the beginning of argument list. Module
638 files in F<~/.optex.d/date/> directory are used only for C<date>
639 command. If the module is placed on F<~/.optex.d/> directory, it can
640 be used from all commands.
641  
642 If you want use C<-Mes> module, make a file F<~/.optex.d/es.pm> with
643 following content.
644  
645 package es;
646 $ENV{LANG} = 'es_ES';
647 1;
648  
649 % date -Mes
650 domingo, 22 de octubre de 2017, 18:00:00 JST
651  
652 When the specified module was not found in library path, B<optex>
653 ignores the option and stops argument processing immediately. Ignored
654 options are passed through to the target command.
655  
656 Module is also used with subroutine call. Suppose
657 F<~/.optex.d/env.pm> module look like:
658  
659 package env;
660 sub setenv {
661 while (($a, $b) = splice @_, 0, 2) {
662 $ENV{$a} = $b;
663 }
664 }
665 1;
666  
667 Then it can be used in more generic fashion. In the next example,
668 first format is easy to read, but second one is more easy to type
669 because it does not have special characters to be escaped.
670  
671 % date -Menv::setenv(LANG=de_DE) # need shell quote
672 % date -Menv::setenv=LANG=de_DE # alternative format
673 So 22 Okt 2017 18:00:00 JST
674  
675 Option aliases can be also declared in the module, at the end of file,
676 following special literal C<__DATA__>. Using this, you can prepare
677 multiple set of options for different purposes. Think about generic
678 B<i18n> module:
679  
680 package i18n;
681 1;
682 __DATA__
683 option --cn -Menv::setenv(LANG=zh_CN) // 中国語 - 簡体字
684 option --tw -Menv::setenv(LANG=zh_TW) // 中国語 - 繁体字
685 option --us -Menv::setenv(LANG=en_US) // 英語
686 option --fr -Menv::setenv(LANG=fr_FR) // フランス語
687 option --de -Menv::setenv(LANG=de_DE) // ドイツ語
688 option --it -Menv::setenv(LANG=it_IT) // イタリア語
689 option --jp -Menv::setenv(LANG=ja_JP) // 日本語
690 option --kr -Menv::setenv(LANG=ko_KR) // 韓国語
691 option --br -Menv::setenv(LANG=pt_BR) // ポルトガル語 - ブラジル
692 option --es -Menv::setenv(LANG=es_ES) // スペイン語
693 option --ru -Menv::setenv(LANG=ru_RU) // ロシア語
694  
695 This can be used like:
696  
697 % date -Mi18n --tw
698 2017年10月22日 週日 18時00分00秒 JST
699  
700 You can declare autoload module in your F<~/.optex.d/optex.rc> like:
701  
702 autoload -Mi18n --cn --tw --us --fr --de --it --jp --kr --br --es --ru
703  
704 Then you can use them without module option. In this case, option
705 C<--ru> is replaced by C<-Mi18n --ru> automatically.
706  
707 % date --ru
708 воскресенье, 22 октября 2017 г. 18:00:00 (JST)
709  
710 Module C<i18n> is implemented as L<Getopt::EX::i18n> and included in
711 this distribution. So it can be used as above without additional
712 installation.
713  
714 Modules can also define built-in options using C<builtin> directive in
715 the C<__DATA__> section. Built-in options are processed by
716 L<Getopt::Long> and must be specified before the target command name.
717 For example:
718  
719 optex -Mxform --xform-visible=2 cat file
720  
721 Here C<--xform-visible> is a built-in option defined in the C<xform>
722 module.
723  
724 =head1 STANDARD MODULES
725  
726 Standard modules are installed at C<App::optex>, and they can be
727 addressed with and without C<App::optex> prefix.
728  
729 =over 4
730  
731 =item -MB<help>
732  
733 Print available option list. Option name is printed with substitution
734 form, or help message if defined. Use B<-x> option to omit help
735 message.
736  
737 Option B<--man> or B<-h> will print document if available. Option
738 B<-l> will print module path. Option B<-m> will show the module
739 itself. When used after other modules, print information about the
740 last declared module. Next command show the document about B<second>
741 module.
742  
743 % optex -Mfirst -Msecond -Mhelp --man
744  
745 =item -MB<debug>
746  
747 Print debug messages.
748  
749 =item -MB<util::argv>
750  
751 Module to manipulate command argument.
752 See L<App::optex::util::argv> for detail.
753  
754 =item -MB<util::filter>
755  
756 Module to implement command input/output filters.
757 See L<App::optex::util::filter> for detail.
758  
759 =back
760  
761 =head1 Getopt::EX MODULES
762  
763 In addition to its own modules, B<optex> can also use C<Getopt::EX>
764 modules. The standard C<Getopt::EX> modules installed are these.
765  
766 =over 4
767  
768 =item -MB<i18n> (L<Getopt::EX::i18n>)
769  
770 You can display a Greek calendar by doing the following:
771  
772 optex -Mi18n cal --gr
773  
774 =back
775  
776 =head1 OPTIONS
777  
778 These options are not effective when B<optex> was executed from
779 symbolic link.
780  
781 =over 4
782  
783  
784 =item B<--link>, B<--ln> [ I<command> ]
785  
786 Create symbolic link in F<~/.optex.d/bin> directory.
787  
788  
789 =item B<--unlink>, B<--rm> [ B<-f> ] [ I<command> ]
790  
791 Remove symbolic link in F<~/.optex.d/bin> directory.
792  
793  
794 =item B<--ls> [ B<-l> ] [ I<command> ]
795  
796 List symbolic link files in F<~/.optex.d/bin> directory.
797  
798  
799 =item B<--rc> [ B<-l> ] [ B<-m> ] [ I<command> ]
800  
801 List rc files in F<~/.optex.d> directory.
802  
803  
804 =item B<--nop>, B<-x> I<command>
805  
806 Stop option manipulation. Use full pathname otherwise.
807  
808  
809 =item B<-->[B<no>]B<module>
810  
811 B<optex> deals with module option (-M) on target command by default.
812 However, there is a command which also uses same option for own
813 purpose. Option B<--nomodule> disables that behavior. Other option
814 interpretation is still effective, and there is no problem using
815 module option in rc or module files.
816  
817  
818 =item B<--exit> I<status>
819  
820 Usually B<optex> exits with status of executed command. This option
821 override it and force to exit with specified status code.
822  
823  
824 =back
825  
826  
827 =head1 CONFIGURATION FILE
828  
829 When starting up, B<optex> reads configuration file
830 F<~/.optex.d/config.toml> which is supposed to be written in TOML
831 format.
832  
833 =head2 PARAMETERS
834  
835 =over 4
836  
837 =item B<no-module>
838  
839 Set commands for which B<optex> does not interpret module option
840 B<-M>. If the target command is found in this list, it is executed as
841 if option B<--no-module> is given to B<optex>.
842  
843 no-module = [
844 "greple",
845 "pgrep",
846 ]
847  
848 =item B<alias>
849  
850 Set command aliases. Example:
851  
852 [alias]
853 pgrep = [ "greple", "-Mperl", "--code" ]
854 hello = "echo -n 'hello world!'"
855  
856 Command alias can be invoked either from symbolic link and command
857 argument.
858  
859 =item B<include>
860  
861 Load extra TOML fragments before applying the main configuration.
862 Accepts either a string or an array. Each entry may be a literal path
863 or a glob pattern. Tilde is expanded, and relative paths are resolved
864 against the file that declared the include. Includes are processed
865 depth-first; hashes merge recursively, arrays append, and scalars use
866 last-in-wins semantics. The main F<config.toml> is applied last so it
867 can override included values.
868  
869 include = [
870 "~/.optex.d/config.d/*.toml",
871 "local.toml",
872 ]
873  
874 Include directives can nest; cycles (including self-globs) are detected
875 and reported as errors.
876  
877 =back
878  
879  
880 =head1 FILES AND DIRECTORIES
881  
882 =over 4
883  
884  
885 =item F<PERLLIB/App/optex>
886  
887 System module directory.
888  
889  
890 =item F<~/.optex.d/>
891  
892 Personal root directory.
893  
894  
895 =item F<~/.optex.d/config.toml>
896  
897 Configuration file.
898  
899  
900 =item F<~/.optex.d/default.rc>
901  
902 Common startup file.
903  
904  
905 =item F<~/.optex.d/>I<command>F<.rc>
906  
907 Startup file for I<command>.
908  
909  
910 =item F<~/.optex.d/>I<command>F</>
911  
912 Module directory for I<command>.
913  
914  
915 =item F<~/.optex.d/>I<command>F</default.pm>
916  
917 Default module for I<command>.
918  
919  
920 =item F<~/.optex.d/bin>
921  
922 Default directory to store symbolic links.
923  
924 This is not necessary, but it seems a good idea to make special
925 directory to contain symbolic links for B<optex>, placing it in your
926 command search path. Then you can easily add/remove it from the path,
927 or create/remove symbolic links.
928  
929 =back
930  
931  
932 =head1 ENVIRONMENT
933  
934 =over 4
935  
936 =item OPTEX_ROOT
937  
938 Override default root directory F<~/.optex.d>.
939  
940 =item OPTEX_CONFIG
941  
942 Override default configuration file F<OPTEX_ROOT/config.toml>.
943  
944 =item OPTEX_MODULE_PATH
945  
946 Set module paths separated by colon (C<:>). These are inserted before
947 standard path.
948  
949 =item OPTEX_BINDIR
950  
951 Override default symbolic link directory F<OPTEX_ROOT/bin>.
952  
953 =item OPTEX_SCRIPT_PATH
954  
955 Specify the path to use when creating symbolic links with C<--ln>.
956 If not set, C<$0> is used. This is useful when B<optex> is invoked
957 through a wrapper script (e.g., Homebrew installation) and you want
958 the symbolic links to point to the wrapper rather than the actual
959 script.
960  
961 =item OPTEX_INVOKED_AS
962  
963 Specify the original command path used to invoke B<optex>. This is
964 useful when B<optex> is invoked through a wrapper script and the
965 original C<$0> is lost. When a symbolic link to the wrapper is
966 executed, the wrapper should set this variable to its own C<$0> so
967 that B<optex> can determine the correct command name.
968  
969 =back
970  
971  
972 =head1 SEE ALSO
973  
974 L<Getopt::EX>, L<Getopt::EX::Loader>, L<Getopt::EX::Module>
975  
976 L<App::optex::textconv>
977  
978 L<App::optex::xform>
979  
980 =head1 AUTHOR
981  
982 Kazumasa Utashiro
983  
984  
985 =head1 LICENSE
986  
987 You can redistribute it and/or modify it under the same terms
988 as Perl itself.
989  
990 Copyright ©︎ 2017-2026 Kazumasa Utashiro
991  
992  
993 =cut
994  
995  
996 # LocalWords: optex rc iso greple awk pdf LANG ENV Oct JST domingo
997 # LocalWords: setenv autoload PERLLIB BINDIR Utashiro Kazumasa
↑ Summary blib/lib/App/optex/util/argv.pm »