diff --git a/internal/dev/flutter.go b/internal/dev/flutter.go index 8519a4e..4a4ba22 100644 --- a/internal/dev/flutter.go +++ b/internal/dev/flutter.go @@ -3,18 +3,15 @@ package dev import ( "bufio" "context" - "encoding/json" "fmt" "io" "os" "os/exec" - "path/filepath" - "regexp" - "runtime" "strings" "time" "github.com/MobAI-App/ios-builder/internal/config" + "github.com/MobAI-App/ios-builder/internal/hotreload" "github.com/MobAI-App/ios-builder/internal/mobai" ) @@ -82,7 +79,6 @@ func (h *FlutterHandler) Stop() { } func (h *FlutterHandler) findDebugURL(ctx context.Context, debugOutput <-chan mobai.DebugOutput) (string, <-chan mobai.DebugOutput, error) { - re := regexp.MustCompile(`(?:Observatory|Dart VM service)[^h]*(http://[^\s]+)`) timeout := time.After(30 * time.Second) for { @@ -98,9 +94,9 @@ func (h *FlutterHandler) findDebugURL(ctx context.Context, debugOutput <-chan mo if output.Type == "error" { return "", nil, fmt.Errorf("debug error: %s", output.Message) } - if m := re.FindStringSubmatch(output.Data); len(m) >= 2 { - fmt.Printf("Found debug service: %s\n", m[1]) - return m[1], debugOutput, nil + if u := hotreload.VMServiceURL(output.Data); u != "" { + fmt.Printf("Found debug service: %s\n", u) + return u, debugOutput, nil } } } @@ -186,7 +182,7 @@ func (h *FlutterHandler) startFileWatcher(ctx context.Context) { watchCtx, cancel := context.WithCancel(ctx) h.cancelWatch = cancel - cfg := FileWatcherConfig{ + cfg := hotreload.FileWatcherConfig{ Dirs: h.watchConfig.Dirs, Patterns: h.watchConfig.Patterns, Ignore: h.watchConfig.Ignore, @@ -197,11 +193,11 @@ func (h *FlutterHandler) startFileWatcher(ctx context.Context) { }, } - if needsPolling(cfg.Dirs) { + if hotreload.NeedsPolling(cfg.Dirs) { fmt.Println("\n[builder] WSL2 detected, using polling watcher for Windows filesystem") - h.watcher = NewPollingWatcher(&cfg) + h.watcher = hotreload.NewPollingWatcher(&cfg) } else { - w, err := NewFileWatcher(&cfg) + w, err := hotreload.NewFileWatcher(&cfg) if err != nil { fmt.Printf("\n[builder] Warning: failed to start file watcher: %v\n", err) return @@ -220,66 +216,18 @@ func (h *FlutterHandler) startFileWatcher(ctx context.Context) { // EnsureCustomDevice ensures Flutter custom_devices.json has mobai-ios configured. func EnsureCustomDevice(mobaiURL string) error { - if err := exec.Command("flutter", "config", "--enable-custom-devices").Run(); err != nil { - return fmt.Errorf("failed to enable custom devices - run 'flutter config --enable-custom-devices' manually first: %w", err) - } - - var configPath string - if runtime.GOOS == "windows" { - appData := os.Getenv("APPDATA") - if appData == "" { - return fmt.Errorf("APPDATA environment variable not set") - } - configPath = filepath.Join(appData, ".flutter_custom_devices.json") - } else { - homeDir, err := os.UserHomeDir() - if err != nil { - return fmt.Errorf("get home dir: %w", err) - } - flutterDir := filepath.Join(homeDir, ".config", "flutter") - if err := os.MkdirAll(flutterDir, 0755); err != nil { - return fmt.Errorf("create flutter config dir: %w", err) - } - configPath = filepath.Join(flutterDir, "custom_devices.json") - } - execPath, err := os.Executable() if err != nil { return fmt.Errorf("get executable path: %w", err) } - pingCmd := []string{execPath, "mobai", "--url", mobaiURL, "ping"} - installCmd := []string{execPath, "mobai", "--url", mobaiURL, "install", "${localPath}"} - runDebugCmd := []string{execPath, "mobai", "--url", mobaiURL, "run-debug", "${appName}"} - forwardCmd := []string{execPath, "mobai", "--url", mobaiURL, "forward", "${devicePort}", "${hostPort}"} - - config := map[string]any{ - "custom-devices": []any{ - map[string]any{ - "id": "mobai-ios", - "label": "MobAI iOS Device", - "sdkNameAndVersion": "iOS (via MobAI)", - "platform": nil, - "enabled": true, - "ping": pingCmd, - "pingSuccessRegex": "success", - "install": installCmd, - "uninstall": []string{"echo", "uninstall not supported"}, - "runDebug": runDebugCmd, - "forwardPort": forwardCmd, - "forwardPortSuccessRegex": "forwarded", - }, - }, - } - - output, err := json.MarshalIndent(config, "", " ") - if err != nil { - return fmt.Errorf("marshal config: %w", err) - } - - if err := os.WriteFile(configPath, output, 0644); err != nil { - return fmt.Errorf("write config: %w", err) - } - - return nil + return hotreload.WriteCustomDevice(&hotreload.CustomDevice{ + Ping: []string{execPath, "mobai", "--url", mobaiURL, "ping"}, + PingSuccessRegex: "success", + Install: []string{execPath, "mobai", "--url", mobaiURL, "install", "${localPath}"}, + Uninstall: []string{"echo", "uninstall not supported"}, + RunDebug: []string{execPath, "mobai", "--url", mobaiURL, "run-debug", "${appName}"}, + ForwardPort: []string{execPath, "mobai", "--url", mobaiURL, "forward", "${devicePort}", "${hostPort}"}, + ForwardPortSuccessRegex: "forwarded", + }) } diff --git a/internal/dev/reactnative.go b/internal/dev/reactnative.go index ecbeb99..37d8d5d 100644 --- a/internal/dev/reactnative.go +++ b/internal/dev/reactnative.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "github.com/MobAI-App/ios-builder/internal/hotreload" "github.com/MobAI-App/ios-builder/internal/mobai" ) @@ -63,7 +64,7 @@ func (h *ReactNativeHandler) Setup(ctx context.Context) error { // Attach monitors app output for React Native development. func (h *ReactNativeHandler) Attach(ctx context.Context, deviceID string, debugOutput <-chan mobai.DebugOutput) error { - ip := getLocalIP() + ip := hotreload.LocalIP() fmt.Println() fmt.Printf("Metro bundler: http://%s:%d\n", ip, h.metroPort) @@ -105,14 +106,12 @@ func (h *ReactNativeHandler) Attach(ctx context.Context, deviceID string, debugO // DebugConfig returns launch arguments to configure Metro connection. // React Native reads RCT_jsLocation from NSUserDefaults, which can be set via launch arguments. func (h *ReactNativeHandler) DebugConfig() *mobai.DebugConfig { - ip := getLocalIP() + ip := hotreload.LocalIP() fmt.Printf("Detected host IP: %s\n", ip) - jsLocation := fmt.Sprintf("%s:%d", ip, h.metroPort) - return &mobai.DebugConfig{ - Arguments: []string{"-RCT_jsLocation", jsLocation}, + Arguments: hotreload.MetroLaunchArguments(ip, h.metroPort), } } @@ -193,31 +192,3 @@ func getWorkingDir() string { } return wd } - -func getLocalIP() string { - if isWSL() { - cmd := exec.Command("powershell.exe", "-NoProfile", "-Command", - `Get-NetIPAddress -AddressFamily IPv4 | Where-Object { ($_.IPAddress -notlike "169.*") -and ($_.IPAddress -notlike "127.*") -and ($_.IPAddress -notlike "172.*") } | Select-Object -First 1 -ExpandProperty IPAddress`) - output, err := cmd.Output() - if err != nil { - return "localhost" - } - ip := strings.TrimSpace(string(output)) - if ip == "" { - return "localhost" - } - return ip - } - - conn, err := net.Dial("udp", "8.8.8.8:80") - if err != nil { - return "localhost" - } - defer func() { _ = conn.Close() }() - - localAddr, ok := conn.LocalAddr().(*net.UDPAddr) - if !ok { - return "localhost" - } - return localAddr.IP.String() -} diff --git a/internal/hotreload/customdevice.go b/internal/hotreload/customdevice.go new file mode 100644 index 0000000..36379d3 --- /dev/null +++ b/internal/hotreload/customdevice.go @@ -0,0 +1,99 @@ +package hotreload + +import ( + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" +) + +// CustomDeviceID is the Flutter device id of the MobAI iOS custom device: +// flutter attach -d mobai-ios. +const CustomDeviceID = "mobai-ios" + +// CustomDevice is the commands Flutter's custom device runs for the MobAI +// iOS device. Flutter fills in ${localPath}, ${appName}, ${devicePort} and +// ${hostPort}; each success regex must match a line of the command's output. +// Flutter keeps the forward command running for the life of the forward and +// takes its exit as a failed forward. +type CustomDevice struct { + Ping []string + PingSuccessRegex string + Install []string + Uninstall []string + RunDebug []string + ForwardPort []string + ForwardPortSuccessRegex string +} + +// WriteCustomDevice turns on Flutter's custom devices and writes d as the +// mobai-ios device to Flutter's custom_devices.json. +func WriteCustomDevice(d *CustomDevice) error { + if err := exec.Command("flutter", "config", "--enable-custom-devices").Run(); err != nil { + return fmt.Errorf("failed to enable custom devices - run 'flutter config --enable-custom-devices' manually first: %w", err) + } + + var configPath string + if runtime.GOOS == "windows" { + appData := os.Getenv("APPDATA") + if appData == "" { + return fmt.Errorf("APPDATA environment variable not set") + } + configPath = filepath.Join(appData, ".flutter_custom_devices.json") + } else { + homeDir, err := os.UserHomeDir() + if err != nil { + return fmt.Errorf("get home dir: %w", err) + } + flutterDir := filepath.Join(homeDir, ".config", "flutter") + if err := os.MkdirAll(flutterDir, 0755); err != nil { + return fmt.Errorf("create flutter config dir: %w", err) + } + configPath = filepath.Join(flutterDir, "custom_devices.json") + } + + config := map[string]any{ + "custom-devices": []any{ + map[string]any{ + "id": CustomDeviceID, + "label": "MobAI iOS Device", + "sdkNameAndVersion": "iOS (via MobAI)", + "platform": nil, + "enabled": true, + "ping": d.Ping, + "pingSuccessRegex": d.PingSuccessRegex, + "install": d.Install, + "uninstall": d.Uninstall, + "runDebug": d.RunDebug, + "forwardPort": d.ForwardPort, + "forwardPortSuccessRegex": d.ForwardPortSuccessRegex, + }, + }, + } + + output, err := json.MarshalIndent(config, "", " ") + if err != nil { + return fmt.Errorf("marshal config: %w", err) + } + + if err := os.WriteFile(configPath, output, 0644); err != nil { + return fmt.Errorf("write config: %w", err) + } + + return nil +} + +// vmServiceRE finds the Dart VM service URL a debug build prints at launch. +var vmServiceRE = regexp.MustCompile(`(?:Observatory|Dart VM service)[^h]*(http://[^\s]+)`) + +// VMServiceURL returns the Dart VM service URL in a line of a Flutter debug +// build's output, or "". +func VMServiceURL(line string) string { + if m := vmServiceRE.FindStringSubmatch(line); len(m) >= 2 { + return m[1] + } + return "" +} diff --git a/internal/hotreload/customdevice_test.go b/internal/hotreload/customdevice_test.go new file mode 100644 index 0000000..0be30fc --- /dev/null +++ b/internal/hotreload/customdevice_test.go @@ -0,0 +1,19 @@ +package hotreload + +import "testing" + +func TestVMServiceURL(t *testing.T) { + tests := []struct { + line string + want string + }{ + {"flutter: The Dart VM service is listening on http://127.0.0.1:52361/kKx2tUbXYuM=/", "http://127.0.0.1:52361/kKx2tUbXYuM=/"}, + {"Observatory listening on http://127.0.0.1:1024/abc=/\n", "http://127.0.0.1:1024/abc=/"}, + {"flutter: hello", ""}, + } + for _, tt := range tests { + if got := VMServiceURL(tt.line); got != tt.want { + t.Errorf("VMServiceURL(%q) = %q, want %q", tt.line, got, tt.want) + } + } +} diff --git a/internal/hotreload/metro.go b/internal/hotreload/metro.go new file mode 100644 index 0000000..ab81728 --- /dev/null +++ b/internal/hotreload/metro.go @@ -0,0 +1,46 @@ +package hotreload + +import ( + "fmt" + "net" + "os/exec" + "strings" +) + +// MetroLaunchArguments are the launch arguments that point a React Native +// debug build at the Metro bundler on host:port. React Native reads +// RCT_jsLocation from NSUserDefaults, which launch arguments set. +func MetroLaunchArguments(host string, port int) []string { + return []string{"-RCT_jsLocation", fmt.Sprintf("%s:%d", host, port)} +} + +// LocalIP is this machine's address on the local network, the one a phone on +// the same Wi-Fi reaches it at; under WSL, the Windows host's. "localhost" +// when there is none. +func LocalIP() string { + if isWSL2() { + cmd := exec.Command("powershell.exe", "-NoProfile", "-Command", + `Get-NetIPAddress -AddressFamily IPv4 | Where-Object { ($_.IPAddress -notlike "169.*") -and ($_.IPAddress -notlike "127.*") -and ($_.IPAddress -notlike "172.*") } | Select-Object -First 1 -ExpandProperty IPAddress`) + output, err := cmd.Output() + if err != nil { + return "localhost" + } + ip := strings.TrimSpace(string(output)) + if ip == "" { + return "localhost" + } + return ip + } + + conn, err := net.Dial("udp", "8.8.8.8:80") + if err != nil { + return "localhost" + } + defer func() { _ = conn.Close() }() + + localAddr, ok := conn.LocalAddr().(*net.UDPAddr) + if !ok { + return "localhost" + } + return localAddr.IP.String() +} diff --git a/internal/dev/watcher.go b/internal/hotreload/watcher.go similarity index 81% rename from internal/dev/watcher.go rename to internal/hotreload/watcher.go index 447e543..dcdeddc 100644 --- a/internal/dev/watcher.go +++ b/internal/hotreload/watcher.go @@ -1,4 +1,9 @@ -package dev +// Package hotreload holds the pieces of hot reload through MobAI that need no +// terminal: the MobAI iOS custom device Flutter attaches through, the Dart VM +// service URL a debug build prints, the file watcher that triggers reloads, +// and pointing a React Native debug build at Metro. The dev commands build on +// it, and pkg/dev exposes it to other programs. +package hotreload import ( "context" @@ -31,8 +36,8 @@ func isWindowsMountedPath(path string) bool { return strings.HasPrefix(absPath, "/mnt/") } -// needsPolling determines if polling should be used instead of inotify. -func needsPolling(dirs []string) bool { +// NeedsPolling determines if polling should be used instead of inotify. +func NeedsPolling(dirs []string) bool { if !isWSL2() { return false } @@ -44,6 +49,21 @@ func needsPolling(dirs []string) bool { return false } +// Watcher watches files and calls OnChange, until Stop. +type Watcher interface { + Start(ctx context.Context) error + Stop() +} + +// NewWatcher returns the watcher that works for cfg's directories: a polling +// one for Windows files under WSL2, where change events do not arrive. +func NewWatcher(cfg *FileWatcherConfig) (Watcher, error) { + if NeedsPolling(cfg.Dirs) { + return NewPollingWatcher(cfg), nil + } + return NewFileWatcher(cfg) +} + // FileWatcherConfig holds configuration for the file watcher. type FileWatcherConfig struct { Dirs []string diff --git a/internal/dev/watcher_poll.go b/internal/hotreload/watcher_poll.go similarity index 99% rename from internal/dev/watcher_poll.go rename to internal/hotreload/watcher_poll.go index 5ffaba1..46da271 100644 --- a/internal/dev/watcher_poll.go +++ b/internal/hotreload/watcher_poll.go @@ -1,4 +1,4 @@ -package dev +package hotreload import ( "context" diff --git a/internal/dev/watcher_test.go b/internal/hotreload/watcher_test.go similarity index 99% rename from internal/dev/watcher_test.go rename to internal/hotreload/watcher_test.go index 8db9aec..b956fe2 100644 --- a/internal/dev/watcher_test.go +++ b/internal/hotreload/watcher_test.go @@ -1,4 +1,4 @@ -package dev +package hotreload import ( "context" diff --git a/pkg/dev/dev.go b/pkg/dev/dev.go new file mode 100644 index 0000000..815d370 --- /dev/null +++ b/pkg/dev/dev.go @@ -0,0 +1,63 @@ +// Package dev exposes the hot reload pieces of the dev commands to code +// outside this module: the MobAI iOS custom device that flutter attach +// drives, the Dart VM service URL a debug build prints, the file watcher +// that triggers reloads, and the launch arguments that point a React Native +// debug build at Metro. +// +// A program that runs its own dev sessions through MobAI supplies the custom +// device's commands itself instead of builder's mobai subcommands. +package dev + +import ( + "github.com/MobAI-App/ios-builder/internal/hotreload" +) + +// CustomDeviceID is the Flutter device id of the MobAI iOS custom device: +// flutter attach -d mobai-ios. +const CustomDeviceID = hotreload.CustomDeviceID + +// CustomDevice is the commands Flutter's custom device runs for the MobAI +// iOS device. Flutter fills in ${localPath}, ${appName}, ${devicePort} and +// ${hostPort}; each success regex must match a line of the command's output. +// Flutter keeps the forward command running for the life of the forward and +// takes its exit as a failed forward. +type CustomDevice = hotreload.CustomDevice + +// WriteCustomDevice turns on Flutter's custom devices and writes d as the +// mobai-ios device to Flutter's custom_devices.json, replacing what is there. +func WriteCustomDevice(d *CustomDevice) error { + return hotreload.WriteCustomDevice(d) +} + +// VMServiceURL returns the Dart VM service URL in a line of a Flutter debug +// build's output, or "". +func VMServiceURL(line string) string { + return hotreload.VMServiceURL(line) +} + +// FileWatcherConfig is what a Watcher watches: directories, the file +// suffixes that count, the suffixes to ignore, the debounce, and the call +// made after a change. +type FileWatcherConfig = hotreload.FileWatcherConfig + +// Watcher watches files and calls OnChange, until Stop. +type Watcher = hotreload.Watcher + +// NewWatcher returns the watcher that works for cfg's directories: a polling +// one for Windows files under WSL2, where change events do not arrive. +func NewWatcher(cfg *FileWatcherConfig) (Watcher, error) { + return hotreload.NewWatcher(cfg) +} + +// LocalIP is this machine's address on the local network, the one a phone on +// the same Wi-Fi reaches it at; under WSL, the Windows host's. "localhost" +// when there is none. +func LocalIP() string { + return hotreload.LocalIP() +} + +// MetroLaunchArguments are the launch arguments that point a React Native +// debug build at the Metro bundler on host:port. +func MetroLaunchArguments(host string, port int) []string { + return hotreload.MetroLaunchArguments(host, port) +}