aboutsummaryrefslogtreecommitdiff
path: root/Plugin/Convert.pm
blob: e5f37e1c9b0ff03ecb5d9c5ce2e29acd5309a245 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package Plugin::Convert;

use strict;
use warnings;
use IPC::Open2;

sub configure {
	my $self = shift;
	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) = @_;

	my $from = (split / to /, $rest)[0];
	my $to = (split / to /, $rest)[1];

	return "Syntax: convert <from> [to <to>]" unless ($from);

	my $converted = convert_common($from, $to);
	return "Define $from: $converted" unless $to;
	return "Convert $from -> $to: $converted";
}

sub define {
	my ($self, $irc, $logger, $who, $where, $ided, $rest, $no_reenter, @arguments) = @_;

	return "Syntax: define [unit/expression]" unless ($rest);

	my $defn = convert_common($rest, undef);
	return "Define $rest: $defn";
}

1;