| 1 | package BATsh::Env; | ||
| 2 | # Copyright (c) 2026 INABA Hitoshi <ina.cpan@gmail.com> | ||
| 3 | ###################################################################### | ||
| 4 | # | ||
| 5 | # BATsh::Env - Shared environment variable store | ||
| 6 | # | ||
| 7 | # v0.02 changes: | ||
| 8 | # - Variable names are case-insensitive (cmd.exe compatible). | ||
| 9 | # Stored internally in uppercase. | ||
| 10 | # - SETLOCAL ENABLEDELAYEDEXPANSION flag tracked per scope. | ||
| 11 | # - expand_cmd expands !VAR! when delayed expansion is active. | ||
| 12 | # - expand_cmd expands %0..%9 and %* positional parameters. | ||
| 13 | # - _expand_tilde_param: %~[fdpnx]*N batch-parameter tilde modifiers. | ||
| 14 | # Modifiers f(full path), d(drive), p(dir), n(basename), x(ext). | ||
| 15 | # Uses File::Spec and Cwd for cross-platform absolute path resolution. | ||
| 16 | # - init() guards undef %ENV values (Windows compatibility). | ||
| 17 | # | ||
| 18 | ###################################################################### | ||
| 19 | |||
| 20 | use strict; | ||
| 21 | BEGIN { if ($] < 5.006 && !defined(&warnings::import)) { $INC{'warnings.pm'} = 'stub'; eval 'package warnings; sub import {}' } } | ||
| 22 | use warnings; local $^W = 1; | ||
| 23 | BEGIN { pop @INC if $INC[-1] eq '.' } | ||
| 24 | |||
| 25 | use vars qw($VERSION); | ||
| 26 | $VERSION = '0.09'; | ||
| 27 | |||
| 28 | require BATsh::MB; | ||
| 29 | |||
| 30 | use File::Spec (); | ||
| 31 | BEGIN { eval { require Cwd } } | ||
| 32 | BEGIN { eval { require POSIX } } | ||
| 33 | $VERSION = $VERSION; | ||
| 34 | |||
| 35 | # Keys stored in UPPERCASE for case-insensitive lookup | ||
| 36 | use vars qw(%STORE); | ||
| 37 | |||
| 38 | # Delayed expansion flag | ||
| 39 | use vars qw($DELAYED_EXPANSION); | ||
| 40 | $DELAYED_EXPANSION = 0; | ||
| 41 | |||
| 42 | # SETLOCAL scope stack: each entry = { store => \%snap, delayed => $flag } | ||
| 43 | use vars qw(@SETLOCAL_STACK); | ||
| 44 | @SETLOCAL_STACK = (); | ||
| 45 | |||
| 46 | sub init { | ||
| 47 | %STORE = (); | ||
| 48 | for my $k (keys %ENV) { | ||
| 49 | $STORE{uc($k)} = defined $ENV{$k} ? $ENV{$k} : ''; | ||
| 50 | } | ||
| 51 | $DELAYED_EXPANSION = 0; | ||
| 52 | } | ||
| 53 | |||
| 54 | sub _key { return uc($_[0]) } | ||
| 55 | |||
| 56 | sub get { my ($c, $n) = @_; return $STORE{_key($n)} } | ||
| 57 | sub set { my ($c, $n, $v) = @_; $STORE{_key($n)} = defined $v ? $v : '' } | ||
| 58 | sub unset { my ($c, $n) = @_; delete $STORE{_key($n)} } | ||
| 59 | sub exists_var { my ($c, $n) = @_; return exists $STORE{_key($n)} ? 1 : 0 } | ||
| 60 | sub sync_to_env { | ||
| 61 | %ENV = (); | ||
| 62 | for my $k (keys %STORE) { | ||
| 63 | next if index($k, '%') >= 0; # %0..%9, %*, %%V: not env names | ||
| 64 | $ENV{$k} = BATsh::MB::dec($STORE{$k}); | ||
| 65 | } | ||
| 66 | } | ||
| 67 | sub snapshot { my %s = %STORE; return { %s } } | ||
| 68 | sub restore { my ($c, $s) = @_; %STORE = %{$s} } | ||
| 69 | sub delayed_expansion { return $DELAYED_EXPANSION } | ||
| 70 | |||
| 71 | sub setlocal { | ||
| 72 | my ($opts) = @_; | ||
| 73 | $opts = '' unless defined $opts; | ||
| 74 | my %snap = %STORE; | ||
| 75 | push @SETLOCAL_STACK, { store => { %snap }, delayed => $DELAYED_EXPANSION }; | ||
| 76 | if ($opts =~ /ENABLEDELAYEDEXPANSION/i) { $DELAYED_EXPANSION = 1 } | ||
| 77 | elsif ($opts =~ /DISABLEDELAYEDEXPANSION/i) { $DELAYED_EXPANSION = 0 } | ||
| 78 | # ENABLEEXTENSIONS / DISABLEEXTENSIONS: accepted, not modelled | ||
| 79 | } | ||
| 80 | |||
| 81 | sub endlocal { | ||
| 82 | unless (@SETLOCAL_STACK) { | ||
| 83 | warn "[BATsh] Warning: ENDLOCAL without matching SETLOCAL\n"; | ||
| 84 | return; | ||
| 85 | } | ||
| 86 | my $f = pop @SETLOCAL_STACK; | ||
| 87 | %STORE = %{$f->{store}}; | ||
| 88 | $DELAYED_EXPANSION = $f->{delayed}; | ||
| 89 | } | ||
| 90 | |||
| 91 | # ---------------------------------------------------------------- | ||
| 92 | # expand_cmd: %VAR% expansion, then optional !VAR! delayed expansion | ||
| 93 | # ---------------------------------------------------------------- | ||
| 94 | sub expand_cmd { | ||
| 95 | my ($class, $str) = @_; | ||
| 96 | return '' unless defined $str; | ||
| 97 | |||
| 98 | # %~[modifiers][0-9]: batch parameter modifiers (e.g. %~dp0, %~nx1) | ||
| 99 | # Must be processed BEFORE %VAR% to avoid being mis-parsed. | ||
| 100 | $str =~ s/%~([fdpnxs]*)([0-9])/_expand_tilde_param($1, $2)/ge; | ||
| 101 | |||
| 102 | # Batch positional parameters: %0..%9 and %* (single % prefix, no closing %) | ||
| 103 | # Must expand BEFORE %VAR% so that "%0 foo=%1" is not mis-parsed by | ||
| 104 | # the greedy %([^%]+)% pattern as a single named variable. | ||
| 105 | $str =~ s/%([0-9*])/ | ||
| 106 | do { my $k = "%$1"; exists($STORE{$k}) ? $STORE{$k} : '' } | ||
| 107 | /ge; | ||
| 108 | |||
| 109 | # %VAR:~n,m% substring and %VAR:str1=str2% substitution | ||
| 110 | # Must be processed BEFORE plain %VAR% expansion. | ||
| 111 | $str =~ s/%([A-Za-z_][A-Za-z0-9_]*):([^% | ||
| 112 | ]+)%/_expand_var_modifier($1,$2)/ge; | ||
| 113 | |||
| 114 | # %VAR% substitution: dynamic pseudo-variables first, then STORE lookup | ||
| 115 | $str =~ s/%([^%\r\n]+)%/_expand_named_var($1)/ge; | ||
| 116 | |||
| 117 | # %% -> literal % | ||
| 118 | $str =~ s/%%/%/g; | ||
| 119 | |||
| 120 | # !VAR! delayed expansion (only when enabled) | ||
| 121 | if ($DELAYED_EXPANSION) { | ||
| 122 | $str =~ s/!([A-Za-z_][A-Za-z0-9_]*)!/ | ||
| 123 | do { my $k=uc($1); exists($STORE{$k}) ? $STORE{$k} : '' } | ||
| 124 | /ge; | ||
| 125 | } | ||
| 126 | |||
| 127 | return $str; | ||
| 128 | } | ||
| 129 | |||
| 130 | # ---------------------------------------------------------------- | ||
| 131 | # _expand_tilde_param: resolve %~[fdpnx]*N batch-parameter modifiers | ||
| 132 | # | ||
| 133 | # Modifier letters (combinable, same as cmd.exe): | ||
| 134 | # (none) strip surrounding double-quotes only | ||
| 135 | # f fully qualified path (absolute) | ||
| 136 | # d drive letter only (e.g. "C:" on Windows, "" on Unix) | ||
| 137 | # p path component only (directory, with trailing separator) | ||
| 138 | # n filename without extension | ||
| 139 | # x extension only (including leading dot, e.g. ".bat") | ||
| 140 | # | ||
| 141 | # The value is taken from %N in the Env store (%0..%9). | ||
| 142 | # ---------------------------------------------------------------- | ||
| 143 | # _expand_named_var: resolve %VARNAME% with dynamic pseudo-variable support | ||
| 144 | # | ||
| 145 | # Dynamic pseudo-variables (read-only, computed at expansion time): | ||
| 146 | # %RANDOM% pseudo-random integer 0-32767 (cmd.exe range) | ||
| 147 | # %DATE% current date YYYY-MM-DD | ||
| 148 | # %TIME% current time HH:MM:SS.cc | ||
| 149 | # %CD% current working directory | ||
| 150 | # %CMDCMDLINE% empty string (not meaningful in a pure-Perl interpreter) | ||
| 151 | # %ERRORLEVEL% current ERRORLEVEL from BATsh::CMD (via hook function) | ||
| 152 | # | ||
| 153 | # All other names: looked up in %STORE (case-insensitive, as cmd.exe). | ||
| 154 | # ---------------------------------------------------------------- | ||
| 155 | sub _expand_named_var { | ||
| 156 | my ($name) = @_; | ||
| 157 | my $upper = uc($name); | ||
| 158 | if ($upper eq 'RANDOM') { | ||
| 159 | return int(rand(32768)); | ||
| 160 | } | ||
| 161 | if ($upper eq 'DATE') { | ||
| 162 | my @t = localtime(time()); | ||
| 163 | return sprintf('%04d-%02d-%02d', $t[5]+1900, $t[4]+1, $t[3]); | ||
| 164 | } | ||
| 165 | if ($upper eq 'TIME') { | ||
| 166 | my @t = localtime(time()); | ||
| 167 | return sprintf('%02d:%02d:%02d.%02d', $t[2], $t[1], $t[0], 0); | ||
| 168 | } | ||
| 169 | if ($upper eq 'CD') { | ||
| 170 | return BATsh::MB::enc(defined(&Cwd::cwd) ? Cwd::cwd() : '.'); | ||
| 171 | } | ||
| 172 | if ($upper eq 'CMDCMDLINE') { | ||
| 173 | return ''; | ||
| 174 | } | ||
| 175 | if ($upper eq 'ERRORLEVEL') { | ||
| 176 | return defined(&BATsh::CMD::_get_errorlevel) | ||
| 177 | ? BATsh::CMD::_get_errorlevel() | ||
| 178 | : (exists($STORE{ERRORLEVEL}) ? $STORE{ERRORLEVEL} : '0'); | ||
| 179 | } | ||
| 180 | return exists($STORE{$upper}) ? $STORE{$upper} : ''; | ||
| 181 | } | ||
| 182 | |||
| 183 | # ---------------------------------------------------------------- | ||
| 184 | # _expand_var_modifier: %VAR:~n,m% substring / %VAR:str1=str2% substitution | ||
| 185 | # | ||
| 186 | # Substring form (cmd.exe compatible): | ||
| 187 | # %VAR:~n% characters from offset n to end | ||
| 188 | # %VAR:~n,m% m characters starting at offset n (negative = from end) | ||
| 189 | # | ||
| 190 | # Substitution form: | ||
| 191 | # %VAR:str1=str2% replace first occurrence of str1 with str2 | ||
| 192 | # %VAR:*str1=str2% replace from start up-to-and-including first str1 | ||
| 193 | # with str2 (cmd.exe *-prefix behaviour) | ||
| 194 | # ---------------------------------------------------------------- | ||
| 195 | sub _expand_var_modifier { | ||
| 196 | my ($varname, $modifier) = @_; | ||
| 197 | my $val = do { | ||
| 198 | my $k = uc($varname); | ||
| 199 | exists($STORE{$k}) ? $STORE{$k} : '' | ||
| 200 | }; | ||
| 201 | |||
| 202 | # Substring: ~n or ~n,m | ||
| 203 | if ($modifier =~ /\A~(-?\d+)(?:,(-?\d+))?\z/) { | ||
| 204 | my ($n, $m) = ($1, $2); | ||
| 205 | my $len = BATsh::MB::mb_length($val); | ||
| 206 | my $start = ($n < 0) ? $len + $n : $n; | ||
| 207 | $start = 0 if $start < 0; | ||
| 208 | return '' if $start >= $len; | ||
| 209 | if (!defined $m) { | ||
| 210 | return BATsh::MB::mb_substr($val, $start); | ||
| 211 | } | ||
| 212 | my $end; | ||
| 213 | if ($m < 0) { | ||
| 214 | $end = $len + $m; | ||
| 215 | } | ||
| 216 | else { | ||
| 217 | $end = $start + $m; | ||
| 218 | } | ||
| 219 | $end = $len if $end > $len; | ||
| 220 | return '' if $end <= $start; | ||
| 221 | return BATsh::MB::mb_substr($val, $start, $end - $start); | ||
| 222 | } | ||
| 223 | |||
| 224 | # Substitution: str1=str2 or *str1=str2 | ||
| 225 | if ($modifier =~ /\A(\*?)([^=]*)=(.*)\z/) { | ||
| 226 | my ($star, $str1, $str2) = ($1, $2, $3); | ||
| 227 | if ($star eq '*') { | ||
| 228 | my $pos = index(lc($val), lc($str1)); | ||
| 229 | if ($pos >= 0) { | ||
| 230 | return $str2 . substr($val, $pos + length($str1)); | ||
| 231 | } | ||
| 232 | return $val; | ||
| 233 | } | ||
| 234 | else { | ||
| 235 | my $lval = lc($val); | ||
| 236 | my $lstr1 = lc($str1); | ||
| 237 | my $pos = index($lval, $lstr1); | ||
| 238 | if ($pos >= 0) { | ||
| 239 | return substr($val, 0, $pos) . $str2 | ||
| 240 | . substr($val, $pos + length($str1)); | ||
| 241 | } | ||
| 242 | return $val; | ||
| 243 | } | ||
| 244 | } | ||
| 245 | |||
| 246 | # Unrecognised modifier: return as-is | ||
| 247 | return '%' . $varname . ':' . $modifier . '%'; | ||
| 248 | } | ||
| 249 | |||
| 250 | # Uses File::Spec (platform-aware) and a hand-rolled path splitter so | ||
| 251 | # that Windows-style paths work correctly on Windows and Unix-style | ||
| 252 | # paths work on Unix without requiring Win32-specific modules. | ||
| 253 | # ---------------------------------------------------------------- | ||
| 254 | sub _expand_tilde_param { | ||
| 255 | my ($mods, $n) = @_; | ||
| 256 | my $key = "%$n"; | ||
| 257 | my $val = exists($STORE{$key}) ? $STORE{$key} : ''; | ||
| 258 | |||
| 259 | # Always strip surrounding double-quotes first | ||
| 260 | $val =~ s/\A"//; | ||
| 261 | $val =~ s/"\z//; | ||
| 262 | |||
| 263 | # With no recognised modifiers, just return the dequoted value | ||
| 264 | return $val unless $mods =~ /[fdpnx]/; | ||
| 265 | |||
| 266 | # --- Normalise: extract drive letter first, then convert \ to / --- | ||
| 267 | # Extracting the drive before splitting avoids "C:" being treated as | ||
| 268 | # a path component and re-attached incorrectly. | ||
| 269 | my $drv = ''; # e.g. "C:" on Windows, "" on Unix | ||
| 270 | my $path = $val; | ||
| 271 | $path =~ s{\\}{/}g; # normalise separators | ||
| 272 | if ($path =~ s{\A([A-Za-z]:)}{}) { $drv = $1 } | ||
| 273 | |||
| 274 | # --- resolve to absolute path when f/d/p requested --- | ||
| 275 | if ($mods =~ /[fdp]/) { | ||
| 276 | unless ($path =~ m{\A/} || $drv ne '') { | ||
| 277 | # relative Unix path: prepend cwd | ||
| 278 | my $cwd = BATsh::MB::enc(defined(&Cwd::cwd) ? Cwd::cwd() : '.'); | ||
| 279 | $cwd =~ s{\\}{/}g; | ||
| 280 | $cwd =~ s{/+\z}{}; | ||
| 281 | $path = "$cwd/$path"; | ||
| 282 | } | ||
| 283 | # Ensure exactly one leading slash | ||
| 284 | $path = "/$path" unless $path =~ m{\A/}; | ||
| 285 | # Collapse . and .. | ||
| 286 | my @segs; | ||
| 287 | for my $p (split m{/+}, $path) { | ||
| 288 | next if $p eq '' || $p eq '.'; | ||
| 289 | if ($p eq '..') { pop @segs if @segs } | ||
| 290 | else { push @segs, $p } | ||
| 291 | } | ||
| 292 | $path = '/' . join('/', @segs); | ||
| 293 | $path = '/' if $path eq '/'; | ||
| 294 | } | ||
| 295 | |||
| 296 | # --- split path into directory and filename --- | ||
| 297 | my ($dirs, $file) = ('', ''); | ||
| 298 | if ($path =~ m{\A(.*/)([^/]*)\z}) { | ||
| 299 | ($dirs, $file) = ($1, $2); | ||
| 300 | } | ||
| 301 | else { | ||
| 302 | $file = $path; | ||
| 303 | } | ||
| 304 | |||
| 305 | # --- split filename into base and extension --- | ||
| 306 | my ($base, $ext) = ('', ''); | ||
| 307 | if ($file =~ m{\A(.+)(\.[^.]+)\z}) { | ||
| 308 | ($base, $ext) = ($1, $2); | ||
| 309 | } | ||
| 310 | else { | ||
| 311 | $base = $file; | ||
| 312 | } | ||
| 313 | |||
| 314 | # --- build result --- | ||
| 315 | if ($mods =~ /f/) { | ||
| 316 | # Full absolute path: drive + dirs + file | ||
| 317 | # dirs already ends with / when non-root | ||
| 318 | return $drv . $dirs . $file; | ||
| 319 | } | ||
| 320 | |||
| 321 | my $result = ''; | ||
| 322 | $result .= $drv if $mods =~ /d/; | ||
| 323 | $result .= $dirs if $mods =~ /p/; | ||
| 324 | $result .= $base if $mods =~ /n/; | ||
| 325 | $result .= $ext if $mods =~ /x/; | ||
| 326 | return $result; | ||
| 327 | } | ||
| 328 | |||
| 329 | # ---------------------------------------------------------------- | ||
| 330 | # expand_sh: $VAR and ${VAR} (SH mode) | ||
| 331 | # ---------------------------------------------------------------- | ||
| 332 | sub expand_sh { | ||
| 333 | my ($class, $str) = @_; | ||
| 334 | return '' unless defined $str; | ||
| 335 | $str =~ s/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/ | ||
| 336 | do { my $k=$1; defined($STORE{$k}) ? $STORE{$k} : defined($STORE{uc($k)}) ? $STORE{uc($k)} : '' } | ||
| 337 | /ge; | ||
| 338 | $str =~ s/\$([A-Za-z_][A-Za-z0-9_]*)/ | ||
| 339 | do { my $k=$1; defined($STORE{$k}) ? $STORE{$k} : defined($STORE{uc($k)}) ? $STORE{uc($k)} : '' } | ||
| 340 | /ge; | ||
| 341 | return $str; | ||
| 342 | } | ||
| 343 | |||
| 344 | 1; | ||
| 345 | |||
| 346 | __END__ |