sub key2script ($) {
my ($key) = @_;
- return $key if $key =~ m!\A/!;
+ return $key if (index($key, '/') >= 0);
# n.b. we may have scripts which don't start with "public-inbox" in
# the future:
$key =~ s/\A([-\.])/public-inbox$1/;
'blib/script/'.$key;
}
+my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
+ [ *STDERR{IO}, '>&' ]);
+
sub _prepare_redirects ($) {
my ($fhref) = @_;
- my @x = ([ \*STDIN, '<&' ], [ \*STDOUT, '>&' ], [ \*STDERR, '>&' ]);
- for (my $fd = 0; $fd <= $#x; $fd++) {
+ my $orig_io = [];
+ for (my $fd = 0; $fd <= $#io_mode; $fd++) {
my $fh = $fhref->[$fd] or next;
- my ($oldfh, $mode) = @{$x[$fd]};
+ my ($oldfh, $mode) = @{$io_mode[$fd]};
+ open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
+ $orig_io->[$fd] = $orig;
+ open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
+ }
+ $orig_io;
+}
+
+sub _undo_redirects ($) {
+ my ($orig_io) = @_;
+ for (my $fd = 0; $fd <= $#io_mode; $fd++) {
+ my $fh = $orig_io->[$fd] or next;
+ my ($oldfh, $mode) = @{$io_mode[$fd]};
open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
}
}
my $f = key2script($key);
open my $fh, '<', $f or die "open $f: $!";
my $str = do { local $/; <$fh> };
- my ($fc, $rest) = ($key =~ m/([a-z])([a-z0-9]+)\z/);
- $fc = uc($fc);
- my $pkg = "PublicInbox::TestScript::$fc$rest";
+ my $pkg = (split(m!/!, $f))[-1];
+ $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
+ $pkg .= "_T" if $3;
+ $pkg =~ tr/-.//d;
+ $pkg = "PublicInbox::TestScript::$pkg";
eval <<EOF;
package $pkg;
use strict;
*exit = *PublicInbox::TestCommon::run_script_exit;
sub main {
+# the below "line" directive is a magic comment, see perlsyn(1) manpage
+# line 1 "$f"
$str
0;
}
$r == $pid or die "waitpid: expected $pid, got $r";
}
} else { # localize and run everything in the same process:
- local *STDIN = *STDIN;
- local *STDOUT = *STDOUT;
- local *STDERR = *STDERR;
+ # note: "local *STDIN = *STDIN;" and so forth did not work in
+ # old versions of perl
local %ENV = $env ? (%ENV, %$env) : %ENV;
local %SIG = %SIG;
local $0 = join(' ', @$cmd);
- _prepare_redirects($fhref);
+ my $orig_io = _prepare_redirects($fhref);
_run_sub($sub, $key, \@argv);
+ _undo_redirects($orig_io);
}
# slurp the redirects back into user-supplied strings