beancount-tools-in-Perl/bean-query-cli.plx
2020-08-30 20:14:38 -07:00

57 lines
1.4 KiB
Perl
Executable file

#!/usr/bin/perl
use strict;
use warnings;
use Term::ReadLine;
use Term::ReadKey;
use File::Spec::Functions;
use IPC::Shareable;
require 'bean-query-daemon-lib.pl';
my $term = new Term::ReadLine 'bean-query-d';
my $prompt = 'bqd> ';
my $dir = $ENV{HOME};
$dir = "~$ENV{USER}" if not defined $dir and defined $ENV{USER};
$dir = "~$ENV{LOGNAME}" if not defined $dir and defined $ENV{LOGNAME};
my $pager = $ENV{PAGER} || '/usr/bin/less';
my ($isPaging, $saveOut) = (0, undef);
sub startpage {
return if $isPaging;
open($saveOut, '>&', STDOUT);
open(STDOUT, "|-", $pager);
$isPaging = 1;
}
sub endpage {
return unless $isPaging;
close(STDOUT);
open(STDOUT, '>&', $saveOut);
$isPaging = 0;
}
BeancountQueryInitialize();
my $histfile = catfile($dir, '.bean-shell-history');
$term->ReadHistory($histfile);
my $cmd = "";
while ( (defined ($cmd = $term->readline($prompt))) and $cmd ne 'exit') {
next if $cmd =~ /^\s*$/;
chomp $cmd;
$term->AddHistory($cmd);
$term->WriteHistory($histfile);
my $fileName = BeancountQuerySubmit($cmd, 'text', 1);
open(my $fh, "<", $fileName);
my($beanOutput, $lineCount) = ("", 0);
my($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
while (my $line = <$fh>) { $beanOutput .= $line; $lineCount++; print STDERR ".";}
close $fh;
BeancountQueryComplete();
startpage() if ($lineCount >= $hchar);
print $beanOutput;
endpage();
}
print "\n";