From a9af007e92c653e39f28fe411c08ec388748a144 Mon Sep 17 00:00:00 2001 From: David Phillips Date: Sat, 30 Mar 2019 16:58:51 +1300 Subject: Convert: add define command While the convert command allows single-arg mode it's handy to have a command that reads closer to english. It also factors out some of the conditional statements. Hopefully this doesn't collide with a define command in any future dictionary plugin. --- Plugin/Convert.pm | 61 +++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 41 insertions(+), 20 deletions(-) diff --git a/Plugin/Convert.pm b/Plugin/Convert.pm index 75f4ba0..46af1e2 100755 --- a/Plugin/Convert.pm +++ b/Plugin/Convert.pm @@ -9,10 +9,42 @@ sub configure { my $cmdref = shift; $cmdref->($self, "convert", sub { $self->convert(@_); } ); + $cmdref->($self, "define", sub { $self->define(@_); } ); return $self; } +sub convert_common { + my ($from, $to) = @_; + + my ($out, $in, $pid); + my @command = ( + 'units', + '-1', + '--compact', + '--quiet', + $from + ); + + if ($to) { + push @command, $to; + } + + eval { + $pid = open2($out, $in, @command); + } or do { + return "Error: units command not installed"; + }; + + my $output = <$out>; + chomp $output; + waitpid($pid, 0); + my $exit_status = $? >> 8; + return "Error: $output" if $exit_status; + + return "$output" +} + sub convert { my ($self, $irc, $logger, $who, $where, $ided, $rest, $no_reenter, @arguments) = @_; @@ -21,28 +53,17 @@ sub convert { return "Syntax: convert [to ]\n" unless ($from); - my ($out, $in); - my $pid; - if ($to) { - $pid = open2($out, $in, 'units', '-1', '--compact', '--quiet', $from, $to); - } else { - $pid = open2($out, $in, 'units', '-1', '--compact', '--quiet', $from); - } - - my $converted = <$out>; - chomp $converted; + my $converted = convert_common($from, $to); + return "Convert $from -> $to: $converted\n"; +} - close($in); - waitpid($pid, 0); +sub define { + my ($self, $irc, $logger, $who, $where, $ided, $rest, $no_reenter, @arguments) = @_; - my $exit_status = $? >> 8; - # `units` doesn't actually seem to set this non-zero, but use it anyway - return "Error: $converted" if $exit_status; + return "Syntax: define [unit/expression]\n" unless ($rest); - if ($to) { - return "Convert $from -> $to: $converted\n"; - } else { - return "Define $from: $converted\n"; - } + my $defn = convert_common($rest, undef); + return "Define $rest: $defn\n"; } + 1; -- cgit v1.1