Skip to content
quarry Artifact [8984c17a47]
Login

Artifact [8984c17a47]

Artifact 8984c17a4719595a2ae9faac4c686ff73f6a63deafb41b47d425abb39f3de7e9:


package xfer

import (
	"os/exec"
	"strings"
	"testing"
)

// The reaper matches on --fronted, which is set only for children whose
// sole client is the loopback gate. Anything else — a zit serve an
// operator started by hand, on a port they chose — must survive.
func TestReaperMatchesOnlyFrontedChildren(t *testing.T) {
	if _, err := exec.LookPath("pgrep"); err != nil {
		t.Skip("no pgrep")
	}
	// The pattern the reaper uses, checked against the command line the
	// fronter actually builds and against ones it must not touch.
	const pattern = "zit serve --port .* --fronted"
	ours := "zit serve --port 51234 --fronted"
	if !matches(pattern, ours) {
		t.Errorf("the reaper would not find its own child: %q", ours)
	}
	for _, theirs := range []string{
		"zit serve --port 8080",
		"zit serve",
		"quarry serve --addr :8950",
	} {
		if matches(pattern, theirs) {
			t.Errorf("the reaper would kill something that is not its child: %q", theirs)
		}
	}
}

// matches approximates pgrep -f: the pattern is a regex against the
// whole command line.
func matches(pattern, cmdline string) bool {
	out, err := exec.Command("sh", "-c",
		"printf %s "+shq(cmdline)+" | grep -qE "+shq(pattern)+" && echo yes").Output()
	return err == nil && strings.TrimSpace(string(out)) == "yes"
}

func shq(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }