allow jreplclient repl to be packed into __DATA__
[scpubgit/Tak.git] / jreplclient
1 #!/usr/bin/env perl
2
3 use strictures 1;
4 use IPC::Open2;
5 use Term::ReadLine;
6 use JSON::PP qw(encode_json decode_json);
7
8 my $cmd = do {
9   if (my $host = $ARGV[0]) {
10     'ssh '.$host.' perl -'
11   } else {
12     'perl -'
13   }
14 };
15
16 my $pid = open2(my $out, my $in, $cmd);
17
18 {
19   my $jr;
20   if (!eof(*DATA)) {
21     $jr = \*DATA
22   } else {
23     open $jr, '<', 'jsonrepl.packed' or die "No packed repl: $!";
24   }
25   while (<$jr>) { print $in $_ }
26   print $in "__END__\n";
27 }
28
29 my $read = Term::ReadLine->new('REPL');
30
31 while (1) {
32   my $line = $read->readline('re.pl$ ');
33   exit unless defined $line;
34   next unless length $line;
35   print $in encode_json([ EVAL => $line ])."\n";
36   my $reply = decode_json scalar readline($out);
37   if ($reply->[0] eq 'MISTAKE') {
38     die "Botch: ".join(': ', @{$reply}[1,2]);
39   }
40   my $ret = $reply->[1];
41   print $ret->{return};
42   if ($ret->{stdout}) {
43     chomp($ret->{stdout});
44     print "STDOUT:\n${\$ret->{stdout}}\n";
45   }
46   if ($ret->{stderr}) {
47     chomp($ret->{stderr});
48     print "STDERR:\n${\$ret->{stderr}}\n";
49   }
50 }