57 lines
1.9 KiB
Nim
57 lines
1.9 KiB
Nim
# SPDX-FileCopyrightText: ☭ 2022 Emery Hemingway
|
|
# SPDX-License-Identifier: Unlicense
|
|
|
|
import std/[asyncdispatch, deques, re, streams, strutils, osproc]
|
|
import preserves
|
|
import syndicate
|
|
import ./protocol
|
|
|
|
bootDataspace("main") do (root: Ref; turn: var Turn):
|
|
var
|
|
actions: seq[tuple[regex: Regex; cmd: string; args: seq[Assertion]]]
|
|
children: Deque[Process]
|
|
|
|
connectStdio(root, turn)
|
|
|
|
onPublish(turn, root, ?ActionHandler) do (pat: string; cmd: seq[Assertion]):
|
|
# TODO: during
|
|
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]
|
|
|
|
onPublish(turn, root, ?ListenOn[Ref]) do (a: Assertion):
|
|
let ds = unembed a
|
|
onMessage(turn, ds, ?XdgOpen) do (uris: seq[string]):
|
|
while children.len > 0 and not children.peekFirst.running:
|
|
var child = children.popFirst()
|
|
if child.peekExitCode != 0:
|
|
stderr.writeLine child.errorStream.readAll
|
|
close child
|
|
# TODO check children on a timer?
|
|
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)
|
|
var child = startProcess(
|
|
command = act.cmd, args = args, options = {})
|
|
children.addLast child
|
|
if not matched:
|
|
stderr.writeLine "no actions matched for ", uri
|
|
|
|
runForever()
|