syndicated-open/src/uri_runner.nim

55 lines
2.0 KiB
Nim
Raw Normal View History

2023-05-06 19:05:08 +00:00
# SPDX-FileCopyrightText: ☭ Emery Hemingway
2022-02-26 23:39:22 +00:00
# SPDX-License-Identifier: Unlicense
2023-05-18 09:46:17 +00:00
import std/[re, tables]
import preserves, syndicate, syndicate/patterns
import ./protocol
2023-05-18 09:46:17 +00:00
# importing std/re doesn't actually link against PCRE
{.passC: staticExec("pkg-config --cflags libpcre").}
{.passL: staticExec("pkg-config --libs libpcre").}
type RegexAction = tuple[regex: Regex, entity: Ref, action: Assertion]
proc rewrite(result: var Assertion; uri: string; regex: Regex) =
proc op(pr: var Assertion) =
if pr.isString:
pr.string = replacef(uri, regex, pr.string)
apply(result, op)
2022-02-26 23:39:22 +00:00
2023-05-06 19:05:08 +00:00
runActor("main") do (root: Ref; turn: var Turn):
connectStdio(root, turn)
2023-05-18 09:46:17 +00:00
during(turn, root, ?UriRunnerConfig) do (handlerspace: Ref, urispace: Ref):
# sanity chek
onMessage(turn, handlerspace, ?XdgOpen) do (uri: string):
raiseAssert "got a message in the wrong dataspace!"
onPublish(turn, urispace, ?ActionHandler) do (pat: string; entity: Ref; act: Assertion):
raiseAssert "got an assertion in the wrong dataspace!"
during(turn, handlerspace, dropType(ActionHandler)) do:
2022-02-26 23:39:22 +00:00
2023-05-18 09:46:17 +00:00
var handlers: Table[Handle, RegexAction]
during(turn, handlerspace, ?ActionHandler) do (pat: string; entity: Ref; act: Assertion):
# `duringHandle` is a symbol exposed by the `during` macro
handlers[duringHandle] = (re(pat, {reIgnoreCase, reStudy}), entity, act,)
do:
del(handlers, duringHandle)
2023-05-18 09:46:17 +00:00
onMessage(turn, urispace, ?XdgOpen) do (uri: string):
assert len(handlers) > 0
var matched = false
for handler in handlers.values:
if match(uri, handler.regex):
2022-02-26 23:39:22 +00:00
matched = true
2023-05-18 09:46:17 +00:00
var action = handler.action
try:
rewrite(action, uri, handler.regex)
message(turn, handler.entity, action)
except CatchableError:
stderr.writeLine "rewrite failed on ", action
2022-02-26 23:39:22 +00:00
if not matched:
stderr.writeLine "no actions matched for ", uri
2023-05-18 09:46:17 +00:00