From fb0b0c4cf068f243982cc650521b16e170f4d9ca Mon Sep 17 00:00:00 2001
From: Přemysl Janouch
Date: Mon, 29 Feb 2016 03:11:33 +0100
Subject: factoids: allow querying definitions by number
---
plugins/zyklonb/factoids | 42 ++++++++++++++++++++++++++++++------------
1 file changed, 30 insertions(+), 12 deletions(-)
(limited to 'plugins/zyklonb')
diff --git a/plugins/zyklonb/factoids b/plugins/zyklonb/factoids
index 3b6be64..00a9fbf 100755
--- a/plugins/zyklonb/factoids
+++ b/plugins/zyklonb/factoids
@@ -72,9 +72,11 @@ my %db = %{db_load $db_path};
sub learn {
my ($respond, $input) = @_;
return &$respond("usage: = ")
- unless $input =~ /^([^=]+?)\s*=\s*(.+?)\s*$/;
+ unless $input =~ /^([^=]+?)(?:\s+(\d+))?\s*=\s*(.+?)\s*$/;
- my ($name, $definition) = ($1, $2);
+ my ($name, $number, $definition) = ($1, $2, $3);
+ return &$respond("trailing numbers in names are disallowed")
+ if defined $2;
$db{$name} = [] unless exists $db{$name};
my $entries = $db{$name};
@@ -86,6 +88,19 @@ sub learn {
db_save $db_path, \%db;
}
+sub check_number {
+ my ($respond, $name, $number) = @_;
+ my $entries = $db{$name};
+ if ($number > @$entries) {
+ &$respond(qq/"$name" has only ${\scalar @$entries} definitions/);
+ } elsif (not $number) {
+ &$respond("number must not be zero");
+ } else {
+ return 1;
+ }
+ return 0;
+}
+
sub forget {
my ($respond, $input) = @_;
return &$respond("usage: ")
@@ -96,10 +111,7 @@ sub forget {
unless exists $db{$name};
my $entries = $db{$name};
- return &$respond(qq/"$name" has only ${\scalar @$entries} definitions/)
- if $number > @$entries;
- return &$respond("number must not be zero")
- unless $number;
+ return unless check_number $respond, $name, $number;
splice @$entries, --$number, 1;
&$respond("forgotten");
@@ -108,16 +120,22 @@ sub forget {
sub whatis {
my ($respond, $input) = @_;
- return &$respond("usage: ")
- unless $input =~ /^([^=]+?)\s*$/;
+ return &$respond("usage: []")
+ unless $input =~ /^([^=]+?)(?:\s+(\d+))?\s*$/;
- my ($name) = ($1);
+ my ($name, $number) = ($1, $2);
return &$respond(qq/"$name" is undefined/)
unless exists $db{$name};
- my $i = 1;
- my $definition = join ", ", map { "#${\$i++} $_" } @{$db{$name}};
- &$respond(qq/"$name" is $definition/);
+ my $entries = $db{$name};
+ if (defined $number) {
+ return unless check_number $respond, $name, $number;
+ &$respond(qq/"$name" is #$number $entries->[$number - 1]/);
+ } else {
+ my $i = 1;
+ my $definition = join ", ", map { "#${\$i++} $_" } @{$entries};
+ &$respond(qq/"$name" is $definition/);
+ }
}
sub wildcard {
--
cgit v1.2.3-70-g09d2