lib/BATsh.pm

filter: Statementstmt 92.2% 454 / 492 Branchbran 78.7% 233 / 296 Conditioncond 66.3% 69 / 104 MC/DCmcdc 45.9% 28 / 61 Subroutinesub 84.6% 33 / 39 Podpod 0.0% 0 / 16 totaltotal 81.0% 817 / 1008 CC 196 SCAR 30.7
CC
196
Cov
85%
repl
65.2
_sh_depth_delta
42.0
_process_lines
22.1
CRAP 21.5
« lib/BATsh/CMD.pm ↑ Summary lib/BATsh/MB.pm »
1 package BATsh;
2 ######################################################################
3 #
4 # BATsh - Bilingual Shell for cmd.exe and bash in one script
5 #
6 # https://metacpan.org/dist/BATsh
7 #
8 # Copyright (c) 2026 INABA Hitoshi <ina.cpan@gmail.com>
9 #
10 # This version implements both cmd.exe and sh/bash command sets
11 # entirely in Perl. No external cmd.exe, bash, or sh is required.
12 #
13 ######################################################################
14  
15 67 ▶use 5.00503;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 67 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 67 ▶BEGIN { if ($] < 5.006 && !defined(&warnings::import)) { $INC{'warnings.pm'} = 'stub'; eval 'package warnings; sub import {}' } }
Subroutine BEGIN: called CC=3 SCAR=11.4
Branch: 1 branch
BranchTrueFalseTotal
if ($] < "5.006" and not defined &warnings::import) 3 64 67
Condition33%1/3
$] < "5.006" and not defined &warnings::import
!ll&&!rl&&r
6400
MC/DC0%0/2
$] < "5.006" and not defined &warnings::import
$] < "5.006" not defined &warnings::import
Truth table33%1/3
A and not(B)
A= $] < "5.006"B= not defined &warnings::import
ABresult
0X0
100
111
18 67 ▶use warnings; local $^W = 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 67 ▶BEGIN { pop @INC if $INC[-1] eq '.' }
Subroutine BEGIN: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if $INC[-1] eq "." 3 61 64
20  
21 85 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
22 67 ▶BEGIN { eval { require Cwd } }
Subroutine BEGIN: called CC=1 SCAR=0.0
23 64 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
24 64 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
25 61 $VERSION = '0.11';
26 61 $VERSION = $VERSION;
27  
28 61 require BATsh::MB;
29 61 require BATsh::Env;
30 61 require BATsh::CMD;
31 61 require BATsh::SH;
32  
33 ###############################################################################
34 # Architecture
35 ###############################################################################
36 #
37 # BATsh is a bilingual shell interpreter.
38 #
39 # It splits a script into CMD sections and SH sections, then executes
40 # each section using its own pure-Perl interpreter:
41 #
42 # BATsh::CMD -- cmd.exe command set (SET, ECHO, IF, FOR, GOTO, ...)
43 # BATsh::SH -- sh/bash command set (echo, export, if/fi, for/done, ...)
44 # BATsh::Env -- shared variable store (bridge between both modes)
45 #
46 # MODE DETECTION: first non-empty, non-comment token of each section.
47 # CMD: token is [A-Z 0-9 _ - \ / : . @ %]+ with at least one A-Z
48 # SH: anything else
49 #
50 # SECTION BOUNDARY:
51 # CMD: parenthesis ( ) depth returns to 0
52 # SH: keyword depth (if/fi, for/done, ...) returns to 0
53 #
54 # ENV BRIDGE:
55 # BATsh::Env::STORE is the single variable table.
56 # CMD %VAR% and SH $VAR both read/write the same store.
57 #
58 ###############################################################################
59  
60 ###############################################################################
61 # Global state
62 ###############################################################################
63 61 my $_TMPCOUNT = 0;
64  
65 # Subroutine registry: { LABEL => \@lines }
66 61 my %_SUBROUTINES = ();
67  
68 # Script-level exit state: set (to the exit code) the moment an SH "exit"
69 # or a CMD "EXIT" executes in any section, including inside a sourced file
70 # or a CALL'd subroutine. Once set, no further section is executed, and
71 # run()/run_string()/run_lines() return this code. Reset at the start of
72 # each top-level run.
73 61 my $_SCRIPT_EXIT = undef;
74  
75 ###############################################################################
76 # Constructor
77 ###############################################################################
78 0 ▶sub new {
Subroutine new: not called CC=2 SCAR=17.9
Pod undocumented
79 0 my ($class, %args) = @_;
80 0 BATsh::Env::init();
81 0 ▶ return bless { verbose => $args{verbose} || 0 }, $class;
Condition0%0/2
$args{'verbose'} || 0
l!l
00
MC/DC0%0/1
$args{'verbose'} || 0
$args{'verbose'}
Truth table0%0/2
A
A= $args{'verbose'}
Aresult
11
00
82 }
83  
84 ###############################################################################
85 # Public run interface
86 ###############################################################################
87 38 ▶sub run {
Subroutine run: called CC=6 SCAR=18.1
Pod undocumented
88 38 my ($class_or_self, $file, %args) = @_;
89 38 ▶ unless (-f $file) { croak "BATsh->run: file not found: $file" }
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $file) 1 37 38
90 37 local *SRCFH;
91 37 ▶ open(SRCFH, $file) or croak "BATsh->run: cannot open $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open SRCFH, $file or croak("BATsh->run: cannot open ${file}: $!") 37 0 37
92 37 my @lines = <SRCFH>;
93 37 close(SRCFH);
94 37 _prepare_source(\@lines, $args{encoding});
95 37 _ensure_env_init();
96 # Set batch positional parameters: %0 = script path, %1..%9 = args, %* = all args
97 37 ▶ my @script_args = defined($args{args}) ? @{$args{args}} : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'args'} ? : 37 0 37
98 37 _set_batch_args($file, @script_args);
99 37 $_SCRIPT_EXIT = undef;
100 37 ▶ BATsh::SH::reset_sh_options() if defined &BATsh::SH::reset_sh_options;
Branch: 1 branch
BranchTrueFalseTotal
if defined &BATsh::SH::reset_sh_options 37 0 37
101 37 _process_lines(@lines);
102 37 my $rc = _final_status();
103 37 ▶ BATsh::SH::fire_exit_trap("BATsh::SH") if defined &BATsh::SH::fire_exit_trap;
Branch: 1 branch
BranchTrueFalseTotal
if defined &BATsh::SH::fire_exit_trap 37 0 37
104 37 return $rc;
105 }
106  
107 512 ▶sub run_string {
Subroutine run_string: called CC=6 SCAR=18.2
Pod undocumented
108 512 my ($class_or_self, $source, %args) = @_;
109 512 ▶ croak "BATsh->run_string: source required" unless defined $source;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $source 0 512 512
110 512 my @lines = map { "$_\n" } split(/\n/, $source, -1);
111 512 _prepare_source(\@lines, $args{encoding});
112 512 _ensure_env_init();
113 # Optional positional parameters (used by "batsh - args..." and by
114 # callers that feed a script body as a string): %0 defaults to '-'.
115 512 ▶ if (defined $args{args}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"args"}) 2 510 512
116 _set_batch_args(defined $args{script_name} ? $args{script_name} : '-',
117 2 ▶ @{$args{args}});
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'script_name'} ? : 2 0 2
118 }
119 512 $_SCRIPT_EXIT = undef;
120 512 ▶ BATsh::SH::reset_sh_options() if defined &BATsh::SH::reset_sh_options;
Branch: 1 branch
BranchTrueFalseTotal
if defined &BATsh::SH::reset_sh_options 512 0 512
121 512 _process_lines(@lines);
122 512 my $rc = _final_status();
123 512 ▶ BATsh::SH::fire_exit_trap("BATsh::SH") if defined &BATsh::SH::fire_exit_trap;
Branch: 1 branch
BranchTrueFalseTotal
if defined &BATsh::SH::fire_exit_trap 512 0 512
124 512 return $rc;
125 }
126  
127 0 ▶sub run_lines {
Subroutine run_lines: not called CC=3 SCAR=24.8
Pod undocumented
128 0 my ($class_or_self, @lines) = @_;
129 0 _prepare_source(\@lines, undef);
130 0 _ensure_env_init();
131 0 $_SCRIPT_EXIT = undef;
132 0 ▶ BATsh::SH::reset_sh_options() if defined &BATsh::SH::reset_sh_options;
Branch: 1 branch
BranchTrueFalseTotal
if defined &BATsh::SH::reset_sh_options 0 0 0
133 0 _process_lines(@lines);
134 0 my $rc = _final_status();
135 0 ▶ BATsh::SH::fire_exit_trap("BATsh::SH") if defined &BATsh::SH::fire_exit_trap;
Branch: 1 branch
BranchTrueFalseTotal
if defined &BATsh::SH::fire_exit_trap 0 0 0
136 0 return $rc;
137 }
138  
139 # ----------------------------------------------------------------
140 # _final_status -- the exit status of the run just finished: the code of
141 # an executed exit/EXIT if any, else the last command's status. After
142 # every section flush both interpreters hold the same value (see
143 # _flush_cmd/_flush_sh), so the SH side is authoritative here.
144 # ----------------------------------------------------------------
145 555 ▶sub _final_status {
Subroutine _final_status: called CC=2 SCAR=6.9
146 555 ▶ return $_SCRIPT_EXIT if defined $_SCRIPT_EXIT;
Branch: 1 branch
BranchTrueFalseTotal
if defined $_SCRIPT_EXIT 28 527 555
147 527 return BATsh::SH::get_status();
148 }
149  
150 # ----------------------------------------------------------------
151 # last_status -- public accessor: the unified $? / %ERRORLEVEL% value.
152 # ----------------------------------------------------------------
153 1 ▶sub last_status { return _final_status() }
Subroutine last_status: called CC=1 SCAR=0.0
Pod undocumented
154  
155 554 ▶sub _ensure_env_init {
Subroutine _ensure_env_init: called CC=2 SCAR=6.9
156 # Init only once per process
157 554 ▶ BATsh::Env::init() unless %BATsh::Env::STORE;
Branch: 1 branch
BranchTrueFalseTotal
unless %BATsh::Env::STORE 1 553 554
158 }
159  
160 ###############################################################################
161 # set_encoding -- select the script encoding for multibyte-safe execution
162 # BATsh->set_encoding('cp932'); # also: sjis gbk uhc big5 utf8 none auto
163 # The default is 'auto': a non-UTF-8 script containing bytes >= 0x80 is
164 # treated as CP932 and guarded (see BATsh::MB). The environment variable
165 # BATSH_ENCODING, when set, overrides the default before the first run.
166 ###############################################################################
167 61 my $_ENV_ENCODING_APPLIED = 0;
168  
169 4 ▶sub set_encoding {
Subroutine set_encoding: called CC=4 SCAR=16.4
Pod undocumented
170 4 my ($class_or_self, $enc) = @_;
171 4 ▶ $enc = $class_or_self
Branch: 1 branch
BranchTrueFalseTotal
if not defined $enc and defined $class_or_self and not $class_or_self =~ /\ABATsh\b/ 0 4 4
Condition33%2/6
not defined $enc and defined $class_or_self and not $class_or_self =~ /\ABATsh\b/
!ll&&!rl&&r
400
not defined $enc and defined $class_or_self
!ll&&!rl&&r
400
MC/DC0%0/3
not defined $enc and defined $class_or_self and not $class_or_self =~ /\ABATsh\b/
not defined $enc defined $class_or_self not $class_or_self =~ /\ABATsh\b/
Truth table25%1/4
not(A) and B and not(C)
A= not defined $encB= defined $class_or_selfC= not $class_or_self =~ /\ABATsh\b/
ABCresult
0XX0
10X0
1100
1111
172 if !defined($enc) && defined($class_or_self)
173 && $class_or_self !~ /\ABATsh\b/;
174 4 $_ENV_ENCODING_APPLIED = 1; # explicit choice beats BATSH_ENCODING
175 4 return BATsh::MB::set_encoding($enc);
176 }
177  
178 0 ▶sub encoding { return BATsh::MB::encoding() }
Subroutine encoding: not called CC=1 SCAR=6.9
Pod undocumented
179  
180 ###############################################################################
181 # _prepare_source -- per-run encoding setup on the raw script lines
182 # 1. strip a UTF-8 BOM from the first line
183 # 2. apply an explicit per-run encoding, or BATSH_ENCODING (once),
184 # or leave the current ('auto' by default) setting in place
185 # 3. under 'auto', detect the source encoding and activate the guard
186 # 4. guard-transform every line in place (identity when inactive)
187 ###############################################################################
188 554 ▶sub _prepare_source {
Subroutine _prepare_source: called CC=9 SCAR=25.9
189 554 my ($lines_ref, $encoding) = @_;
190 554 ▶ $lines_ref->[0] = BATsh::MB::strip_bom($lines_ref->[0]) if @{$lines_ref};
Branch: 1 branch
BranchTrueFalseTotal
if @{$lines_ref;} 554 0 554
191 554 ▶ if (defined $encoding && $encoding ne '') {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $encoding and $encoding ne '') { } 0 554 554
elsif (not $_ENV_ENCODING_APPLIED and defined $ENV{'BATSH_ENCODING'} and $ENV{'BATSH_ENCODING'} ne '') { } 0 1108 1108
Condition33%1/3
defined $encoding and $encoding ne ""
!ll&&!rl&&r
55400
MC/DC0%0/2
defined $encoding and $encoding ne ""
defined $encoding $encoding ne ""
Truth table33%1/3
A and B
A= defined $encodingB= $encoding ne ""
ABresult
0X0
100
111
192 0 BATsh::MB::set_encoding($encoding);
193 0 $_ENV_ENCODING_APPLIED = 1;
194 }
195 ▶ elsif (!$_ENV_ENCODING_APPLIED
Condition50%3/6
not $_ENV_ENCODING_APPLIED and defined $ENV{"BATSH_ENCODING"} and $ENV{"BATSH_ENCODING"} ne ""
!ll&&!rl&&r
55400
not $_ENV_ENCODING_APPLIED and defined $ENV{"BATSH_ENCODING"}
!ll&&!rl&&r
185360
MC/DC0%0/3
not $_ENV_ENCODING_APPLIED and defined $ENV{"BATSH_ENCODING"} and $ENV{"BATSH_ENCODING"} ne ""
not $_ENV_ENCODING_APPLIED defined $ENV{"BATSH_ENCODING"} $ENV{"BATSH_ENCODING"} ne ""
Truth table50%2/4
not(A) and B and C
A= not $_ENV_ENCODING_APPLIEDB= defined $ENV{"BATSH_ENCODING"}C= $ENV{"BATSH_ENCODING"} ne ""
ABCresult
0XX0
10X0
1100
1111
196 && defined $ENV{BATSH_ENCODING} && $ENV{BATSH_ENCODING} ne '') {
197 0 BATsh::MB::set_encoding($ENV{BATSH_ENCODING});
198 0 $_ENV_ENCODING_APPLIED = 1;
199 }
200 554 BATsh::MB::activate_for(join('', @{$lines_ref}));
201 554 ▶ if (BATsh::MB::active()) {
Branch: 1 branch
BranchTrueFalseTotal
if (BATsh::MB::active()) 17 537 554
202 17 for my $l (@{$lines_ref}) { $l = BATsh::MB::enc($l) }
203 }
204 554 return 1;
205 }
206  
207 ###############################################################################
208 # _set_batch_args -- populate %0..%9 and %* in the Env store
209 # %0 = script path (as passed to run())
210 # %1 = first argument, ..., %9 = ninth argument
211 # %* = all arguments joined by single space (does not include %0)
212 ###############################################################################
213 43 ▶sub _set_batch_args {
Subroutine _set_batch_args: called CC=8 SCAR=21.2
214 43 my ($script, @args) = @_;
215 # Arguments arrive as RAW bytes from outside the interpreter
216 # (command line / caller); guard them before they enter the store.
217 43 ▶ @args = map { BATsh::MB::enc(defined $_ ? $_ : '') } @args;
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 14 0 14
218 # Normalise $0: resolve to absolute path using File::Spec
219 43 ▶ my $abs_script = defined $script ? $script : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $script ? : 43 0 43
220 43 ▶ if ($abs_script ne '' && !File::Spec->file_name_is_absolute($abs_script)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($abs_script ne "" and not "File::Spec"->file_name_is_absolute($abs_script)) 5 38 43
Condition66%2/3
$abs_script ne "" and not "File::Spec"->file_name_is_absolute($abs_script)
!ll&&!rl&&r
0385
MC/DC50%1/2
$abs_script ne "" and not "File::Spec"->file_name_is_absolute($abs_script)
$abs_script ne "" not "File::Spec"->file_name_is_absolute($abs_script)
Truth table66%2/3
A and not(B)
A= $abs_script ne ""B= not "File::Spec"->file_name_is_absolute($abs_script)
ABresult
0X0
100
111
221 5 ▶ my $cwd = defined(&Cwd::cwd) ? Cwd::cwd() : '.';
Branch: 1 branch
BranchTrueFalseTotal
defined &Cwd::cwd ? : 5 0 5
222 5 $abs_script = File::Spec->catfile($cwd, $abs_script);
223 }
224 43 BATsh::Env->set('%0', BATsh::MB::enc($abs_script));
225 43 for my $n (1 .. 9) {
226 387 ▶ BATsh::Env->set("%$n", defined($args[$n - 1]) ? $args[$n - 1] : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $args[$n - 1] ? : 14 373 387
227 }
228 43 BATsh::Env->set('%*', join(' ', @args));
229 }
230  
231 ###############################################################################
232 # classify_token
233 ###############################################################################
234 1769 ▶sub classify_token {
Subroutine classify_token: called CC=4 SCAR=13.9
Pod undocumented
235 1769 my ($class_or_token, $token) = @_;
236 1769 ▶ unless (defined $token) { $token = $class_or_token }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $token) 1769 0 1769
237 1769 ▶ if ($token =~ /\A[A-Z0-9_\-\\\/\.:@%]+\z/ && $token =~ /[A-Z]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($token =~ m[\A[A-Z0-9_\-\\/\.:\@%]+\z] and $token =~ /[A-Z]/) 531 1238 1769
Condition100%3/3
$token =~ m[\A[A-Z0-9_\-\\/\.:\@%]+\z] and $token =~ /[A-Z]/
!ll&&!rl&&r
12353531
MC/DC100%2/2
$token =~ m[\A[A-Z0-9_\-\\/\.:\@%]+\z] and $token =~ /[A-Z]/
$token =~ m[\A[A-Z0-9_\-\\/\.:\@%]+\z] $token =~ /[A-Z]/
Truth table100%3/3
A and B
A= $token =~ m[\A[A-Z0-9_\-\\/\.:\@%]+\z]B= $token =~ /[A-Z]/
ABresult
0X0
100
111
238 531 return 'CMD';
239 }
240 1238 return 'SH';
241 }
242  
243 ###############################################################################
244 # Line parser
245 # Returns ($mode, $stripped_line, $first_token)
246 ###############################################################################
247 2389 ▶sub _parse_line {
Subroutine _parse_line: called CC=5 SCAR=16.1
248 2389 my ($line) = @_;
249 2389 (my $s = $line) =~ s/\r?\n\z//;
250 2389 ▶ return ('EMPTY', $s, '') if $s =~ /\A\s*\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /\A\s*\z/ 348 2041 2389
251 2041 ▶ return ('COMMENT', $s, '') if $s =~ /\A\s*(?:::|\@?REM(?:\s|\z))/i;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /\A\s*(?:::|\@?REM(?:\s|\z))/i 148 1893 2041
252 1893 ▶ return ('COMMENT', $s, '') if $s =~ /\A\s*#(?!!)/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /\A\s*#(?!!)/ 146 1747 1893
253 1747 (my $t = $s) =~ s/\A\s+//;
254 1747 ▶ my $first = ($t =~ /\A(\S+)/) ? $1 : '';
Branch: 1 branch
BranchTrueFalseTotal
$t =~ /\A(\S+)/ ? : 1747 0 1747
255 1747 return (classify_token($first), $s, $first);
256 }
257  
258 ###############################################################################
259 # CMD section depth: count unquoted ( )
260 ###############################################################################
261 550 ▶sub _cmd_paren_delta {
Subroutine _cmd_paren_delta: called CC=6 SCAR=17.9
262 550 my ($line) = @_;
263 550 my ($delta, $in_q) = (0, 0);
264 550 for my $ch (split //, $line) {
265 10690 ▶ if ($ch eq '"') { $in_q = !$in_q }
Branch: 2 branches
BranchTrueFalseTotal
if ($ch eq '"') { } 104 10586 10690
elsif (not $in_q) { } 10344 242 10586
266 elsif (!$in_q) {
267 10344 ▶ $delta++ if $ch eq '(';
Branch: 1 branch
BranchTrueFalseTotal
if $ch eq "(" 68 10276 10344
268 10344 ▶ $delta-- if $ch eq ')';
Branch: 1 branch
BranchTrueFalseTotal
if $ch eq ")" 68 10276 10344
269 }
270 }
271 550 return $delta;
272 }
273  
274 ###############################################################################
275 # SH section depth
276 ###############################################################################
277 61 my %_SH_OPEN = map { $_ => 1 } qw(if for while until case function select);
278 61 my %_SH_CLOSE = map { $_ => 1 } qw(fi done esac);
279  
280 # Net SH block-depth change for an ENTIRE line.
281 #
282 # A single physical line may both open and close a block, e.g.
283 # for i in 1 2 3; do echo $i; done (net 0)
284 # while COND; do ...; done; done (net -1, nested close)
285 # Looking only at the first token (as earlier versions did) counted the
286 # leading "for"/"while" but never the inline "done", so the SH section was
287 # left open and a following CMD line (e.g. ECHO ...%VAR%...) was wrongly
288 # absorbed into the SH section and run by the SH interpreter.
289 #
290 # Opener keywords (if for while until case function select) and "{" add 1;
291 # closer keywords (fi done esac) and "}" subtract 1, but only when they are in
292 # command position (line start, or just after ; & | ( ) { } or do/then/else/
293 # elif). Single- and double-quoted text, $( ... ) command substitutions and
294 # `...` backticks are skipped so that a "done" inside a string or substitution
295 # does not affect the depth. Perl 5.005_03 compatible (no regex features
296 # beyond character classes; substr/index style scanning).
297 1205 ▶sub _sh_depth_delta {
Subroutine _sh_depth_delta: called CC=42 SCAR=37.4
298 1205 my ($line) = @_;
299 1205 ▶ return 0 unless defined $line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 0 1205 1205
300  
301 # Fast path: a bare single keyword token (the common multi-line case).
302 1205 ▶ if ($line !~ /[\s;&|(){}'"`]/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($line =~ /[\s;&|(){}'"`]/) 181 1024 1205
303 181 my $l = lc($line);
304 181 ▶ return 1 if exists $_SH_OPEN{$l};
Branch: 1 branch
BranchTrueFalseTotal
if exists $_SH_OPEN{$l} 3 178 181
305 178 ▶ return -1 if exists $_SH_CLOSE{$l};
Branch: 1 branch
BranchTrueFalseTotal
if exists $_SH_CLOSE{$l} 58 120 178
306 120 return 0;
307 }
308  
309 1024 my $delta = 0;
310 1024 my $cmdpos = 1; # next bareword starts a new statement?
311 1024 my $i = 0;
312 1024 my $n = length($line);
313 1024 ▶ while ($i < $n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $n) 7441 1024 8465
314 7441 my $c = substr($line, $i, 1);
315  
316 7441 ▶ if ($c eq "'") { # single-quoted region
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq "'") 64 7377 7441
317 64 $i++;
318 64 ▶ $i++ while $i < $n && substr($line, $i, 1) ne "'";
Branch: 1 branch
BranchTrueFalseTotal
$i < $n and substr($line, $i, 1) ne "'" and do { ++$i } 560 64 624
Condition66%2/3
$i < $n and substr($line, $i, 1) ne "'"
!ll&&!rl&&r
064560
MC/DC50%1/2
$i < $n and substr($line, $i, 1) ne "'"
$i < $n substr($line, $i, 1) ne "'"
Truth table66%2/3
A and B
A= $i < $nB= substr($line, $i, 1) ne "'"
ABresult
0X0
100
111
319 64 $i++; $cmdpos = 0; next;
320 }
321 7377 ▶ if ($c eq '"') { # double-quoted region
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq "\"") 418 6959 7377
322 418 $i++;
323 418 ▶ while ($i < $n && substr($line, $i, 1) ne '"') {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $n and substr($line, $i, 1) ne "\"") 7333 418 7751
Condition66%2/3
$i < $n and substr($line, $i, 1) ne "\""
!ll&&!rl&&r
04187333
MC/DC50%1/2
$i < $n and substr($line, $i, 1) ne "\""
$i < $n substr($line, $i, 1) ne "\""
Truth table66%2/3
A and B
A= $i < $nB= substr($line, $i, 1) ne "\""
ABresult
0X0
100
111
324 7333 ▶ if (substr($line, $i, 1) eq '\\') { $i += 2; next }
Branch: 1 branch
BranchTrueFalseTotal
if (substr($line, $i, 1) eq "\\") 18 7315 7333
325 7315 $i++;
326 }
327 418 $i++; $cmdpos = 0; next;
328 }
329 6959 ▶ if ($c eq '`') { # backtick substitution
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq "`") 1 6958 6959
330 1 $i++;
331 1 ▶ $i++ while $i < $n && substr($line, $i, 1) ne '`';
Branch: 1 branch
BranchTrueFalseTotal
$i < $n and substr($line, $i, 1) ne "`" and do { ++$i } 10 1 11
Condition66%2/3
$i < $n and substr($line, $i, 1) ne "`"
!ll&&!rl&&r
0110
MC/DC50%1/2
$i < $n and substr($line, $i, 1) ne "`"
$i < $n substr($line, $i, 1) ne "`"
Truth table66%2/3
A and B
A= $i < $nB= substr($line, $i, 1) ne "`"
ABresult
0X0
100
111
332 1 $i++; $cmdpos = 0; next;
333 }
334 6958 ▶ if ($c eq '$' && $i + 1 < $n && substr($line, $i + 1, 1) eq '(') {
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq "\$" and $i + 1 < $n and substr($line, $i + 1, 1) eq "(") 43 6915 6958
Condition83%5/6
$c eq "\$" and $i + 1 < $n and substr($line, $i + 1, 1) eq "("
!ll&&!rl&&r
680511043
$c eq "\$" and $i + 1 < $n
!ll&&!rl&&r
68050153
MC/DC66%2/3
$c eq "\$" and $i + 1 < $n and substr($line, $i + 1, 1) eq "("
$c eq "\$" $i + 1 < $n substr($line, $i + 1, 1) eq "("
Truth table75%3/4
A and B and C
A= $c eq "\$"B= $i + 1 < $nC= substr($line, $i + 1, 1) eq "("
ABCresult
0XX0
10X0
1100
1111
335 43 $i += 2; # $( ... ) -- skip balanced parens
336 43 my $d = 1;
337 43 ▶ while ($i < $n && $d > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $n and $d > 0) 456 43 499
Condition100%3/3
$i < $n and $d > 0
!ll&&!rl&&r
385456
MC/DC100%2/2
$i < $n and $d > 0
$i < $n $d > 0
Truth table100%3/3
A and B
A= $i < $nB= $d > 0
ABresult
0X0
100
111
338 456 my $ch = substr($line, $i, 1);
339 456 ▶ $d++ if $ch eq '(';
Branch: 1 branch
BranchTrueFalseTotal
if $ch eq "(" 39 417 456
340 456 ▶ $d-- if $ch eq ')';
Branch: 1 branch
BranchTrueFalseTotal
if $ch eq ")" 82 374 456
341 456 $i++;
342 }
343 43 $cmdpos = 0; next;
344 }
345 6915 ▶ if ($c =~ /\s/) { $i++; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($c =~ /\s/) 3228 3687 6915
346 3687 ▶ if ($c eq ';' || $c eq '&' || $c eq '|') { $cmdpos = 1; $i++; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq ";" or $c eq "&" or $c eq "|") 453 3234 3687
Condition100%6/6
$c eq ";" or $c eq "&" or $c eq "|"
l!l&&r!l&&!r
411423234
$c eq ";" or $c eq "&"
l!l&&r!l&&!r
376353276
MC/DC100%3/3
$c eq ";" or $c eq "&" or $c eq "|"
$c eq ";" $c eq "&" $c eq "|"
Truth table100%4/4
A or B or C
A= $c eq ";"B= $c eq "&"C= $c eq "|"
ABCresult
1XX1
01X1
0011
0000
347 3234 ▶ if ($c eq '(') { $cmdpos = 1; $i++; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq "(") 95 3139 3234
348 3139 ▶ if ($c eq ')') { $cmdpos = 1; $i++; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq ")") 145 2994 3139
349 2994 ▶ if ($c eq '{') { $delta++ if $cmdpos; $cmdpos = 1; $i++; next }
Branch: 2 branches
BranchTrueFalseTotal
if ($c eq "{") 47 2947 2994
if $cmdpos 25 22 47
350 2947 ▶ if ($c eq '}') { $delta-- if $cmdpos; $cmdpos = 1; $i++; next }
Branch: 2 branches
BranchTrueFalseTotal
if ($c eq "}") 47 2900 2947
if $cmdpos 25 22 47
351  
352 # Bareword
353 2900 my $word = '';
354 2900 ▶ while ($i < $n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $n) 13325 582 13907
355 13325 my $wc = substr($line, $i, 1);
356 13325 ▶ last if $wc =~ /[\s;&|(){}'"`]/;
Branch: 1 branch
BranchTrueFalseTotal
if $wc =~ /[\s;&|(){}'"`]/ 2318 11007 13325
357 11007 $word .= $wc; $i++;
358 }
359 2900 ▶ if ($cmdpos) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmdpos) { } 1541 1359 2900
360 1541 my $lw = lc($word);
361 1541 ▶ if (exists $_SH_OPEN{$lw}) { $delta++ }
Branch: 2 branches
BranchTrueFalseTotal
if (exists $_SH_OPEN{$lw}) { } 137 1404 1541
elsif (exists $_SH_CLOSE{$lw}) { } 82 1322 1404
362 82 elsif (exists $_SH_CLOSE{$lw}) { $delta-- }
363 # do/then/else/elif keep the FOLLOWING word in command position so
364 # that an opener directly after them (e.g. "do for ...") is counted.
365 1541 ▶ $cmdpos = ($lw eq 'do' || $lw eq 'then'
Branch: 1 branch
BranchTrueFalseTotal
$lw eq 'do' || $lw eq 'then' || $lw eq 'else' || $lw eq 'elif' ? : 131 1410 1541
Condition100%9/9
$lw eq "do" or $lw eq "then" or $lw eq "else" or $lw eq "elif"
l!l&&r!l&&!r
12651410
$lw eq "do" or $lw eq "then" or $lw eq "else"
l!l&&r!l&&!r
12331415
$lw eq "do" or $lw eq "then"
l!l&&r!l&&!r
76471418
MC/DC100%4/4
$lw eq "do" or $lw eq "then" or $lw eq "else" or $lw eq "elif"
$lw eq "do" $lw eq "then" $lw eq "else" $lw eq "elif"
Truth table100%5/5
A or B or C or D
A= $lw eq "do"B= $lw eq "then"C= $lw eq "else"D= $lw eq "elif"
ABCDresult
1XXX1
01XX1
001X1
00011
00000
366 || $lw eq 'else' || $lw eq 'elif') ? 1 : 0;
367 }
368 else {
369 1359 $cmdpos = 0;
370 }
371 }
372 1024 return $delta;
373 }
374  
375 ###############################################################################
376 # Subroutine extraction
377 ###############################################################################
378 593 ▶sub _extract_subroutines {
Subroutine _extract_subroutines: called CC=16 SCAR=27.8
379 593 my (@lines) = @_;
380 593 my @out = (); my $in_sub = ''; my @sub_body = ();
381  
382 # Determine which :LABEL lines are subroutine ENTRY points (to be lifted
383 # out of the main stream and stored in %_SUBROUTINES) versus ordinary
384 # GOTO labels (which stay in the stream for the CMD interpreter).
385 #
386 # Two independent signals are unioned:
387 #
388 # (a) CALL targets: any label named by a "CALL :LABEL" anywhere in the
389 # script is an entry point. This is the decisive signal -- a label
390 # you CALL is a subroutine -- and it lets a subroutine contain its
391 # own internal GOTO labels without being mis-split.
392 #
393 # (b) The RET heuristic: a label whose block ends in RET/RETURN before
394 # the next label. Kept for backward compatibility so a subroutine
395 # invoked only indirectly is still recognised.
396 #
397 # A label is opened as a subroutine ONLY at the top level (not while
398 # already inside a subroutine body); once inside a body, every :LABEL is
399 # an internal label that travels with the body so that GOTO within the
400 # subroutine resolves, and only RET/RETURN closes the body.
401 593 my %is_sub_label = ();
402  
403 # (a) CALL targets (matched anywhere on the line, e.g. "IF .. CALL :X").
404 593 for my $line (@lines) {
405 2561 (my $s = $line) =~ s/\r?\n\z//;
406 2561 ▶ while ($s =~ /\bCALL\s+:([A-Za-z_][A-Za-z0-9_]*)/ig) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s =~ /\bCALL\s+:([A-Za-z_][A-Za-z0-9_]*)/gi) 48 2561 2609
407 48 $is_sub_label{uc($1)} = 1;
408 }
409 }
410  
411 # (b) RET heuristic.
412 {
413 593 my $cur = '';
414 593 for my $line (@lines) {
415 2561 (my $s = $line) =~ s/\r?\n\z//;
416 2561 $s =~ s/\A\s+//;
417 2561 ▶ if ($s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/) {
Branch: 3 branches
BranchTrueFalseTotal
if ($s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/) { } 80 2481 2561
elsif ($cur ne '' and $s =~ /\A(?:RET|RETURN)\s*\z/i) { } 32 2449 2481
elsif ($cur ne '' and $s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/) { } 0 4593 4593
418 80 $cur = uc($1);
419 }
420 ▶ elsif ($cur ne '' && $s =~ /\A(?:RET|RETURN)\s*\z/i) {
Condition100%3/3
$cur ne "" and $s =~ /\A(?:RET|RETURN)\s*\z/i
!ll&&!rl&&r
214430532
MC/DC100%2/2
$cur ne "" and $s =~ /\A(?:RET|RETURN)\s*\z/i
$cur ne "" $s =~ /\A(?:RET|RETURN)\s*\z/i
Truth table100%3/3
A and B
A= $cur ne ""B= $s =~ /\A(?:RET|RETURN)\s*\z/i
ABresult
0X0
100
111
421 32 $is_sub_label{$cur} = 1;
422 32 $cur = '';
423 }
424 ▶ elsif ($cur ne '' && $s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/) {
Condition66%2/3
$cur ne "" and $s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/
!ll&&!rl&&r
21443050
MC/DC0%0/2
$cur ne "" and $s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/
$cur ne "" $s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/
Truth table66%2/3
A and B
A= $cur ne ""B= $s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/
ABresult
0X0
100
111
425 # New label before RET: previous one is a GOTO label, not sub
426 0 $cur = uc($1);
427 }
428 }
429 }
430  
431 593 for my $line (@lines) {
432 2561 (my $s = $line) =~ s/\r?\n\z//;
433 2561 $s =~ s/\A\s+//;
434 2561 ▶ if ($s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/) 80 2481 2561
435 80 my $lbl = uc($1);
436 80 ▶ if ($in_sub ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($in_sub ne "") 17 63 80
437 # Inside a subroutine: this is an internal label of the body
438 # (a GOTO target), not a new subroutine. Keep it with the
439 # body so the CMD interpreter can resolve GOTO :internal.
440 17 push @sub_body, $line;
441 17 next;
442 }
443 63 ▶ if ($is_sub_label{$lbl}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_sub_label{$lbl}) 32 31 63
444 # Top-level subroutine entry: lift it out of the main stream.
445 32 $in_sub = $lbl; @sub_body = ();
446 32 next; # remove the entry-label line from the stream
447 }
448 # Top-level GOTO label: keep in stream for the CMD interpreter.
449 31 push @out, $line;
450 31 next;
451 }
452 2481 ▶ if ($in_sub ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($in_sub ne "") 112 2369 2481
453 112 ▶ if ($s =~ /\A(?:RET|RETURN)\s*\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s =~ /\A(?:RET|RETURN)\s*\z/i) { } 32 80 112
454 32 $_SUBROUTINES{$in_sub} = [@sub_body];
455 32 $in_sub = ''; @sub_body = ();
456 }
457 else {
458 80 push @sub_body, $line;
459 }
460 112 next;
461 }
462 2369 push @out, $line;
463 }
464 593 ▶ $_SUBROUTINES{$in_sub} = [@sub_body] if $in_sub ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $in_sub ne "" 0 593 593
465 593 return @out;
466 }
467  
468 ###############################################################################
469 # call_sub / source_file
470 ###############################################################################
471 39 ▶sub call_sub {
Subroutine call_sub: called CC=11 SCAR=24.0
Pod undocumented
472 39 my ($class_or_self, $label, @args) = @_;
473 39 $label = uc($label); $label =~ s/^://;
474 croak "BATsh->call_sub: undefined subroutine :$label"
475 39 ▶ unless exists $_SUBROUTINES{$label};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $_SUBROUTINES{$label} 0 39 39
476  
477 # --- Save the caller's positional-parameter frame -----------------
478 # CALL :label is a true subroutine call: the callee gets its own
479 # %0..%9 / %* (and the SH-side BATSH_ARG* mirror), and the caller's
480 # parameters are restored on return. An undef snapshot means the key
481 # was absent and must be removed again on restore.
482 39 my @frame_keys = ('%0', '%1', '%2', '%3', '%4', '%5',
483 '%6', '%7', '%8', '%9', '%*',
484 'BATSH_ARGC',
485 'BATSH_ARG1', 'BATSH_ARG2', 'BATSH_ARG3',
486 'BATSH_ARG4', 'BATSH_ARG5', 'BATSH_ARG6',
487 'BATSH_ARG7', 'BATSH_ARG8', 'BATSH_ARG9');
488 39 my %saved;
489 39 for my $k (@frame_keys) {
490 819 ▶ $saved{$k} = exists $BATsh::Env::STORE{$k} ? $BATsh::Env::STORE{$k}
Branch: 1 branch
BranchTrueFalseTotal
exists $BATsh::Env::STORE{$k} ? : 424 395 819
491 : undef;
492 }
493  
494 # --- Install the subroutine's own arguments -----------------------
495 # %0 is the label token (":LABEL"), matching cmd.exe, so that %~..0
496 # modifiers and %0 inside the subroutine refer to the label, not the
497 # outer script. %1..%9 are the call arguments; %* is their join.
498 39 BATsh::Env->set('%0', ":$label");
499 39 for my $n (1 .. 9) {
500 351 ▶ BATsh::Env->set("%$n", defined($args[$n-1]) ? $args[$n-1] : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $args[$n - 1] ? : 57 294 351
501 }
502 39 BATsh::Env->set('%*', join(' ', @args));
503  
504 # SH-side mirror so a subroutine body written in SH mode still sees
505 # $1..$9 / $@. Keys beyond the supplied argument count are removed so
506 # a shorter call does not inherit the caller's stale BATSH_ARG* values.
507 39 $BATsh::Env::STORE{'BATSH_ARGC'} = scalar @args;
508 39 for my $n (1 .. 9) {
509 351 ▶ if ($n <= scalar @args) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n <= scalar @args) { } 57 294 351
510 57 $BATsh::Env::STORE{"BATSH_ARG$n"} = $args[$n-1];
511 }
512 else {
513 294 delete $BATsh::Env::STORE{"BATSH_ARG$n"};
514 }
515 }
516  
517 # --- Run the body, then always restore the caller frame -----------
518 39 my $ok = eval { _process_lines(@{$_SUBROUTINES{$label}}); 1 };
519 39 my $err = $@;
520 39 for my $k (@frame_keys) {
521 819 ▶ if (defined $saved{$k}) { $BATsh::Env::STORE{$k} = $saved{$k} }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $saved{$k}) { } 424 395 819
522 395 else { delete $BATsh::Env::STORE{$k} }
523 }
524 39 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 39 39
525 39 return 1;
526 }
527  
528 5 ▶sub source_file {
Subroutine source_file: called CC=3 SCAR=11.1
Pod undocumented
529 5 my ($class_or_self, $file) = @_;
530 # The filename may arrive guard-transformed (from a CALL/source line
531 # inside a DBCS script); un-guard it before touching the filesystem.
532 5 $file = BATsh::MB::dec($file);
533 5 ▶ croak "BATsh->source_file: file not found: $file" unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 0 5 5
534 5 local *SFHH;
535 5 ▶ open(SFHH, $file) or croak "BATsh->source_file: cannot open $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open SFHH, $file or croak("BATsh->source_file: cannot open ${file}: $!") 5 0 5
536 5 my @src = <SFHH>;
537 5 close(SFHH);
538 5 _prepare_source(\@src, undef);
539 5 _process_lines(@src);
540 5 return 1;
541 }
542  
543 ###############################################################################
544 # SETLOCAL / ENDLOCAL (public API)
545 ###############################################################################
546 0 ▶sub setlocal { BATsh::Env::setlocal() }
Subroutine setlocal: not called CC=1 SCAR=6.9
Pod undocumented
547 0 ▶sub endlocal { BATsh::Env::endlocal() }
Subroutine endlocal: not called CC=1 SCAR=6.9
Pod undocumented
548  
549 ###############################################################################
550 # _exec_cmd_section -- run CMD lines through BATsh::CMD
551 ###############################################################################
552 158 ▶sub _exec_cmd_section {
Subroutine _exec_cmd_section: called CC=7 SCAR=19.6
553 158 my (@lines) = @_;
554 158 ▶ return if defined $_SCRIPT_EXIT; # exit/EXIT already executed
Branch: 1 branch
BranchTrueFalseTotal
if defined $_SCRIPT_EXIT 0 158 158
555 # Handle BATsh-native directives before CMD interpreter
556 158 my @batch = ();
557 158 for my $line (@lines) {
558 709 (my $s = $line) =~ s/\r?\n\z//;
559 709 $s =~ s/\A\s+//;
560 709 ▶ if ($s =~ /\ASETLOCAL(?:\s+(.*))?\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s =~ /\ASETLOCAL(?:\s+(.*))?\z/i) 8 701 709
561 8 ▶ my $opts = defined $1 ? $1 : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $1 ? : 0 8 8
562 # Pass the whole line through to CMD interpreter so it sees
563 # ENABLEDELAYEDEXPANSION etc; also update Env flags here.
564 8 push @batch, $line;
565 8 next;
566 }
567 701 ▶ if ($s =~ /\AENDLOCAL\s*\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s =~ /\AENDLOCAL\s*\z/i) 8 693 701
568 # Handled inside CMD.pm / _dispatch
569 8 push @batch, $line;
570 8 next;
571 }
572 # NOTE: CALL :label and CALL file.batsh are intentionally NOT
573 # intercepted here. They are handled by the CMD interpreter's
574 # _cmd_call (which delegates to call_sub / source_file). Letting
575 # CALL stay inside the batch keeps the whole CMD section in one
576 # exec_block, so a GOTO whose loop body contains a CALL still finds
577 # its label, and a subroutine body may use its own internal labels.
578 693 push @batch, $line;
579 }
580 158 ▶ _flush_cmd(\@batch) if @batch;
Branch: 1 branch
BranchTrueFalseTotal
if @batch 158 0 158
581 }
582  
583 158 ▶sub _flush_cmd {
Subroutine _flush_cmd: called CC=4 SCAR=14.0
584 158 my ($lines_ref) = @_;
585 158 ▶ return unless @{$lines_ref};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$lines_ref;} 0 158 158
586 158 ▶ return if defined $_SCRIPT_EXIT;
Branch: 1 branch
BranchTrueFalseTotal
if defined $_SCRIPT_EXIT 0 158 158
587 158 BATsh::CMD::exec_block('BATsh::CMD', $lines_ref,
588 _batsh => __PACKAGE__,
589 _pushd_stack => [],
590 );
591 # Status bridge: mirror the CMD-side ERRORLEVEL into the SH-side $?
592 # so the next SH section sees the outcome of this CMD section.
593 158 BATsh::SH::set_status(BATsh::CMD::_get_errorlevel());
594 # EXIT executed: terminate the whole script with ERRORLEVEL.
595 158 ▶ if (BATsh::CMD::_exit_requested()) {
Branch: 1 branch
BranchTrueFalseTotal
if (BATsh::CMD::_exit_requested()) 6 152 158
596 6 BATsh::CMD::_clear_exit_requested();
597 6 $_SCRIPT_EXIT = BATsh::CMD::_get_errorlevel();
598 }
599 }
600  
601 ###############################################################################
602 # _exec_sh_section -- run SH lines through BATsh::SH
603 ###############################################################################
604 503 ▶sub _exec_sh_section {
Subroutine _exec_sh_section: called CC=8 SCAR=21.0
605 503 my (@lines) = @_;
606 503 ▶ return if defined $_SCRIPT_EXIT; # exit/EXIT already executed
Branch: 1 branch
BranchTrueFalseTotal
if defined $_SCRIPT_EXIT 1 502 503
607 502 my @batch = ();
608 502 for my $line (@lines) {
609 1665 (my $s = $line) =~ s/\r?\n\z//;
610 1665 $s =~ s/\A\s+//;
611 # Fast path: a PLAIN literal ".batsh" operand is sourced here, so
612 # that the sourced file is seen as a bilingual script rather than
613 # as a batch of SH lines. The operand must be anchored and free
614 # of quotes, $ and backticks: a quoted or expandable operand --
615 # source "$dir/init.batsh" . 'my script.batsh'
616 # -- has to reach BATsh::SH::_cmd_source() instead, which is the
617 # only place where expansion and dequoting have happened. Before
618 # 0.11 the pattern was unanchored, so a quoted operand matched
619 # here with its opening quote still attached and source_file()
620 # was handed a name that could not exist.
621 1665 ▶ if ($s =~ /\A(?:source|\.)\s+(\S+\.batsh)\s*\z/ && $1 !~ /["'\$`]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s =~ /\A(?:source|\.)\s+(\S+\.batsh)\s*\z/ and not $1 =~ /["'\$`]/) 1 1664 1665
Condition66%2/3
$s =~ /\A(?:source|\.)\s+(\S+\.batsh)\s*\z/ and not $1 =~ /["'\$`]/
!ll&&!rl&&r
166401
MC/DC50%1/2
$s =~ /\A(?:source|\.)\s+(\S+\.batsh)\s*\z/ and not $1 =~ /["'\$`]/
$s =~ /\A(?:source|\.)\s+(\S+\.batsh)\s*\z/ not $1 =~ /["'\$`]/
Truth table66%2/3
A and not(B)
A= $s =~ /\A(?:source|\.)\s+(\S+\.batsh)\s*\z/B= not $1 =~ /["'\$`]/
ABresult
0X0
100
111
622 1 my $bfile = $1;
623 1 ▶ _flush_sh(\@batch) if @batch; @batch = ();
Branch: 1 branch
BranchTrueFalseTotal
if @batch 0 1 1
624 1 eval { source_file('', $bfile) };
625 1 ▶ warn $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
626 1 next;
627 }
628 1664 push @batch, $line;
629 }
630 502 ▶ _flush_sh(\@batch) if @batch;
Branch: 1 branch
BranchTrueFalseTotal
if @batch 502 0 502
631 }
632  
633 502 ▶sub _flush_sh {
Subroutine _flush_sh: called CC=4 SCAR=13.9
634 502 my ($lines_ref) = @_;
635 502 ▶ return unless @{$lines_ref};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$lines_ref;} 0 502 502
636 502 ▶ return if defined $_SCRIPT_EXIT;
Branch: 1 branch
BranchTrueFalseTotal
if defined $_SCRIPT_EXIT 1 501 502
637 501 BATsh::SH::exec_block('BATsh::SH', $lines_ref,
638 _batsh => __PACKAGE__,
639 );
640 # Status bridge: mirror the SH-side $? into the CMD-side ERRORLEVEL
641 # so the next CMD section sees the outcome of this SH section
642 # (ECHO %ERRORLEVEL%, IF ERRORLEVEL n, ...).
643 501 BATsh::CMD::_set_errorlevel(BATsh::SH::get_status());
644 # exit executed: terminate the whole script with its code.
645 501 my $ec = BATsh::SH::exit_code_pending();
646 501 ▶ $_SCRIPT_EXIT = $ec if defined $ec;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ec 26 475 501
647 }
648  
649 ###############################################################################
650 # _process_lines -- main dispatcher
651 ###############################################################################
652 593 ▶sub _process_lines {
Subroutine _process_lines: called CC=22 SCAR=30.9
653 593 my (@source) = @_;
654 593 @source = _extract_subroutines(@source);
655  
656 593 my @pending = (); my $cur_mode = ''; my $depth = 0;
657  
658 # Here-document tracking: while a here-document body is being collected,
659 # body lines are appended to the current section verbatim and are NOT
660 # reclassified (so an uppercase-leading body line is not misrouted to CMD).
661 # Activation is deferred by one line so the trigger line itself is
662 # classified normally.
663 593 my $hd_delim = undef; # active delimiter (collecting body)
664 593 my $hd_dash = 0;
665 593 my $pending_hd_delim = undef; # set on the trigger line, activated next iter
666 593 my $pending_hd_dash = 0;
667  
668 593 for my $raw (@source) {
669 2400 chomp $raw;
670  
671 # Promote a pending here-document to active (trigger line already pushed)
672 2400 ▶ if (defined $pending_hd_delim) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pending_hd_delim) 13 2387 2400
673 13 $hd_delim = $pending_hd_delim;
674 13 $hd_dash = $pending_hd_dash;
675 13 $pending_hd_delim = undef;
676 }
677  
678 # Collecting a here-document body: pass through unclassified.
679 2400 ▶ if (defined $hd_delim) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $hd_delim) 29 2371 2400
680 29 push @pending, $raw;
681 29 my $probe = $raw;
682 29 ▶ $probe =~ s/\A\t+// if $hd_dash;
Branch: 1 branch
BranchTrueFalseTotal
if $hd_dash 2 27 29
683 29 ▶ $hd_delim = undef if $probe eq $hd_delim;
Branch: 1 branch
BranchTrueFalseTotal
if $probe eq $hd_delim 12 17 29
684 29 next;
685 }
686  
687 2371 my ($mode, $line, $first) = _parse_line($raw);
688  
689 # Detect a here-document opener on an SH line; defer activation so the
690 # trigger line is classified normally this iteration.
691 2371 ▶ if ($mode eq 'SH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "SH") 1219 1152 2371
692 1219 my @hd = BATsh::SH::_hd_detect($raw);
693 1219 ▶ if (@hd) {
Branch: 1 branch
BranchTrueFalseTotal
if (@hd) 13 1206 1219
694 13 $pending_hd_delim = $hd[2];
695 13 $pending_hd_dash = $hd[1];
696 }
697 }
698  
699 2371 ▶ if ($mode eq 'EMPTY' || $mode eq 'COMMENT') {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "EMPTY" or $mode eq "COMMENT") 636 1735 2371
Condition100%3/3
$mode eq "EMPTY" or $mode eq "COMMENT"
l!l&&r!l&&!r
3462901735
MC/DC100%2/2
$mode eq "EMPTY" or $mode eq "COMMENT"
$mode eq "EMPTY" $mode eq "COMMENT"
Truth table100%3/3
A or B
A= $mode eq "EMPTY"B= $mode eq "COMMENT"
ABresult
1X1
011
000
700 # A comment carries no execution effect, so it must never be handed
701 # to an interpreter verbatim. A CMD-style comment (":: ..." or
702 # "REM ...") carried into an SH section would be dispatched to the
703 # external shell (SH treats only "#" as a comment), and any "( )" or
704 # other shell metacharacter in the comment then makes /bin/sh fail
705 # with a syntax error. The reverse ("# ..." into CMD) is likewise
706 # not a CMD comment. Routing it as a BLANK line is skipped
707 # identically by both interpreters and in every nesting depth, and
708 # avoids the real cmd.exe quirk of "::" inside a "( )" block.
709 636 ▶ push @pending, '' if $cur_mode ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $cur_mode ne "" 605 31 636
710 636 next;
711 }
712  
713 1735 ▶ if ($cur_mode eq '') {
Branch: 2 branches
BranchTrueFalseTotal
if ($cur_mode eq '') { } 593 1142 1735
elsif ($mode eq $cur_mode) { } 1053 89 1142
714 593 $cur_mode = $mode; $depth = 0;
715 593 push @pending, $line;
716 593 ▶ $depth += ($mode eq 'CMD') ? _cmd_paren_delta($line) : _sh_depth_delta($line);
Branch: 1 branch
BranchTrueFalseTotal
$mode eq 'CMD' ? : 124 469 593
717 }
718 elsif ($mode eq $cur_mode) {
719 1053 push @pending, $line;
720 1053 ▶ $depth += ($mode eq 'CMD') ? _cmd_paren_delta($line) : _sh_depth_delta($line);
Branch: 1 branch
BranchTrueFalseTotal
$mode eq 'CMD' ? : 360 693 1053
721 1053 ▶ $depth = 0 if $depth < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $depth < 0 0 1053 1053
722 }
723 else {
724 89 ▶ if ($depth > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($depth > 0) { } 28 61 89
725 28 push @pending, $line;
726 28 ▶ $depth += ($cur_mode eq 'CMD') ? _cmd_paren_delta($line) : _sh_depth_delta($line);
Branch: 1 branch
BranchTrueFalseTotal
$cur_mode eq 'CMD' ? : 28 0 28
727 28 ▶ $depth = 0 if $depth < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $depth < 0 0 28 28
728 }
729 else {
730 61 ▶ _flush_section($cur_mode, @pending) if @pending;
Branch: 1 branch
BranchTrueFalseTotal
if @pending 61 0 61
731 61 @pending = ($line); $cur_mode = $mode; $depth = 0;
732 61 ▶ $depth += ($mode eq 'CMD') ? _cmd_paren_delta($line) : _sh_depth_delta($line);
Branch: 1 branch
BranchTrueFalseTotal
$mode eq 'CMD' ? : 32 29 61
733 }
734 }
735 }
736 593 ▶ _flush_section($cur_mode, @pending) if @pending;
Branch: 1 branch
BranchTrueFalseTotal
if @pending 593 0 593
737 }
738  
739 661 ▶sub _flush_section {
Subroutine _flush_section: called CC=3 SCAR=11.0
740 661 my ($mode, @lines) = @_;
741 661 ▶ return unless @lines;
Branch: 1 branch
BranchTrueFalseTotal
unless @lines 0 661 661
742 661 ▶ if ($mode eq 'CMD') { _exec_cmd_section(@lines) }
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq 'CMD') { } 158 503 661
743 503 else { _exec_sh_section(@lines) }
744 }
745  
746 ###############################################################################
747 # REPL
748 ###############################################################################
749 5 ▶sub repl {
Subroutine repl: called CC=24 SCAR=41.8
Pod undocumented
750 5 my ($class_or_self) = @_;
751 5 _ensure_env_init();
752 5 $_SCRIPT_EXIT = undef;
753 5 ▶ BATsh::SH::reset_sh_options() if defined &BATsh::SH::reset_sh_options;
Branch: 1 branch
BranchTrueFalseTotal
if defined &BATsh::SH::reset_sh_options 5 0 5
754 5 print "BATsh $VERSION - Bilingual Shell\n";
755 5 print "Uppercase => CMD mode, lowercase => SH mode. EXIT/exit to quit.\n\n";
756  
757 # One statement per variable: in a "my" list an array is greedy and
758 # swallows the whole right-hand side, so "my (@buf, $depth, $cur_mode)
759 # = ((), 0, '')" would leave @buf = (0, '') and both scalars undef.
760 5 my @buf = ();
761 5 my $depth = 0;
762 5 my $cur_mode = '';
763 5 my ($hd_delim, $hd_dash, $pending_hd_delim, $pending_hd_dash)
764 = (undef, 0, undef, 0);
765 5 while (1) {
766 11 ▶ print $depth > 0 || defined($hd_delim) ? ' +> ' : 'BATsh> ';
Branch: 1 branch
BranchTrueFalseTotal
$depth > 0 || defined $hd_delim ? : 0 11 11
Condition33%1/3
$depth > 0 or defined $hd_delim
l!l&&r!l&&!r
0011
MC/DC0%0/2
$depth > 0 or defined $hd_delim
$depth > 0 defined $hd_delim
Truth table33%1/3
A or B
A= $depth > 0B= defined $hd_delim
ABresult
1X1
011
000
767 11 my $line = <STDIN>;
768 11 ▶ last unless defined $line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 1 10 11
769 10 chomp $line;
770  
771 # Guard-transform DBCS input (auto-activates on first DBCS line)
772 10 BATsh::MB::activate_for($line);
773 10 $line = BATsh::MB::enc($line);
774  
775 # Promote pending here-document (trigger already buffered)
776 10 ▶ if (defined $pending_hd_delim) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pending_hd_delim) 0 10 10
777 0 $hd_delim = $pending_hd_delim; $hd_dash = $pending_hd_dash;
778 0 $pending_hd_delim = undef;
779 }
780 # Collecting here-document body: buffer verbatim, do not flush/classify
781 10 ▶ if (defined $hd_delim) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $hd_delim) 0 10 10
782 0 push @buf, $line;
783 0 my $probe = $line;
784 0 ▶ $probe =~ s/\A\t+// if $hd_dash;
Branch: 1 branch
BranchTrueFalseTotal
if $hd_dash 0 0 0
785 0 ▶ $hd_delim = undef if $probe eq $hd_delim;
Branch: 1 branch
BranchTrueFalseTotal
if $probe eq $hd_delim 0 0 0
786 0 ▶ if (!defined($hd_delim) && $depth == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $hd_delim and $depth == 0) 0 0 0
Condition0%0/3
not defined $hd_delim and $depth == 0
!ll&&!rl&&r
000
MC/DC0%0/2
not defined $hd_delim and $depth == 0
not defined $hd_delim $depth == 0
Truth table0%0/3
not(A) and B
A= not defined $hd_delimB= $depth == 0
ABresult
0X0
100
111
787 0 _flush_section($cur_mode, @buf);
788 0 @buf = (); $cur_mode = ''; $depth = 0;
789 0 ▶ last if defined $_SCRIPT_EXIT; # "exit N" ends the REPL
Branch: 1 branch
BranchTrueFalseTotal
if defined $_SCRIPT_EXIT 0 0 0
790 }
791 0 next;
792 }
793  
794 10 ▶ if ($line =~ /\A\s*(?:EXIT|exit)\s*\z/) { print "Bye.\n"; last }
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\A\s*(?:EXIT|exit)\s*\z/) 3 7 10
795 7 ▶ next if $depth == 0 && $line =~ /\A\s*\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $depth == 0 and $line =~ /\A\s*\z/ 0 7 7
Condition33%1/3
$depth == 0 and $line =~ /\A\s*\z/
!ll&&!rl&&r
070
MC/DC0%0/2
$depth == 0 and $line =~ /\A\s*\z/
$depth == 0 $line =~ /\A\s*\z/
Truth table33%1/3
A and B
A= $depth == 0B= $line =~ /\A\s*\z/
ABresult
0X0
100
111
796 7 push @buf, $line;
797 # (undef, ...) in a my list is a Perl 5.10 spelling; the list is
798 # taken as a whole and indexed instead, for 5.005_03.
799 7 my @parsed = _parse_line($line);
800 7 my $first = $parsed[2];
801 7 ▶ $cur_mode = classify_token($first) if $depth == 0 && $cur_mode eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $depth == 0 and $cur_mode eq "" 7 0 7
Condition33%1/3
$depth == 0 and $cur_mode eq ""
!ll&&!rl&&r
007
MC/DC0%0/2
$depth == 0 and $cur_mode eq ""
$depth == 0 $cur_mode eq ""
Truth table33%1/3
A and B
A= $depth == 0B= $cur_mode eq ""
ABresult
0X0
100
111
802 # Detect here-document opener (SH only); defer activation one line
803 7 ▶ if ($cur_mode eq 'SH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cur_mode eq "SH") 5 2 7
804 5 my @hd = BATsh::SH::_hd_detect($line);
805 0 ▶ if (@hd) { $pending_hd_delim = $hd[2]; $pending_hd_dash = $hd[1] }
Branch: 1 branch
BranchTrueFalseTotal
if (@hd) 0 5 5
806 }
807 7 ▶ $depth += ($cur_mode eq 'CMD') ? _cmd_paren_delta($line) : _sh_depth_delta($line);
Branch: 1 branch
BranchTrueFalseTotal
$cur_mode eq 'CMD' ? : 2 5 7
808 7 ▶ $depth = 0 if $depth < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $depth < 0 0 7 7
809 7 ▶ if ($depth == 0 && !defined($pending_hd_delim)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($depth == 0 and not defined $pending_hd_delim) 7 0 7
Condition33%1/3
$depth == 0 and not defined $pending_hd_delim
!ll&&!rl&&r
007
MC/DC0%0/2
$depth == 0 and not defined $pending_hd_delim
$depth == 0 not defined $pending_hd_delim
Truth table33%1/3
A and not(B)
A= $depth == 0B= not defined $pending_hd_delim
ABresult
0X0
100
111
810 7 _flush_section($cur_mode, @buf);
811 7 @buf = (); $cur_mode = ''; $depth = 0;
812 7 ▶ last if defined $_SCRIPT_EXIT; # "exit N" / "EXIT N" ends the REPL
Branch: 1 branch
BranchTrueFalseTotal
if defined $_SCRIPT_EXIT 1 6 7
813 }
814 }
815 5 return _final_status();
816 }
817  
818 ###############################################################################
819 # Accessors
820 ###############################################################################
821 0 ▶sub version { return $VERSION }
Subroutine version: not called CC=1 SCAR=6.9
Pod undocumented
822 2 ▶sub sh_available { return 1 } # always: built-in SH interpreter
Subroutine sh_available: called CC=1 SCAR=0.0
Pod undocumented
823  
824 ###############################################################################
825 # main -- command-line entry point (used by bin/batsh.pl and the modulino).
826 # Returns the process exit code.
827 ###############################################################################
828 29 ▶sub main {
Subroutine main: called CC=15 SCAR=27.2
Pod undocumented
829 29 my ($class_or_self, @argv) = @_;
830 29 BATsh::Env::init();
831 # --encoding=ENC / --encoding ENC : cp932 sjis gbk uhc big5 utf8 none auto
832 29 ▶ while (@argv && $argv[0] =~ /\A--encoding(?:=(.*))?\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (@argv and $argv[0] =~ /\A--encoding(?:=(.*))?\z/) 1 28 29
Condition100%3/3
@argv and $argv[0] =~ /\A--encoding(?:=(.*))?\z/
!ll&&!rl&&r
5231
MC/DC100%2/2
@argv and $argv[0] =~ /\A--encoding(?:=(.*))?\z/
@argv $argv[0] =~ /\A--encoding(?:=(.*))?\z/
Truth table100%3/3
A and B
A= @argvB= $argv[0] =~ /\A--encoding(?:=(.*))?\z/
ABresult
0X0
100
111
833 1 my $e = $1;
834 1 shift @argv;
835 1 ▶ $e = shift @argv if !defined $e && @argv;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $e and @argv 0 1 1
Condition33%1/3
not defined $e and @argv
!ll&&!rl&&r
100
MC/DC0%0/2
not defined $e and @argv
not defined $e @argv
Truth table33%1/3
not(A) and B
A= not defined $eB= @argv
ABresult
0X0
100
111
836 1 ▶ BATsh->set_encoding($e) if defined $e;
Branch: 1 branch
BranchTrueFalseTotal
if defined $e 1 0 1
837 }
838 28 ▶ if (@argv && ($argv[0] eq '--version' || $argv[0] eq '-v')) {
Branch: 1 branch
BranchTrueFalseTotal
if (@argv and $argv[0] eq "--version" || $argv[0] eq "-v") 1 27 28
Condition83%5/6
@argv and $argv[0] eq "--version" || $argv[0] eq "-v"
!ll&&!rl&&r
5221
$argv[0] eq "--version" or $argv[0] eq "-v"
l!l&&r!l&&!r
1022
MC/DC66%2/3
@argv and $argv[0] eq "--version" || $argv[0] eq "-v"
@argv $argv[0] eq "--version" $argv[0] eq "-v"
Truth table75%3/4
A and B or C
A= @argvB= $argv[0] eq "--version"C= $argv[0] eq "-v"
ABCresult
0XX0
1000
11X1
1011
839 1 print "BATsh $VERSION\n";
840 1 return 0;
841 }
842 27 ▶ if (@argv && ($argv[0] eq '--help' || $argv[0] eq '-h')) {
Branch: 1 branch
BranchTrueFalseTotal
if (@argv and $argv[0] eq "--help" || $argv[0] eq "-h") 1 26 27
Condition83%5/6
@argv and $argv[0] eq "--help" || $argv[0] eq "-h"
!ll&&!rl&&r
5211
$argv[0] eq "--help" or $argv[0] eq "-h"
l!l&&r!l&&!r
1021
MC/DC66%2/3
@argv and $argv[0] eq "--help" || $argv[0] eq "-h"
@argv $argv[0] eq "--help" $argv[0] eq "-h"
Truth table75%3/4
A and B or C
A= @argvB= $argv[0] eq "--help"C= $argv[0] eq "-h"
ABCresult
0XX0
1000
11X1
1011
843 1 print <<"END_OF_USAGE";
844 usage: batsh.pl [--encoding=ENC] script.batsh [args...]
845 batsh.pl [--encoding=ENC] - (read the script from STDIN)
846 batsh.pl [--encoding=ENC] -e 'source' (run inline source)
847 batsh.pl (interactive REPL)
848 batsh.pl --version | --help
849  
850 The installed name is batsh.pl; on Windows MakeMaker's pl2bat also
851 provides batsh.
852 ENC: cp932 sjis gbk uhc big5 utf8 none auto (default: auto)
853 The process exit code is the script's exit code (exit N / EXIT [/B] N,
854 or the status of the last command).
855 END_OF_USAGE
856 1 return 0;
857 }
858 26 ▶ if (@argv == 0) { return BATsh->repl() }
Branch: 1 branch
BranchTrueFalseTotal
if (@argv == 0) 5 21 26
859 21 ▶ if ($argv[0] eq '-e') {
Branch: 1 branch
BranchTrueFalseTotal
if ($argv[0] eq "-e") 2 19 21
860 2 shift @argv;
861 2 return BATsh->run_string(join("\n", @argv));
862 }
863 19 ▶ if ($argv[0] eq '-') {
Branch: 1 branch
BranchTrueFalseTotal
if ($argv[0] eq "-") 2 17 19
864 2 shift @argv;
865 2 my @lines = <STDIN>;
866 2 return BATsh->run_string(join('', @lines),
867 script_name => '-', args => [@argv]);
868 }
869 17 my $f = shift @argv;
870 17 return BATsh->run($f, args => [@argv]);
871 }
872  
873 ###############################################################################
874 # Run as script
875 ###############################################################################
876 61 ▶unless (caller) {
Branch: 1 branch
BranchTrueFalseTotal
unless (caller) 0 61 61
877 0 exit(BATsh->main(@ARGV));
878 }
879  
880 61 1;
881  
882 __END__
« lib/BATsh/CMD.pm ↑ Summary lib/BATsh/MB.pm »