diff --git a/bean-query-goofy-daemon.plx b/bean-query-goofy-daemon.plx index bc8eb8e..18ffe22 100755 --- a/bean-query-goofy-daemon.plx +++ b/bean-query-goofy-daemon.plx @@ -13,8 +13,11 @@ use File::Temp qw/:mktemp/; use POSIX qw(mkfifo); use IPC::Shareable; -use IPC::Run qw(start pump finish timeout); +use Expect; +# We have to set the PAGER to a passthrough text program to assure that +# output does not get paused +$ENV{PAGER} = "/usr/bin/cat"; my $BEANCOUNT_QUERY_CMD = "/usr/bin/bean-query"; @@ -71,7 +74,7 @@ my %beancountData; tie %beancountData, 'IPC::Shareable', $glue, { %options } or die "server: tie failed\n"; -my ($currentFormat, $runningBeanQuery, $rbcIn, $rbcOut, $rbcErr); +my ($currentFormat, $runningBeanQuery); sub StartRunningBeanQuery { my($format) = @_; @@ -81,8 +84,14 @@ sub StartRunningBeanQuery { my @cmd = ($BEANCOUNT_QUERY_CMD); push(@cmd, '-f', $format) if defined $format; push(@cmd, $LOAD_FILE); - $runningBeanQuery = start \@cmd, 'pty>', \$rbcOut, '2>', \$rbcErr; - pump $runningBeanQuery until $rbcOut =~ /^\s*beancount\s*\>\s*/m; + $runningBeanQuery = Expect->spawn(@cmd); + $runningBeanQuery->log_stdout(0); + $runningBeanQuery->expect(undef, -re => '^\s*beancount\s*\>\s*') + or die("Unable to find beancount prompt, output was instead: ". + $runningBeanQuery->before() . $runningBeanQuery->after()); + print STDERR "Beancount started with output of:\n", $runningBeanQuery->before(), + $runningBeanQuery->match(), $runningBeanQuery->after(), "\n" + if ($VERBOSE > 3); } StartRunningBeanQuery('text'); @@ -123,12 +132,13 @@ while (1) { next; } print STDERR "Runing query: $query{question}\n" if $VERBOSE > 0; - $rbcOut = ""; - $rbcErr = ""; my $ques = $query{question}; $ques =~ s/\n/ /gm; - $rbcIn = "$ques\n"; - pump $runningBeanQuery until $rbcOut =~ /^\s*beancount\s*\>\s*/m; + $runningBeanQuery->send("$ques\n"); + $runningBeanQuery->expect(undef, 'beancount>') # *Don't* use regex here! + # See `git annotate` on this line for why no regex. + or die("Unable to find beancount prompt, output was instead: ". + $runningBeanQuery->before() . $runningBeanQuery->after()); (tied %query)->shlock; print STDERR "Acquired shlock on tied variable.\n" if $VERBOSE > 1; $query{fifoName} = undef; @@ -142,6 +152,7 @@ while (1) { open(my $fifoFH, ">", $fifoFileName); print STDERR "and beginning write to it." if $VERBOSE > 1; my($seenSeperator, $prevLine) = (0, ""); + my $rbcOut = $runningBeanQuery->before(); foreach my $line (split /\n/, $rbcOut) { # Occasionally, some of the SELECT statement is printed back to # $rbcOut. Avoid reproducing this in output by waiting for the line @@ -161,8 +172,6 @@ while (1) { $prevLine = $line; } close $fifoFH; - $rbcOut = ""; - $rbcIn = ""; (tied %query)->shlock; $query{question} = undef; (tied %query)->shunlock; print STDERR "...done! Data now in $fifoFileName\n" if $VERBOSE > 0; }