implement find

This commit is contained in:
Daniel Barlow 2024-04-20 18:42:42 +01:00
parent 4df963996c
commit 712c9b266f

View file

@ -10,10 +10,22 @@
(k:lower) v) (k:lower) v)
(tset :path (string.sub s 1 (- nl 1)))))) (tset :path (string.sub s 1 (- nl 1))))))
(fn event-matches? [e terms]
(accumulate [match? true
name value (pairs terms)]
(and match? (= value (. e name)))))
(fn find-in-database [db terms]
(accumulate [found []
_ e (pairs db)]
(if (event-matches? e terms)
(doto found (table.insert e))
found)))
(fn database [] (fn database []
(let [db {}] (let [db {}]
{ {
:find (fn [_ terms] [(. db (next db))]) :find (fn [_ terms] (find-in-database db terms))
:add (fn [_ event-string] :add (fn [_ event-string]
(let [e (parse-uevent event-string)] (let [e (parse-uevent event-string)]
(tset db e.path e))) (tset db e.path e)))
@ -23,14 +35,12 @@
`(do ,body)) `(do ,body))
(example (example
"given an empty database, search for some criteria matches no entries" "given an empty database, searching it finds no entries"
(let [db (database)] (let [db (database)]
(expect= (db:find {:partname "boot"}) []))) (expect= (db:find {:partname "boot"}) [])))
(example (local sda-uevent
"when I add a device, I can find it" "add@/devices/pci0000:00/0000:00:13.0/usb1/1-1/1-1:1.0/host0/target0:0:0/0:0:0:0/block/sda\0ACTION=add
(let [db (database)]
(db:add "add@/devices/pci0000:00/0000:00:13.0/usb1/1-1/1-1:1.0/host0/target0:0:0/0:0:0:0/block/sda\0ACTION=add
DEVPATH=/devices/pci0000:00/0000:00:13.0/usb1/1-1/1-1:1.0/host0/target0:0:0/0:0:0:0/block/sda DEVPATH=/devices/pci0000:00/0000:00:13.0/usb1/1-1/1-1:1.0/host0/target0:0:0/0:0:0:0/block/sda
SUBSYSTEM=block SUBSYSTEM=block
MAJOR=8 MAJOR=8
@ -39,11 +49,30 @@ DEVNAME=sda
DEVTYPE=disk DEVTYPE=disk
DISKSEQ=2 DISKSEQ=2
SEQNUM=1527") SEQNUM=1527")
(let [[m & more] (db:find {:devname "boot"})]
(example
"when I add a device, I can find it"
(let [db (database)]
(db:add sda-uevent)
(let [[m & more] (db:find {:devname "sda"})]
(expect= m.devname "sda") (expect= m.devname "sda")
(expect= m.major "8") (expect= m.major "8")
(expect= more [])))) (expect= more []))))
(example
"when I add a device, I cannot find it with wrong terms"
(let [db (database)]
(db:add sda-uevent)
(expect= (db:find {:devname "sdb"}) [])))
(example
"when I search on multiple terms it uses all of them"
(let [db (database)]
(db:add sda-uevent)
(expect= (# (db:find {:devname "sda" :devtype "disk"})) 1)
(expect= (# (db:find {:devname "sda" :devtype "dosk"})) 0)))
(print "OK") (print "OK")