| 1 | package BATsh::CMD; | ||
| 2 | # Copyright (c) 2026 INABA Hitoshi <ina.cpan@gmail.com> | ||
| 3 | ###################################################################### | ||
| 4 | # | ||
| 5 | # BATsh::CMD - Pure Perl cmd.exe interpreter | ||
| 6 | # | ||
| 7 | # v0.02 changes (cmd.exe compatibility fixes): | ||
| 8 | # 1. Environment variable case-insensitivity (via Env.pm) | ||
| 9 | # 2. ^ escape character: protects & | < > and line continuation | ||
| 10 | # 3. Redirect/pipe: > >> 2> 2>> < | parsed before dispatch | ||
| 11 | # 4. SETLOCAL ENABLEDELAYEDEXPANSION + !VAR! (via Env.pm) | ||
| 12 | # 5. IF block pre-expansion: entire IF block expanded at parse time | ||
| 13 | # (matching cmd.exe's "parse before execute" semantics) | ||
| 14 | # 6. FOR /F: tokens= delims= skip= eol= usebackq | ||
| 15 | # 7. IF /I must be parsed BEFORE plain == to avoid shadowing | ||
| 16 | # 8. ECHO no longer resets ERRORLEVEL | ||
| 17 | # 9. SETLOCAL passes option string to Env::setlocal() | ||
| 18 | # 10. IF EXIST handles quoted paths with spaces | ||
| 19 | # 11. Pipeline (|): _split_compound detects |, _exec_pipe chains via tmpfile | ||
| 20 | # 12. SET /P VAR=Prompt: reads one line from STDIN | ||
| 21 | # 13. SHIFT / SHIFT /N: shifts %1..%9 and rebuilds %* (dispatched builtin) | ||
| 22 | # 14. Batch-parameter tilde modifiers via Env::expand_cmd(): | ||
| 23 | # %~0 %~f1 %~d0 %~p0 %~n1 %~x1 %~dp0 %~nx1 (f d p n x combinable), | ||
| 24 | # and on CALL :label arguments once they populate %1..%9 | ||
| 25 | # 15. & && || compound commands (_exec_compound) | ||
| 26 | # 16. %0..%9 and %* positional parameter expansion in expand_cmd() | ||
| 27 | # 17. CALL :label arg1 arg2: installs the subroutine's own %0..%9 / %* | ||
| 28 | # (quote-aware, %-expanded) via BATsh->call_sub, which saves and | ||
| 29 | # restores the caller's positional-parameter frame | ||
| 30 | # | ||
| 31 | ###################################################################### | ||
| 32 | |||
| 33 | use strict; | ||
| 34 | BEGIN { if ($] < 5.006 && !defined(&warnings::import)) { $INC{'warnings.pm'} = 'stub'; eval 'package warnings; sub import {}' } } | ||
| 35 | use warnings; local $^W = 1; | ||
| 36 | BEGIN { pop @INC if $INC[-1] eq '.' } | ||
| 37 | |||
| 38 | use File::Spec (); | ||
| 39 | use File::Copy (); | ||
| 40 | use File::Path (); | ||
| 41 | use Carp qw(croak); | ||
| 42 | use vars qw($VERSION); | ||
| 43 | $VERSION = '0.09'; | ||
| 44 | $VERSION = $VERSION; | ||
| 45 | |||
| 46 | require BATsh::Env; | ||
| 47 | require BATsh::MB; | ||
| 48 | # For BATsh::SH::_glob_paths(): CMD-mode wildcards (FOR sets, DEL) are | ||
| 49 | # expanded by the same pure-Perl matcher the SH side uses, because Perl's | ||
| 50 | # built-in glob() reads a backslash as an escape and would destroy an | ||
| 51 | # ordinary Windows pattern such as C:\dir\*.txt. | ||
| 52 | require BATsh::SH; | ||
| 53 | |||
| 54 | # ---------------------------------------------------------------- | ||
| 55 | # Module-level state | ||
| 56 | # ---------------------------------------------------------------- | ||
| 57 | my $ECHO_ON = 1; | ||
| 58 | my $ERRORLEVEL = 0; | ||
| 59 | my $_GOTO_LABEL = ''; | ||
| 60 | my $_EXIT_REQUESTED = 0; # set by EXIT; consumed by BATsh.pm (script exit) | ||
| 61 | |||
| 62 | # ---------------------------------------------------------------- | ||
| 63 | # Public: execute an array of CMD lines | ||
| 64 | # ---------------------------------------------------------------- | ||
| 65 | sub exec_block { | ||
| 66 | my ($class, $lines_ref, %opts) = @_; | ||
| 67 | my @lines = @{$lines_ref}; | ||
| 68 | |||
| 69 | # Preprocess: join ^ line-continuations | ||
| 70 | @lines = _join_continuations(@lines); | ||
| 71 | |||
| 72 | # Build label index | ||
| 73 | my %labels = (); | ||
| 74 | for my $i (0 .. $#lines) { | ||
| 75 | my $l = $lines[$i]; | ||
| 76 | $l =~ s/\r?\n\z//; | ||
| 77 | $l =~ s/\A\s+//; | ||
| 78 | if ($l =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/) { | ||
| 79 | $labels{uc($1)} = $i; | ||
| 80 | } | ||
| 81 | } | ||
| 82 | |||
| 83 | my $i = 0; | ||
| 84 | while ($i <= $#lines) { | ||
| 85 | my $raw = $lines[$i]; | ||
| 86 | $i++; | ||
| 87 | $raw =~ s/\r?\n\z//; | ||
| 88 | my $rc = _exec_line($class, $raw, \@lines, { %labels }, \$i, { %opts }); | ||
| 89 | |||
| 90 | if ($_GOTO_LABEL ne '') { | ||
| 91 | my $lbl = $_GOTO_LABEL; | ||
| 92 | $_GOTO_LABEL = ''; | ||
| 93 | if (exists $labels{$lbl}) { | ||
| 94 | $i = $labels{$lbl} + 1; | ||
| 95 | } | ||
| 96 | elsif ($lbl eq 'EOF') { | ||
| 97 | last; | ||
| 98 | } | ||
| 99 | else { | ||
| 100 | _warn("GOTO: label :$lbl not found"); | ||
| 101 | } | ||
| 102 | next; | ||
| 103 | } | ||
| 104 | if (defined $rc && $rc eq '__EXIT__') { | ||
| 105 | return $ERRORLEVEL; | ||
| 106 | } | ||
| 107 | } | ||
| 108 | return $ERRORLEVEL; | ||
| 109 | } | ||
| 110 | |||
| 111 | # ---------------------------------------------------------------- | ||
| 112 | # _get_errorlevel: public accessor for the current ERRORLEVEL value. | ||
| 113 | # Used by BATsh::Env::_expand_named_var for %ERRORLEVEL% expansion. | ||
| 114 | # ---------------------------------------------------------------- | ||
| 115 | sub _get_errorlevel { return $ERRORLEVEL } | ||
| 116 | |||
| 117 | # ---------------------------------------------------------------- | ||
| 118 | # _set_errorlevel: set ERRORLEVEL from outside the CMD interpreter. | ||
| 119 | # Used by BATsh.pm to bridge the SH-side $? into %ERRORLEVEL% at | ||
| 120 | # every SH->CMD section boundary. Call as a plain function. | ||
| 121 | # ---------------------------------------------------------------- | ||
| 122 | sub _set_errorlevel { | ||
| 123 | $ERRORLEVEL = defined $_[0] ? int($_[0]) : 0; | ||
| 124 | return $ERRORLEVEL; | ||
| 125 | } | ||
| 126 | |||
| 127 | # ---------------------------------------------------------------- | ||
| 128 | # _exit_requested / _clear_exit_requested: EXIT was executed in a CMD | ||
| 129 | # section. BATsh.pm polls the flag after each CMD block to terminate | ||
| 130 | # the whole script with ERRORLEVEL as the process exit code, then | ||
| 131 | # clears it. Call as plain functions. | ||
| 132 | # ---------------------------------------------------------------- | ||
| 133 | sub _exit_requested { return $_EXIT_REQUESTED } | ||
| 134 | sub _clear_exit_requested { $_EXIT_REQUESTED = 0; return 0 } | ||
| 135 | |||
| 136 | # ---------------------------------------------------------------- | ||
| 137 | # _join_continuations: merge lines ending with bare ^ (not ^^ or "^") | ||
| 138 | # cmd.exe rule: ^ at end-of-line (outside quotes) joins next line, | ||
| 139 | # consuming the ^ and leading whitespace of the next line. | ||
| 140 | # ---------------------------------------------------------------- | ||
| 141 | sub _join_continuations { | ||
| 142 | my @in = @_; | ||
| 143 | my @out; | ||
| 144 | my $i = 0; | ||
| 145 | while ($i <= $#in) { | ||
| 146 | my $line = $in[$i]; $i++; | ||
| 147 | $line =~ s/\r?\n\z//; | ||
| 148 | # Count unescaped ^ at end: odd count = continuation | ||
| 149 | while ($line =~ /\A((?:[^^]|\^\^)*)\^\z/) { | ||
| 150 | # Strip the trailing ^, append next line (minus leading ws) | ||
| 151 | $line = $1; | ||
| 152 | if ($i <= $#in) { | ||
| 153 | my $next = $in[$i]; $i++; | ||
| 154 | $next =~ s/\r?\n\z//; | ||
| 155 | $next =~ s/\A\s+//; | ||
| 156 | $line .= $next; | ||
| 157 | } | ||
| 158 | else { last } | ||
| 159 | } | ||
| 160 | push @out, $line; | ||
| 161 | } | ||
| 162 | return @out; | ||
| 163 | } | ||
| 164 | |||
| 165 | # ---------------------------------------------------------------- | ||
| 166 | # _unescape_caret: replace ^X with X (^ is escape char in cmd.exe) | ||
| 167 | # Called AFTER %VAR% expansion for non-block contexts. | ||
| 168 | # ---------------------------------------------------------------- | ||
| 169 | sub _unescape_caret { | ||
| 170 | my ($str) = @_; | ||
| 171 | $str =~ s/\^(.)/$1/g; | ||
| 172 | return $str; | ||
| 173 | } | ||
| 174 | |||
| 175 | # ---------------------------------------------------------------- | ||
| 176 | # Execute one logical line | ||
| 177 | # $pre_expanded: if true, skip %VAR% expansion (already done by FOR) | ||
| 178 | # $block_expanded: if true, skip expansion entirely (IF block body) | ||
| 179 | # ---------------------------------------------------------------- | ||
| 180 | sub _exec_line { | ||
| 181 | my ($class, $raw, $lines_ref, $labels_ref, $i_ref, $opts_ref, $pre_expanded) = @_; | ||
| 182 | $pre_expanded = 0 unless defined $pre_expanded; | ||
| 183 | |||
| 184 | my $line = $raw; | ||
| 185 | $line =~ s/\A\s+//; | ||
| 186 | |||
| 187 | my $suppress_echo = 0; | ||
| 188 | if ($line =~ s/\A\@//) { $suppress_echo = 1; } | ||
| 189 | |||
| 190 | return 0 if $line =~ /\A\s*\z/; | ||
| 191 | return 0 if $line =~ /\A::/; | ||
| 192 | return 0 if $line =~ /\AREM(?:\s|\z)/i; | ||
| 193 | return 0 if $line =~ /\A:[A-Za-z_]/; | ||
| 194 | return 0 if $line =~ /\A\s*\)\s*(?:ELSE\s*.*)??\s*\z/i; | ||
| 195 | return 0 if $line =~ /\A#/; | ||
| 196 | |||
| 197 | if (!$pre_expanded) { | ||
| 198 | $line = _expand_line($line); | ||
| 199 | } | ||
| 200 | elsif (BATsh::Env::delayed_expansion()) { | ||
| 201 | # Even in pre_expanded blocks, !VAR! must be expanded at runtime | ||
| 202 | $line = BATsh::Env->expand_cmd($line); | ||
| 203 | } | ||
| 204 | |||
| 205 | # Handle compound commands: & && || (outside quotes, after expansion) | ||
| 206 | # Split on & / && / || and execute left to right | ||
| 207 | if ($line =~ /[&|]/) { | ||
| 208 | my @parts = _split_compound($line); | ||
| 209 | if (@parts > 1) { | ||
| 210 | return _exec_compound($class, \@parts, $lines_ref, $labels_ref, $i_ref, $opts_ref); | ||
| 211 | } | ||
| 212 | } | ||
| 213 | |||
| 214 | # Handle redirection stripping before dispatch | ||
| 215 | my ($clean_line, $redirs) = _strip_redirects($line); | ||
| 216 | |||
| 217 | return _dispatch_with_redirs($class, $clean_line, $redirs, $lines_ref, $labels_ref, $i_ref, $opts_ref); | ||
| 218 | } | ||
| 219 | |||
| 220 | # ---------------------------------------------------------------- | ||
| 221 | # _expand_line: %VAR% expansion protecting FOR loop variables | ||
| 222 | # ---------------------------------------------------------------- | ||
| 223 | sub _expand_line { | ||
| 224 | my ($line) = @_; | ||
| 225 | if ($line =~ /\AFOR\s/i) { | ||
| 226 | if ($line =~ /\A(FOR\s+(?:\/[A-Za-z]\s+(?:"[^"]*"\s+)?)?%%[A-Za-z]\s+(?:\/[A-Za-z]\s+)?IN\s*\([^)]*\)\s+DO\s+)(.*)\z/i) { | ||
| 227 | my ($for_head, $do_part) = ($1, $2); | ||
| 228 | $for_head =~ s/%%([A-Za-z])/"\x00FOR_$1\x00"/ge; | ||
| 229 | $for_head = BATsh::Env->expand_cmd($for_head); | ||
| 230 | $for_head =~ s/\x00FOR_([A-Za-z])\x00/%%$1/g; | ||
| 231 | $do_part =~ s/%%([A-Za-z])/"\x00FOR_$1\x00"/ge; | ||
| 232 | $do_part =~ s/%([^%\r\n]+)%/"\x00PCT_$1\x00"/ge; | ||
| 233 | return $for_head . $do_part; | ||
| 234 | } | ||
| 235 | else { | ||
| 236 | $line =~ s/%%([A-Za-z])/"\x00FOR_$1\x00"/ge; | ||
| 237 | $line = BATsh::Env->expand_cmd($line); | ||
| 238 | $line =~ s/\x00FOR_([A-Za-z])\x00/%%$1/g; | ||
| 239 | return $line; | ||
| 240 | } | ||
| 241 | } | ||
| 242 | else { | ||
| 243 | $line =~ s/%%([A-Za-z])/"\x00FOR_$1\x00"/ge; | ||
| 244 | $line = BATsh::Env->expand_cmd($line); | ||
| 245 | $line =~ s/\x00FOR_([A-Za-z])\x00/%%$1/g; | ||
| 246 | return $line; | ||
| 247 | } | ||
| 248 | } | ||
| 249 | |||
| 250 | # ---------------------------------------------------------------- | ||
| 251 | # _split_compound: split on bare & && || (respecting quotes and ^) | ||
| 252 | # Returns list of { op => '&'|'&&'|'||'|'', cmd => $str } | ||
| 253 | # ---------------------------------------------------------------- | ||
| 254 | sub _split_compound { | ||
| 255 | my ($line) = @_; | ||
| 256 | my @parts; | ||
| 257 | my $cur = ''; | ||
| 258 | my $in_q = 0; | ||
| 259 | my @chars = split //, $line; | ||
| 260 | my $n = scalar @chars; | ||
| 261 | my $j = 0; | ||
| 262 | while ($j < $n) { | ||
| 263 | my $ch = $chars[$j]; | ||
| 264 | if ($ch eq '^' && !$in_q) { | ||
| 265 | # escaped: take next char literally | ||
| 266 | $j++; | ||
| 267 | if ($j < $n) { $cur .= $chars[$j]; $j++ } | ||
| 268 | next; | ||
| 269 | } | ||
| 270 | if ($ch eq '"') { $in_q = !$in_q; $cur .= $ch; $j++; next } | ||
| 271 | if (!$in_q && $ch eq '&') { | ||
| 272 | if ($j+1 < $n && $chars[$j+1] eq '&') { | ||
| 273 | push @parts, { op => '', cmd => $cur }; $cur = ''; $j += 2; | ||
| 274 | push @parts, { op => '&&', cmd => '' }; | ||
| 275 | } | ||
| 276 | else { | ||
| 277 | push @parts, { op => '', cmd => $cur }; $cur = ''; $j++; | ||
| 278 | push @parts, { op => '&', cmd => '' }; | ||
| 279 | } | ||
| 280 | next; | ||
| 281 | } | ||
| 282 | if (!$in_q && $ch eq '|') { | ||
| 283 | if ($j+1 < $n && $chars[$j+1] eq '|') { | ||
| 284 | push @parts, { op => '', cmd => $cur }; $cur = ''; $j += 2; | ||
| 285 | push @parts, { op => '||', cmd => '' }; | ||
| 286 | } | ||
| 287 | elsif ($j+1 < $n && $chars[$j+1] ne '>') { | ||
| 288 | # pipe: record left side and mark as pipe op | ||
| 289 | push @parts, { op => '', cmd => $cur }; $cur = ''; $j++; | ||
| 290 | push @parts, { op => '|', cmd => '' }; | ||
| 291 | } | ||
| 292 | else { | ||
| 293 | $cur .= $ch; $j++; next; | ||
| 294 | } | ||
| 295 | next; | ||
| 296 | } | ||
| 297 | $cur .= $ch; $j++; | ||
| 298 | } | ||
| 299 | push @parts, { op => '', cmd => $cur } if $cur =~ /\S/; | ||
| 300 | return @parts; | ||
| 301 | } | ||
| 302 | |||
| 303 | # ---------------------------------------------------------------- | ||
| 304 | # _exec_compound: execute & / && / || compound commands | ||
| 305 | # ---------------------------------------------------------------- | ||
| 306 | sub _exec_compound { | ||
| 307 | my ($class, $parts, $lines_ref, $labels_ref, $i_ref, $opts_ref) = @_; | ||
| 308 | |||
| 309 | # If any part uses pipe operator, delegate entirely to _exec_pipe | ||
| 310 | # before executing any segment (so left-side stdout is captured first). | ||
| 311 | for my $part (@{$parts}) { | ||
| 312 | if ($part->{op} eq '|') { | ||
| 313 | return _exec_pipe($class, $parts, $lines_ref, $labels_ref, $i_ref, $opts_ref); | ||
| 314 | } | ||
| 315 | } | ||
| 316 | |||
| 317 | my $pending_op = ''; | ||
| 318 | my $rc = 0; | ||
| 319 | for my $part (@{$parts}) { | ||
| 320 | my $op = $part->{op}; | ||
| 321 | my $cmd = $part->{cmd}; | ||
| 322 | $cmd =~ s/\A\s+//; $cmd =~ s/\s+\z//; | ||
| 323 | |||
| 324 | if ($op eq '') { | ||
| 325 | # This is a command to run, pending_op tells us under what condition | ||
| 326 | if ($pending_op eq '') { | ||
| 327 | $rc = _exec_single($class, $cmd, $lines_ref, $labels_ref, $i_ref, $opts_ref) if $cmd =~ /\S/; | ||
| 328 | } | ||
| 329 | elsif ($pending_op eq '&&') { | ||
| 330 | $rc = _exec_single($class, $cmd, $lines_ref, $labels_ref, $i_ref, $opts_ref) if $ERRORLEVEL == 0 && $cmd =~ /\S/; | ||
| 331 | } | ||
| 332 | elsif ($pending_op eq '||') { | ||
| 333 | $rc = _exec_single($class, $cmd, $lines_ref, $labels_ref, $i_ref, $opts_ref) if $ERRORLEVEL != 0 && $cmd =~ /\S/; | ||
| 334 | } | ||
| 335 | elsif ($pending_op eq '&') { | ||
| 336 | $rc = _exec_single($class, $cmd, $lines_ref, $labels_ref, $i_ref, $opts_ref) if $cmd =~ /\S/; | ||
| 337 | } | ||
| 338 | $pending_op = ''; | ||
| 339 | } | ||
| 340 | else { | ||
| 341 | $pending_op = $op; | ||
| 342 | } | ||
| 343 | } | ||
| 344 | return $rc; | ||
| 345 | } | ||
| 346 | |||
| 347 | sub _exec_single { | ||
| 348 | my ($class, $cmd, $lines_ref, $labels_ref, $i_ref, $opts_ref) = @_; | ||
| 349 | return 0 unless $cmd =~ /\S/; | ||
| 350 | my ($clean, $redirs) = _strip_redirects($cmd); | ||
| 351 | return _dispatch_with_redirs($class, $clean, $redirs, $lines_ref, $labels_ref, $i_ref, $opts_ref); | ||
| 352 | } | ||
| 353 | |||
| 354 | # ---------------------------------------------------------------- | ||
| 355 | # _exec_pipe: execute cmd1 | cmd2 [| cmd3 ...] via temporary files. | ||
| 356 | # Left side stdout -> tmpfile; right side reads tmpfile as stdin. | ||
| 357 | # Perl 5.005_03 compatible: bareword filehandles, 2-arg open only. | ||
| 358 | # ---------------------------------------------------------------- | ||
| 359 | use vars qw(*_PIPE_SAVOUT *_PIPE_SAVIN *_PIPE_WFH *_PIPE_RFH); | ||
| 360 | |||
| 361 | sub _exec_pipe { | ||
| 362 | my ($class, $parts, $lines_ref, $labels_ref, $i_ref, $opts_ref) = @_; | ||
| 363 | |||
| 364 | # Collect command segments from parts list. | ||
| 365 | # parts layout (from _split_compound): | ||
| 366 | # { op=>'', cmd=>'left_cmd ' } | ||
| 367 | # { op=>'|', cmd=>'' } | ||
| 368 | # { op=>'', cmd=>' right_cmd'} | ||
| 369 | # Segments are op='' chunks; '|' entries are separators. | ||
| 370 | my @segments; | ||
| 371 | my $cur = ''; | ||
| 372 | for my $part (@{$parts}) { | ||
| 373 | my $op = $part->{op}; | ||
| 374 | my $cmd = $part->{cmd}; | ||
| 375 | if ($op eq '|') { | ||
| 376 | push @segments, $cur; | ||
| 377 | $cur = ''; | ||
| 378 | } | ||
| 379 | elsif ($op eq '') { | ||
| 380 | $cur .= $cmd; | ||
| 381 | } | ||
| 382 | else { | ||
| 383 | # &&, ||, & after a pipe: attach to current segment | ||
| 384 | $cur .= " $op $cmd"; | ||
| 385 | } | ||
| 386 | } | ||
| 387 | push @segments, $cur; | ||
| 388 | |||
| 389 | my $rc = 0; | ||
| 390 | my $base = File::Spec->catfile(File::Spec->tmpdir(), | ||
| 391 | "batsh_pipe_$$"); | ||
| 392 | my $input_f = undef; # tmpfile feeding this segment's stdin | ||
| 393 | my $n_segs = scalar @segments; | ||
| 394 | |||
| 395 | for my $idx (0 .. $n_segs - 1) { | ||
| 396 | my $seg = $segments[$idx]; | ||
| 397 | $seg =~ s/\A\s+//; $seg =~ s/\s+\z//; | ||
| 398 | next unless $seg =~ /\S/; | ||
| 399 | |||
| 400 | my $is_last = ($idx == $n_segs - 1) ? 1 : 0; | ||
| 401 | my $output_f = $is_last ? undef : "${base}_${idx}.tmp"; | ||
| 402 | |||
| 403 | # --- redirect STDIN from previous segment output --- | ||
| 404 | my $saved_in = 0; | ||
| 405 | if (defined $input_f && -f $input_f) { | ||
| 406 | open(_PIPE_RFH, $input_f) | ||
| 407 | or do { _warn("pipe: open $input_f: $!"); last }; | ||
| 408 | open(_PIPE_SAVIN, '<&STDIN') | ||
| 409 | or do { close(_PIPE_RFH); last }; | ||
| 410 | open(STDIN, '<&_PIPE_RFH') | ||
| 411 | or do { close(_PIPE_RFH); open(STDIN, '<&_PIPE_SAVIN'); close(_PIPE_SAVIN); last }; | ||
| 412 | close(_PIPE_RFH); | ||
| 413 | $saved_in = 1; | ||
| 414 | } | ||
| 415 | |||
| 416 | # --- redirect STDOUT to next segment input file --- | ||
| 417 | my $saved_out = 0; | ||
| 418 | if (defined $output_f) { | ||
| 419 | open(_PIPE_WFH, ">$output_f") | ||
| 420 | or do { | ||
| 421 | if ($saved_in) { open(STDIN, '<&_PIPE_SAVIN'); close(_PIPE_SAVIN) } | ||
| 422 | _warn("pipe: open $output_f: $!"); | ||
| 423 | last; | ||
| 424 | }; | ||
| 425 | open(_PIPE_SAVOUT, '>&STDOUT') | ||
| 426 | or do { | ||
| 427 | close(_PIPE_WFH); | ||
| 428 | if ($saved_in) { open(STDIN, '<&_PIPE_SAVIN'); close(_PIPE_SAVIN) } | ||
| 429 | last; | ||
| 430 | }; | ||
| 431 | open(STDOUT, '>&_PIPE_WFH') | ||
| 432 | or do { | ||
| 433 | close(_PIPE_WFH); | ||
| 434 | open(STDOUT, '>&_PIPE_SAVOUT'); close(_PIPE_SAVOUT); | ||
| 435 | if ($saved_in) { open(STDIN, '<&_PIPE_SAVIN'); close(_PIPE_SAVIN) } | ||
| 436 | last; | ||
| 437 | }; | ||
| 438 | close(_PIPE_WFH); | ||
| 439 | $saved_out = 1; | ||
| 440 | } | ||
| 441 | |||
| 442 | # --- run the segment --- | ||
| 443 | $rc = _exec_single($class, $seg, $lines_ref, $labels_ref, $i_ref, $opts_ref); | ||
| 444 | |||
| 445 | # --- restore STDOUT --- | ||
| 446 | if ($saved_out) { | ||
| 447 | open(STDOUT, '>&_PIPE_SAVOUT'); | ||
| 448 | close(_PIPE_SAVOUT); | ||
| 449 | } | ||
| 450 | |||
| 451 | # --- restore STDIN and clean up input tmpfile --- | ||
| 452 | if ($saved_in) { | ||
| 453 | open(STDIN, '<&_PIPE_SAVIN'); | ||
| 454 | close(_PIPE_SAVIN); | ||
| 455 | unlink $input_f; | ||
| 456 | } | ||
| 457 | |||
| 458 | $input_f = $output_f; # next segment reads what we just wrote | ||
| 459 | } | ||
| 460 | |||
| 461 | # Clean up any leftover tmpfile (e.g. if last segment was skipped) | ||
| 462 | unlink $input_f if defined $input_f && -f $input_f; | ||
| 463 | |||
| 464 | return $rc; | ||
| 465 | } | ||
| 466 | |||
| 467 | # ---------------------------------------------------------------- | ||
| 468 | # _strip_redirects: parse > >> 2> 2>> < from end of command | ||
| 469 | # Returns ($clean_cmd, \@redirs) where @redirs = ([fd,mode,file], ...) | ||
| 470 | # ---------------------------------------------------------------- | ||
| 471 | sub _strip_redirects { | ||
| 472 | my ($line) = @_; | ||
| 473 | my @redirs; | ||
| 474 | # Parse redirects while respecting ^ escapes and quotes. | ||
| 475 | # A > or < preceded by ^ is NOT a redirect. | ||
| 476 | # Strategy: walk char-by-char to find bare (unescaped, unquoted) redirects. | ||
| 477 | my @chars = split //, $line; | ||
| 478 | my $n = scalar @chars; | ||
| 479 | my ($in_q, $i) = (0, 0); | ||
| 480 | my $clean = ''; | ||
| 481 | my @found; # [pos_in_clean, fd, append, file_str] | ||
| 482 | |||
| 483 | while ($i < $n) { | ||
| 484 | my $ch = $chars[$i]; | ||
| 485 | if ($ch eq '^' && !$in_q) { | ||
| 486 | # Escape: pass through both ^ and next char as literals | ||
| 487 | $clean .= $ch; | ||
| 488 | $i++; | ||
| 489 | $clean .= $chars[$i] if $i < $n; | ||
| 490 | $i++; | ||
| 491 | next; | ||
| 492 | } | ||
| 493 | if ($ch eq '"') { $in_q = !$in_q; $clean .= $ch; $i++; next } | ||
| 494 | if (!$in_q && ($ch eq '>' || $ch eq '<')) { | ||
| 495 | my $fd = 1; | ||
| 496 | my $is_in = ($ch eq '<') ? 1 : 0; | ||
| 497 | # Check if the character immediately before (in clean, ignoring trailing space) | ||
| 498 | # is a bare fd digit that is not part of a word. | ||
| 499 | # Only '2' (stderr) and '1' (stdout explicit) are valid fd numbers in cmd.exe. | ||
| 500 | # We accept N> only if N is a single digit preceded by space/start-of-string. | ||
| 501 | if ($clean =~ s/(?:\A|(?<=[ \t]))([12])[ \t]*\z//) { | ||
| 502 | $fd = int($1); | ||
| 503 | } | ||
| 504 | my $append = 0; | ||
| 505 | $i++; | ||
| 506 | if (!$is_in && $i < $n && $chars[$i] eq '>') { $append = 1; $i++ } | ||
| 507 | # Skip whitespace before filename | ||
| 508 | $i++ while $i < $n && $chars[$i] =~ /[ \t]/; | ||
| 509 | # Read filename (until space/tab or end) | ||
| 510 | my $file = ''; | ||
| 511 | if ($i < $n && $chars[$i] eq '"') { | ||
| 512 | $i++; | ||
| 513 | while ($i < $n && $chars[$i] ne '"') { $file .= $chars[$i++] } | ||
| 514 | $i++; # closing " | ||
| 515 | } | ||
| 516 | else { | ||
| 517 | while ($i < $n && $chars[$i] !~ /[ \t]/) { $file .= $chars[$i++] } | ||
| 518 | } | ||
| 519 | push @found, [$is_in ? 0 : $fd, $append, $file]; | ||
| 520 | next; | ||
| 521 | } | ||
| 522 | $clean .= $ch; $i++; | ||
| 523 | } | ||
| 524 | $clean =~ s/\s+\z//; | ||
| 525 | return ($clean, \@found); | ||
| 526 | } | ||
| 527 | |||
| 528 | # ---------------------------------------------------------------- | ||
| 529 | # _dispatch_with_redirs: set up redirections then dispatch | ||
| 530 | # Perl 5.005_03 compatible: fixed bareword FHs, 2-argument open. | ||
| 531 | # ---------------------------------------------------------------- | ||
| 532 | |||
| 533 | # Fixed bareword filehandles used only inside _dispatch_with_redirs. | ||
| 534 | # Pre-declared at package level so they are valid under strict. | ||
| 535 | use vars qw(*_REDIR_SRC *_REDIR_DST *_REDIR_SAVOUT *_REDIR_SAVERR *_REDIR_SAVIN); | ||
| 536 | |||
| 537 | sub _dispatch_with_redirs { | ||
| 538 | my ($class, $line, $redirs, $lines_ref, $labels_ref, $i_ref, $opts_ref) = @_; | ||
| 539 | |||
| 540 | return _dispatch($class, $line, $lines_ref, $labels_ref, $i_ref, $opts_ref) | ||
| 541 | unless @{$redirs}; | ||
| 542 | |||
| 543 | # Process redirections one at a time using fixed bareword FHs. | ||
| 544 | # We support one redirect per fd (last one wins, matching cmd.exe). | ||
| 545 | # Collect: stdin_file, stdout_file, stdout_append, stderr_file, stderr_append | ||
| 546 | my ($in_file, $out_file, $out_app, $err_file, $err_app); | ||
| 547 | for my $r (@{$redirs}) { | ||
| 548 | my ($fd, $append, $file) = @{$r}; | ||
| 549 | $file = BATsh::MB::dec($file); | ||
| 550 | if ($fd == 0) { $in_file = $file } | ||
| 551 | elsif ($fd == 1) { $out_file = $file; $out_app = $append } | ||
| 552 | else { $err_file = $file; $err_app = $append } | ||
| 553 | } | ||
| 554 | |||
| 555 | my $ok = 1; | ||
| 556 | my ($saved_in, $saved_out, $saved_err) = (0, 0, 0); | ||
| 557 | |||
| 558 | # stdin | ||
| 559 | if (defined $in_file && $ok) { | ||
| 560 | open(_REDIR_SRC, $in_file) or do { _warn("Cannot open $in_file: $!"); $ok=0 }; | ||
| 561 | if ($ok) { | ||
| 562 | open(_REDIR_SAVIN, '<&STDIN') or do { $ok=0 }; | ||
| 563 | } | ||
| 564 | if ($ok) { | ||
| 565 | open(STDIN, '<&_REDIR_SRC') or do { $ok=0 }; | ||
| 566 | close(_REDIR_SRC); | ||
| 567 | $saved_in = 1; | ||
| 568 | } | ||
| 569 | } | ||
| 570 | |||
| 571 | # stdout | ||
| 572 | if (defined $out_file && $ok) { | ||
| 573 | my $mode = $out_app ? '>>' : '>'; | ||
| 574 | open(_REDIR_DST, "$mode$out_file") or do { _warn("Cannot open $out_file: $!"); $ok=0 }; | ||
| 575 | if ($ok) { | ||
| 576 | open(_REDIR_SAVOUT, '>&STDOUT') or do { $ok=0 }; | ||
| 577 | } | ||
| 578 | if ($ok) { | ||
| 579 | open(STDOUT, '>&_REDIR_DST') or do { $ok=0 }; | ||
| 580 | close(_REDIR_DST); | ||
| 581 | $saved_out = 1; | ||
| 582 | } | ||
| 583 | } | ||
| 584 | |||
| 585 | # stderr | ||
| 586 | if (defined $err_file && $ok) { | ||
| 587 | my $mode = $err_app ? '>>' : '>'; | ||
| 588 | open(_REDIR_DST, "$mode$err_file") or do { _warn("Cannot open $err_file: $!"); $ok=0 }; | ||
| 589 | if ($ok) { | ||
| 590 | open(_REDIR_SAVERR, '>&STDERR') or do { $ok=0 }; | ||
| 591 | } | ||
| 592 | if ($ok) { | ||
| 593 | open(STDERR, '>&_REDIR_DST') or do { $ok=0 }; | ||
| 594 | close(_REDIR_DST); | ||
| 595 | $saved_err = 1; | ||
| 596 | } | ||
| 597 | } | ||
| 598 | |||
| 599 | my $rc = 0; | ||
| 600 | $rc = _dispatch($class, $line, $lines_ref, $labels_ref, $i_ref, $opts_ref) if $ok; | ||
| 601 | |||
| 602 | # Restore in reverse order | ||
| 603 | if ($saved_err) { open(STDERR, '>&_REDIR_SAVERR'); close(_REDIR_SAVERR) } | ||
| 604 | if ($saved_out) { open(STDOUT, '>&_REDIR_SAVOUT'); close(_REDIR_SAVOUT) } | ||
| 605 | if ($saved_in) { open(STDIN, '<&_REDIR_SAVIN'); close(_REDIR_SAVIN) } | ||
| 606 | |||
| 607 | return $rc; | ||
| 608 | } | ||
| 609 | |||
| 610 | # ---------------------------------------------------------------- | ||
| 611 | # Command dispatcher | ||
| 612 | # ---------------------------------------------------------------- | ||
| 613 | sub _dispatch { | ||
| 614 | my ($class, $line, $lines_ref, $labels_ref, $i_ref, $opts_ref) = @_; | ||
| 615 | |||
| 616 | my ($cmd, $rest) = _split_cmd($line); | ||
| 617 | return 0 unless defined $cmd && $cmd ne ''; | ||
| 618 | |||
| 619 | my $CMD = uc($cmd); | ||
| 620 | |||
| 621 | if ($CMD eq 'ECHO') { return _cmd_echo($rest) } | ||
| 622 | if ($CMD eq '@ECHO') { return _cmd_echo($rest) } | ||
| 623 | if ($CMD eq 'SET') { return _cmd_set($rest) } | ||
| 624 | if ($CMD eq 'IF') { return _cmd_if($class, $line, $lines_ref, $labels_ref, $i_ref, $opts_ref) } | ||
| 625 | if ($CMD eq 'FOR') { return _cmd_for($class, $line, $lines_ref, $labels_ref, $i_ref, $opts_ref) } | ||
| 626 | if ($CMD eq 'GOTO') { | ||
| 627 | $rest =~ s/\A\s+//; $rest =~ s/\s+\z//; $rest =~ s/\A://; | ||
| 628 | $_GOTO_LABEL = uc($rest); | ||
| 629 | return 0; | ||
| 630 | } | ||
| 631 | if ($CMD eq 'CALL') { return _cmd_call($class, $rest, $opts_ref) } | ||
| 632 | if ($CMD eq 'SHIFT') { return _cmd_shift($rest) } | ||
| 633 | if ($CMD eq 'SETLOCAL') { | ||
| 634 | $rest =~ s/\A\s+//; $rest =~ s/\s+\z//; | ||
| 635 | BATsh::Env::setlocal($rest); | ||
| 636 | return 0; | ||
| 637 | } | ||
| 638 | if ($CMD eq 'ENDLOCAL') { BATsh::Env::endlocal(); return 0 } | ||
| 639 | if ($CMD eq 'CD' || $CMD eq 'CHDIR') { return _cmd_cd($rest) } | ||
| 640 | if ($CMD eq 'DIR') { return _cmd_dir($rest) } | ||
| 641 | if ($CMD eq 'COPY') { return _cmd_copy($rest) } | ||
| 642 | if ($CMD eq 'DEL' || $CMD eq 'ERASE') { return _cmd_del($rest) } | ||
| 643 | if ($CMD eq 'MOVE') { return _cmd_move($rest) } | ||
| 644 | if ($CMD eq 'MKDIR' || $CMD eq 'MD') { return _cmd_mkdir($rest) } | ||
| 645 | if ($CMD eq 'RMDIR' || $CMD eq 'RD') { return _cmd_rmdir($rest) } | ||
| 646 | if ($CMD eq 'REN' || $CMD eq 'RENAME') { return _cmd_rename($rest) } | ||
| 647 | if ($CMD eq 'TYPE') { return _cmd_type($rest) } | ||
| 648 | if ($CMD eq 'PAUSE') { | ||
| 649 | print "Press any key to continue . . . "; | ||
| 650 | my $ch = ''; | ||
| 651 | eval { local $| = 1; require POSIX; POSIX::tcgetattr(0); read(STDIN, $ch, 1) }; | ||
| 652 | print "\n"; | ||
| 653 | return 0; | ||
| 654 | } | ||
| 655 | if ($CMD eq 'EXIT') { | ||
| 656 | $rest =~ s/\A\s+//; | ||
| 657 | my $is_b = ($rest =~ s{/B\s*}{}i) ? 1 : 0; | ||
| 658 | $rest =~ s/\A\s+//; | ||
| 659 | # EXIT n / EXIT /B n set the exit code; a bare EXIT [/B] keeps the | ||
| 660 | # current ERRORLEVEL (cmd.exe: exit code of the batch is the last | ||
| 661 | # ERRORLEVEL when no code is given). | ||
| 662 | $ERRORLEVEL = int($rest) if $rest =~ /\A\d+\z/; | ||
| 663 | $_EXIT_REQUESTED = 1; | ||
| 664 | return '__EXIT__'; | ||
| 665 | } | ||
| 666 | if ($CMD eq 'CLS') { print "\033[2J\033[H"; return 0 } | ||
| 667 | if ($CMD eq 'TITLE') { print "\033]0;$rest\007"; return 0 } | ||
| 668 | if ($CMD eq 'VER') { print "BATsh [Version $BATsh::VERSION]\n"; return 0 } | ||
| 669 | if ($CMD eq 'PUSHD') { | ||
| 670 | $rest =~ s/\A\s+//; $rest =~ s/\s+\z//; | ||
| 671 | push @{$opts_ref->{'_pushd_stack'}}, Cwd::cwd(); | ||
| 672 | return _cmd_cd($rest); | ||
| 673 | } | ||
| 674 | if ($CMD eq 'POPD') { | ||
| 675 | if (defined $opts_ref->{'_pushd_stack'} && @{$opts_ref->{'_pushd_stack'}}) { | ||
| 676 | chdir(pop @{$opts_ref->{'_pushd_stack'}}); | ||
| 677 | } | ||
| 678 | return 0; | ||
| 679 | } | ||
| 680 | |||
| 681 | return _cmd_external($cmd, $rest); | ||
| 682 | } | ||
| 683 | |||
| 684 | # ---------------------------------------------------------------- | ||
| 685 | # ECHO (does NOT reset ERRORLEVEL -- cmd.exe compatible) | ||
| 686 | # ---------------------------------------------------------------- | ||
| 687 | sub _cmd_echo { | ||
| 688 | my ($rest) = @_; | ||
| 689 | $rest =~ s/\A\s+//; | ||
| 690 | |||
| 691 | if ($rest =~ /\AOFF\s*\z/i) { $ECHO_ON = 0; return 0; } | ||
| 692 | if ($rest =~ /\AON\s*\z/i) { $ECHO_ON = 1; return 0; } | ||
| 693 | if ($rest =~ /\A\.\s*\z/) { print "\n"; return 0; } | ||
| 694 | if ($rest =~ /\A\s*\z/) { print "ECHO is " . ($ECHO_ON ? "on" : "off") . "\n"; return 0; } | ||
| 695 | |||
| 696 | # Remove ^ escapes for display (they were protection, not content) | ||
| 697 | $rest = _unescape_caret($rest); | ||
| 698 | print BATsh::MB::dec($rest), "\n"; | ||
| 699 | # ERRORLEVEL intentionally NOT modified here | ||
| 700 | return 0; | ||
| 701 | } | ||
| 702 | |||
| 703 | # ---------------------------------------------------------------- | ||
| 704 | # SET | ||
| 705 | # ---------------------------------------------------------------- | ||
| 706 | sub _cmd_set { | ||
| 707 | my ($rest) = @_; | ||
| 708 | $rest =~ s/\A\s+//; | ||
| 709 | |||
| 710 | # SET /P VAR=PromptString (interactive prompt input) | ||
| 711 | if ($rest =~ s/\A\/P\s*//i) { | ||
| 712 | if ($rest =~ /\A([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)/) { | ||
| 713 | my ($var, $prompt) = ($1, $2); | ||
| 714 | print BATsh::MB::dec($prompt); | ||
| 715 | my $input = <STDIN>; | ||
| 716 | $input = '' unless defined $input; | ||
| 717 | chomp $input; | ||
| 718 | BATsh::Env->set($var, BATsh::MB::enc($input)); | ||
| 719 | $ERRORLEVEL = 0; | ||
| 720 | } | ||
| 721 | return 0; | ||
| 722 | } | ||
| 723 | |||
| 724 | # SET /A | ||
| 725 | if ($rest =~ s/\A\/A\s*//i) { | ||
| 726 | if ($rest =~ /\A\s*([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)/) { | ||
| 727 | BATsh::Env->set($1, _eval_arith($2)); | ||
| 728 | } | ||
| 729 | else { | ||
| 730 | print _eval_arith($rest) . "\n"; | ||
| 731 | } | ||
| 732 | $ERRORLEVEL = 0; | ||
| 733 | return 0; | ||
| 734 | } | ||
| 735 | |||
| 736 | # SET with no args: display all | ||
| 737 | if ($rest =~ /\A\s*\z/) { | ||
| 738 | for my $k (sort keys %BATsh::Env::STORE) { | ||
| 739 | print "$k=", BATsh::MB::dec($BATsh::Env::STORE{$k}), "\n"; | ||
| 740 | } | ||
| 741 | return 0; | ||
| 742 | } | ||
| 743 | |||
| 744 | # SET VAR=value (variable name may contain spaces before =) | ||
| 745 | if ($rest =~ /\A([^=]+?)\s*=(.*)/) { | ||
| 746 | BATsh::Env->set($1, $2); | ||
| 747 | $ERRORLEVEL = 0; | ||
| 748 | return 0; | ||
| 749 | } | ||
| 750 | |||
| 751 | # SET VAR (display matching prefix) | ||
| 752 | if ($rest =~ /\A(\S+)\s*\z/) { | ||
| 753 | my $prefix = uc($1); | ||
| 754 | for my $k (sort keys %BATsh::Env::STORE) { | ||
| 755 | if (index(uc($k), $prefix) == 0) { | ||
| 756 | print "$k=", BATsh::MB::dec($BATsh::Env::STORE{$k}), "\n"; | ||
| 757 | } | ||
| 758 | } | ||
| 759 | return 0; | ||
| 760 | } | ||
| 761 | |||
| 762 | return 0; | ||
| 763 | } | ||
| 764 | |||
| 765 | # ---------------------------------------------------------------- | ||
| 766 | # SET /A arithmetic evaluator | ||
| 767 | # Supports: + - * / % ^ & | ~ << >> () hex (0x) and variable refs | ||
| 768 | # ---------------------------------------------------------------- | ||
| 769 | sub _eval_arith { | ||
| 770 | my ($expr) = @_; | ||
| 771 | # Expand variable names | ||
| 772 | $expr =~ s/([A-Za-z_][A-Za-z0-9_]*)/ | ||
| 773 | do { my $v = BATsh::Env->get($1); defined $v && $v =~ m|^-?\d+$| ? $v : 0 } | ||
| 774 | /ge; | ||
| 775 | # Convert 0xHEX literals | ||
| 776 | $expr =~ s/0x([0-9A-Fa-f]+)/hex($1)/ge; | ||
| 777 | # %% -> % (modulo) | ||
| 778 | $expr =~ s/%%/%/g; | ||
| 779 | # Safe eval: digits, operators, hex chars already substituted | ||
| 780 | if ($expr =~ /\A[\d\s\+\-\*\/\%\(\)\^\&\|\~\<\>]+\z/) { | ||
| 781 | # Perl ^ is XOR, same as cmd.exe SET /A | ||
| 782 | my $result = eval $expr; | ||
| 783 | return defined $result ? int($result) : 0; | ||
| 784 | } | ||
| 785 | return 0; | ||
| 786 | } | ||
| 787 | |||
| 788 | # ---------------------------------------------------------------- | ||
| 789 | # IF | ||
| 790 | # | ||
| 791 | # cmd.exe parse order: | ||
| 792 | # IF [NOT] /I "a"=="b" ... (case-insensitive string) | ||
| 793 | # IF [NOT] ERRORLEVEL n ... | ||
| 794 | # IF [NOT] EXIST path ... | ||
| 795 | # IF [NOT] DEFINED var ... | ||
| 796 | # IF [NOT] "a"=="b" ... (case-sensitive string) | ||
| 797 | # | ||
| 798 | # IMPORTANT: /I must be checked BEFORE plain == to avoid /I being | ||
| 799 | # consumed as part of the left-hand operand. | ||
| 800 | # | ||
| 801 | # Block expansion: the THEN/ELSE bodies of a parenthesised IF block | ||
| 802 | # are expanded at parse time (before any SET inside runs), matching | ||
| 803 | # cmd.exe's behaviour. Only !VAR! (delayed) is deferred to runtime. | ||
| 804 | # ---------------------------------------------------------------- | ||
| 805 | sub _cmd_if { | ||
| 806 | my ($class, $line, $lines_ref, $labels_ref, $i_ref, $opts_ref) = @_; | ||
| 807 | |||
| 808 | (my $rest = $line) =~ s/\AIF\s+//i; | ||
| 809 | |||
| 810 | my $negate = 0; | ||
| 811 | if ($rest =~ s/\ANOT\s+//i) { $negate = 1; } | ||
| 812 | |||
| 813 | my $condition = 0; | ||
| 814 | |||
| 815 | # /I must be tried first | ||
| 816 | if ($rest =~ s/\A\/I\s+//i) { | ||
| 817 | # Case-insensitive comparison | ||
| 818 | if ($rest =~ s/\A("(?:[^"]*)"|[^\s=][^\s=]*)\s*==\s*("(?:[^"]*)"|[^\s=]*)\s*//) { | ||
| 819 | my ($a, $b) = ($1, $2); | ||
| 820 | $a =~ s/\A"//; $a =~ s/"\z//; | ||
| 821 | $b =~ s/\A"//; $b =~ s/"\z//; | ||
| 822 | $condition = (lc($a) eq lc($b)) ? 1 : 0; | ||
| 823 | } | ||
| 824 | } | ||
| 825 | # ERRORLEVEL n | ||
| 826 | elsif ($rest =~ s/\AERRORLEVEL\s+(\d+)\s*//i) { | ||
| 827 | $condition = ($ERRORLEVEL >= int($1)) ? 1 : 0; | ||
| 828 | } | ||
| 829 | # EXIST path (handles quoted paths with spaces) | ||
| 830 | elsif ($rest =~ s/\AEXIST\s+//i) { | ||
| 831 | my $path; | ||
| 832 | if ($rest =~ s/\A"([^"]+)"\s*//) { | ||
| 833 | $path = $1; | ||
| 834 | } | ||
| 835 | elsif ($rest =~ s/\A(\S+)\s*//) { | ||
| 836 | $path = $1; | ||
| 837 | } | ||
| 838 | $condition = (defined $path && -e BATsh::MB::dec($path)) ? 1 : 0; | ||
| 839 | } | ||
| 840 | # DEFINED var | ||
| 841 | elsif ($rest =~ s/\ADEFINED\s+(\S+)\s*//i) { | ||
| 842 | $condition = BATsh::Env->exists_var($1) ? 1 : 0; | ||
| 843 | } | ||
| 844 | # "str"=="str" or str==str (case-sensitive) | ||
| 845 | elsif ($rest =~ s/\A("(?:[^"]*)"|[^\s=][^\s=]*)\s*==\s*("(?:[^"]*)"|[^\s=]*)\s*//) { | ||
| 846 | my ($a, $b) = ($1, $2); | ||
| 847 | $a =~ s/\A"//; $a =~ s/"\z//; | ||
| 848 | $b =~ s/\A"//; $b =~ s/"\z//; | ||
| 849 | $condition = ($a eq $b) ? 1 : 0; | ||
| 850 | } | ||
| 851 | |||
| 852 | $condition = !$condition if $negate; | ||
| 853 | |||
| 854 | my ($then_body, $else_body) = _parse_if_bodies($rest, $lines_ref, $i_ref); | ||
| 855 | |||
| 856 | # Block expansion: expand %VAR% in the bodies NOW (parse-time), | ||
| 857 | # before any commands inside the block execute. | ||
| 858 | # !VAR! is NOT expanded here (that is deferred to execute-time via Env). | ||
| 859 | $then_body = _block_expand($then_body) if defined $then_body; | ||
| 860 | $else_body = _block_expand($else_body) if defined $else_body; | ||
| 861 | |||
| 862 | if ($condition) { | ||
| 863 | return _exec_body($class, $then_body, $lines_ref, $labels_ref, $i_ref, $opts_ref, 1); | ||
| 864 | } | ||
| 865 | elsif (defined $else_body) { | ||
| 866 | return _exec_body($class, $else_body, $lines_ref, $labels_ref, $i_ref, $opts_ref, 1); | ||
| 867 | } | ||
| 868 | return 0; | ||
| 869 | } | ||
| 870 | |||
| 871 | # ---------------------------------------------------------------- | ||
| 872 | # _block_expand: expand %VAR% in a block string at parse time. | ||
| 873 | # Protects %%V FOR loop variables and !VAR! delayed references. | ||
| 874 | # ---------------------------------------------------------------- | ||
| 875 | sub _block_expand { | ||
| 876 | my ($body) = @_; | ||
| 877 | return $body unless defined $body; | ||
| 878 | # Protect !VAR! -- replace with placeholder to survive %% pass | ||
| 879 | $body =~ s/(!(?:[A-Za-z_][A-Za-z0-9_]*)!)/"\x00DELAY\x00$1\x00DELAY\x00"/ge; | ||
| 880 | # Protect %%V | ||
| 881 | $body =~ s/%%([A-Za-z])/"\x00FOR_$1\x00"/ge; | ||
| 882 | # Expand %VAR% | ||
| 883 | $body =~ s/%([^%\r\n]+)%/ | ||
| 884 | do { my $k=uc($1); exists($BATsh::Env::STORE{$k}) ? $BATsh::Env::STORE{$k} : '' } | ||
| 885 | /ge; | ||
| 886 | # %% -> % | ||
| 887 | $body =~ s/%%/%/g; | ||
| 888 | # Restore | ||
| 889 | $body =~ s/\x00FOR_([A-Za-z])\x00/%%$1/g; | ||
| 890 | $body =~ s/\x00DELAY\x00(!(?:[A-Za-z_][A-Za-z0-9_]*)!)\x00DELAY\x00/$1/g; | ||
| 891 | return $body; | ||
| 892 | } | ||
| 893 | |||
| 894 | sub _parse_if_bodies { | ||
| 895 | my ($rest, $lines_ref, $i_ref) = @_; | ||
| 896 | my ($then_body, $else_body); | ||
| 897 | $rest =~ s/\A\s+//; | ||
| 898 | if ($rest =~ s/\A\(//) { | ||
| 899 | # First try the fully-inline single-line form on THIS physical | ||
| 900 | # line: ( then-body ) [ ELSE ( else-body ) | ELSE else-body ] | ||
| 901 | # _match_paren finds the ')' that closes the just-opened '(' on | ||
| 902 | # the same line (quote- and nesting-aware). If the block instead | ||
| 903 | # spans following lines (no closing ')' here), fall back to the | ||
| 904 | # multi-line reader. | ||
| 905 | my ($inner, $after) = _match_paren($rest); | ||
| 906 | if (defined $inner) { | ||
| 907 | $then_body = $inner; | ||
| 908 | $after =~ s/\A\s+//; | ||
| 909 | if ($after =~ s/\AELSE\s*//i) { | ||
| 910 | if ($after =~ /\A\(/) { | ||
| 911 | $after =~ s/\A\(//; | ||
| 912 | my ($einner) = _match_paren($after); | ||
| 913 | $else_body = defined($einner) ? $einner : $after; | ||
| 914 | } | ||
| 915 | elsif ($after =~ /\S/) { | ||
| 916 | $else_body = $after; | ||
| 917 | } | ||
| 918 | } | ||
| 919 | } | ||
| 920 | else { | ||
| 921 | $then_body = _read_paren_block($rest, $lines_ref, $i_ref, \$else_body); | ||
| 922 | } | ||
| 923 | } | ||
| 924 | else { | ||
| 925 | if ($rest =~ s/\s+ELSE\s+(.+)\z//i) { $else_body = $1 } | ||
| 926 | $then_body = $rest; | ||
| 927 | } | ||
| 928 | return ($then_body, $else_body); | ||
| 929 | } | ||
| 930 | |||
| 931 | # _match_paren: $str begins with the content right AFTER an opening '(' | ||
| 932 | # (depth already 1). Scan for the matching ')' at depth 0, honouring | ||
| 933 | # double quotes. Returns (inside_content, remainder_after_close) when | ||
| 934 | # the paren closes within $str, or (undef, undef) when it does not | ||
| 935 | # (i.e. the block continues on following physical lines). | ||
| 936 | sub _match_paren { | ||
| 937 | my ($str) = @_; | ||
| 938 | my @c = split //, $str; | ||
| 939 | my $n = scalar @c; | ||
| 940 | my $dep = 0; | ||
| 941 | my $in_q = 0; | ||
| 942 | my $i = 0; | ||
| 943 | while ($i < $n) { | ||
| 944 | my $ch = $c[$i]; | ||
| 945 | if ($ch eq '"') { $in_q = !$in_q; $i++; next } | ||
| 946 | if (!$in_q) { | ||
| 947 | if ($ch eq '(') { $dep++; $i++; next } | ||
| 948 | if ($ch eq ')') { | ||
| 949 | if ($dep == 0) { | ||
| 950 | my $inside = join('', @c[0 .. $i-1]); | ||
| 951 | my $after = ($i+1 <= $n-1) ? join('', @c[$i+1 .. $n-1]) : ''; | ||
| 952 | return ($inside, $after); | ||
| 953 | } | ||
| 954 | $dep--; $i++; next; | ||
| 955 | } | ||
| 956 | } | ||
| 957 | $i++; | ||
| 958 | } | ||
| 959 | return (undef, undef); | ||
| 960 | } | ||
| 961 | |||
| 962 | sub _read_paren_block { | ||
| 963 | my ($first_content, $lines_ref, $i_ref, $else_ref) = @_; | ||
| 964 | my @body = (); | ||
| 965 | push @body, $first_content if defined $first_content && $first_content =~ /\S/; | ||
| 966 | my $depth = 1; | ||
| 967 | while ($$i_ref <= $#{$lines_ref}) { | ||
| 968 | my $l = $lines_ref->[$$i_ref]; | ||
| 969 | $$i_ref++; | ||
| 970 | $l =~ s/\r?\n\z//; | ||
| 971 | my $ls = $l; $ls =~ s/\A\s+//; | ||
| 972 | if ($depth == 1 && $ls =~ /\A\)\s*ELSE\s*\(\s*\z/i) { | ||
| 973 | if (defined $else_ref) { $$else_ref = _read_paren_block('', $lines_ref, $i_ref) } | ||
| 974 | last; | ||
| 975 | } | ||
| 976 | if ($depth == 1 && $ls =~ /\A\)\s*ELSE\s+(.+)\z/i) { | ||
| 977 | if (defined $else_ref) { $$else_ref = $1 } | ||
| 978 | last; | ||
| 979 | } | ||
| 980 | my ($delta, $in_q) = (0, 0); | ||
| 981 | for my $ch (split //, $l) { | ||
| 982 | if ($ch eq '"') { $in_q = !$in_q } | ||
| 983 | elsif (!$in_q) { $delta++ if $ch eq '('; $delta-- if $ch eq ')' } | ||
| 984 | } | ||
| 985 | $depth += $delta; | ||
| 986 | if ($depth <= 0) { | ||
| 987 | $l =~ s/\)\s*\z//; | ||
| 988 | push @body, $l if $l =~ /\S/; | ||
| 989 | last; | ||
| 990 | } | ||
| 991 | push @body, $l; | ||
| 992 | } | ||
| 993 | return join("\n", @body); | ||
| 994 | } | ||
| 995 | |||
| 996 | sub _exec_body { | ||
| 997 | my ($class, $body, $lines_ref, $labels_ref, $i_ref, $opts_ref, $pre_expanded) = @_; | ||
| 998 | return 0 unless defined $body && $body =~ /\S/; | ||
| 999 | $pre_expanded = 0 unless defined $pre_expanded; | ||
| 1000 | my @sub_lines = split /\n/, $body; | ||
| 1001 | my $sub_i = 0; | ||
| 1002 | my %sub_labels = (); | ||
| 1003 | for my $j (0 .. $#sub_lines) { | ||
| 1004 | my $ls = $sub_lines[$j]; $ls =~ s/\A\s+//; | ||
| 1005 | if ($ls =~ /\A:([A-Za-z_][A-Za-z0-9_]*)\s*\z/) { | ||
| 1006 | $sub_labels{uc($1)} = $j; | ||
| 1007 | } | ||
| 1008 | } | ||
| 1009 | while ($sub_i <= $#sub_lines) { | ||
| 1010 | my $sl = $sub_lines[$sub_i]; | ||
| 1011 | $sub_i++; | ||
| 1012 | # For pre_expanded blocks: still need to handle !VAR! at runtime | ||
| 1013 | my $rc = _exec_line($class, $sl, \@sub_lines, { %sub_labels }, \$sub_i, $opts_ref, $pre_expanded); | ||
| 1014 | return $rc if defined $rc && $rc eq '__EXIT__'; | ||
| 1015 | if ($_GOTO_LABEL ne '') { | ||
| 1016 | my $lbl = $_GOTO_LABEL; | ||
| 1017 | $_GOTO_LABEL = ''; | ||
| 1018 | if (exists $sub_labels{$lbl}) { | ||
| 1019 | $sub_i = $sub_labels{$lbl} + 1; | ||
| 1020 | } | ||
| 1021 | else { | ||
| 1022 | $_GOTO_LABEL = $lbl; | ||
| 1023 | return 0; | ||
| 1024 | } | ||
| 1025 | } | ||
| 1026 | } | ||
| 1027 | return 0; | ||
| 1028 | } | ||
| 1029 | |||
| 1030 | # ---------------------------------------------------------------- | ||
| 1031 | # FOR | ||
| 1032 | # ---------------------------------------------------------------- | ||
| 1033 | sub _cmd_for { | ||
| 1034 | my ($class, $line, $lines_ref, $labels_ref, $i_ref, $opts_ref) = @_; | ||
| 1035 | |||
| 1036 | # FOR /F "options" %%V IN (source) DO cmd | ||
| 1037 | if ($line =~ /\AFOR\s+\/F\s+("(?:[^"]*)"|'(?:[^']*)'|[^\s]+)\s+(?:%%|\x00FOR_)([A-Za-z])(?:\x00)?\s+IN\s*\(([^)]*)\)\s+DO\s+(.*)/i) { | ||
| 1038 | return _cmd_for_f($class, $1, $2, $3, $4, $lines_ref, $labels_ref, $i_ref, $opts_ref); | ||
| 1039 | } | ||
| 1040 | |||
| 1041 | # FOR /L %%V IN (start,step,end) DO cmd | ||
| 1042 | if ($line =~ /\AFOR\s+\/L\s+(?:%%|\x00FOR_)([A-Za-z])(?:\x00)?\s+IN\s*\(([^)]*)\)\s+DO\s+(.*)/i) { | ||
| 1043 | my ($var, $range, $do_part) = ($1, $2, $3); | ||
| 1044 | my ($start, $step, $end) = split /,/, $range; | ||
| 1045 | $start = defined $start ? int($start) : 0; | ||
| 1046 | $step = defined $step ? int($step) : 1; | ||
| 1047 | $end = defined $end ? int($end) : 0; | ||
| 1048 | $step = 1 if $step == 0; | ||
| 1049 | return _for_iterate($class, $var, $do_part, $lines_ref, $labels_ref, $i_ref, $opts_ref, | ||
| 1050 | sub { # generator: returns list of values | ||
| 1051 | my @vals; | ||
| 1052 | my $v = $start; | ||
| 1053 | while (($step > 0 && $v <= $end) || ($step < 0 && $v >= $end)) { | ||
| 1054 | push @vals, $v; | ||
| 1055 | $v += $step; | ||
| 1056 | } | ||
| 1057 | return @vals; | ||
| 1058 | }); | ||
| 1059 | } | ||
| 1060 | |||
| 1061 | # FOR %%V IN (list) DO cmd | ||
| 1062 | if ($line =~ /\AFOR\s+(?:%%|\x00FOR_)([A-Za-z])(?:\x00)?\s+IN\s*\(([^)]*)\)\s+DO\s+(.*)/i) { | ||
| 1063 | my ($var, $list_str, $do_part) = ($1, $2, $3); | ||
| 1064 | my @items = split /[\s,]+/, $list_str; | ||
| 1065 | my @expanded = (); | ||
| 1066 | for my $item (@items) { | ||
| 1067 | $item =~ s/\A\s+//; $item =~ s/\s+\z//; | ||
| 1068 | next if $item eq ''; | ||
| 1069 | if ($item =~ /[*?]/) { | ||
| 1070 | my @g = map { BATsh::MB::enc($_) } | ||
| 1071 | BATsh::SH::_glob_paths(BATsh::MB::dec($item)); | ||
| 1072 | push @expanded, @g ? @g : ($item); | ||
| 1073 | } | ||
| 1074 | else { push @expanded, $item } | ||
| 1075 | } | ||
| 1076 | return _for_iterate($class, $var, $do_part, $lines_ref, $labels_ref, $i_ref, $opts_ref, | ||
| 1077 | sub { return @expanded }); | ||
| 1078 | } | ||
| 1079 | |||
| 1080 | _warn("FOR: unsupported syntax: $line"); | ||
| 1081 | return 1; | ||
| 1082 | } | ||
| 1083 | |||
| 1084 | # ---------------------------------------------------------------- | ||
| 1085 | # _for_iterate: common FOR loop body runner | ||
| 1086 | # ---------------------------------------------------------------- | ||
| 1087 | sub _for_iterate { | ||
| 1088 | my ($class, $var, $do_part, $lines_ref, $labels_ref, $i_ref, $opts_ref, $gen) = @_; | ||
| 1089 | |||
| 1090 | # Pre-read paren body if do_part is "(" | ||
| 1091 | my $paren_body_template = undef; | ||
| 1092 | { | ||
| 1093 | my $probe = $do_part; | ||
| 1094 | $probe =~ s/\x00FOR_[A-Za-z]\x00//g; | ||
| 1095 | $probe =~ s/\x00PCT_[^\x00]+\x00//g; | ||
| 1096 | $probe =~ s/%%[A-Za-z]//g; | ||
| 1097 | if ($probe =~ /\A\s*\(\s*\z/) { | ||
| 1098 | $paren_body_template = _read_paren_block('', $lines_ref, $i_ref); | ||
| 1099 | } | ||
| 1100 | } | ||
| 1101 | |||
| 1102 | # If we have a paren block, expand %VAR% ONCE at FOR-parse time | ||
| 1103 | # (cmd.exe expands the whole block before any iteration runs). | ||
| 1104 | # PCT placeholders (%%V protected vars) are restored to %VAR% first, | ||
| 1105 | # then _block_expand runs the single-pass %VAR% substitution. | ||
| 1106 | # The result is a template with loop-var placeholders still intact. | ||
| 1107 | my $paren_expanded = undef; | ||
| 1108 | if (defined $paren_body_template) { | ||
| 1109 | my $tpl = $paren_body_template; | ||
| 1110 | # Restore PCT placeholders -> %VAR% so _block_expand can see them | ||
| 1111 | $tpl =~ s/\x00PCT_([^\x00]+)\x00/%$1%/g; | ||
| 1112 | # But protect the loop variable itself from _block_expand | ||
| 1113 | # (it will be substituted per-iteration below) | ||
| 1114 | $tpl =~ s/%%$var/"\x00LOOPVAR\x00"/ge; | ||
| 1115 | $tpl =~ s/\x00FOR_$var\x00/"\x00LOOPVAR\x00"/ge; | ||
| 1116 | # Single-pass %VAR% expansion at FOR-line parse time | ||
| 1117 | $paren_expanded = _block_expand($tpl); | ||
| 1118 | # _block_expand already restored other %%X -> %%X, leave loop placeholder | ||
| 1119 | } | ||
| 1120 | |||
| 1121 | my @values = $gen->(); | ||
| 1122 | |||
| 1123 | for my $val (@values) { | ||
| 1124 | BATsh::Env->set("%%$var", $val); | ||
| 1125 | |||
| 1126 | if (defined $paren_expanded) { | ||
| 1127 | # Substitute loop variable placeholder with current value | ||
| 1128 | my $body = $paren_expanded; | ||
| 1129 | $body =~ s/\x00LOOPVAR\x00/$val/g; | ||
| 1130 | # At runtime: if delayed expansion is on, expand !VAR! | ||
| 1131 | # _exec_body with pre_expanded=1 handles this via _exec_line | ||
| 1132 | _exec_body($class, $body, $lines_ref, $labels_ref, $i_ref, $opts_ref, 1); | ||
| 1133 | } | ||
| 1134 | else { | ||
| 1135 | my $do_line = $do_part; | ||
| 1136 | # Replace loop variable placeholder/shorthand with current value | ||
| 1137 | $do_line =~ s/%%$var/$val/g; | ||
| 1138 | $do_line =~ s/\x00FOR_$var\x00/$val/g; | ||
| 1139 | # Restore other FOR-variable placeholders to %%X form | ||
| 1140 | $do_line =~ s/\x00FOR_([A-Za-z])\x00/%%$1/g; | ||
| 1141 | # Restore %VAR% placeholders so expand_cmd can expand them | ||
| 1142 | $do_line =~ s/\x00PCT_([^\x00]+)\x00/%$1%/g; | ||
| 1143 | $do_line = BATsh::Env->expand_cmd($do_line); | ||
| 1144 | _exec_line($class, $do_line, $lines_ref, $labels_ref, $i_ref, $opts_ref, 1); | ||
| 1145 | } | ||
| 1146 | last if $_GOTO_LABEL ne ''; | ||
| 1147 | } | ||
| 1148 | return 0; | ||
| 1149 | } | ||
| 1150 | |||
| 1151 | # ---------------------------------------------------------------- | ||
| 1152 | # FOR /F | ||
| 1153 | # | ||
| 1154 | # Options string (inside quotes): tokens= delims= skip= eol= usebackq | ||
| 1155 | # Source: | ||
| 1156 | # "filename" -- iterate lines of file (or usebackq: command output) | ||
| 1157 | # 'command' -- command output (or usebackq: literal filename) | ||
| 1158 | # ("string") -- tokenize the string itself | ||
| 1159 | # ---------------------------------------------------------------- | ||
| 1160 | sub _cmd_for_f { | ||
| 1161 | my ($class, $opts_str, $var, $source_str, $do_part, $lines_ref, $labels_ref, $i_ref, $opts_ref) = @_; | ||
| 1162 | |||
| 1163 | # Strip outer quotes from opts_str | ||
| 1164 | $opts_str =~ s/\A"//; $opts_str =~ s/"\z//; | ||
| 1165 | |||
| 1166 | # Parse options | ||
| 1167 | my $tokens_spec = '1'; # default: first token only | ||
| 1168 | my $delims = " \t"; # default delimiters | ||
| 1169 | my $skip = 0; | ||
| 1170 | my $eol = ';'; # default: skip lines starting with ; | ||
| 1171 | my $usebackq = 0; | ||
| 1172 | |||
| 1173 | $usebackq = 1 if $opts_str =~ /usebackq/i; | ||
| 1174 | if ($opts_str =~ /tokens=(\S+)/i) { | ||
| 1175 | $tokens_spec = $1; | ||
| 1176 | $tokens_spec =~ s/,\z//; | ||
| 1177 | } | ||
| 1178 | if ($opts_str =~ /delims=([^\s"]*)/i) { | ||
| 1179 | $delims = $1; | ||
| 1180 | $delims = ' ' if $delims eq ''; # delims= (empty) means no split? No: empty = space only | ||
| 1181 | } | ||
| 1182 | elsif ($opts_str =~ /delims=\s*\z/i) { | ||
| 1183 | $delims = ''; # delims= with nothing = no delimiter (whole line = one token) | ||
| 1184 | } | ||
| 1185 | if ($opts_str =~ /skip=(\d+)/i) { $skip = int($1) } | ||
| 1186 | if ($opts_str =~ /eol=(.)/i) { $eol = $1 } | ||
| 1187 | |||
| 1188 | # Parse tokens spec: e.g. "1,2,3" "1-3" "1,2*" "*" | ||
| 1189 | my @token_indices = _parse_tokens_spec($tokens_spec); | ||
| 1190 | my $want_star = ($tokens_spec =~ /\*/) ? 1 : 0; | ||
| 1191 | |||
| 1192 | # Determine source lines | ||
| 1193 | my @lines_to_process; | ||
| 1194 | $source_str =~ s/\A\s+//; $source_str =~ s/\s+\z//; | ||
| 1195 | |||
| 1196 | if ($source_str =~ /\A'([^']*)'\z/ || ($usebackq && $source_str =~ /\A`([^`]*)`\z/)) { | ||
| 1197 | # Command output | ||
| 1198 | my $cmd = BATsh::MB::dec($1); | ||
| 1199 | BATsh::Env->sync_to_env(); | ||
| 1200 | local *CMDOUT; | ||
| 1201 | open(CMDOUT, "$cmd |") or return 1; | ||
| 1202 | @lines_to_process = map { BATsh::MB::enc($_) } <CMDOUT>; | ||
| 1203 | close(CMDOUT); | ||
| 1204 | } | ||
| 1205 | elsif ($usebackq && $source_str =~ /\A"([^"]*)"\z/) { | ||
| 1206 | # usebackq: "..." = filename | ||
| 1207 | my $file = BATsh::MB::dec($1); | ||
| 1208 | local *FFH; | ||
| 1209 | open(FFH, $file) or do { _warn("FOR /F: cannot open $file"); return 1 }; | ||
| 1210 | @lines_to_process = map { BATsh::MB::enc($_) } <FFH>; | ||
| 1211 | close(FFH); | ||
| 1212 | } | ||
| 1213 | elsif ($source_str =~ /\A"([^"]*)"\z/ && !$usebackq) { | ||
| 1214 | # No usebackq: "string" = literal string to tokenize | ||
| 1215 | @lines_to_process = ("$1\n"); | ||
| 1216 | } | ||
| 1217 | elsif ($source_str =~ /\A(\S+)\z/) { | ||
| 1218 | # Bare filename | ||
| 1219 | my $file = BATsh::MB::dec($1); | ||
| 1220 | local *FFH2; | ||
| 1221 | open(FFH2, $file) or do { _warn("FOR /F: cannot open $file"); return 1 }; | ||
| 1222 | @lines_to_process = map { BATsh::MB::enc($_) } <FFH2>; | ||
| 1223 | close(FFH2); | ||
| 1224 | } | ||
| 1225 | else { | ||
| 1226 | _warn("FOR /F: cannot parse source: $source_str"); | ||
| 1227 | return 1; | ||
| 1228 | } | ||
| 1229 | |||
| 1230 | # Skip leading lines | ||
| 1231 | splice(@lines_to_process, 0, $skip) if $skip > 0; | ||
| 1232 | |||
| 1233 | # Pre-read paren body if needed | ||
| 1234 | my $paren_body = undef; | ||
| 1235 | { | ||
| 1236 | my $probe = $do_part; | ||
| 1237 | $probe =~ s/%%[A-Za-z]//g; | ||
| 1238 | if ($probe =~ /\A\s*\(\s*\z/) { | ||
| 1239 | $paren_body = _read_paren_block('', $lines_ref, $i_ref); | ||
| 1240 | } | ||
| 1241 | } | ||
| 1242 | |||
| 1243 | # Determine variable names: %%a and following letters for extra tokens | ||
| 1244 | my @var_names; | ||
| 1245 | for my $i (0 .. $#token_indices) { | ||
| 1246 | push @var_names, chr(ord($var) + $i); | ||
| 1247 | } | ||
| 1248 | # Star token goes to the next letter after the listed ones | ||
| 1249 | my $star_var = chr(ord($var) + scalar @token_indices); | ||
| 1250 | |||
| 1251 | for my $src_line (@lines_to_process) { | ||
| 1252 | $src_line =~ s/\r?\n\z//; | ||
| 1253 | # Skip eol lines | ||
| 1254 | next if $eol ne '' && $src_line =~ /\A\Q$eol\E/; | ||
| 1255 | next if $src_line =~ /\A\s*\z/; | ||
| 1256 | |||
| 1257 | # Tokenize | ||
| 1258 | my @tokens; | ||
| 1259 | if ($delims eq '') { | ||
| 1260 | @tokens = ($src_line); | ||
| 1261 | } | ||
| 1262 | else { | ||
| 1263 | my $escaped_delims = quotemeta($delims); | ||
| 1264 | @tokens = split /[$escaped_delims]+/, $src_line; | ||
| 1265 | # cmd.exe skips leading delimiters | ||
| 1266 | if ($src_line =~ /\A[$escaped_delims]/) { | ||
| 1267 | shift @tokens if @tokens && $tokens[0] eq ''; | ||
| 1268 | } | ||
| 1269 | } | ||
| 1270 | |||
| 1271 | # Assign to variables | ||
| 1272 | for my $i (0 .. $#token_indices) { | ||
| 1273 | my $tidx = $token_indices[$i] - 1; # 0-based | ||
| 1274 | BATsh::Env->set("%%$var_names[$i]", defined $tokens[$tidx] ? $tokens[$tidx] : ''); | ||
| 1275 | } | ||
| 1276 | if ($want_star && @tokens > $token_indices[-1]) { | ||
| 1277 | # Star: remainder from token N onwards joined by first delimiter | ||
| 1278 | my $delim1 = length($delims) > 0 ? substr($delims, 0, 1) : ' '; | ||
| 1279 | my $remainder = join($delim1, @tokens[$token_indices[-1] .. $#tokens]); | ||
| 1280 | BATsh::Env->set("%%$star_var", $remainder); | ||
| 1281 | } | ||
| 1282 | |||
| 1283 | # Execute body | ||
| 1284 | if (defined $paren_body) { | ||
| 1285 | my $body = $paren_body; | ||
| 1286 | # Restore any \x00FOR_x\x00 placeholders before substituting values | ||
| 1287 | $body =~ s/\x00FOR_([A-Za-z])\x00/%%$1/g; | ||
| 1288 | for my $vn (@var_names, $want_star ? ($star_var) : ()) { | ||
| 1289 | my $val = defined(BATsh::Env->get("%%$vn")) ? BATsh::Env->get("%%$vn") : ''; | ||
| 1290 | $body =~ s/%%$vn/$val/g; | ||
| 1291 | } | ||
| 1292 | $body = _block_expand($body); | ||
| 1293 | _exec_body($class, $body, $lines_ref, $labels_ref, $i_ref, $opts_ref, 1); | ||
| 1294 | } | ||
| 1295 | else { | ||
| 1296 | my $do_line = $do_part; | ||
| 1297 | # Restore \x00FOR_x\x00 -> %%x, then substitute values | ||
| 1298 | $do_line =~ s/\x00FOR_([A-Za-z])\x00/%%$1/g; | ||
| 1299 | for my $vn (@var_names, $want_star ? ($star_var) : ()) { | ||
| 1300 | my $val = defined(BATsh::Env->get("%%$vn")) ? BATsh::Env->get("%%$vn") : ''; | ||
| 1301 | $do_line =~ s/%%$vn/$val/g; | ||
| 1302 | } | ||
| 1303 | $do_line = BATsh::Env->expand_cmd($do_line); | ||
| 1304 | _exec_line($class, $do_line, $lines_ref, $labels_ref, $i_ref, $opts_ref, 1); | ||
| 1305 | } | ||
| 1306 | last if $_GOTO_LABEL ne ''; | ||
| 1307 | } | ||
| 1308 | return 0; | ||
| 1309 | } | ||
| 1310 | |||
| 1311 | # ---------------------------------------------------------------- | ||
| 1312 | # _parse_tokens_spec: "1,2,3-5,*" -> (1,2,3,4,5) | ||
| 1313 | # ---------------------------------------------------------------- | ||
| 1314 | sub _parse_tokens_spec { | ||
| 1315 | my ($spec) = @_; | ||
| 1316 | $spec =~ s/\*//g; # star handled separately | ||
| 1317 | my @indices; | ||
| 1318 | for my $part (split /,/, $spec) { | ||
| 1319 | $part =~ s/\A\s+//; $part =~ s/\s+\z//; | ||
| 1320 | next unless $part =~ /\S/; | ||
| 1321 | if ($part =~ /\A(\d+)-(\d+)\z/) { | ||
| 1322 | push @indices, ($1 .. $2); | ||
| 1323 | } | ||
| 1324 | elsif ($part =~ /\A(\d+)\z/) { | ||
| 1325 | push @indices, $1; | ||
| 1326 | } | ||
| 1327 | } | ||
| 1328 | @indices = (1) unless @indices; | ||
| 1329 | return @indices; | ||
| 1330 | } | ||
| 1331 | |||
| 1332 | # ---------------------------------------------------------------- | ||
| 1333 | # CALL | ||
| 1334 | # ---------------------------------------------------------------- | ||
| 1335 | sub _cmd_call { | ||
| 1336 | my ($class, $rest, $opts_ref) = @_; | ||
| 1337 | $rest =~ s/\A\s+//; | ||
| 1338 | |||
| 1339 | if ($rest =~ /\A:([A-Za-z_][A-Za-z0-9_]*)(.*)/i) { | ||
| 1340 | my ($lbl, $argstr) = (uc($1), $2); | ||
| 1341 | # $rest reaches here already %-expanded by _expand_line, so split the | ||
| 1342 | # argument string with double-quote awareness and let call_sub install | ||
| 1343 | # the %0..%9 / %* frame (and restore the caller's on return). | ||
| 1344 | my @args = _split_call_args($argstr); | ||
| 1345 | if (defined $opts_ref->{'_batsh'}) { | ||
| 1346 | $opts_ref->{'_batsh'}->call_sub($lbl, @args); | ||
| 1347 | } | ||
| 1348 | return 0; | ||
| 1349 | } | ||
| 1350 | |||
| 1351 | if ($rest =~ /(\S+\.batsh)(.*)/i) { | ||
| 1352 | my $file = $1; | ||
| 1353 | if (defined $opts_ref->{'_batsh'}) { | ||
| 1354 | $opts_ref->{'_batsh'}->source_file($file); | ||
| 1355 | } | ||
| 1356 | return 0; | ||
| 1357 | } | ||
| 1358 | |||
| 1359 | # CALL cmd args: execute with double-expansion | ||
| 1360 | # Re-expand the already-expanded string (second pass) | ||
| 1361 | my $reexpanded = BATsh::Env->expand_cmd($rest); | ||
| 1362 | return _cmd_external($reexpanded, ''); | ||
| 1363 | } | ||
| 1364 | |||
| 1365 | # ---------------------------------------------------------------- | ||
| 1366 | # _split_call_args: split a CALL argument string into words, honouring | ||
| 1367 | # double quotes (cmd.exe uses double quotes only). Surrounding quotes | ||
| 1368 | # are removed. | ||
| 1369 | # ---------------------------------------------------------------- | ||
| 1370 | sub _split_call_args { | ||
| 1371 | my ($s) = @_; | ||
| 1372 | $s = '' unless defined $s; | ||
| 1373 | $s =~ s/\A\s+//; $s =~ s/\s+\z//; | ||
| 1374 | return () if $s eq ''; | ||
| 1375 | my @out; | ||
| 1376 | my $cur = ''; | ||
| 1377 | my $have = 0; | ||
| 1378 | my $in_q = 0; | ||
| 1379 | for my $c (split //, $s) { | ||
| 1380 | if ($c eq '"') { $in_q = !$in_q; $have = 1; next } | ||
| 1381 | if ($c =~ /\s/ && !$in_q) { | ||
| 1382 | if ($have) { push @out, $cur; $cur = ''; $have = 0 } | ||
| 1383 | next; | ||
| 1384 | } | ||
| 1385 | $cur .= $c; $have = 1; | ||
| 1386 | } | ||
| 1387 | push @out, $cur if $have; | ||
| 1388 | return @out; | ||
| 1389 | } | ||
| 1390 | |||
| 1391 | # ---------------------------------------------------------------- | ||
| 1392 | # SHIFT [/N] -- shift positional parameters %1..%9 left, rebuild %* | ||
| 1393 | # | ||
| 1394 | # Plain SHIFT moves %2 into %1, %3 into %2, ... %9 into %8, and clears | ||
| 1395 | # %9. SHIFT /N begins the shift at %N (parameters %1..%(N-1) are left | ||
| 1396 | # unchanged), matching cmd.exe. %0 is left untouched (BATsh's documented | ||
| 1397 | # contract shifts %1..%9 and %*; this also keeps a CALL'd label's name | ||
| 1398 | # stable). The SH-side BATSH_ARG* mirror is updated so an SH subroutine | ||
| 1399 | # body sees the same shift via $1..$9. | ||
| 1400 | # ---------------------------------------------------------------- | ||
| 1401 | sub _cmd_shift { | ||
| 1402 | my ($rest) = @_; | ||
| 1403 | $rest = '' unless defined $rest; | ||
| 1404 | my $start = 1; | ||
| 1405 | if ($rest =~ /\/(\d)/) { $start = int($1) } | ||
| 1406 | $start = 1 if $start < 1; | ||
| 1407 | $start = 9 if $start > 9; | ||
| 1408 | |||
| 1409 | for (my $n = $start; $n < 9; $n++) { | ||
| 1410 | my $next = BATsh::Env->get('%' . ($n + 1)); | ||
| 1411 | BATsh::Env->set('%' . $n, defined($next) ? $next : ''); | ||
| 1412 | } | ||
| 1413 | BATsh::Env->set('%9', ''); | ||
| 1414 | |||
| 1415 | # Rebuild %* from the contiguous run of non-empty positional params. | ||
| 1416 | my @remaining; | ||
| 1417 | for my $n (1 .. 9) { | ||
| 1418 | my $v = BATsh::Env->get("%$n"); | ||
| 1419 | last unless defined $v && $v ne ''; | ||
| 1420 | push @remaining, $v; | ||
| 1421 | } | ||
| 1422 | BATsh::Env->set('%*', join(' ', @remaining)); | ||
| 1423 | |||
| 1424 | # Keep the SH-side mirror consistent with the shifted %1..%9. | ||
| 1425 | for my $n (1 .. 9) { | ||
| 1426 | my $v = BATsh::Env->get("%$n"); | ||
| 1427 | $BATsh::Env::STORE{"BATSH_ARG$n"} = defined $v ? $v : ''; | ||
| 1428 | } | ||
| 1429 | $BATsh::Env::STORE{'BATSH_ARGC'} = scalar @remaining; | ||
| 1430 | |||
| 1431 | $ERRORLEVEL = 0; | ||
| 1432 | return 0; | ||
| 1433 | } | ||
| 1434 | |||
| 1435 | # ---------------------------------------------------------------- | ||
| 1436 | # CD / CHDIR | ||
| 1437 | # ---------------------------------------------------------------- | ||
| 1438 | sub _cmd_cd { | ||
| 1439 | my ($rest) = @_; | ||
| 1440 | $rest = BATsh::MB::dec($rest); | ||
| 1441 | $rest =~ s/\A\s+//; $rest =~ s/\s+\z//; | ||
| 1442 | $rest =~ s/\A"//; $rest =~ s/"\z//; | ||
| 1443 | if ($rest eq '' || $rest =~ /\A\/D\s*\z/i) { | ||
| 1444 | print Cwd::cwd(), "\n"; | ||
| 1445 | return 0; | ||
| 1446 | } | ||
| 1447 | $rest =~ s/\A\/D\s*//i; | ||
| 1448 | unless (chdir($rest)) { | ||
| 1449 | print "The system cannot find the path specified.\n"; | ||
| 1450 | $ERRORLEVEL = 1; | ||
| 1451 | return 1; | ||
| 1452 | } | ||
| 1453 | BATsh::Env->set('CD', BATsh::MB::enc(Cwd::cwd())); | ||
| 1454 | $ERRORLEVEL = 0; | ||
| 1455 | return 0; | ||
| 1456 | } | ||
| 1457 | |||
| 1458 | # ---------------------------------------------------------------- | ||
| 1459 | # _cmd_strip_switches: remove a command's own /X switches from its | ||
| 1460 | # argument string. The pattern used before v0.09 -- s{\s*/[A-Za-z:]+}{}g | ||
| 1461 | # -- deleted every "/word" run, so it also ate the directory components | ||
| 1462 | # of a forward-slash pathname: DEL /tmp/log/*.tmp lost "/tmp" and "/log" | ||
| 1463 | # and then complained about a file called "\*.tmp". A switch is now only | ||
| 1464 | # removed when its letter is one this command actually has (optionally | ||
| 1465 | # followed by :attributes) and it stands as a word of its own. | ||
| 1466 | # ---------------------------------------------------------------- | ||
| 1467 | sub _cmd_strip_switches { | ||
| 1468 | my ($str, $letters) = @_; | ||
| 1469 | return '' unless defined $str; | ||
| 1470 | my $again = 1; | ||
| 1471 | while ($again) { | ||
| 1472 | $again = 0; | ||
| 1473 | $again = 1 if $str =~ s{\A/([$letters])(?::[-A-Za-z]*)?(?=\s|\z)\s*}{}i; | ||
| 1474 | } | ||
| 1475 | $str =~ s{\s+/([$letters])(?::[-A-Za-z]*)?(?=\s|\z)}{}ig; | ||
| 1476 | return $str; | ||
| 1477 | } | ||
| 1478 | |||
| 1479 | # ---------------------------------------------------------------- | ||
| 1480 | # DIR | ||
| 1481 | # ---------------------------------------------------------------- | ||
| 1482 | sub _cmd_dir { | ||
| 1483 | |||
| 1484 | my ($rest) = @_; | ||
| 1485 | $rest = BATsh::MB::dec($rest); | ||
| 1486 | $rest =~ s/\A\s+//; $rest =~ s/\s+\z//; | ||
| 1487 | my $target = $rest eq '' ? '.' : $rest; | ||
| 1488 | $target = _cmd_strip_switches($target, 'ABSPWOQTLNXCR'); | ||
| 1489 | $target =~ s/\s+\z//; | ||
| 1490 | $target = '.' if $target eq ''; | ||
| 1491 | $target =~ s/\A"//; $target =~ s/"\z//; | ||
| 1492 | unless (-e $target) { print "File Not Found\n"; $ERRORLEVEL = 1; return 1 } | ||
| 1493 | local *DH; | ||
| 1494 | if (-d $target) { | ||
| 1495 | opendir(DH, $target) or do { print "Access denied.\n"; return 1 }; | ||
| 1496 | my @entries = sort readdir(DH); | ||
| 1497 | closedir(DH); | ||
| 1498 | print " Directory of $target\n\n"; | ||
| 1499 | for my $e (@entries) { | ||
| 1500 | next if $e eq '.' || $e eq '..'; | ||
| 1501 | my $full = "$target/$e"; | ||
| 1502 | if (-d $full) { printf "%-40s <DIR>\n", $e } | ||
| 1503 | else { printf "%-40s %12d\n", $e, (-s $full) } | ||
| 1504 | } | ||
| 1505 | } | ||
| 1506 | else { printf "%-40s %12d\n", $target, (-s $target) } | ||
| 1507 | $ERRORLEVEL = 0; | ||
| 1508 | return 0; | ||
| 1509 | } | ||
| 1510 | |||
| 1511 | # ---------------------------------------------------------------- | ||
| 1512 | # File operations | ||
| 1513 | # ---------------------------------------------------------------- | ||
| 1514 | sub _cmd_copy { | ||
| 1515 | my ($rest) = @_; | ||
| 1516 | $rest = BATsh::MB::dec($rest); | ||
| 1517 | $rest =~ s/\A\s+//; $rest =~ s/\s*\/[YN]\s*//gi; | ||
| 1518 | my ($src, $dst) = split /\s+/, $rest, 2; | ||
| 1519 | unless (defined $src && defined $dst) { print "The syntax of the command is incorrect.\n"; return 1 } | ||
| 1520 | $src =~ s/\A"//; $src =~ s/"\z//; | ||
| 1521 | $dst =~ s/\A"//; $dst =~ s/"\z//; | ||
| 1522 | unless (File::Copy::copy($src, $dst)) { | ||
| 1523 | print "The system cannot find the file specified.\n"; $ERRORLEVEL = 1; return 1 | ||
| 1524 | } | ||
| 1525 | print " 1 file(s) copied.\n"; $ERRORLEVEL = 0; return 0; | ||
| 1526 | } | ||
| 1527 | |||
| 1528 | sub _cmd_del { | ||
| 1529 | my ($rest) = @_; | ||
| 1530 | $rest = BATsh::MB::dec($rest); | ||
| 1531 | $rest =~ s/\A\s+//; | ||
| 1532 | $rest = _cmd_strip_switches($rest, 'PFSQA'); | ||
| 1533 | $rest =~ s/\s+\z//; | ||
| 1534 | $rest =~ s/\A"//; $rest =~ s/"\z//; | ||
| 1535 | my @files = BATsh::SH::_glob_paths($rest); | ||
| 1536 | @files = ($rest) unless @files; | ||
| 1537 | for my $f (@files) { | ||
| 1538 | unlink($f) or print "Could not find $f\n"; | ||
| 1539 | } | ||
| 1540 | $ERRORLEVEL = 0; return 0; | ||
| 1541 | } | ||
| 1542 | |||
| 1543 | sub _cmd_move { | ||
| 1544 | my ($rest) = @_; | ||
| 1545 | $rest = BATsh::MB::dec($rest); | ||
| 1546 | $rest =~ s/\A\s+//; $rest =~ s/\s*\/[YN]\s*//gi; | ||
| 1547 | my ($src, $dst) = split /\s+/, $rest, 2; | ||
| 1548 | unless (defined $src && defined $dst) { print "The syntax of the command is incorrect.\n"; return 1 } | ||
| 1549 | $src =~ s/\A"//; $src =~ s/"\z//; | ||
| 1550 | $dst =~ s/\A"//; $dst =~ s/"\z//; | ||
| 1551 | unless (File::Copy::move($src, $dst)) { | ||
| 1552 | print "The system cannot find the file specified.\n"; $ERRORLEVEL = 1; return 1 | ||
| 1553 | } | ||
| 1554 | print " 1 file(s) moved.\n"; $ERRORLEVEL = 0; return 0; | ||
| 1555 | } | ||
| 1556 | |||
| 1557 | sub _cmd_mkdir { | ||
| 1558 | my ($rest) = @_; | ||
| 1559 | $rest = BATsh::MB::dec($rest); | ||
| 1560 | $rest =~ s/\A\s+//; $rest =~ s/\s+\z//; $rest =~ s/\A"//; $rest =~ s/"\z//; | ||
| 1561 | if (-d $rest) { print "A subdirectory or file $rest already exists.\n"; $ERRORLEVEL = 1; return 1 } | ||
| 1562 | File::Path::mkpath($rest); $ERRORLEVEL = 0; return 0; | ||
| 1563 | } | ||
| 1564 | |||
| 1565 | sub _cmd_rmdir { | ||
| 1566 | my ($rest) = @_; | ||
| 1567 | $rest = BATsh::MB::dec($rest); | ||
| 1568 | $rest =~ s/\A\s+//; | ||
| 1569 | my $recurse = ($rest =~ s/\s*\/S\s*//i) ? 1 : 0; | ||
| 1570 | $rest =~ s/\s*\/Q\s*//i; $rest =~ s/\s+\z//; $rest =~ s/\A"//; $rest =~ s/"\z//; | ||
| 1571 | if ($recurse) { File::Path::rmtree($rest) } | ||
| 1572 | else { | ||
| 1573 | unless (rmdir($rest)) { | ||
| 1574 | print "The directory is not empty.\n"; $ERRORLEVEL = 1; return 1 | ||
| 1575 | } | ||
| 1576 | } | ||
| 1577 | $ERRORLEVEL = 0; return 0; | ||
| 1578 | } | ||
| 1579 | |||
| 1580 | sub _cmd_rename { | ||
| 1581 | my ($rest) = @_; | ||
| 1582 | $rest = BATsh::MB::dec($rest); | ||
| 1583 | $rest =~ s/\A\s+//; | ||
| 1584 | my ($src, $dst) = split /\s+/, $rest, 2; | ||
| 1585 | unless (defined $src && defined $dst) { print "The syntax of the command is incorrect.\n"; return 1 } | ||
| 1586 | unless (rename($src, $dst)) { | ||
| 1587 | print "Could not rename $src to $dst: $!\n"; $ERRORLEVEL = 1; return 1 | ||
| 1588 | } | ||
| 1589 | $ERRORLEVEL = 0; return 0; | ||
| 1590 | } | ||
| 1591 | |||
| 1592 | sub _cmd_type { | ||
| 1593 | my ($rest) = @_; | ||
| 1594 | $rest = BATsh::MB::dec($rest); | ||
| 1595 | $rest =~ s/\A\s+//; $rest =~ s/\s+\z//; $rest =~ s/\A"//; $rest =~ s/"\z//; | ||
| 1596 | local *TFH; | ||
| 1597 | unless (open(TFH, $rest)) { | ||
| 1598 | print "The system cannot find the file specified.\n"; $ERRORLEVEL = 1; return 1 | ||
| 1599 | } | ||
| 1600 | while (<TFH>) { print } | ||
| 1601 | close(TFH); | ||
| 1602 | $ERRORLEVEL = 0; return 0; | ||
| 1603 | } | ||
| 1604 | |||
| 1605 | # ---------------------------------------------------------------- | ||
| 1606 | # External command | ||
| 1607 | # ---------------------------------------------------------------- | ||
| 1608 | sub _cmd_external { | ||
| 1609 | my ($cmd, $rest) = @_; | ||
| 1610 | $rest = '' unless defined $rest; | ||
| 1611 | $rest =~ s/\A\s+//; | ||
| 1612 | my $full = $rest ne '' ? "$cmd $rest" : $cmd; | ||
| 1613 | $full = _unescape_caret($full); | ||
| 1614 | $full = BATsh::MB::dec($full); | ||
| 1615 | BATsh::Env->sync_to_env(); | ||
| 1616 | my $rc = system($full); | ||
| 1617 | $ERRORLEVEL = ($rc == 0) ? 0 : (($rc >> 8) || 1); | ||
| 1618 | return $ERRORLEVEL; | ||
| 1619 | } | ||
| 1620 | |||
| 1621 | # ---------------------------------------------------------------- | ||
| 1622 | # _split_cmd: split "COMMAND rest" respecting quotes | ||
| 1623 | # ---------------------------------------------------------------- | ||
| 1624 | sub _split_cmd { | ||
| 1625 | my ($line) = @_; | ||
| 1626 | if ($line =~ /\A(\S+)\s*(.*)\z/s) { | ||
| 1627 | return ($1, $2); | ||
| 1628 | } | ||
| 1629 | return ($line, ''); | ||
| 1630 | } | ||
| 1631 | |||
| 1632 | sub _warn { print STDERR "[BATsh::CMD] ", BATsh::MB::dec($_[0]), "\n" } | ||
| 1633 | |||
| 1634 | # ---------------------------------------------------------------- | ||
| 1635 | # Accessors | ||
| 1636 | # ---------------------------------------------------------------- | ||
| 1637 | sub errorlevel { return $ERRORLEVEL } | ||
| 1638 | sub set_errorlevel { $ERRORLEVEL = $_[1] } | ||
| 1639 | sub echo_on { return $ECHO_ON } | ||
| 1640 | |||
| 1641 | BEGIN { | ||
| 1642 | eval { require Cwd }; | ||
| 1643 | if ($@) { | ||
| 1644 | eval 'sub Cwd::cwd { return $ENV{CD} || "." }'; | ||
| 1645 | } | ||
| 1646 | } | ||
| 1647 | |||
| 1648 | 1; | ||
| 1649 | |||
| 1650 | __END__ |