|
| 1 | +package simulator |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "os/exec" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +type simctlDevice struct { |
| 11 | + UDID string `json:"udid"` |
| 12 | + Name string `json:"name"` |
| 13 | + State string `json:"state"` |
| 14 | + IsAvailable bool `json:"isAvailable"` |
| 15 | +} |
| 16 | + |
| 17 | +type simctlOutput struct { |
| 18 | + Devices map[string][]simctlDevice `json:"devices"` |
| 19 | +} |
| 20 | + |
| 21 | +func CheckToolsAvailable() map[string]bool { |
| 22 | + available := make(map[string]bool) |
| 23 | + for _, tool := range []string{"xcrun"} { |
| 24 | + _, err := exec.LookPath(tool) |
| 25 | + available[tool] = err == nil |
| 26 | + } |
| 27 | + return available |
| 28 | +} |
| 29 | + |
| 30 | +func ListIOSDevices() ([]string, error) { |
| 31 | + out, err := exec.Command("xcrun", "simctl", "list", "devices", "booted", "--json").Output() |
| 32 | + if err != nil { |
| 33 | + return nil, fmt.Errorf("xcrun simctl failed: %w", err) |
| 34 | + } |
| 35 | + |
| 36 | + var payload simctlOutput |
| 37 | + if err := json.Unmarshal(out, &payload); err != nil { |
| 38 | + return nil, fmt.Errorf("failed to parse simctl JSON: %w", err) |
| 39 | + } |
| 40 | + |
| 41 | + var names []string |
| 42 | + for _, devices := range payload.Devices { |
| 43 | + for _, d := range devices { |
| 44 | + if strings.EqualFold(d.State, "Booted") && d.IsAvailable { |
| 45 | + names = append(names, fmt.Sprintf("%s (%s)", d.Name, d.UDID)) |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + return names, nil |
| 50 | +} |
| 51 | + |
| 52 | +func GetBootedIOSDevices() ([]simctlDevice, error) { |
| 53 | + out, err := exec.Command("xcrun", "simctl", "list", "devices", "booted", "--json").Output() |
| 54 | + if err != nil { |
| 55 | + return nil, fmt.Errorf("xcrun simctl failed: %w", err) |
| 56 | + } |
| 57 | + |
| 58 | + var payload simctlOutput |
| 59 | + if err := json.Unmarshal(out, &payload); err != nil { |
| 60 | + return nil, fmt.Errorf("failed to parse simctl JSON: %w", err) |
| 61 | + } |
| 62 | + |
| 63 | + var devices []simctlDevice |
| 64 | + for _, devices := range payload.Devices { |
| 65 | + for _, d := range devices { |
| 66 | + if strings.EqualFold(d.State, "Booted") && d.IsAvailable { |
| 67 | + devices = append(devices, d) |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + return devices, nil |
| 72 | +} |
0 commit comments