refactor: rename project uatu -> sanderling (#24)

* refactor: rename Go module path uatu -> sanderling

Module path github.com/priyanshujain/uatu -> github.com/priyanshujain/sanderling,
including all imports and the proto go_package option. Generated .pb.go files
rewritten in-place; safe to regenerate with protoc later.

* chore(proto): regenerate driverpb after module path rename

The previous sed-based module rename corrupted the embedded descriptor
byte lengths. buf generate rewrites them cleanly.

* refactor: rename CLI binary uatu -> sanderling

Updates Makefile target + UATU_BIN var, .goreleaser project/build IDs,
.gitignore comment, and all user-facing strings in the CLI help text,
error messages, and tests. Binary is now bin/sanderling.

* refactor(sdk): rename Kotlin package dev.uatu.sdk -> dev.sanderling.sdk

Moves sdk/android/src/{main,test}/kotlin/dev/uatu -> dev/sanderling and
rewrites package declarations, imports, and the Gradle namespace. Class
names (Uatu, UatuRuntime) are renamed in a follow-up commit.

* refactor(sidecar): rename Kotlin package dev.uatu.sidecar -> dev.sanderling.sidecar

Moves sidecar/src/{main,test}/kotlin/dev/uatu -> dev/sanderling and
rewrites package declarations, imports, and the application mainClass.

* refactor: rename Uatu API surface -> Sanderling

- Kotlin: Uatu -> Sanderling, UatuRuntime -> SanderlingRuntime (+ files).
- JS host binding: globalThis.__uatu__ -> __sanderling__ (Go verifier,
  spec-api, tests).
- TS interface: UatuRuntime -> SanderlingRuntime; internal tags
  __uatuFormula / __uatuActionGenerator -> __sanderling* variants.
- Go trace: UatuVersion field + uatu_version JSON tag renamed.
- Socket naming: uatu-agent / uatu-agent-reader -> sanderling-agent*.
- Sample app, docs, inline-JS test strings updated to match.

* refactor(examples): rename examples/folio/uatu -> examples/folio/sanderling

Renames the example spec directory; updates justfile paths + gitignore
entries accordingly. Package.json name/description and @uatu/spec
dependency are renamed in the npm + docs commits.

* chore(build): rename gradle property + rootProject.name uatu -> sanderling

- Renames the uatu.version gradle property and all its -P references in
  Makefile, build.gradle.kts files, and .github/workflows/release.yml.
- settings.gradle.kts rootProject.name = "sanderling".
- Renames .env.local.example header + release-cli workflow job name.

* refactor(proto): rename proto package uatu.driver.v1 -> sanderling.driver.v1

Updates the proto package and java_package, regenerates driver.pb.go +
driver_grpc.pb.go, rewrites Kotlin imports and the gRPC ServiceName
assertion in driver_test.go.

* refactor: rename npm package @uatu/spec -> @sanderling/spec

Renames package name in pkg/spec-api/package.json + lockfile, all
consumer imports (examples/folio spec, testdata, verifier tests), the
esbuild alias in cmd/sanderling/test_run.go, and related doc references.

* docs: rename uatu -> sanderling in README, docs, and URLs

- README + docs/{manual,development}/*: narrative + GitHub + Pages URLs.
- POM + npm package.json repo/homepage/bugs URLs.
- .gitignore + embed_stub + Makefile-comment references updated to
  'make sanderling'.
- Minor narrative comments in cmd/sanderling/test_run.go and
  internal/inspect/server.go.

* refactor: rename remaining internal uatu strings -> sanderling

- SANDERLING_TEST_PHONE/OTP env vars (cmd + bundler tests).
- sanderling-sidecar runtime tmp dir + extracted JAR filename.
- Inspect web UI: @sanderling/inspect-web package, title, theme
  localStorage key, RunList empty-state copy, uatu_version TS field.
- Sample app storage key sanderling.ledger.v1.
- Test data: sanderling_test AVD name + com.example.sanderling_test.
- Release docs tarball name template.
This commit is contained in:
pj authored and GitHub committed 2026-04-21 11:57:49 +07:00
1 parent 13bb2feb82
commit 8ccf95c1cf
111 files changed
+514 -514

No files matched your search

+235
View File
@@ -0,0 +1,235 @@
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"time"
)
// ensureDevice makes sure an Android device is ready for adb commands.
// Resolution order:
// - if an adb device is already online, use it;
// - else if avdName is set, validate and boot it;
// - else if exactly one AVD exists locally, boot it;
// - else fail with a helpful message listing the available AVDs.
func ensureDevice(ctx context.Context, avdName string, stdout io.Writer) error {
devices, err := listAdbDevices(ctx)
if err != nil {
return fmt.Errorf("list adb devices: %w", err)
}
if len(devices) > 0 {
fmt.Fprintf(stdout, "using connected device: %s\n", devices[0])
return nil
}
avds, err := listAVDs(ctx)
if err != nil {
return fmt.Errorf("list AVDs: %w", err)
}
target, err := pickAVD(avdName, avds)
if err != nil {
return err
}
fmt.Fprintf(stdout, "booting AVD %q...\n", target)
if err := bootAVD(ctx, target); err != nil {
return fmt.Errorf("boot AVD %q: %w", target, err)
}
if err := waitForBoot(ctx, 180*time.Second); err != nil {
return fmt.Errorf("wait for AVD boot: %w", err)
}
fmt.Fprintf(stdout, "AVD %q ready\n", target)
return nil
}
func pickAVD(requested string, available []string) (string, error) {
if requested != "" {
if !slices.Contains(available, requested) {
return "", fmt.Errorf("AVD %q does not exist (available: %s)", requested, strings.Join(available, ", "))
}
return requested, nil
}
switch len(available) {
case 0:
return "", fmt.Errorf("no android device connected and no AVD found; create one in Android Studio or `avdmanager create avd`")
case 1:
return available[0], nil
default:
return "", fmt.Errorf("no android device connected and multiple AVDs available (%s); pick one with --avd", strings.Join(available, ", "))
}
}
func listAdbDevices(ctx context.Context) ([]string, error) {
adb, err := adbBinary()
if err != nil {
return nil, err
}
output, err := exec.CommandContext(ctx, adb, "devices").Output()
if err != nil {
return nil, err
}
return parseAdbDevices(string(output)), nil
}
func parseAdbDevices(output string) []string {
var serials []string
scanner := bufio.NewScanner(strings.NewReader(output))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "List of devices") {
continue
}
fields := strings.Fields(line)
if len(fields) >= 2 && fields[1] == "device" {
serials = append(serials, fields[0])
}
}
return serials
}
func listAVDs(ctx context.Context) ([]string, error) {
emulator, err := emulatorBinary()
if err != nil {
return nil, err
}
output, err := exec.CommandContext(ctx, emulator, "-list-avds").Output()
if err != nil {
return nil, err
}
return parseAVDList(string(output)), nil
}
func adbBinary() (string, error) { return findAndroidTool("adb", "platform-tools") }
func emulatorBinary() (string, error) { return findAndroidTool("emulator", "emulator") }
// findAndroidTool locates a binary from the Android SDK. It checks PATH,
// then $ANDROID_HOME/<subdir>/<name> and $ANDROID_SDK_ROOT/<subdir>/<name>,
// then the canonical install locations used by Android Studio and Homebrew.
// Returns a descriptive error when nothing works, so the user knows to set
// $ANDROID_HOME instead of getting a raw "executable file not found".
func findAndroidTool(name, subdir string) (string, error) {
if path, err := exec.LookPath(name); err == nil {
return path, nil
}
var tried []string
for _, root := range androidSDKCandidates() {
candidate := filepath.Join(root, subdir, name)
if info, err := os.Stat(candidate); err == nil && !info.IsDir() {
return candidate, nil
}
tried = append(tried, candidate)
}
return "", fmt.Errorf("could not locate %q: not on PATH and not under any known Android SDK root (set $ANDROID_HOME to point at your SDK; tried %v)", name, tried)
}
func androidSDKCandidates() []string {
var roots []string
seen := map[string]bool{}
addRoot := func(path string) {
if path == "" || seen[path] {
return
}
seen[path] = true
roots = append(roots, path)
}
addRoot(os.Getenv("ANDROID_HOME"))
addRoot(os.Getenv("ANDROID_SDK_ROOT"))
if home, err := os.UserHomeDir(); err == nil {
addRoot(filepath.Join(home, "Library", "Android", "sdk"))
addRoot(filepath.Join(home, "Android", "Sdk"))
}
addRoot("/opt/homebrew/share/android-commandlinetools")
addRoot("/usr/local/share/android-commandlinetools")
return roots
}
func parseAVDList(output string) []string {
var avds []string
scanner := bufio.NewScanner(strings.NewReader(output))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "INFO") {
continue
}
avds = append(avds, line)
}
return avds
}
func bootAVD(_ context.Context, name string) error {
emulator, err := emulatorBinary()
if err != nil {
return err
}
command := exec.Command(emulator, "-avd", name, "-no-snapshot-save", "-no-audio", "-no-boot-anim")
if err := command.Start(); err != nil {
return err
}
go func() { _ = command.Wait() }()
return nil
}
func waitForBoot(ctx context.Context, timeout time.Duration) error {
deadline, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
if completed, _ := bootCompleted(deadline); completed {
return nil
}
select {
case <-deadline.Done():
return deadline.Err()
case <-ticker.C:
}
}
}
// envWithAndroidPlatformTools returns env with the directory containing adb
// prepended to PATH, so child processes (the sidecar) can invoke adb even
// when the user hasn't set up their shell PATH.
func envWithAndroidPlatformTools(env []string) []string {
adb, err := adbBinary()
if err != nil {
return env
}
adbDir := filepath.Dir(adb)
result := make([]string, 0, len(env))
found := false
for _, entry := range env {
if current, ok := strings.CutPrefix(entry, "PATH="); ok {
if !pathContains(current, adbDir) {
entry = "PATH=" + adbDir + string(os.PathListSeparator) + current
}
found = true
}
result = append(result, entry)
}
if !found {
result = append(result, "PATH="+adbDir)
}
return result
}
func pathContains(path, directory string) bool {
return slices.Contains(strings.Split(path, string(os.PathListSeparator)), directory)
}
func bootCompleted(ctx context.Context) (bool, error) {
adb, err := adbBinary()
if err != nil {
return false, err
}
output, err := exec.CommandContext(ctx, adb, "shell", "getprop", "sys.boot_completed").Output()
if err != nil {
return false, err
}
return strings.TrimSpace(string(output)) == "1", nil
}
+93
View File
@@ -0,0 +1,93 @@
package main
import (
"reflect"
"testing"
)
func TestParseAdbDevices_OnlineOnly(t *testing.T) {
output := `List of devices attached
emulator-5554 device
emulator-5556 offline
physical-abc device
`
got := parseAdbDevices(output)
want := []string{"emulator-5554", "physical-abc"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
}
func TestParseAdbDevices_Empty(t *testing.T) {
output := "List of devices attached\n\n"
got := parseAdbDevices(output)
if len(got) != 0 {
t.Fatalf("got %v, want empty", got)
}
}
func TestParseAVDList_DropsInfoLines(t *testing.T) {
output := `INFO | Storing crashdata in: /tmp/x
Medium_Phone_API_36.0
sanderling_test
`
got := parseAVDList(output)
want := []string{"Medium_Phone_API_36.0", "sanderling_test"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
}
func TestPickAVD_ExplicitName(t *testing.T) {
got, err := pickAVD("Pixel_7", []string{"Pixel_7", "sanderling_test"})
if err != nil {
t.Fatal(err)
}
if got != "Pixel_7" {
t.Fatalf("got %q, want Pixel_7", got)
}
}
func TestPickAVD_ExplicitMissing(t *testing.T) {
_, err := pickAVD("Nope", []string{"Pixel_7"})
if err == nil {
t.Fatal("expected error")
}
}
func TestPickAVD_SingleAvailable(t *testing.T) {
got, err := pickAVD("", []string{"sanderling_test"})
if err != nil {
t.Fatal(err)
}
if got != "sanderling_test" {
t.Fatalf("got %q, want sanderling_test", got)
}
}
func TestPickAVD_AmbiguousWithoutHint(t *testing.T) {
_, err := pickAVD("", []string{"a", "b"})
if err == nil {
t.Fatal("expected error when multiple AVDs and no --avd")
}
}
func TestPickAVD_NoneAvailable(t *testing.T) {
_, err := pickAVD("", nil)
if err == nil {
t.Fatal("expected error when no AVDs exist")
}
}
func TestPathContains(t *testing.T) {
path := "/usr/bin:/opt/tools:/usr/local/bin"
if !pathContains(path, "/opt/tools") {
t.Error("expected /opt/tools in PATH")
}
if pathContains(path, "/nope") {
t.Error("did not expect /nope in PATH")
}
}
+132
View File
@@ -0,0 +1,132 @@
package main
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"time"
"github.com/priyanshujain/sanderling/internal/sidecar"
)
type doctorCheck struct {
Name string
Run func(ctx context.Context) error
}
func defaultDoctorChecks() []doctorCheck {
return []doctorCheck{
{Name: "adb on PATH", Run: checkExecutableOnPath("adb")},
{Name: "emulator on PATH or under ANDROID_HOME", Run: checkEmulator},
{Name: "java 17+ on PATH", Run: checkJavaVersion},
{Name: "sidecar JAR is real (not placeholder)", Run: checkSidecarJAR},
}
}
func checkSidecarJAR(_ context.Context) error {
if sidecar.IsPlaceholder() {
return fmt.Errorf("placeholder JAR embedded; run `make sidecar && make sanderling` to embed the real fat JAR")
}
if sidecar.EmbeddedSize() == 0 {
return fmt.Errorf("embedded JAR is empty")
}
return nil
}
func runDoctorChecks(ctx context.Context, checks []doctorCheck, stdout io.Writer) error {
failures := 0
for _, check := range checks {
callCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := check.Run(callCtx)
cancel()
if err != nil {
fmt.Fprintf(stdout, "FAIL %s: %v\n", check.Name, err)
failures++
continue
}
fmt.Fprintf(stdout, "OK %s\n", check.Name)
}
if failures > 0 {
return fmt.Errorf("%d check(s) failed", failures)
}
return nil
}
func checkExecutableOnPath(name string) func(context.Context) error {
return func(_ context.Context) error {
if _, err := exec.LookPath(name); err != nil {
return fmt.Errorf("not found: %w", err)
}
return nil
}
}
func checkEmulator(_ context.Context) error {
if _, err := exec.LookPath("emulator"); err == nil {
return nil
}
androidHome := os.Getenv("ANDROID_HOME")
if androidHome == "" {
androidHome = os.Getenv("ANDROID_SDK_ROOT")
}
if androidHome == "" {
return fmt.Errorf("not on PATH and ANDROID_HOME is unset")
}
candidate := filepath.Join(androidHome, "emulator", "emulator")
if _, err := os.Stat(candidate); err != nil {
return fmt.Errorf("not found at %s", candidate)
}
return nil
}
var javaVersionPattern = regexp.MustCompile(`(?:java|openjdk)[^"]*"(\d+)(?:\.(\d+))?`)
func checkJavaVersion(ctx context.Context) error {
if _, err := exec.LookPath("java"); err != nil {
return fmt.Errorf("java not found: %w", err)
}
output, err := exec.CommandContext(ctx, "java", "-version").CombinedOutput()
if err != nil {
return fmt.Errorf("java -version: %w", err)
}
major, err := parseJavaMajor(string(output))
if err != nil {
return err
}
if major < 17 {
return fmt.Errorf("java major version %d is less than 17", major)
}
return nil
}
func parseJavaMajor(versionOutput string) (int, error) {
match := javaVersionPattern.FindStringSubmatch(versionOutput)
if match == nil {
return 0, fmt.Errorf("could not parse java version from %q", firstLine(versionOutput))
}
major, err := strconv.Atoi(match[1])
if err != nil {
return 0, fmt.Errorf("non-numeric major %q", match[1])
}
if major == 1 && len(match) >= 3 && match[2] != "" {
minor, err := strconv.Atoi(match[2])
if err == nil {
return minor, nil
}
}
return major, nil
}
func firstLine(text string) string {
for index := 0; index < len(text); index++ {
if text[index] == '\n' {
return text[:index]
}
}
return text
}
+83
View File
@@ -0,0 +1,83 @@
package main
import (
"bytes"
"context"
"errors"
"strings"
"testing"
)
func TestRunDoctorChecks_AllPass(t *testing.T) {
var stdout bytes.Buffer
checks := []doctorCheck{
{Name: "always ok", Run: func(context.Context) error { return nil }},
{Name: "also ok", Run: func(context.Context) error { return nil }},
}
if err := runDoctorChecks(context.Background(), checks, &stdout); err != nil {
t.Fatalf("expected nil error, got %v", err)
}
output := stdout.String()
if !strings.Contains(output, "OK always ok") || !strings.Contains(output, "OK also ok") {
t.Errorf("expected OK lines, got: %s", output)
}
}
func TestRunDoctorChecks_ReportsFailures(t *testing.T) {
var stdout bytes.Buffer
checks := []doctorCheck{
{Name: "ok", Run: func(context.Context) error { return nil }},
{Name: "broken", Run: func(context.Context) error { return errors.New("boom") }},
}
err := runDoctorChecks(context.Background(), checks, &stdout)
if err == nil || !strings.Contains(err.Error(), "1 check(s) failed") {
t.Fatalf("expected failure summary, got %v", err)
}
output := stdout.String()
if !strings.Contains(output, "FAIL broken") {
t.Errorf("expected FAIL line, got: %s", output)
}
}
func TestParseJavaMajor_AcceptsModernFormat(t *testing.T) {
cases := []struct {
input string
major int
}{
{`openjdk version "17.0.10"` + "\n", 17},
{`openjdk version "21" 2023-09-19` + "\n", 21},
{`java version "25.0.2" 2026-01-20` + "\n", 25},
{`openjdk version "1.8.0_402"` + "\n", 8},
}
for _, testCase := range cases {
got, err := parseJavaMajor(testCase.input)
if err != nil {
t.Errorf("parseJavaMajor(%q): unexpected error %v", testCase.input, err)
continue
}
if got != testCase.major {
t.Errorf("parseJavaMajor(%q): got %d, want %d", testCase.input, got, testCase.major)
}
}
}
func TestParseJavaMajor_RejectsUnrecognized(t *testing.T) {
_, err := parseJavaMajor("not java output\n")
if err == nil {
t.Errorf("expected error for unrecognized output")
}
}
func TestCheckExecutableOnPath_FindsRealCommand(t *testing.T) {
check := checkExecutableOnPath("ls")
if err := check(context.Background()); err != nil {
t.Errorf("ls should be on PATH on macOS/linux, got %v", err)
}
}
func TestCheckExecutableOnPath_MissingCommand(t *testing.T) {
check := checkExecutableOnPath("definitely-not-a-real-command-xyz-123")
if err := check(context.Background()); err == nil {
t.Errorf("expected error for missing command")
}
}
+119
View File
@@ -0,0 +1,119 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os/exec"
"runtime"
"strconv"
"time"
"github.com/priyanshujain/sanderling/internal/inspect"
)
type inspectOptions struct {
port int
noOpen bool
dev bool
directory string
}
func parseInspectArgs(args []string, stderr io.Writer) (inspectOptions, error) {
flagSet := flag.NewFlagSet("inspect", flag.ContinueOnError)
flagSet.SetOutput(stderr)
var options inspectOptions
flagSet.IntVar(&options.port, "port", 0, "TCP port to listen on (0 = ephemeral)")
flagSet.BoolVar(&options.noOpen, "no-open", false, "do not open the default browser on startup")
flagSet.BoolVar(&options.dev, "dev", false, "reverse-proxy non-API requests to "+inspect.DevTarget)
if err := flagSet.Parse(args); err != nil {
return inspectOptions{}, err
}
rest := flagSet.Args()
if len(rest) > 1 {
return inspectOptions{}, errors.New("inspect takes at most one positional argument (run or runs directory)")
}
if len(rest) == 1 {
options.directory = rest[0]
}
return options, nil
}
func runInspect(options inspectOptions, stdout io.Writer) error {
runsDirectory, deepLinkID, err := inspect.ResolveRunsDirectory(options.directory)
if err != nil {
return err
}
devTarget := ""
if options.dev {
devTarget = inspect.DevTarget
}
server, err := inspect.NewServer(inspect.ServerOptions{
RunsDirectory: runsDirectory,
DevTarget: devTarget,
})
if err != nil {
return err
}
listener, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(options.port))
if err != nil {
return fmt.Errorf("listen: %w", err)
}
address := listener.Addr().(*net.TCPAddr)
browseURL := buildBrowseURL(address, deepLinkID)
fmt.Fprintf(stdout, "sanderling inspect listening on %s (runs=%s)\n", browseURL, runsDirectory)
context, cancel := context.WithCancel(context.Background())
defer cancel()
watcherDone := make(chan struct{})
go func() {
_ = server.Watcher().Run(context)
close(watcherDone)
}()
httpServer := &http.Server{Handler: server.Handler(), ReadHeaderTimeout: 10 * time.Second}
serverDone := make(chan error, 1)
go func() { serverDone <- httpServer.Serve(listener) }()
if !options.noOpen {
if err := openBrowser(browseURL); err != nil {
fmt.Fprintf(stdout, "warning: could not open browser: %v\n", err)
}
}
err = <-serverDone
cancel()
<-watcherDone
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
}
func buildBrowseURL(address *net.TCPAddr, deepLinkID string) string {
target := url.URL{Scheme: "http", Host: address.String(), Path: "/"}
if deepLinkID != "" {
target.Path = "/runs/" + deepLinkID
}
return target.String()
}
func openBrowser(target string) error {
var command *exec.Cmd
switch runtime.GOOS {
case "darwin":
command = exec.Command("open", target)
case "windows":
command = exec.Command("cmd", "/c", "start", target)
default:
command = exec.Command("xdg-open", target)
}
return command.Start()
}
+45
View File
@@ -0,0 +1,45 @@
package main
import (
"bytes"
"io"
"strings"
"testing"
)
func TestParseInspectArgs_Defaults(t *testing.T) {
options, err := parseInspectArgs(nil, io.Discard)
if err != nil {
t.Fatal(err)
}
if options.port != 0 || options.noOpen || options.dev || options.directory != "" {
t.Errorf("unexpected defaults: %+v", options)
}
}
func TestParseInspectArgs_AllFlags(t *testing.T) {
options, err := parseInspectArgs([]string{"--port", "9090", "--no-open", "--dev", "/tmp/runs"}, io.Discard)
if err != nil {
t.Fatal(err)
}
if options.port != 9090 || !options.noOpen || !options.dev || options.directory != "/tmp/runs" {
t.Errorf("unexpected options: %+v", options)
}
}
func TestParseInspectArgs_RejectsTooManyPositional(t *testing.T) {
_, err := parseInspectArgs([]string{"a", "b"}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "at most one") {
t.Fatalf("expected too-many-args error, got %v", err)
}
}
func TestRun_HelpListsInspectCommand(t *testing.T) {
var stdout bytes.Buffer
if err := run([]string{"sanderling"}, &stdout, io.Discard); err != nil {
t.Fatal(err)
}
if !strings.Contains(stdout.String(), "inspect") {
t.Errorf("usage missing inspect command: %q", stdout.String())
}
}
+112
View File
@@ -0,0 +1,112 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"os"
"time"
)
// Version is stamped at build time via goreleaser ldflags.
// Default "dev" marks untagged local builds.
var Version = "dev"
type testOptions struct {
spec string
bundleID string
launcherActivity string
platform string
avd string
duration time.Duration
seed int64
output string
}
const topUsage = `sanderling is a property-based UI fuzzer for mobile apps.
Usage:
sanderling <command> [flags]
Commands:
test Run a spec against an app for a fixed duration.
inspect Serve a local web UI for browsing runs/.
doctor Check that the host environment is ready to run sanderling.
version Print the sanderling version.
Run "sanderling <command> -h" for command-specific flags.
`
func parseTestArgs(args []string, stderr io.Writer) (testOptions, error) {
flagSet := flag.NewFlagSet("test", flag.ContinueOnError)
flagSet.SetOutput(stderr)
var options testOptions
flagSet.StringVar(&options.spec, "spec", "", "path to the TypeScript spec (required)")
flagSet.StringVar(&options.bundleID, "bundle-id", "", "target app bundle ID (required)")
flagSet.StringVar(&options.launcherActivity, "launcher-activity", "", "optional <pkg>/<activity> to launch (overrides default resolution)")
flagSet.StringVar(&options.platform, "platform", "android", "target platform: android (ios deferred)")
flagSet.StringVar(&options.avd, "avd", "", "Android AVD name to boot if no device is connected")
flagSet.DurationVar(&options.duration, "duration", 5*time.Minute, "total test duration")
flagSet.Int64Var(&options.seed, "seed", 0, "RNG seed (0 = random)")
flagSet.StringVar(&options.output, "output", "./runs", "output directory for traces")
if err := flagSet.Parse(args); err != nil {
return testOptions{}, err
}
if options.spec == "" {
return testOptions{}, errors.New("--spec is required")
}
if options.bundleID == "" {
return testOptions{}, errors.New("--bundle-id is required")
}
if options.platform != "android" {
return testOptions{}, fmt.Errorf("unsupported platform: %q (only android in v0.1)", options.platform)
}
return options, nil
}
func runTest(options testOptions, stdout io.Writer) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
return runTestPipeline(ctx, options, stdout)
}
func runDoctor(stdout io.Writer) error {
return runDoctorChecks(context.Background(), defaultDoctorChecks(), stdout)
}
func run(args []string, stdout, stderr io.Writer) error {
if len(args) < 2 || args[1] == "-h" || args[1] == "--help" || args[1] == "help" {
fmt.Fprint(stdout, topUsage)
return nil
}
switch args[1] {
case "test":
options, err := parseTestArgs(args[2:], stderr)
if err != nil {
return err
}
return runTest(options, stdout)
case "inspect":
options, err := parseInspectArgs(args[2:], stderr)
if err != nil {
return err
}
return runInspect(options, stdout)
case "doctor":
return runDoctor(stdout)
case "version", "-v", "--version":
fmt.Fprintln(stdout, Version)
return nil
default:
return fmt.Errorf("unknown command: %q (try 'sanderling help')", args[1])
}
}
func main() {
if err := run(os.Args, os.Stdout, os.Stderr); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
+156
View File
@@ -0,0 +1,156 @@
package main
import (
"bytes"
"io"
"strings"
"testing"
"time"
)
func TestParseTestArgs_Defaults(t *testing.T) {
options, err := parseTestArgs([]string{
"--spec", "s.ts",
"--bundle-id", "com.example",
"--avd", "Pixel_5_API_33",
}, io.Discard)
if err != nil {
t.Fatal(err)
}
if options.spec != "s.ts" || options.bundleID != "com.example" {
t.Errorf("unexpected options: %+v", options)
}
if options.platform != "android" {
t.Errorf("platform default: got %q, want android", options.platform)
}
if options.duration != 5*time.Minute {
t.Errorf("duration default: got %v, want 5m", options.duration)
}
if options.output != "./runs" {
t.Errorf("output default: got %q, want ./runs", options.output)
}
if options.seed != 0 {
t.Errorf("seed default: got %d, want 0", options.seed)
}
}
func TestParseTestArgs_AllFlags(t *testing.T) {
options, err := parseTestArgs([]string{
"--spec", "s.ts",
"--bundle-id", "com.example",
"--platform", "android",
"--avd", "Pixel_5_API_33",
"--duration", "10m",
"--seed", "42",
"--output", "./out",
}, io.Discard)
if err != nil {
t.Fatal(err)
}
if options.avd != "Pixel_5_API_33" || options.duration != 10*time.Minute || options.seed != 42 || options.output != "./out" {
t.Errorf("unexpected options: %+v", options)
}
}
func TestParseTestArgs_RequiresSpec(t *testing.T) {
_, err := parseTestArgs([]string{"--bundle-id", "com.example", "--avd", "x"}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "--spec") {
t.Fatalf("expected missing --spec error, got %v", err)
}
}
func TestParseTestArgs_RequiresBundleID(t *testing.T) {
_, err := parseTestArgs([]string{"--spec", "s.ts", "--avd", "x"}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "--bundle-id") {
t.Fatalf("expected missing --bundle-id error, got %v", err)
}
}
func TestParseTestArgs_AVDIsOptional(t *testing.T) {
options, err := parseTestArgs([]string{"--spec", "s.ts", "--bundle-id", "com.example"}, io.Discard)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if options.avd != "" {
t.Fatalf("avd default: got %q, want empty", options.avd)
}
}
func TestParseTestArgs_RejectsNonAndroidPlatform(t *testing.T) {
_, err := parseTestArgs([]string{
"--spec", "s.ts",
"--bundle-id", "com.example",
"--platform", "ios",
"--avd", "x",
}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "unsupported platform") {
t.Fatalf("expected unsupported-platform error, got %v", err)
}
}
func TestRun_HelpPrintsUsage(t *testing.T) {
var stdout bytes.Buffer
if err := run([]string{"sanderling"}, &stdout, io.Discard); err != nil {
t.Fatal(err)
}
if !strings.Contains(stdout.String(), "sanderling <command>") {
t.Errorf("usage missing, got: %q", stdout.String())
}
}
func TestRun_VersionPrintsVersion(t *testing.T) {
prev := Version
Version = "1.2.3-test"
defer func() { Version = prev }()
for _, arg := range []string{"version", "--version", "-v"} {
var stdout bytes.Buffer
if err := run([]string{"sanderling", arg}, &stdout, io.Discard); err != nil {
t.Fatalf("%s: %v", arg, err)
}
if strings.TrimSpace(stdout.String()) != "1.2.3-test" {
t.Errorf("%s: got %q, want 1.2.3-test", arg, stdout.String())
}
}
}
func TestRun_UnknownCommand(t *testing.T) {
err := run([]string{"sanderling", "wat"}, io.Discard, io.Discard)
if err == nil || !strings.Contains(err.Error(), "unknown command") {
t.Fatalf("expected unknown-command error, got %v", err)
}
}
func TestRun_Doctor(t *testing.T) {
var stdout bytes.Buffer
// Doctor may pass or fail depending on host environment; we just want to
// confirm it runs and emits per-check lines.
_ = run([]string{"sanderling", "doctor"}, &stdout, io.Discard)
output := stdout.String()
if !strings.Contains(output, "OK") && !strings.Contains(output, "FAIL") {
t.Errorf("doctor output missing OK/FAIL lines: %q", output)
}
}
func TestRun_TestSubcommand_PipelineErrors(t *testing.T) {
// Without a real spec, a real device, or a bootable AVD the pipeline
// must surface a specific error rather than panicking — proves the flag
// wiring reaches the runner.
err := run([]string{
"sanderling", "test",
"--spec", "definitely-missing-spec.ts",
"--bundle-id", "com.example",
"--avd", "definitely-missing-avd",
}, io.Discard, io.Discard)
if err == nil {
t.Fatal("expected error, got nil")
}
message := err.Error()
ok := strings.Contains(message, "bundle") ||
strings.Contains(message, "device") ||
strings.Contains(message, "AVD") ||
strings.Contains(message, "emulator")
if !ok {
t.Errorf("expected pipeline error (bundle/device/AVD/emulator), got %v", err)
}
}
+52
View File
@@ -0,0 +1,52 @@
package main
import (
"context"
"fmt"
"io"
"log/slog"
"strings"
)
// newProgressLogger wires a slog.Logger that prints user-facing progress
// lines to the CLI's stdout stream. Info messages render as
// "msg key=value ..." to match the prose style of other CLI prints;
// warnings and errors get a "warn:" / "error:" prefix so they stand
// out in the same stream.
func newProgressLogger(writer io.Writer) *slog.Logger {
return slog.New(&progressHandler{writer: writer, level: slog.LevelInfo})
}
type progressHandler struct {
writer io.Writer
level slog.Level
}
func (h *progressHandler) Enabled(_ context.Context, level slog.Level) bool {
return level >= h.level
}
func (h *progressHandler) Handle(_ context.Context, record slog.Record) error {
var builder strings.Builder
if record.Level >= slog.LevelWarn {
fmt.Fprintf(&builder, "%s: ", strings.ToLower(record.Level.String()))
}
builder.WriteString(record.Message)
record.Attrs(func(attr slog.Attr) bool {
fmt.Fprintf(&builder, " %s=%s", attr.Key, formatAttrValue(attr.Value))
return true
})
builder.WriteByte('\n')
_, err := io.WriteString(h.writer, builder.String())
return err
}
func (h *progressHandler) WithAttrs(_ []slog.Attr) slog.Handler { return h }
func (h *progressHandler) WithGroup(_ string) slog.Handler { return h }
func formatAttrValue(value slog.Value) string {
if value.Kind() == slog.KindString {
return fmt.Sprintf("%q", value.String())
}
return value.String()
}
+266
View File
@@ -0,0 +1,266 @@
package main
import (
"context"
"fmt"
"io"
"math/rand/v2"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"time"
"github.com/priyanshujain/sanderling/internal/agent"
"github.com/priyanshujain/sanderling/internal/bundler"
"github.com/priyanshujain/sanderling/internal/driver/maestro"
"github.com/priyanshujain/sanderling/internal/runner"
"github.com/priyanshujain/sanderling/internal/sidecar"
"github.com/priyanshujain/sanderling/internal/trace"
"github.com/priyanshujain/sanderling/internal/verifier"
)
const (
socketName = "sanderling-agent"
sidecarStartupTimeout = 30 * time.Second
sdkAcceptTimeout = 60 * time.Second
)
func runTestPipeline(ctx context.Context, options testOptions, stdout io.Writer) error {
if options.platform == "android" {
if err := ensureDevice(ctx, options.avd, stdout); err != nil {
return err
}
}
aliases := map[string]string{}
if specApiPath := resolveSpecAPIPath(options.spec); specApiPath != "" {
aliases["@sanderling/spec"] = specApiPath
// Also alias published subpath exports so specs importing from
// "@sanderling/spec/defaults/properties" resolve to the in-tree source.
base := filepath.Dir(specApiPath)
aliases["@sanderling/spec/defaults/properties"] = filepath.Join(base, "defaults/properties.ts")
}
bundle, err := bundler.Bundle(bundler.Options{
EntryFile: options.spec,
Defines: map[string]string{
"SANDERLING_TEST_PHONE": os.Getenv("SANDERLING_TEST_PHONE"),
"SANDERLING_TEST_OTP": os.Getenv("SANDERLING_TEST_OTP"),
},
Aliases: aliases,
})
if err != nil {
return fmt.Errorf("bundle spec: %w", err)
}
fmt.Fprintf(stdout, "bundled spec: %d bytes (sha256=%s)\n", len(bundle.JavaScript), bundle.SHA256[:12])
sidecarDirectory := filepath.Join(os.TempDir(), "sanderling-sidecar")
jarPath, err := sidecar.Extract(sidecarDirectory)
if err != nil {
return fmt.Errorf("extract sidecar: %w", err)
}
fmt.Fprintf(stdout, "sidecar JAR: %s (size=%d)\n", jarPath, sidecar.EmbeddedSize())
sidecarPort, err := pickFreePort()
if err != nil {
return err
}
sidecarCommand := exec.CommandContext(ctx, "java", "-jar", jarPath,
"--port", strconv.Itoa(sidecarPort),
"--platform", options.platform,
)
sidecarCommand.Stdout = stdout
sidecarCommand.Stderr = stdout
sidecarCommand.Env = envWithAndroidPlatformTools(os.Environ())
if err := sidecarCommand.Start(); err != nil {
return fmt.Errorf("spawn sidecar: %w", err)
}
defer func() {
if sidecarCommand.Process != nil {
_ = sidecarCommand.Process.Kill()
}
}()
fmt.Fprintf(stdout, "sidecar pid=%d listening on 127.0.0.1:%d\n", sidecarCommand.Process.Pid, sidecarPort)
driverClient, err := maestro.Dial(fmt.Sprintf("127.0.0.1:%d", sidecarPort))
if err != nil {
return fmt.Errorf("dial sidecar: %w", err)
}
defer driverClient.Close()
healthCtx, healthCancel := context.WithTimeout(ctx, sidecarStartupTimeout)
if err := driverClient.WaitForHealth(healthCtx, 250*time.Millisecond); err != nil {
healthCancel()
return fmt.Errorf("sidecar health check: %w", err)
}
healthCancel()
fmt.Fprintln(stdout, "sidecar is healthy")
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return fmt.Errorf("agent listener: %w", err)
}
defer listener.Close()
agentPort := listener.Addr().(*net.TCPAddr).Port
if err := adbReverse(socketName, agentPort); err != nil {
return fmt.Errorf("adb reverse: %w", err)
}
defer func() {
if err := adbReverseRemove(socketName); err != nil {
fmt.Fprintf(stdout, "warning: adb reverse cleanup: %v\n", err)
}
}()
fmt.Fprintf(stdout, "forwarded localabstract:%s -> tcp:%d\n", socketName, agentPort)
agentServer := agent.NewServer(listener)
type acceptResult struct {
connection *agent.Conn
err error
}
acceptChannel := make(chan acceptResult, 1)
go func() {
acceptCtx, cancel := context.WithTimeout(ctx, sdkAcceptTimeout)
defer cancel()
connection, acceptErr := agentServer.Accept(acceptCtx)
acceptChannel <- acceptResult{connection: connection, err: acceptErr}
}()
if err := driverClient.Launch(ctx, options.bundleID, options.launcherActivity, false); err != nil {
return fmt.Errorf("launch app: %w", err)
}
fmt.Fprintf(stdout, "launched %s; waiting for SDK to connect (%.0fs timeout)\n", options.bundleID, sdkAcceptTimeout.Seconds())
result := <-acceptChannel
if result.err != nil {
return fmt.Errorf("accept SDK: %w", result.err)
}
connection := result.connection
defer connection.Close()
hello := connection.Hello()
fmt.Fprintf(stdout, "SDK connected: platform=%s app=%s sdk=%s\n", hello.Platform, hello.AppPackage, hello.Version)
seed := options.seed
if seed == 0 {
seed = time.Now().UnixNano()
}
verifierInstance, err := verifier.New(verifier.WithRand(rand.New(rand.NewPCG(uint64(seed), 0))))
if err != nil {
return fmt.Errorf("verifier: %w", err)
}
if err := verifierInstance.Load(string(bundle.JavaScript)); err != nil {
return fmt.Errorf("load spec: %w", err)
}
fmt.Fprintln(stdout, "spec loaded into verifier")
runDirectory := filepath.Join(options.output, time.Now().UTC().Format("20060102-150405"))
traceWriter, err := trace.NewWriter(runDirectory)
if err != nil {
return fmt.Errorf("trace writer: %w", err)
}
defer traceWriter.Close()
meta := trace.Meta{
Seed: seed,
SpecPath: options.spec,
BundleSHA256: bundle.SHA256,
Platform: options.platform,
BundleID: options.bundleID,
StartedAt: time.Now().UTC(),
SanderlingVersion: "0.0.1",
}
if err := traceWriter.WriteMeta(meta); err != nil {
return fmt.Errorf("trace meta: %w", err)
}
defer func() {
endedAt := time.Now().UTC()
meta.EndedAt = &endedAt
_ = traceWriter.WriteMeta(meta)
}()
fmt.Fprintf(stdout, "trace dir: %s\n", runDirectory)
fmt.Fprintf(stdout, "running for %s (seed=%d)\n", options.duration, seed)
summary, err := runner.Run(ctx, runner.Options{
Duration: options.duration,
SnapshotTimeout: 5 * time.Second,
IdleTimeout: 1 * time.Second,
BundleID: options.bundleID,
Connection: connection,
Driver: driverClient,
Verifier: verifierInstance,
TraceWriter: traceWriter,
Logger: newProgressLogger(stdout),
})
terminateCtx, terminateCancel := context.WithTimeout(context.Background(), 5*time.Second)
_ = driverClient.Terminate(terminateCtx)
terminateCancel()
if err != nil {
return fmt.Errorf("runner: %w", err)
}
fmt.Fprintf(stdout, "\nrun complete: %d steps in %s\n", summary.Steps, summary.EndTime.Sub(summary.StartTime).Round(time.Millisecond))
if len(summary.Violations) == 0 {
fmt.Fprintln(stdout, "no violations.")
} else {
fmt.Fprintf(stdout, "%d violation record(s):\n", len(summary.Violations))
for _, violation := range summary.Violations {
fmt.Fprintf(stdout, " step %d: %v\n", violation.StepIndex, violation.Properties)
}
}
return nil
}
// resolveSpecAPIPath returns the path to pkg/spec-api/src/index.ts inside
// a sanderling source checkout, searched upward from the spec file and the cwd.
// Returns "" when not found, in which case esbuild resolves @sanderling/spec via
// node_modules the way a downstream user's project would.
func resolveSpecAPIPath(specPath string) string {
candidates := []string{}
if absoluteSpec, err := filepath.Abs(specPath); err == nil {
directory := filepath.Dir(absoluteSpec)
for {
candidates = append(candidates, filepath.Join(directory, "pkg/spec-api/src/index.ts"))
parent := filepath.Dir(directory)
if parent == directory {
break
}
directory = parent
}
}
if cwd, err := os.Getwd(); err == nil {
candidates = append(candidates, filepath.Join(cwd, "pkg/spec-api/src/index.ts"))
}
for _, candidate := range candidates {
if _, err := os.Stat(candidate); err == nil {
return candidate
}
}
return ""
}
func pickFreePort() (int, error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return 0, err
}
defer listener.Close()
return listener.Addr().(*net.TCPAddr).Port, nil
}
func adbReverse(socket string, port int) error {
adb, err := adbBinary()
if err != nil {
return err
}
command := exec.Command(adb, "reverse", "localabstract:"+socket, fmt.Sprintf("tcp:%d", port))
return command.Run()
}
func adbReverseRemove(socket string) error {
adb, err := adbBinary()
if err != nil {
return err
}
return exec.Command(adb, "reverse", "--remove", "localabstract:"+socket).Run()
}
+52
View File
@@ -0,0 +1,52 @@
package main
import (
"os"
"path/filepath"
"testing"
)
func TestResolveSpecAPIPath_FindsUpwardSibling(t *testing.T) {
root := t.TempDir()
apiPath := filepath.Join(root, "pkg", "spec-api", "src", "index.ts")
if err := os.MkdirAll(filepath.Dir(apiPath), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(apiPath, []byte("export {}"), 0o644); err != nil {
t.Fatal(err)
}
specPath := filepath.Join(root, "examples", "app", "spec.ts")
if err := os.MkdirAll(filepath.Dir(specPath), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(specPath, []byte(""), 0o644); err != nil {
t.Fatal(err)
}
got := resolveSpecAPIPath(specPath)
if got != apiPath {
t.Fatalf("got %q, want %q", got, apiPath)
}
}
func TestResolveSpecAPIPath_ReturnsEmptyWhenMissing(t *testing.T) {
root := t.TempDir()
specPath := filepath.Join(root, "spec.ts")
if err := os.WriteFile(specPath, []byte(""), 0o644); err != nil {
t.Fatal(err)
}
cwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chdir(cwd) })
if err := os.Chdir(root); err != nil {
t.Fatal(err)
}
got := resolveSpecAPIPath(specPath)
if got != "" {
t.Fatalf("got %q, want empty (no sanderling source tree reachable)", got)
}
}