# SPDX-FileCopyrightText: ☭ Emery Hemingway # SPDX-License-Identifier: Unlicense import std/[re, tables] import preserves, syndicate, syndicate/patterns import ./protocol # 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) runActor("main") do (root: Ref; turn: var Turn): connectStdio(root, turn) 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: 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) onMessage(turn, urispace, ?XdgOpen) do (uri: string): assert len(handlers) > 0 var matched = false for handler in handlers.values: if match(uri, handler.regex): matched = true var action = handler.action try: rewrite(action, uri, handler.regex) message(turn, handler.entity, action) except CatchableError: stderr.writeLine "rewrite failed on ", action if not matched: stderr.writeLine "no actions matched for ", uri