# SPDX-FileCopyrightText: ☭ 2022 Emery Hemingway # SPDX-License-Identifier: Unlicense import std/[asyncdispatch, re] import preserves, syndicate import ./protocol, ./exec bootDataspace("main") do (root: Ref; turn: var Turn): var actions: seq[tuple[regex: Regex; cmd: string; args: seq[Assertion]]] connectStdio(root, turn) onPublish(turn, root, ?ActionHandler) do (pat: string; cmd: seq[Assertion]): if cmd.len < 2: stderr.writeLine "ignoring ", $cmd, " for ", pat else: if cmd[0].isString: var act = (re(pat, {reIgnoreCase, reStudy}), cmd[0].string, cmd[1..cmd.high],) actions.add act else: stderr.writeLine "not a valid program specification: ", cmd[0] during(turn, root, ?ListenOn[Ref]) do (a: Assertion): let ds = unembed a onMessage(turn, ds, ?XdgOpen) do (uris: seq[string]): for uri in uris: var matched: bool for act in actions: if match(uri, act.regex): matched = true var args = newSeq[string](act.args.len) for i, arg in act.args: if arg.isString: args[i] = replacef(uri, act.regex, arg.string) elif arg.isInteger: if arg.int == 0: args[i] = uri else: args[i] = replacef(uri, act.regex, "$" & $arg.int) message(turn, root, Exec( argv: CommandLine( orKind: CommandLineKind.full, full: FullCommandLine( program: act.cmd, args: args)), restartPolicy: RestartPolicy.never)) if not matched: stderr.writeLine "no actions matched for ", uri do: # The Syndicate server retracts all assertions when # the config is rewritten. actions.setLen 0 runForever()