From f0fbf39900b26200ed9c0cc01d4af35224306da7 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:41:47 +0100 Subject: [PATCH 01/16] test(installer): add recorded macOS outputs for the media mode Co-Authored-By: Claude Sonnet 5.5 --- .../media/testdata/darwin/info-disk0.json | 1 + .../testdata/darwin/info-external-apfs.json | 45 +++++++++++++++++++ .../media/testdata/darwin/info-ramdisk.json | 1 + .../media/testdata/darwin/info-root.json | 1 + .../media/testdata/darwin/info-usb.json | 45 +++++++++++++++++++ .../media/testdata/darwin/list-physical.json | 1 + .../internal/media/testdata/imager-mac-ok.txt | 15 +++++++ 7 files changed, 109 insertions(+) create mode 100644 installer/internal/media/testdata/darwin/info-disk0.json create mode 100644 installer/internal/media/testdata/darwin/info-external-apfs.json create mode 100644 installer/internal/media/testdata/darwin/info-ramdisk.json create mode 100644 installer/internal/media/testdata/darwin/info-root.json create mode 100644 installer/internal/media/testdata/darwin/info-usb.json create mode 100644 installer/internal/media/testdata/darwin/list-physical.json create mode 100644 installer/internal/media/testdata/imager-mac-ok.txt diff --git a/installer/internal/media/testdata/darwin/info-disk0.json b/installer/internal/media/testdata/darwin/info-disk0.json new file mode 100644 index 00000000..8bb0e9c4 --- /dev/null +++ b/installer/internal/media/testdata/darwin/info-disk0.json @@ -0,0 +1 @@ +{"OSInternalMedia":false,"VolumeName":"","PartitionMapPartition":false,"SystemImage":false,"DeviceBlockSize":512,"MountPoint":"","DeviceNode":"\/dev\/disk0","RemovableMediaOrExternalDevice":false,"SMARTDeviceSpecificKeysMayVaryNotGuaranteed":{},"FreeSpace":0,"CanBeMadeBootableRequiresDestroy":false,"Internal":true,"WholeDisk":true,"EjectableOnly":false,"CanBeMadeBootable":false,"VolumeSize":0,"Writable":true,"LowLevelFormatSupported":false,"VirtualOrPhysical":"Unknown","RAIDMaster":false,"Size":348966092800,"RemovableMedia":false,"EjectableMediaAutomaticUnderSoftwareControl":false,"WritableVolume":false,"SolidState":true,"BusProtocol":"","IORegistryEntryName":"Apple Inc. VirtIO Block Media","ParentWholeDisk":"disk0","Bootable":false,"Content":"GUID_partition_scheme","IOKitSize":348966092800,"GlobalPermissionsEnabled":false,"MediaType":"","Ejectable":false,"SupportsGlobalPermissionsDisable":false,"DeviceIdentifier":"disk0","MediaName":"Apple Inc. VirtIO Block Media","TotalSize":348966092800,"OS9DriversInstalled":false,"RAIDSlice":false,"Removable":false,"DeviceTreePath":"IODeviceTree:\/arm-io\/pcie@30000000\/pci106b,1a00@6\/AppleVirtIOStorageDevice","SMARTStatus":"Not Supported","WritableMedia":true} \ No newline at end of file diff --git a/installer/internal/media/testdata/darwin/info-external-apfs.json b/installer/internal/media/testdata/darwin/info-external-apfs.json new file mode 100644 index 00000000..607362d7 --- /dev/null +++ b/installer/internal/media/testdata/darwin/info-external-apfs.json @@ -0,0 +1,45 @@ +{ + "OSInternalMedia": false, + "VolumeName": "", + "PartitionMapPartition": false, + "SystemImage": false, + "DeviceBlockSize": 512, + "MountPoint": "", + "DeviceNode": "/dev/disk5", + "RemovableMediaOrExternalDevice": true, + "SMARTDeviceSpecificKeysMayVaryNotGuaranteed": {}, + "FreeSpace": 0, + "CanBeMadeBootableRequiresDestroy": false, + "Internal": false, + "WholeDisk": true, + "EjectableOnly": false, + "CanBeMadeBootable": false, + "VolumeSize": 0, + "Writable": true, + "LowLevelFormatSupported": false, + "VirtualOrPhysical": "Physical", + "RAIDMaster": false, + "Size": 1000204886016, + "RemovableMedia": false, + "EjectableMediaAutomaticUnderSoftwareControl": true, + "WritableVolume": false, + "BusProtocol": "USB", + "IORegistryEntryName": "Samsung PSSD T7 Media", + "ParentWholeDisk": "disk5", + "Bootable": false, + "Content": "GUID_partition_scheme", + "IOKitSize": 1000204886016, + "GlobalPermissionsEnabled": false, + "MediaType": "Generic", + "Ejectable": true, + "SupportsGlobalPermissionsDisable": false, + "DeviceIdentifier": "disk5", + "MediaName": "Samsung PSSD T7", + "TotalSize": 1000204886016, + "OS9DriversInstalled": false, + "RAIDSlice": false, + "Removable": false, + "DeviceTreePath": "IODeviceTree:/", + "SMARTStatus": "Not Supported", + "WritableMedia": true +} diff --git a/installer/internal/media/testdata/darwin/info-ramdisk.json b/installer/internal/media/testdata/darwin/info-ramdisk.json new file mode 100644 index 00000000..0ea164c9 --- /dev/null +++ b/installer/internal/media/testdata/darwin/info-ramdisk.json @@ -0,0 +1 @@ +{"OSInternalMedia":false,"VolumeName":"","PartitionMapPartition":false,"SystemImage":false,"DeviceBlockSize":512,"MountPoint":"","DeviceNode":"\/dev\/disk7","RemovableMediaOrExternalDevice":true,"SMARTDeviceSpecificKeysMayVaryNotGuaranteed":{},"FreeSpace":0,"CanBeMadeBootableRequiresDestroy":false,"Internal":false,"WholeDisk":true,"EjectableOnly":true,"CanBeMadeBootable":false,"VolumeSize":0,"Writable":true,"LowLevelFormatSupported":false,"VirtualOrPhysical":"Virtual","RAIDMaster":false,"Size":134217728,"RemovableMedia":true,"EjectableMediaAutomaticUnderSoftwareControl":true,"WritableVolume":false,"BusProtocol":"Disk Image","IORegistryEntryName":"Apple read\/write Media","ParentWholeDisk":"disk7","Bootable":false,"Content":"","IOKitSize":134217728,"GlobalPermissionsEnabled":false,"MediaType":"Generic","Ejectable":true,"SupportsGlobalPermissionsDisable":false,"DeviceIdentifier":"disk7","MediaName":"Disk Image","TotalSize":134217728,"OS9DriversInstalled":false,"RAIDSlice":false,"Removable":true,"DeviceTreePath":"IODeviceTree:\/","SMARTStatus":"Not Supported","WritableMedia":true} \ No newline at end of file diff --git a/installer/internal/media/testdata/darwin/info-root.json b/installer/internal/media/testdata/darwin/info-root.json new file mode 100644 index 00000000..74ed55c9 --- /dev/null +++ b/installer/internal/media/testdata/darwin/info-root.json @@ -0,0 +1 @@ +{"DeviceBlockSize":4096,"VolumeSize":0,"Writable":false,"RAIDSlice":false,"APFSContainerSize":343073095680,"APFSSnapshotName":"com.apple.os.update-ECF5104E367CC369B8BD7A90CC030DE52A096EC09BA72FF71581DD3982BBA0A2","APFSSnapshot":true,"EjectableOnly":false,"CanBeMadeBootable":false,"DeviceNode":"\/dev\/disk2s1s1","FileVault":false,"Removable":false,"VolumeAllocationBlockSize":4096,"GlobalPermissionsEnabled":true,"SupportsGlobalPermissionsDisable":true,"RemovableMediaOrExternalDevice":false,"APFSVolumeGroupID":"4A1F17CF-B156-47AC-8FC6-443C31864B5F","MountPoint":"\/","BusProtocol":"","VolumeUUID":"A1916669-9282-46AC-AD35-FC2C808AF0F9","Content":"41504653-0000-11AA-AA11-00306543ECAC","SystemImage":false,"FreeSpace":0,"WritableVolume":false,"FilesystemUserVisibleName":"APFS","EjectableMediaAutomaticUnderSoftwareControl":false,"IORegistryEntryName":"com.apple.os.update-ECF5104E367CC369B8BD7A90CC030DE52A096EC09BA72FF71581DD3982BBA0A2","IOKitSize":343073095680,"SMARTStatus":"Not Supported","APFSContainerFree":102629486592,"Sealed":"Yes","Locked":false,"SMARTDeviceSpecificKeysMayVaryNotGuaranteed":{},"MacOSSystemAPFSEFIDriverVersion":2811160007702004,"APFSContainerReference":"disk2","DiskUUID":"A1916669-9282-46AC-AD35-FC2C808AF0F9","TotalSize":343073095680,"RecoveryDeviceIdentifier":"disk2s3","VolumeName":"Macintosh HD","Bootable":true,"EncryptionThisVolumeProper":false,"MediaName":"","SolidState":true,"FilesystemName":"APFS","DeviceIdentifier":"disk2s1s1","FilesystemType":"apfs","RAIDMaster":false,"Internal":true,"APFSSnapshotUUID":"A1916669-9282-46AC-AD35-FC2C808AF0F9","BooterDeviceIdentifier":"disk2s2","APFSPhysicalStores":[{"APFSPhysicalStore":"disk0s2"}],"Size":343073095680,"WholeDisk":false,"OSInternalMedia":false,"CapacityInUse":12644737024,"Ejectable":false,"Encryption":false,"MediaType":"","RemovableMedia":false,"ParentWholeDisk":"disk2","PartitionMapPartition":false,"CanBeMadeBootableRequiresDestroy":false,"DeviceTreePath":"IODeviceTree:\/arm-io\/pcie@30000000\/pci106b,1a00@6\/AppleVirtIOStorageDevice","WritableMedia":false} \ No newline at end of file diff --git a/installer/internal/media/testdata/darwin/info-usb.json b/installer/internal/media/testdata/darwin/info-usb.json new file mode 100644 index 00000000..d26cba24 --- /dev/null +++ b/installer/internal/media/testdata/darwin/info-usb.json @@ -0,0 +1,45 @@ +{ + "OSInternalMedia": false, + "VolumeName": "", + "PartitionMapPartition": false, + "SystemImage": false, + "DeviceBlockSize": 512, + "MountPoint": "", + "DeviceNode": "/dev/disk4", + "RemovableMediaOrExternalDevice": true, + "SMARTDeviceSpecificKeysMayVaryNotGuaranteed": {}, + "FreeSpace": 0, + "CanBeMadeBootableRequiresDestroy": false, + "Internal": false, + "WholeDisk": true, + "EjectableOnly": true, + "CanBeMadeBootable": false, + "VolumeSize": 0, + "Writable": true, + "LowLevelFormatSupported": false, + "VirtualOrPhysical": "Physical", + "RAIDMaster": false, + "Size": 32010928128, + "RemovableMedia": true, + "EjectableMediaAutomaticUnderSoftwareControl": true, + "WritableVolume": false, + "BusProtocol": "USB", + "IORegistryEntryName": "SanDisk Ultra Media", + "ParentWholeDisk": "disk4", + "Bootable": false, + "Content": "FDisk_partition_scheme", + "IOKitSize": 32010928128, + "GlobalPermissionsEnabled": false, + "MediaType": "Generic", + "Ejectable": true, + "SupportsGlobalPermissionsDisable": false, + "DeviceIdentifier": "disk4", + "MediaName": "SanDisk Ultra", + "TotalSize": 32010928128, + "OS9DriversInstalled": false, + "RAIDSlice": false, + "Removable": true, + "DeviceTreePath": "IODeviceTree:/", + "SMARTStatus": "Not Supported", + "WritableMedia": true +} diff --git a/installer/internal/media/testdata/darwin/list-physical.json b/installer/internal/media/testdata/darwin/list-physical.json new file mode 100644 index 00000000..5259332d --- /dev/null +++ b/installer/internal/media/testdata/darwin/list-physical.json @@ -0,0 +1 @@ +{"AllDisksAndPartitions":[{"Partitions":[{"Size":524288000,"Content":"Apple_APFS_ISC","DeviceIdentifier":"disk0s1","DiskUUID":"38A64141-4DAB-4C0A-ADCD-50310B32A12E"},{"Size":343073095680,"Content":"Apple_APFS","DeviceIdentifier":"disk0s2","DiskUUID":"9CF375C0-9D40-4CA0-A81E-D5A079E05785"},{"Size":5368668672,"Content":"Apple_APFS_Recovery","DeviceIdentifier":"disk0s3","DiskUUID":"A809867C-78EA-48C2-918C-CD79A7C5A815"}],"Size":348966092800,"Content":"GUID_partition_scheme","DeviceIdentifier":"disk0","OSInternal":false}],"VolumesFromDisks":[],"AllDisks":["disk0","disk0s1","disk0s2","disk0s3"],"WholeDisks":["disk0"]} \ No newline at end of file diff --git a/installer/internal/media/testdata/imager-mac-ok.txt b/installer/internal/media/testdata/imager-mac-ok.txt new file mode 100644 index 00000000..e069150e --- /dev/null +++ b/installer/internal/media/testdata/imager-mac-ok.txt @@ -0,0 +1,15 @@ +CacheManager initialized with background thread +Optimal async queue depth: 64 (available: 2953 MB, budget: 442 MB, block size: 1024 KB, baseline: 64 ) +FileOperations log callback installed +Starting background cache operations +Starting background drive list polling +WARNING: writing to system drives is enabled. + Unmounting drive... Opening macOS device: /dev/rdisk7 +Device path detected, using macOS authorization... + Opening drive... Device max write transfer: 2097152 bytes +Successfully opened device, fd=11 (direct I/O enabled) +Block device size: 2147483648 bytes (blocks=4194304, block_size=512) + Zero'ing out first and last MB of drive...  Zero'ing out end of drive...  Opening image file...  Starting extraction... Writing: [> ] 0 % Writing: [> ] 3 % Writing: [-> ] 6 % Writing: [--> ] 10 % Writing: [--> ] 13 % Writing: [---> ] 17 % Writing: [----> ] 21 % Writing: [-----> ] 25 % Writing: [-----> ] 28 % Writing: [------> ] 31 % Writing: [------> ] 34 % Writing: [-------> ] 38 % Writing: [--------> ] 41 % Writing: [--------> ] 44 % Writing: [---------> ] 47 % Writing: [---------> ] 48 % Writing: [----------> ] 50 % Writing: [----------> ] 52 % Writing: [----------> ] 53 % Writing: [----------> ] 54 % Writing: [-----------> ] 55 % Writing: [-----------> ] 56 % Writing: [-----------> ] 57 % Writing: [-----------> ] 58 % Writing: [-----------> ] 59 % Writing: [------------> ] 60 % Writing: [------------> ] 61 % Writing: [------------> ] 62 % Writing: [------------> ] 63 % Writing: [------------> ] 64 % Writing: [-------------> ] 65 % Writing: [-------------> ] 66 % Writing: [-------------> ] 67 % Writing: [-------------> ] 68 % Writing: [-------------> ] 69 % Writing: [--------------> ] 70 % Writing: [--------------> ] 71 % Writing: [--------------> ] 72 % Writing: [--------------> ] 73 % Writing: [--------------> ] 74 % Writing: [---------------> ] 75 % Writing: [---------------> ] 76 % Writing: [---------------> ] 77 % Writing: [---------------> ] 78 % Writing: [---------------> ] 79 % Writing: [----------------> ] 80 % Writing: [----------------> ] 82 % Writing: [----------------> ] 83 % Writing: [----------------> ] 84 % Writing: [-----------------> ] 85 % Writing: [-----------------> ] 86 % Writing: [-----------------> ] 87 % Writing: [-----------------> ] 89 % Writing: [------------------> ] 91 % Writing: [------------------> ] 94 % Writing: [-------------------> ] 96 % Writing: [-------------------> ] 98 % Writing: [-------------------> ] 99 % PrepareForSequentialRead: fd=11 path=/dev/rdisk7 + F_RDAHEAD result: 0 (OK) + F_NOCACHE result: 0 (OK) + Writing: [-------------------->] 100 % Verifying: [> ] 0 % Verifying: [> ] 1 % Verifying: [> ] 2 % Verifying: [> ] 4 % Verifying: [-> ] 6 % Verifying: [-> ] 8 % Verifying: [--> ] 10 % Verifying: [--> ] 11 % Verifying: [--> ] 12 % Verifying: [--> ] 14 % Verifying: [---> ] 17 % Verifying: [---> ] 18 % Verifying: [---> ] 19 % Verifying: [----> ] 22 % Verifying: [----> ] 24 % Verifying: [-----> ] 26 % Verifying: [-----> ] 27 % Verifying: [-----> ] 29 % Verifying: [------> ] 31 % Verifying: [------> ] 34 % Verifying: [-------> ] 36 % Verifying: [-------> ] 38 % Verifying: [--------> ] 40 % Verifying: [--------> ] 43 % Verifying: [--------> ] 44 % Verifying: [---------> ] 48 % Verifying: [----------> ] 51 % Verifying: [-----------> ] 55 % Verifying: [-----------> ] 58 % Verifying: [------------> ] 62 % Verifying: [------------> ] 64 % Verifying: [-------------> ] 68 % Verifying: [--------------> ] 71 % Verifying: [--------------> ] 73 % Verifying: [---------------> ] 76 % Verifying: [---------------> ] 79 % Verifying: [----------------> ] 82 % Verifying: [-----------------> ] 86 % Verifying: [------------------> ] 90 % Verifying: [------------------> ] 91 % Verifying: [------------------> ] 94 % Verifying: [-------------------> ] 98 % Verifying: [-------------------->] 100 % Write successful. From 539c6c9abdd9bbc158a2cf9420b276e3e8752e81 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:43:30 +0100 Subject: [PATCH 02/16] feat(installer): find the Raspberry Pi Imager on macOS Look for the imager app in /Applications and the user's Applications folder, read its version from Info.plist, and treat macOS imagers below 2.0.12 as too old. macOS imagers are started directly with --cli, like the Windows one. Co-Authored-By: Claude Sonnet 5.5 --- installer/internal/media/imager.go | 78 ++++++++++++++- installer/internal/media/imager_darwin.go | 32 +++++++ .../internal/media/imager_otherdarwin.go | 8 ++ installer/internal/media/imager_test.go | 94 +++++++++++++++++++ 4 files changed, 210 insertions(+), 2 deletions(-) create mode 100644 installer/internal/media/imager_darwin.go create mode 100644 installer/internal/media/imager_otherdarwin.go diff --git a/installer/internal/media/imager.go b/installer/internal/media/imager.go index fd7e751f..699761c8 100644 --- a/installer/internal/media/imager.go +++ b/installer/internal/media/imager.go @@ -2,6 +2,7 @@ package media import ( "context" + "path" "regexp" "strconv" "strings" @@ -14,6 +15,7 @@ const ( ImagerNative ImagerKind = "native" ImagerFlatpak ImagerKind = "flatpak" ImagerWindows ImagerKind = "windows" + ImagerMac ImagerKind = "macos" ) // FlatpakID is the Flatpak application ID of the Raspberry Pi Imager. @@ -62,8 +64,13 @@ func imagerVersion(ctx context.Context, env Env, name string, args ...string) st return "" } -// TooOld reports whether the imager is older than major version 2, or its version is unknown. +// TooOld reports whether the imager is too old to use, or its version is unknown. +// Outside macOS that means major version below 2. On macOS 2.0.11.1 hangs when it is +// ejected (issue #1748), so 2.0.12 is the minimum there. func (im Imager) TooOld() bool { + if im.Kind == ImagerMac { + return versionLess(im.Version, "2.0.12") + } major, _, _ := strings.Cut(im.Version, ".") n, err := strconv.Atoi(major) if err != nil { @@ -109,7 +116,7 @@ func (im Imager) Command(a WriteArgs) (name string, args []string) { return "flatpak", args } - if im.Kind == ImagerWindows { + if im.Kind == ImagerWindows || im.Kind == ImagerMac { args = []string{"--cli"} args = append(args, flags...) args = append(args, a.Image, a.Drive) @@ -157,6 +164,73 @@ func FindWindowsImager(env WinEnv) (im Imager, ok bool) { return Imager{}, false } +// MacEnv wraps the macOS system calls so tests can replace them. +type MacEnv struct { + Home string + Exists func(string) bool + PlistVersion func(plist string) (string, error) +} + +// FindMacImager returns the first installed Raspberry Pi Imager app, looking in /Applications +// and then in the user's Applications folder. An empty Home skips the user folder. The version +// comes from the app's Info.plist, without a leading "v". ok is false if no app exists. +func FindMacImager(env MacEnv) (im Imager, ok bool) { + apps := []string{"/Applications/Raspberry Pi Imager.app"} + if env.Home != "" { + apps = append(apps, path.Join(env.Home, "Applications", "Raspberry Pi Imager.app")) + } + for _, app := range apps { + if !env.Exists(app) { + continue + } + version, err := env.PlistVersion(path.Join(app, "Contents", "Info.plist")) + if err != nil { + version = "" + } + version = strings.TrimPrefix(strings.TrimSpace(version), "v") + return Imager{Kind: ImagerMac, Path: path.Join(app, "Contents", "MacOS", "rpi-imager"), Version: version}, true + } + return Imager{}, false +} + +// versionLess reports whether version a is lower than b. Versions compare number by number, +// and missing numbers count as 0. An empty or non-numeric version is lower than any valid one. +func versionLess(a, b string) bool { + pa, okA := parseVersion(a) + pb, okB := parseVersion(b) + if !okA || !okB { + return !okA && okB + } + for i := 0; i < len(pa) || i < len(pb); i++ { + var x, y int + if i < len(pa) { + x = pa[i] + } + if i < len(pb) { + y = pb[i] + } + if x != y { + return x < y + } + } + return false +} + +// parseVersion splits a dotted version into numbers. ok is false if it is empty or has a non-numeric part. +func parseVersion(v string) (parts []int, ok bool) { + if v == "" { + return nil, false + } + for _, s := range strings.Split(v, ".") { + n, err := strconv.Atoi(s) + if err != nil { + return nil, false + } + parts = append(parts, n) + } + return parts, true +} + // trimVersion cuts a four part file version such as "2.0.12.0" to "2.0.12". func trimVersion(version string) string { parts := strings.Split(version, ".") diff --git a/installer/internal/media/imager_darwin.go b/installer/internal/media/imager_darwin.go new file mode 100644 index 00000000..9cb73498 --- /dev/null +++ b/installer/internal/media/imager_darwin.go @@ -0,0 +1,32 @@ +//go:build darwin + +package media + +import ( + "context" + "os" + "os/exec" + "time" +) + +// LocateMacImager finds the installed Raspberry Pi Imager on macOS. It reads the version from +// Info.plist and never starts the imager. +func LocateMacImager() (Imager, bool) { + home, _ := os.UserHomeDir() + return FindMacImager(MacEnv{ + Home: home, + Exists: fileExists, + PlistVersion: plistVersion, + }) +} + +// plistVersion returns the CFBundleShortVersionString of an Info.plist. +func plistVersion(plist string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, "plutil", "-extract", "CFBundleShortVersionString", "raw", "-o", "-", plist).Output() + if err != nil { + return "", err + } + return string(out), nil +} diff --git a/installer/internal/media/imager_otherdarwin.go b/installer/internal/media/imager_otherdarwin.go new file mode 100644 index 00000000..b6f99c33 --- /dev/null +++ b/installer/internal/media/imager_otherdarwin.go @@ -0,0 +1,8 @@ +//go:build !darwin + +package media + +// LocateMacImager reports no imager outside macOS. +func LocateMacImager() (Imager, bool) { + return Imager{}, false +} diff --git a/installer/internal/media/imager_test.go b/installer/internal/media/imager_test.go index 43969acb..f6b56c0c 100644 --- a/installer/internal/media/imager_test.go +++ b/installer/internal/media/imager_test.go @@ -238,3 +238,97 @@ func TestFindWindowsImagerNotInstalled(t *testing.T) { t.Fatal("expected ok == false") } } + +func TestVersionLess(t *testing.T) { + cases := []struct { + a, b string + want bool + }{ + {"2.0.11.1", "2.0.12", true}, + {"2.0.12", "2.0.12", false}, + {"2.1", "2.0.12", false}, + {"", "2.0", true}, + } + for _, c := range cases { + if got := versionLess(c.a, c.b); got != c.want { + t.Errorf("versionLess(%q, %q) = %v, want %v", c.a, c.b, got, c.want) + } + } +} + +func TestMacImagerBelow2012IsTooOld(t *testing.T) { + if !(Imager{Kind: ImagerMac, Version: "2.0.11.1"}).TooOld() { + t.Error("2.0.11.1 must be too old on macOS") + } + if (Imager{Kind: ImagerMac, Version: "2.0.12"}).TooOld() { + t.Error("2.0.12 must not be too old on macOS") + } +} + +func TestLinuxImager20IsNotTooOld(t *testing.T) { + if (Imager{Kind: ImagerNative, Version: "2.0.0"}).TooOld() { + t.Error("2.0.0 on Linux must not be too old") + } +} + +// macEnv answers the macOS lookups from fixed tables. +func macEnv(home string, existing []string, version string, versionErr error) MacEnv { + exists := map[string]bool{} + for _, p := range existing { + exists[p] = true + } + return MacEnv{ + Home: home, + Exists: func(path string) bool { return exists[path] }, + PlistVersion: func(string) (string, error) { + return version, versionErr + }, + } +} + +func TestFindMacImagerPrefersApplications(t *testing.T) { + env := macEnv("/Users/simon", []string{ + "/Applications/Raspberry Pi Imager.app", + "/Users/simon/Applications/Raspberry Pi Imager.app", + }, "2.0.12", nil) + im, ok := FindMacImager(env) + if !ok { + t.Fatal("imager not found") + } + want := Imager{Kind: ImagerMac, Path: "/Applications/Raspberry Pi Imager.app/Contents/MacOS/rpi-imager", Version: "2.0.12"} + if im != want { + t.Fatalf("got %+v, want %+v", im, want) + } +} + +func TestFindMacImagerStripsTheLeadingV(t *testing.T) { + env := macEnv("/Users/simon", []string{ + "/Applications/Raspberry Pi Imager.app", + }, "v2.0.12", nil) + im, ok := FindMacImager(env) + if !ok { + t.Fatal("imager not found") + } + if im.Version != "2.0.12" || im.TooOld() { + t.Fatalf("got %+v, want version 2.0.12 that is not too old", im) + } +} + +func TestFindMacImagerFallsBackToHomeApplications(t *testing.T) { + env := macEnv("/Users/simon", []string{ + "/Users/simon/Applications/Raspberry Pi Imager.app", + }, "2.0.12", nil) + im, ok := FindMacImager(env) + if !ok { + t.Fatal("imager not found") + } + if im.Path != "/Users/simon/Applications/Raspberry Pi Imager.app/Contents/MacOS/rpi-imager" { + t.Fatalf("Path = %q", im.Path) + } +} + +func TestFindMacImagerNotInstalled(t *testing.T) { + if _, ok := FindMacImager(macEnv("/Users/simon", nil, "", nil)); ok { + t.Fatal("expected ok == false") + } +} From 2dde9096d75c0bad5a31082159de33c67d9134b4 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:45:10 +0100 Subject: [PATCH 03/16] feat(installer): write media on macOS with the imager's own authorization The imager asks for the device right itself when the user cannot open the drive. The job now keeps the rights step active while that dialog is open, closes it once the device is opened, and reports a refused dialog as MEDIA_RIGHTS_DENIED. macOS gets its own host file with the Homebrew link. Co-Authored-By: Claude Sonnet 5.5 --- installer/internal/host/media_darwin.go | 31 +++++++++ installer/internal/host/media_other.go | 2 +- installer/internal/media/job.go | 28 ++++++-- installer/internal/media/job_test.go | 79 +++++++++++++++++++++++ installer/internal/media/progress.go | 12 ++++ installer/internal/media/progress_test.go | 26 ++++++++ 6 files changed, 170 insertions(+), 8 deletions(-) create mode 100644 installer/internal/host/media_darwin.go diff --git a/installer/internal/host/media_darwin.go b/installer/internal/host/media_darwin.go new file mode 100644 index 00000000..37a47704 --- /dev/null +++ b/installer/internal/host/media_darwin.go @@ -0,0 +1,31 @@ +//go:build darwin + +package host + +import ( + "context" + + "github.com/Developer-Simon/energy-node-installer/internal/media" + "github.com/Developer-Simon/energy-node-webui/hostapi" +) + +// mediaBrewCommand installiert den Imager ueber Homebrew. +const mediaBrewCommand = "brew install --cask raspberry-pi-imager" + +// mediaPlatform meldet, dass dieser Rechner Medien vorbereiten kann. +func mediaPlatform() (supported bool, links []hostapi.MediaLink) { + return true, []hostapi.MediaLink{ + {Kind: "website", URL: mediaWebsiteURL}, + {Kind: "brew", Command: mediaBrewCommand}, + } +} + +var mediaRunner media.Runner = execRunner + +// mediaEject ist nil: der Imager wirft das Medium selbst aus. +var mediaEject func(context.Context, media.Drive) error + +// locateImager sucht den installierten Imager im Programme-Ordner. +func locateImager(ctx context.Context) (media.Imager, bool) { + return media.LocateMacImager() +} diff --git a/installer/internal/host/media_other.go b/installer/internal/host/media_other.go index cfaff4be..2307862c 100644 --- a/installer/internal/host/media_other.go +++ b/installer/internal/host/media_other.go @@ -1,4 +1,4 @@ -//go:build !linux && !windows +//go:build !linux && !windows && !darwin package host diff --git a/installer/internal/media/job.go b/installer/internal/media/job.go index 946ea04d..fd5e0bd9 100644 --- a/installer/internal/media/job.go +++ b/installer/internal/media/job.go @@ -446,12 +446,14 @@ type jobRun struct { p *plan active StepID // step that is currently active, "" if none - hk HostKey - phase Phase // last write or verify phase seen - sawDone bool - errMsg string - errPhase Phase - samples []rateSample + hk HostKey + authorizing bool // macOS fragt nach dem Recht, Vorbereitungszeilen schliessen Adminrechte nicht + denied bool // macOS-Dialog abgelehnt + phase Phase // last write or verify phase seen + sawDone bool + errMsg string + errPhase Phase + samples []rateSample } type rateSample struct { @@ -673,6 +675,9 @@ func (r *jobRun) runImager(a WriteArgs) (JobState, *JobError) { if perr != nil { return r.fail(codeWriteFailed, perr.Error()) } + if r.denied { + return r.fail(codeRightsDenied, "") + } if r.errMsg != "" { code := codeWriteFailed if r.errPhase == PhaseVerify { @@ -724,10 +729,19 @@ func (r *jobRun) eject() { func (r *jobRun) onProgress(p Progress) { switch p.Phase { case PhasePrepare: - if r.active == StepRights { + if r.active == StepRights && !r.authorizing { r.done(StepRights) } + case PhaseAuthorizing: + r.authorizing = true + r.move(StepRights) + case PhaseAuthorized: + r.authorizing = false + r.done(StepRights) + case PhaseDenied: + r.denied = true case PhaseWrite: + r.authorizing = false r.phase = PhaseWrite if r.active != StepWrite { r.move(StepWrite) diff --git a/installer/internal/media/job_test.go b/installer/internal/media/job_test.go index dc14df96..c6d099bc 100644 --- a/installer/internal/media/job_test.go +++ b/installer/internal/media/job_test.go @@ -807,3 +807,82 @@ func TestAFailedJobEjectsNothing(t *testing.T) { t.Fatal("ejected after a failed write") } } + +// scriptedOut liefert die Ausgabe Zeile fuer Zeile. Vor jeder Zeile ruft hook den Index auf, +// der Scanner liest die naechste Zeile erst, wenn die vorige verarbeitet ist. +type scriptedOut struct { + lines []string + i int + hook func(i int) +} + +func (s *scriptedOut) Read(p []byte) (int, error) { + if s.i >= len(s.lines) { + return 0, io.EOF + } + if s.hook != nil { + s.hook(s.i) + } + n := copy(p, s.lines[s.i]) + s.i++ + return n, nil +} + +func stepState(v JobView, id StepID) StepState { + for _, s := range v.Steps { + if s.ID == id { + return s.State + } + } + return "" +} + +func TestRunImagerMapsMacDenialToRightsDenied(t *testing.T) { + // Nicht aufgezeichnet: die Ausgabe ist aus dem Quellcode (macfile.cpp) gebaut. + out := " Unmounting drive...Opening macOS device: /dev/rdisk7\n" + + "Device path detected, using macOS authorization...\n" + + "Authorization cancelled by user\n" + + "Error: Error opening disk device\n" + fr := &fakeRun{out: out, code: 1} + w := newTestWriter(t, []Drive{sdb}, fr) + if err := w.Start(context.Background(), okWrite); err != nil { + t.Fatal(err) + } + v := waitJob(t, w) + if v.State != JobFailed || v.Error == nil || v.Error.Code != codeRightsDenied { + t.Fatalf("state = %s, error = %+v, want %s", v.State, v.Error, codeRightsDenied) + } +} + +func TestRunImagerKeepsRightsStepWhileMacAsks(t *testing.T) { + lines := []string{ + " Unmounting drive...Opening macOS device: /dev/rdisk7\n", + "Device path detected, using macOS authorization...\n", + " Opening drive...Device max write transfer: 2097152 bytes\n", + "Successfully opened device, fd=11 (direct I/O enabled)\n", + " Writing: [> ] 0 %\n", + "Write successful.\n", + } + var seen []StepState + w := newTestWriter(t, []Drive{sdb}, &fakeRun{}) + // Vor Zeile 2 ist der Dialog offen, vor Zeile 4 ist er beantwortet. + w.Run = func(context.Context, string, ...string) (io.ReadCloser, func() (int, error), error) { + out := &scriptedOut{lines: lines} + out.hook = func(i int) { + if i == 2 || i == 4 { + seen = append(seen, stepState(w.View(), StepRights)) + } + } + return io.NopCloser(out), func() (int, error) { return 0, nil }, nil + } + if err := w.Start(context.Background(), okWrite); err != nil { + t.Fatal(err) + } + v := waitJob(t, w) + if v.State != JobDone { + t.Fatalf("state = %s, error = %+v, want done", v.State, v.Error) + } + if len(seen) != 2 || seen[0] != StepActive || seen[1] != StepDone { + t.Fatalf("rights step while the dialog was open and after it = %v, want [active done]", seen) + } +} diff --git a/installer/internal/media/progress.go b/installer/internal/media/progress.go index 8f79745f..24493add 100644 --- a/installer/internal/media/progress.go +++ b/installer/internal/media/progress.go @@ -18,6 +18,10 @@ const ( PhaseVerify Phase = "verify" PhaseDone Phase = "done" PhaseError Phase = "error" + // macOS: der Imager wartet auf das Recht, dann auf die Antwort des Dialogs. + PhaseAuthorizing Phase = "authorizing" + PhaseAuthorized Phase = "authorized" + PhaseDenied Phase = "denied" ) // Progress is one event read from the imager output. @@ -130,6 +134,14 @@ func parseImagerLine(raw string) (Progress, bool) { return Progress{Phase: PhaseError, Message: strings.TrimSpace(rest)}, true } } + switch { + case strings.HasPrefix(line, "Device path detected, using macOS authorization"): + return Progress{Phase: PhaseAuthorizing}, true + case strings.HasPrefix(line, "Successfully opened device"): + return Progress{Phase: PhaseAuthorized}, true + case strings.HasPrefix(line, "Authorization cancelled by user"): + return Progress{Phase: PhaseDenied}, true + } for _, prefix := range imagerIgnored { if strings.HasPrefix(line, prefix) { return Progress{}, false diff --git a/installer/internal/media/progress_test.go b/installer/internal/media/progress_test.go index b6a92436..7cf96859 100644 --- a/installer/internal/media/progress_test.go +++ b/installer/internal/media/progress_test.go @@ -95,3 +95,29 @@ func TestParseImagerOutputCutsALongError(t *testing.T) { t.Errorf("length = %d, want %d", n, maxErrorMessage) } } + +func TestParseImagerOutputMacRecording(t *testing.T) { + counts := map[Phase]int{} + for _, p := range parseFile(t, "testdata/imager-mac-ok.txt") { + counts[p.Phase]++ + } + if counts[PhaseAuthorizing] != 1 || counts[PhaseAuthorized] != 1 || counts[PhaseWrite] == 0 || counts[PhaseVerify] == 0 || counts[PhaseDone] != 1 || counts[PhaseError] != 0 { + t.Fatalf("phase counts = %v, want one authorizing, one authorized, write, verify, exactly one done and no error", counts) + } +} + +func TestParseImagerOutputMacDenied(t *testing.T) { + // Nicht aufgezeichnet: die Zeilen sind aus dem Quellcode (macfile.cpp) gebaut. + out := "Device path detected, using macOS authorization...\nAuthorization cancelled by user\n" + var got []Progress + if err := ParseImagerOutput(strings.NewReader(out), func(p Progress) { got = append(got, p) }); err != nil { + t.Fatal(err) + } + counts := map[Phase]int{} + for _, p := range got { + counts[p.Phase]++ + } + if counts[PhaseDenied] != 1 || counts[PhaseError] != 0 { + t.Fatalf("got %+v, want exactly one denied and no error", got) + } +} From 7ac1ea0cf417553b27468b940dd18549e9fd6da1 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:45:34 +0100 Subject: [PATCH 04/16] test(installer): feed the macOS imager lines with their carriage returns Co-Authored-By: Claude Sonnet 5.5 --- installer/internal/media/job_test.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/installer/internal/media/job_test.go b/installer/internal/media/job_test.go index c6d099bc..cfa668e9 100644 --- a/installer/internal/media/job_test.go +++ b/installer/internal/media/job_test.go @@ -839,7 +839,8 @@ func stepState(v JobView, id StepID) StepState { func TestRunImagerMapsMacDenialToRightsDenied(t *testing.T) { // Nicht aufgezeichnet: die Ausgabe ist aus dem Quellcode (macfile.cpp) gebaut. - out := " Unmounting drive...Opening macOS device: /dev/rdisk7\n" + + out := " Unmounting drive...\r" + + "Opening macOS device: /dev/rdisk7\n" + "Device path detected, using macOS authorization...\n" + "Authorization cancelled by user\n" + "Error: Error opening disk device\n" @@ -856,9 +857,9 @@ func TestRunImagerMapsMacDenialToRightsDenied(t *testing.T) { func TestRunImagerKeepsRightsStepWhileMacAsks(t *testing.T) { lines := []string{ - " Unmounting drive...Opening macOS device: /dev/rdisk7\n", + " Unmounting drive...\rOpening macOS device: /dev/rdisk7\n", "Device path detected, using macOS authorization...\n", - " Opening drive...Device max write transfer: 2097152 bytes\n", + " Opening drive...\rDevice max write transfer: 2097152 bytes\n", "Successfully opened device, fd=11 (direct I/O enabled)\n", " Writing: [> ] 0 %\n", "Write successful.\n", From c76d1ae2a7b6296ed4ac2c78c8bf19328bed5a49 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:47:41 +0100 Subject: [PATCH 05/16] feat(installer): list macOS drives for the media mode Parse diskutil output and hide the system disk: the parent disk of /, the whole disks of its APFS physical stores and its container. Disk images count as internal, fail closed without a root parent. Co-Authored-By: Claude Sonnet 5.5 --- installer/internal/media/drives_darwin.go | 66 +++++ .../internal/media/drives_darwinparse.go | 260 ++++++++++++++++++ .../internal/media/drives_darwinparse_test.go | 189 +++++++++++++ installer/internal/media/drives_other.go | 2 +- 4 files changed, 516 insertions(+), 1 deletion(-) create mode 100644 installer/internal/media/drives_darwin.go create mode 100644 installer/internal/media/drives_darwinparse.go create mode 100644 installer/internal/media/drives_darwinparse_test.go diff --git a/installer/internal/media/drives_darwin.go b/installer/internal/media/drives_darwin.go new file mode 100644 index 00000000..1d66d145 --- /dev/null +++ b/installer/internal/media/drives_darwin.go @@ -0,0 +1,66 @@ +//go:build darwin + +package media + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os/exec" + "strings" +) + +// ListDrives fragt diskutil nach den Platten. diskutil liefert plist, plutil +// macht daraus JSON fuer ParseDiskutil. +func ListDrives(ctx context.Context) ([]Drive, error) { + physical, err := diskutilJSON(ctx, "list", "-plist", "physical") + if err != nil { + return nil, err + } + all, err := diskutilJSON(ctx, "list", "-plist") + if err != nil { + return nil, err + } + root, err := diskutilJSON(ctx, "info", "-plist", "/") + if err != nil { + return nil, err + } + list, err := mergeContainers(physical, all) + if err != nil { + return nil, err + } + var doc dutilList + if err := json.Unmarshal(physical, &doc); err != nil { + return nil, fmt.Errorf("media: diskutil physical list: %w", err) + } + infos := make(map[string][]byte, len(doc.WholeDisks)) + for _, id := range doc.WholeDisks { + if err := ctx.Err(); err != nil { + return nil, err + } + // Eine fehlgeschlagene Info laesst diese Platte weg. + info, err := diskutilJSON(ctx, "info", "-plist", id) + if err != nil { + continue + } + infos[id] = info + } + return ParseDiskutil(list, infos, root) +} + +// diskutilJSON fuehrt diskutil mit den Argumenten aus und wandelt die plist-Ausgabe +// per plutil in JSON um. +func diskutilJSON(ctx context.Context, args ...string) ([]byte, error) { + plist, err := exec.CommandContext(ctx, "diskutil", args...).Output() + if err != nil { + return nil, fmt.Errorf("media: diskutil %s: %w", strings.Join(args, " "), err) + } + cmd := exec.CommandContext(ctx, "plutil", "-convert", "json", "-o", "-", "-") + cmd.Stdin = bytes.NewReader(plist) + out, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("media: plutil: %w", err) + } + return out, nil +} diff --git a/installer/internal/media/drives_darwinparse.go b/installer/internal/media/drives_darwinparse.go new file mode 100644 index 00000000..52559007 --- /dev/null +++ b/installer/internal/media/drives_darwinparse.go @@ -0,0 +1,260 @@ +package media + +import ( + "encoding/json" + "errors" + "fmt" + "regexp" + "strings" +) + +// dutilList ist der Teil von "diskutil list -plist" als JSON, den die Auswertung braucht. +type dutilList struct { + WholeDisks []string `json:"WholeDisks"` + AllDisksAndPartitions []dutilDisk `json:"AllDisksAndPartitions"` +} + +type dutilDisk struct { + DeviceIdentifier string `json:"DeviceIdentifier"` + Size int64 `json:"Size"` + Content string `json:"Content"` + APFSPhysicalStores []dutilStore `json:"APFSPhysicalStores"` + APFSVolumes []dutilVolume `json:"APFSVolumes"` + Partitions []dutilVolume `json:"Partitions"` +} + +type dutilStore struct { + DeviceIdentifier string `json:"DeviceIdentifier"` +} + +type dutilVolume struct { + DeviceIdentifier string `json:"DeviceIdentifier"` + VolumeName string `json:"VolumeName"` + Content string `json:"Content"` + Size int64 `json:"Size"` +} + +// dutilInfo ist der Teil von "diskutil info -plist" als JSON. +type dutilInfo struct { + ParentWholeDisk string `json:"ParentWholeDisk"` + APFSContainerReference string `json:"APFSContainerReference"` + APFSPhysicalStores []dutilInfoStore `json:"APFSPhysicalStores"` + Internal *bool `json:"Internal"` + RemovableMedia bool `json:"RemovableMedia"` + Removable bool `json:"Removable"` + BusProtocol string `json:"BusProtocol"` + MediaName string `json:"MediaName"` + IORegistryEntryName string `json:"IORegistryEntryName"` + Size int64 `json:"Size"` + TotalSize int64 `json:"TotalSize"` +} + +type dutilInfoStore struct { + APFSPhysicalStore string `json:"APFSPhysicalStore"` +} + +var diskutilWholeRE = regexp.MustCompile(`^(disk\d+)`) + +// diskutilWholeDisk liefert die ganze Platte zu einer Kennung wie disk0s2 (-> disk0). +func diskutilWholeDisk(id string) (string, error) { + m := diskutilWholeRE.FindStringSubmatch(id) + if m == nil { + return "", fmt.Errorf("media: diskutil: unbekannte Kennung %q", id) + } + return m[1], nil +} + +// mergeContainers haengt die APFS-Container aus "diskutil list -plist" an die +// Liste der physischen Platten. Die Liste "physical" kennt keine Container. +func mergeContainers(physical, all []byte) ([]byte, error) { + var p, a dutilList + if err := json.Unmarshal(physical, &p); err != nil { + return nil, fmt.Errorf("media: diskutil physical list: %w", err) + } + if err := json.Unmarshal(all, &a); err != nil { + return nil, fmt.Errorf("media: diskutil list: %w", err) + } + seen := make(map[string]bool, len(p.AllDisksAndPartitions)) + for _, d := range p.AllDisksAndPartitions { + seen[d.DeviceIdentifier] = true + } + for _, d := range a.AllDisksAndPartitions { + if len(d.APFSPhysicalStores) == 0 || seen[d.DeviceIdentifier] { + continue + } + seen[d.DeviceIdentifier] = true + p.AllDisksAndPartitions = append(p.AllDisksAndPartitions, d) + } + return json.Marshal(p) +} + +// ParseDiskutil liefert die Laufwerke ohne das Systemlaufwerk. list ist +// "diskutil list -plist physical" mit den Containern aus mergeContainers, +// infos enthaelt "diskutil info -plist" je Platte, root die Ausgabe fuer "/". +// Fail closed: ohne ParentWholeDisk oder ohne gefundenen physischen Speicher +// des Containers ist das ein Fehler. Platten ohne lesbare Info fallen weg. +func ParseDiskutil(list []byte, infos map[string][]byte, root []byte) ([]Drive, error) { + var l dutilList + if err := json.Unmarshal(list, &l); err != nil { + return nil, fmt.Errorf("media: diskutil list: %w", err) + } + var r dutilInfo + if err := json.Unmarshal(root, &r); err != nil { + return nil, fmt.Errorf("media: diskutil root info: %w", err) + } + if r.ParentWholeDisk == "" { + return nil, errors.New("media: diskutil root info: ParentWholeDisk fehlt") + } + entries := make(map[string]dutilDisk, len(l.AllDisksAndPartitions)) + for _, d := range l.AllDisksAndPartitions { + entries[d.DeviceIdentifier] = d + } + + hidden, err := diskutilSystemDisks(r, entries) + if err != nil { + return nil, err + } + + volumes, err := diskutilContainerVolumes(l.AllDisksAndPartitions) + if err != nil { + return nil, err + } + + drives := make([]Drive, 0, len(l.WholeDisks)) + for _, id := range l.WholeDisks { + if hidden[id] { + continue + } + entry, inList := entries[id] + if inList && len(entry.APFSPhysicalStores) > 0 { + continue + } + raw, ok := infos[id] + if !ok { + continue + } + var info dutilInfo + if err := json.Unmarshal(raw, &info); err != nil { + continue + } + size := info.TotalSize + if size == 0 { + size = info.Size + } + if size <= 0 { + continue + } + parts := make([]Partition, 0, len(entry.Partitions)+len(volumes[id])) + for _, p := range entry.Partitions { + parts = append(parts, Partition{Name: p.DeviceIdentifier, Label: p.VolumeName, FSType: p.Content}) + } + parts = append(parts, volumes[id]...) + drives = append(drives, info.drive(id, size, parts)) + } + return drives, nil +} + +// diskutilSystemDisks sammelt die Platten des Systems: die Eltern-Platte von /, +// die ganzen Platten der Speicher des Containers von / und der Container selbst. +// Speicher auf synthetischen Containern werden rekursiv aufgeloest. +func diskutilSystemDisks(root dutilInfo, entries map[string]dutilDisk) (map[string]bool, error) { + hidden := make(map[string]bool) + queue := []string{root.ParentWholeDisk} + if root.APFSContainerReference != "" { + queue = append(queue, root.APFSContainerReference) + } + for _, s := range root.APFSPhysicalStores { + queue = append(queue, s.APFSPhysicalStore) + } + for len(queue) > 0 { + id := queue[0] + queue = queue[1:] + whole, err := diskutilWholeDisk(id) + if err != nil { + return nil, err + } + if hidden[whole] { + continue + } + hidden[whole] = true + if e, ok := entries[whole]; ok { + for _, s := range e.APFSPhysicalStores { + queue = append(queue, s.DeviceIdentifier) + } + } + } + if root.APFSContainerReference != "" && len(root.APFSPhysicalStores) == 0 { + if e, ok := entries[root.APFSContainerReference]; !ok || len(e.APFSPhysicalStores) == 0 { + return nil, errors.New("media: diskutil: kein physischer Speicher fuer den Systemcontainer gefunden") + } + } + return hidden, nil +} + +// diskutilContainerVolumes liefert die APFS-Volumes je Platte, auf der ein +// Speicher des Containers liegt. +func diskutilContainerVolumes(disks []dutilDisk) (map[string][]Partition, error) { + out := make(map[string][]Partition) + for _, c := range disks { + if len(c.APFSPhysicalStores) == 0 { + continue + } + seen := make(map[string]bool) + for _, s := range c.APFSPhysicalStores { + whole, err := diskutilWholeDisk(s.DeviceIdentifier) + if err != nil { + return nil, err + } + if seen[whole] { + continue + } + seen[whole] = true + for _, v := range c.APFSVolumes { + out[whole] = append(out[whole], Partition{Name: v.DeviceIdentifier, Label: v.VolumeName, FSType: "apfs"}) + } + } + } + return out, nil +} + +func (i dutilInfo) drive(id string, size int64, parts []Partition) Drive { + model := strings.TrimSpace(i.MediaName) + if model == "" { + model = strings.TrimSpace(i.IORegistryEntryName) + } + if model == "" { + model = id + } + return Drive{ + Path: "/dev/" + id, + Model: model, + Size: size, + Transport: diskutilTransport(i.BusProtocol), + Removable: diskutilRemovable(i), + Partitions: parts, + } +} + +func diskutilTransport(bus string) string { + switch bus { + case "USB": + return "usb" + case "Secure Digital": + return "mmc" + case "SATA": + return "sata" + case "PCI-Express", "Apple Fabric": + return "nvme" + case "Disk Image": + return "image" + } + return strings.ToLower(bus) +} + +// diskutilRemovable: Disk-Images gelten als intern, auch wenn sie Wechselmedium melden. +func diskutilRemovable(i dutilInfo) bool { + if i.BusProtocol == "Disk Image" { + return false + } + return i.RemovableMedia || i.Removable || (i.Internal != nil && !*i.Internal) +} diff --git a/installer/internal/media/drives_darwinparse_test.go b/installer/internal/media/drives_darwinparse_test.go new file mode 100644 index 00000000..5dad8698 --- /dev/null +++ b/installer/internal/media/drives_darwinparse_test.go @@ -0,0 +1,189 @@ +package media + +import ( + "encoding/json" + "os" + "strings" + "testing" +) + +// Die Listeneintraege fuer USB-Stick und externe APFS-Platte sind von Hand nach +// dem Muster der aufgezeichneten Ausgaben gebaut, weil es dafuer keinen Mitschnitt gibt. +// Die Infos dazu (info-usb.json, info-external-apfs.json) sind ebenfalls handgebaut. +const darwinDisk0Entry = `{"DeviceIdentifier":"disk0","Size":348966092800,"Content":"GUID_partition_scheme","Partitions":[{"DeviceIdentifier":"disk0s1","Content":"Apple_APFS_ISC","Size":524288000},{"DeviceIdentifier":"disk0s2","Content":"Apple_APFS","Size":343073095680},{"DeviceIdentifier":"disk0s3","Content":"Apple_APFS_Recovery","Size":5368668672}]}` + +const darwinUsbEntry = `{"DeviceIdentifier":"disk4","Size":32010928128,"Content":"FDisk_partition_scheme","Partitions":[{"DeviceIdentifier":"disk4s1","Content":"Windows_FAT_32","VolumeName":"STICK","Size":32000000000}]}` + +const darwinRamDiskEntry = `{"DeviceIdentifier":"disk7","Size":134217728,"Content":"","Partitions":[]}` + +const darwinExternalDiskEntry = `{"DeviceIdentifier":"disk5","Size":1000204886016,"Content":"GUID_partition_scheme","Partitions":[{"DeviceIdentifier":"disk5s2","Content":"Apple_APFS","Size":999000000000}]}` + +const darwinExternalContainerEntry = `{"DeviceIdentifier":"disk6","Size":999000000000,"Content":"Apple_APFS_Container","APFSPhysicalStores":[{"DeviceIdentifier":"disk5s2"}],"APFSVolumes":[{"DeviceIdentifier":"disk6s1","VolumeName":"Daten","Size":500000000000}],"Partitions":[]}` + +func readDarwinFixture(t *testing.T, name string) []byte { + t.Helper() + data, err := os.ReadFile("testdata/darwin/" + name) + if err != nil { + t.Fatal(err) + } + return data +} + +// darwinList baut eine "diskutil list"-Ausgabe aus den Eintraegen. +func darwinList(whole []string, entries ...string) []byte { + return []byte(`{"WholeDisks":["` + strings.Join(whole, `","`) + `"],"AllDisksAndPartitions":[` + strings.Join(entries, ",") + `]}`) +} + +func mustParseDiskutil(t *testing.T, list []byte, infos map[string][]byte, root []byte) []Drive { + t.Helper() + drives, err := ParseDiskutil(list, infos, root) + if err != nil { + t.Fatalf("ParseDiskutil: %v", err) + } + return drives +} + +func TestDiskutilHidesThePhysicalStoreOfRoot(t *testing.T) { + list := darwinList([]string{"disk0", "disk4"}, darwinDisk0Entry, darwinUsbEntry) + infos := map[string][]byte{ + "disk0": readDarwinFixture(t, "info-disk0.json"), + "disk4": readDarwinFixture(t, "info-usb.json"), + } + drives := mustParseDiskutil(t, list, infos, readDarwinFixture(t, "info-root.json")) + if got := drivePaths(drives); !equalStrings(got, []string{"/dev/disk4"}) { + t.Fatalf("got %v, want [/dev/disk4]", got) + } +} + +func TestDiskutilRamDiskIsInternal(t *testing.T) { + list := darwinList([]string{"disk7"}, darwinRamDiskEntry) + infos := map[string][]byte{"disk7": readDarwinFixture(t, "info-ramdisk.json")} + drives := mustParseDiskutil(t, list, infos, readDarwinFixture(t, "info-root.json")) + if len(drives) != 1 { + t.Fatalf("got %d drives, want 1: %v", len(drives), drivePaths(drives)) + } + d := drives[0] + if d.Removable { + t.Errorf("RAM disk is removable, want internal") + } + if d.Transport != "image" { + t.Errorf("Transport = %q, want image", d.Transport) + } +} + +func TestDiskutilUsbStickIsRemovable(t *testing.T) { + list := darwinList([]string{"disk4"}, darwinUsbEntry) + infos := map[string][]byte{"disk4": readDarwinFixture(t, "info-usb.json")} + drives := mustParseDiskutil(t, list, infos, readDarwinFixture(t, "info-root.json")) + if len(drives) != 1 { + t.Fatalf("got %d drives, want 1: %v", len(drives), drivePaths(drives)) + } + d := drives[0] + if !d.Removable || d.Transport != "usb" { + t.Errorf("Removable = %v, Transport = %q, want true and usb", d.Removable, d.Transport) + } + if d.Model != "SanDisk Ultra" { + t.Errorf("Model = %q, want SanDisk Ultra", d.Model) + } + if len(d.Partitions) != 1 || d.Partitions[0].Label != "STICK" { + t.Errorf("Partitions = %+v, want one partition labelled STICK", d.Partitions) + } +} + +func TestDiskutilExternalApfsDiskIsRemovable(t *testing.T) { + list := darwinList([]string{"disk5"}, darwinExternalDiskEntry, darwinExternalContainerEntry) + infos := map[string][]byte{"disk5": readDarwinFixture(t, "info-external-apfs.json")} + drives := mustParseDiskutil(t, list, infos, readDarwinFixture(t, "info-root.json")) + if len(drives) != 1 { + t.Fatalf("got %d drives, want 1: %v", len(drives), drivePaths(drives)) + } + d := drives[0] + if !d.Removable { + t.Errorf("external APFS disk is not removable") + } + found := false + for _, p := range d.Partitions { + if p.Label == "Daten" { + found = true + } + } + if !found { + t.Errorf("Partitions = %+v, want the container volume Daten", d.Partitions) + } +} + +func TestDiskutilDiskWithoutInfoIsHidden(t *testing.T) { + list := darwinList([]string{"disk4", "disk5"}, darwinUsbEntry, darwinExternalDiskEntry) + infos := map[string][]byte{"disk4": readDarwinFixture(t, "info-usb.json")} + drives := mustParseDiskutil(t, list, infos, readDarwinFixture(t, "info-root.json")) + if got := drivePaths(drives); !equalStrings(got, []string{"/dev/disk4"}) { + t.Fatalf("got %v, want [/dev/disk4]", got) + } +} + +func TestDiskutilRecordedRunner(t *testing.T) { + list := readDarwinFixture(t, "list-physical.json") + infos := map[string][]byte{"disk0": readDarwinFixture(t, "info-disk0.json")} + drives := mustParseDiskutil(t, list, infos, readDarwinFixture(t, "info-root.json")) + if len(drives) != 0 { + t.Fatalf("got %v, want no drives", drivePaths(drives)) + } +} + +func TestDiskutilFailsWithoutRootParent(t *testing.T) { + list := darwinList([]string{"disk4"}, darwinUsbEntry) + infos := map[string][]byte{"disk4": readDarwinFixture(t, "info-usb.json")} + root := []byte(`{"APFSContainerReference":"","Internal":true}`) + if _, err := ParseDiskutil(list, infos, root); err == nil { + t.Fatal("ParseDiskutil without ParentWholeDisk: want error") + } +} + +func TestDiskutilFailsWithoutPhysicalStore(t *testing.T) { + list := darwinList([]string{"disk4"}, darwinUsbEntry) + infos := map[string][]byte{"disk4": readDarwinFixture(t, "info-usb.json")} + root := []byte(`{"ParentWholeDisk":"disk2","APFSContainerReference":"disk2","Internal":true}`) + if _, err := ParseDiskutil(list, infos, root); err == nil { + t.Fatal("ParseDiskutil without any physical store: want error") + } +} + +func TestDiskutilMissingInternalIsNotRemovable(t *testing.T) { + entry := `{"DeviceIdentifier":"disk4","Size":8000000000,"Content":"","Partitions":[]}` + info := []byte(`{"ParentWholeDisk":"disk4","MediaName":"Test Disk","TotalSize":8000000000,"BusProtocol":"SATA","Removable":false,"RemovableMedia":false}`) + list := darwinList([]string{"disk4"}, entry) + drives := mustParseDiskutil(t, list, map[string][]byte{"disk4": info}, readDarwinFixture(t, "info-root.json")) + if len(drives) != 1 { + t.Fatalf("got %d drives, want 1: %v", len(drives), drivePaths(drives)) + } + if drives[0].Removable { + t.Errorf("disk without Internal key is removable, want internal") + } +} + +func TestMergeContainersAddsOnlyApfsContainers(t *testing.T) { + physical := readDarwinFixture(t, "list-physical.json") + all := darwinList([]string{"disk0"}, + darwinDisk0Entry, + darwinExternalContainerEntry, + darwinRamDiskEntry, + ) + merged, err := mergeContainers(physical, all) + if err != nil { + t.Fatalf("mergeContainers: %v", err) + } + var doc dutilList + if err := json.Unmarshal(merged, &doc); err != nil { + t.Fatal(err) + } + var ids []string + for _, e := range doc.AllDisksAndPartitions { + ids = append(ids, e.DeviceIdentifier) + } + if !equalStrings(ids, []string{"disk0", "disk6"}) { + t.Fatalf("merged entries = %v, want [disk0 disk6]", ids) + } + if !equalStrings(doc.WholeDisks, []string{"disk0"}) { + t.Fatalf("WholeDisks = %v, want [disk0]", doc.WholeDisks) + } +} diff --git a/installer/internal/media/drives_other.go b/installer/internal/media/drives_other.go index 144e2a16..13f7e41c 100644 --- a/installer/internal/media/drives_other.go +++ b/installer/internal/media/drives_other.go @@ -1,4 +1,4 @@ -//go:build !linux && !windows +//go:build !linux && !windows && !darwin package media From 5864fd92fbe382d06b243f1816c953c30a1cdba0 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:48:49 +0100 Subject: [PATCH 06/16] feat(installer): take timezone, keyboard and country from macOS Co-Authored-By: Claude Sonnet 5.5 --- installer/internal/media/defaults_darwin.go | 38 +++++++++++++++++++ installer/internal/media/defaults_linux.go | 14 ------- installer/internal/media/defaults_other.go | 2 +- installer/internal/media/defaults_unix.go | 22 +++++++++++ installer/internal/media/keyboard_mac.go | 26 +++++++++++++ installer/internal/media/keyboard_mac_test.go | 17 +++++++++ 6 files changed, 104 insertions(+), 15 deletions(-) create mode 100644 installer/internal/media/defaults_darwin.go create mode 100644 installer/internal/media/defaults_unix.go create mode 100644 installer/internal/media/keyboard_mac.go create mode 100644 installer/internal/media/keyboard_mac_test.go diff --git a/installer/internal/media/defaults_darwin.go b/installer/internal/media/defaults_darwin.go new file mode 100644 index 00000000..a340acf1 --- /dev/null +++ b/installer/internal/media/defaults_darwin.go @@ -0,0 +1,38 @@ +//go:build darwin + +package media + +import ( + "context" + "os/exec" + "strings" + "time" +) + +// HostDefaults reads time zone, keyboard and country from macOS. Missing values +// fall back to UTC, us and an empty country. WLAN fields stay empty. +func HostDefaults() Defaults { + d := Defaults{Timezone: "UTC", Keyboard: "us"} + if tz := localTimezone(); tz != "" { + d.Timezone = tz + } + d.Timezones, d.ZoneCountries = embeddedZones() + if kb := keyboardFromMacLayout(defaultsRead("com.apple.HIToolbox", "AppleCurrentKeyboardLayoutInputSourceID")); kb != "" { + d.Keyboard = kb + } + d.Keyboards = keyboardChoices(d.Keyboard) + d.WifiCountry = countryFromLocale(defaultsRead("-g", "AppleLocale")) + return d +} + +// defaultsRead runs `defaults read` with the given arguments and returns the +// trimmed output, or "" on error or after two seconds. +func defaultsRead(args ...string) string { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, "defaults", append([]string{"read"}, args...)...).Output() + if err != nil { + return "" + } + return strings.TrimSpace(string(out)) +} diff --git a/installer/internal/media/defaults_linux.go b/installer/internal/media/defaults_linux.go index 1177699f..e5cfadd8 100644 --- a/installer/internal/media/defaults_linux.go +++ b/installer/internal/media/defaults_linux.go @@ -119,20 +119,6 @@ func unescapeTerse(s string) string { return b.String() } -// localTimezone returns the zone named by the /etc/localtime symlink, or "". -func localTimezone() string { - target, err := os.Readlink("/etc/localtime") - if err != nil { - return "" - } - const marker = "zoneinfo/" - i := strings.Index(target, marker) - if i < 0 { - return "" - } - return target[i+len(marker):] -} - // timezoneList returns the sorted zone names from zone1970.tab plus UTC, or the embedded table. func timezoneList() []string { data, err := os.ReadFile(zone1970Path) diff --git a/installer/internal/media/defaults_other.go b/installer/internal/media/defaults_other.go index 5ee3bfb5..5c440557 100644 --- a/installer/internal/media/defaults_other.go +++ b/installer/internal/media/defaults_other.go @@ -1,4 +1,4 @@ -//go:build !linux && !windows +//go:build !linux && !windows && !darwin package media diff --git a/installer/internal/media/defaults_unix.go b/installer/internal/media/defaults_unix.go new file mode 100644 index 00000000..bb0bf965 --- /dev/null +++ b/installer/internal/media/defaults_unix.go @@ -0,0 +1,22 @@ +//go:build linux || darwin + +package media + +import ( + "os" + "strings" +) + +// localTimezone returns the zone named by the /etc/localtime symlink, or "". +func localTimezone() string { + target, err := os.Readlink("/etc/localtime") + if err != nil { + return "" + } + const marker = "zoneinfo/" + i := strings.Index(target, marker) + if i < 0 { + return "" + } + return target[i+len(marker):] +} diff --git a/installer/internal/media/keyboard_mac.go b/installer/internal/media/keyboard_mac.go new file mode 100644 index 00000000..d69b0791 --- /dev/null +++ b/installer/internal/media/keyboard_mac.go @@ -0,0 +1,26 @@ +package media + +import "strings" + +// macLayoutPrefix steht vor jeder macOS-Tastaturbelegung, z.B. com.apple.keylayout.German. +const macLayoutPrefix = "com.apple.keylayout." + +// macLayouts ordnet die Namen der macOS-Tastaturbelegungen dem Layout der Form zu. +var macLayouts = map[string]string{ + "German": "de", "US": "us", "ABC": "us", "British": "gb", "British-PC": "gb", + "French": "fr", "French-PC": "fr", "Swiss German": "ch", "Swiss French": "ch", + "Italian": "it", "Italian-Pro": "it", "Spanish": "es", "Spanish-ISO": "es", + "Dutch": "nl", "Swedish": "se", "Swedish-Pro": "se", "Danish": "dk", + "Norwegian": "no", "Finnish": "fi", "Polish": "pl", "Polish Pro": "pl", + "Czech": "cz", "Czech-QWERTY": "cz", +} + +// keyboardFromMacLayout returns the layout of a macOS input source ID such as +// "com.apple.keylayout.German", or "" for unknown and non-layout sources. +func keyboardFromMacLayout(id string) string { + name, ok := strings.CutPrefix(strings.TrimSpace(id), macLayoutPrefix) + if !ok { + return "" + } + return macLayouts[name] +} diff --git a/installer/internal/media/keyboard_mac_test.go b/installer/internal/media/keyboard_mac_test.go new file mode 100644 index 00000000..40271118 --- /dev/null +++ b/installer/internal/media/keyboard_mac_test.go @@ -0,0 +1,17 @@ +package media + +import "testing" + +func TestKeyboardFromMacLayout(t *testing.T) { + cases := map[string]string{ + "com.apple.keylayout.German": "de", + "com.apple.keylayout.Swiss German": "ch", + "com.apple.keylayout.Colemak": "", + "com.apple.inputmethod.Kotoeri": "", + } + for in, want := range cases { + if got := keyboardFromMacLayout(in); got != want { + t.Errorf("keyboardFromMacLayout(%q) = %q, want %q", in, got, want) + } + } +} From 6f270aa11fc9ef95c4afedd614dc1e0e1f7fbf69 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:49:16 +0100 Subject: [PATCH 07/16] feat(installer): add the macOS texts of the media mode Co-Authored-By: Claude Sonnet 5.5 --- installer/webui/catalogs/de.json | 6 +++++- installer/webui/catalogs/en.json | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/installer/webui/catalogs/de.json b/installer/webui/catalogs/de.json index 3b0bf4ca..ef16fbf4 100644 --- a/installer/webui/catalogs/de.json +++ b/installer/webui/catalogs/de.json @@ -666,15 +666,18 @@ "media.group.debian": "Andere Hardware (Debian)", "media.group.pi": "Raspberry Pi", "media.imager.missing.text": "Der Installer beschreibt die SD-Karte mit dem Raspberry Pi Imager ab Version 2.0. Installiere ihn über Discover oder von der Webseite und prüfe dann erneut.", + "media.imager.missing.text.darwin": "Der Installer beschreibt Speicherkarten und USB-Sticks mit dem Raspberry Pi Imager ab Version 2.0.12. Lade ihn von der Webseite oder installiere ihn mit Homebrew und prüfe dann erneut.", "media.imager.missing.text.windows": "Der Installer beschreibt Speicherkarten und USB-Sticks mit dem Raspberry Pi Imager ab Version 2.0. Lade ihn von der Webseite oder installiere ihn mit winget und prüfe dann erneut.", "media.imager.missing.title": "Der Raspberry Pi Imager fehlt", "media.imager.old.text": "Nötig ist Version 2.0 oder neuer. Aktualisiere ihn über Discover oder von der Webseite und prüfe dann erneut.", + "media.imager.old.text.darwin": "Nötig ist Version 2.0.12 oder neuer. Aktualisiere ihn von der Webseite oder mit Homebrew und prüfe dann erneut.", "media.imager.old.text.windows": "Nötig ist Version 2.0 oder neuer. Aktualisiere ihn von der Webseite oder mit winget und prüfe dann erneut.", "media.imager.old.title": "Der Raspberry Pi Imager ist zu alt", "media.layout.boot": "Boot", "media.layout.pi": "Die Systempartition wächst beim ersten Start auf die ganze SD-Karte.", "media.layout.system": "System", "media.layout.title": "So wird die SD-Karte aufgeteilt", + "media.link.brew": "Mit Homebrew installieren", "media.link.copied": "Kopiert", "media.link.copy": "Befehl kopieren", "media.link.discover": "In Discover öffnen", @@ -701,6 +704,7 @@ "media.result.download": "Wird geladen", "media.result.offline": "Die Liste der Images ist nicht erreichbar. Prüfe die Internetverbindung.", "media.result.package": "Paket {arch}", + "media.rights.darwin": "macOS fragt gleich nach dem Passwort eines Administrators, damit der Imager schreiben darf.", "media.rights.windows": "Windows fragt gleich nach Administratorrechten, damit der Imager schreiben darf.", "media.settings.arm_serial": "ARM-Geräte zeigen die Installation oft nur über eine serielle Konsole und auf Englisch.", "media.settings.ask_erase": "Vor dem Löschen nachfragen", @@ -745,7 +749,7 @@ "media.step.write": "Schreiben", "media.tag.experimental": "experimentell", "media.tag.unsupported": "nicht unterstützt", - "media.unsupported.text": "Das Vorbereiten eines Mediums funktioniert vorerst unter Linux und Windows. macOS folgt. Die Anleitung beschreibt, wie sich eine SD-Karte von Hand vorbereiten lässt.", + "media.unsupported.text": "Das Vorbereiten eines Mediums funktioniert unter Linux, Windows und macOS. Die Anleitung beschreibt, wie sich eine SD-Karte von Hand vorbereiten lässt.", "media.unsupported.title": "Auf diesem System noch nicht verfügbar", "media.warn.confirm_card": "Ich habe verstanden, dass die SD-Karte gelöscht wird.", "media.warn.confirm_debian": "Ich habe verstanden, dass der Stick beschrieben und die interne Platte des Zielgeräts gelöscht wird.", diff --git a/installer/webui/catalogs/en.json b/installer/webui/catalogs/en.json index e7ec0245..c7ad7ed2 100644 --- a/installer/webui/catalogs/en.json +++ b/installer/webui/catalogs/en.json @@ -666,15 +666,18 @@ "media.group.debian": "Generic", "media.group.pi": "Raspberry Pi", "media.imager.missing.text": "The installer writes the card with the Raspberry Pi Imager 2.0 or newer. Install it from Discover or from the website, then check again.", + "media.imager.missing.text.darwin": "The installer writes memory cards and USB sticks with Raspberry Pi Imager 2.0.12 or newer. Download it from the website or install it with Homebrew, then check again.", "media.imager.missing.text.windows": "The installer writes memory cards and USB sticks with Raspberry Pi Imager 2.0 or newer. Download it from the website or install it with winget, then check again.", "media.imager.missing.title": "The Raspberry Pi Imager is missing", "media.imager.old.text": "Version 2.0 or newer is needed. Update it from Discover or from the website, then check again.", + "media.imager.old.text.darwin": "Version 2.0.12 or newer is needed. Update it from the website or with Homebrew, then check again.", "media.imager.old.text.windows": "Version 2.0 or newer is needed. Update it from the website or with winget, then check again.", "media.imager.old.title": "The Raspberry Pi Imager is too old", "media.layout.boot": "Boot", "media.layout.pi": "The system partition grows to the whole card on first start.", "media.layout.system": "System", "media.layout.title": "How the card is divided", + "media.link.brew": "Install with Homebrew", "media.link.copied": "Copied", "media.link.copy": "Copy command", "media.link.discover": "Open in Discover", @@ -701,6 +704,7 @@ "media.result.download": "Will be downloaded", "media.result.offline": "The list of images cannot be reached. Check the internet connection.", "media.result.package": "Package {arch}", + "media.rights.darwin": "macOS will ask for an administrator password so the imager can write.", "media.rights.windows": "Windows will ask for administrator rights so the imager can write.", "media.settings.arm_serial": "ARM devices often show the installation only on a serial console, and in English.", "media.settings.ask_erase": "Ask before erasing", @@ -745,7 +749,7 @@ "media.step.write": "Write", "media.tag.experimental": "experimental", "media.tag.unsupported": "not supported", - "media.unsupported.text": "Preparing a medium works on Linux and Windows for now. macOS follows. The guide describes how to prepare a card by hand.", + "media.unsupported.text": "Preparing a medium works on Linux, Windows and macOS. The guide describes how to prepare a card by hand.", "media.unsupported.title": "Not available on this system yet", "media.warn.confirm_card": "I understand that the card will be erased.", "media.warn.confirm_debian": "I understand that the stick will be written and the internal disk of the target device erased.", From 1141119e7e5b94d93351a423968f1d19444a0745 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:52:21 +0100 Subject: [PATCH 08/16] feat(installer): show the macOS install paths for the imager The media screens show the Homebrew command on macOS, the rights hint for the write step and no network scan on step 2 when macOS reports no networks. The fake host gets a darwin platform for the e2e test. Co-Authored-By: Claude Sonnet 5.5 --- installer/webui/cmd/fakehost/main.go | 6 +- installer/webui/cmd/fakehost/scenario.go | 2 +- installer/webui/hostapi/hostapitest/fake.go | 3 +- .../webui/hostapi/hostapitest/fake_media.go | 29 +++++++-- installer/webui/static/js/screen-media.js | 16 +++-- installer/webui/templates/screen-media.html | 4 +- installer/webui/test/e2e/media.spec.mjs | 11 ++++ installer/webui/test/screen-media.test.mjs | 64 +++++++++++++++++++ 8 files changed, 119 insertions(+), 16 deletions(-) diff --git a/installer/webui/cmd/fakehost/main.go b/installer/webui/cmd/fakehost/main.go index 39a96e8a..81978c6f 100644 --- a/installer/webui/cmd/fakehost/main.go +++ b/installer/webui/cmd/fakehost/main.go @@ -51,11 +51,11 @@ func main() { deltaFails := flag.Bool("delta-verify-fails", false, "die Teilübertragung besteht die Prüfung nicht: Vorbereiten scheitert, bis das ganze Paket neu übertragen wird") packageOffline := flag.String("package-offline", "", "diese Pakete lassen sich nicht herunterladen, Format caddy[,tailscale]: Vorbereiten fragt, bis je Paket geantwortet ist") diagnoseDelay := flag.Duration("diagnose-delay", 0, "Pause zwischen den Abschnitten der Diagnose im Strom, apt wartet das Achtfache (0: die Diagnose kommt auf einmal)") - mediaPlatform := flag.String("media-platform", "", "Plattform des Mediums: windows (Webseite und winget-Befehl) oder leer fuer Linux") + mediaPlatform := flag.String("media-platform", "", "Plattform des Mediums: windows (Webseite und winget-Befehl), darwin (Webseite und Homebrew-Befehl) oder leer fuer Linux") mediaImagerMissing := flag.Bool("media-imager-missing", false, "kein Raspberry Pi Imager gefunden: die Fehlerkarte erscheint") flag.Parse() - if *mediaPlatform != "" && *mediaPlatform != "windows" { - log.Fatalf("-media-platform: %q ist unbekannt, erlaubt sind windows oder leer", *mediaPlatform) + if *mediaPlatform != "" && *mediaPlatform != "windows" && *mediaPlatform != "darwin" { + log.Fatalf("-media-platform: %q ist unbekannt, erlaubt sind windows, darwin oder leer", *mediaPlatform) } // Den Updater gibt es nur im Dashboard: das Szenario bringt den Wirt mit. if *scenario == "updater" { diff --git a/installer/webui/cmd/fakehost/scenario.go b/installer/webui/cmd/fakehost/scenario.go index 97a6fc83..f204d9e1 100644 --- a/installer/webui/cmd/fakehost/scenario.go +++ b/installer/webui/cmd/fakehost/scenario.go @@ -20,7 +20,7 @@ const fingerprint = "SHA256:xK9v+Lm2Qd8pR4tN1wZa7YcB3fH6jE0sU5gV2nP8kQo" type options struct { dashboard bool - // mediaPlatform: die Plattform des Mediums, "windows" oder leer (Linux). + // mediaPlatform: die Plattform des Mediums, "windows", "darwin" oder leer (Linux). mediaPlatform string // mediaImagerMissing: kein Raspberry Pi Imager gefunden. mediaImagerMissing bool diff --git a/installer/webui/hostapi/hostapitest/fake.go b/installer/webui/hostapi/hostapitest/fake.go index 9bf3e42f..d92ed72c 100644 --- a/installer/webui/hostapi/hostapitest/fake.go +++ b/installer/webui/hostapi/hostapitest/fake.go @@ -110,7 +110,8 @@ type FakeBackend struct { // steuern die unexportierten Felder (siehe fake_media.go). MediaStatusView hostapi.MediaStatus // MediaPlatform waehlt die Plattform des Status: "windows" liefert die - // Links von Windows, leer oder "linux" die Vorgabe aus MediaStatusView. + // Links von Windows, "darwin" die von macOS (ohne WLAN-Netze), leer oder + // "linux" die Vorgabe aus MediaStatusView. MediaPlatform string MediaCatalogView hostapi.MediaCatalog MediaDriveList []hostapi.MediaDrive diff --git a/installer/webui/hostapi/hostapitest/fake_media.go b/installer/webui/hostapi/hostapitest/fake_media.go index 215dd903..10bc8735 100644 --- a/installer/webui/hostapi/hostapitest/fake_media.go +++ b/installer/webui/hostapi/hostapitest/fake_media.go @@ -191,26 +191,42 @@ func mediaDriveFixture() []hostapi.MediaDrive { } // MediaStatus liefert die Vorgaben der Attrappe. Mit MediaPlatform "windows" -// stehen Webseite und winget-Befehl in den Links, wie auf dem echten Host. +// stehen Webseite und winget-Befehl in den Links, mit "darwin" Webseite und +// Homebrew-Befehl, wie auf dem echten Host. func (f *FakeBackend) MediaStatus(ctx context.Context) (hostapi.MediaStatus, error) { f.mu.Lock() defer f.mu.Unlock() status := f.MediaStatusView - if f.MediaPlatform == "windows" { + switch f.MediaPlatform { + case "windows": status.Platform = "windows" status.Links = []hostapi.MediaLink{ {Kind: "website", URL: "https://www.raspberrypi.com/software/"}, {Kind: "winget", Command: "winget install -e --id RaspberryPiFoundation.RaspberryPiImager"}, } + case "darwin": + status.Platform = "darwin" + status.Links = []hostapi.MediaLink{ + {Kind: "website", URL: "https://www.raspberrypi.com/software/"}, + {Kind: "brew", Command: "brew install --cask raspberry-pi-imager"}, + } } return status, nil } -// MediaCatalog liefert die Geraeteliste der Attrappe. +// MediaCatalog liefert die Geraeteliste der Attrappe. Unter macOS hat der +// Rechner keine Netze in Reichweite und keine Vorgabe fuer WLAN; die Vorgaben +// der Attrappe bleiben unangetastet. func (f *FakeBackend) MediaCatalog(ctx context.Context) (hostapi.MediaCatalog, error) { f.mu.Lock() defer f.mu.Unlock() - return f.MediaCatalogView, nil + catalog := f.MediaCatalogView + if f.MediaPlatform == "darwin" { + catalog.Defaults.WifiNetworks = nil + catalog.Defaults.WifiSSID = "" + catalog.Defaults.WifiFreqMHz = 0 + } + return catalog, nil } // MediaDrives liefert ohne internal nur Wechselmedien. @@ -259,10 +275,13 @@ func (f *FakeBackend) MediaCheckWifi(ctx context.Context, req hostapi.MediaWifiC } // MediaWifiNetworks liefert die Netze des Katalogs und dazu eines, das erst -// der neue Suchlauf findet. +// der neue Suchlauf findet. Unter macOS gibt es keine Netze. func (f *FakeBackend) MediaWifiNetworks(ctx context.Context) ([]hostapi.MediaWifiNetwork, error) { f.mu.Lock() defer f.mu.Unlock() + if f.MediaPlatform == "darwin" { + return []hostapi.MediaWifiNetwork{}, nil + } nets := append([]hostapi.MediaWifiNetwork{}, f.MediaCatalogView.Defaults.WifiNetworks...) return append(nets, hostapi.MediaWifiNetwork{SSID: "Garten", Signal: 20, Band24: true}), nil } diff --git a/installer/webui/static/js/screen-media.js b/installer/webui/static/js/screen-media.js index aaa5129d..b09079a6 100644 --- a/installer/webui/static/js/screen-media.js +++ b/installer/webui/static/js/screen-media.js @@ -226,6 +226,12 @@ return this.group === 'debian'; }, + // noNetworkScan: auf macOS ohne Netzliste gibt es keinen Suchlauf und keine + // Passwortpruefung. Nur Name und Passwort bleiben. + get noNetworkScan() { + return this.shell.shared.mediaPlatform === 'darwin' && !(this.defaults.wifi_networks || []).length; + }, + // showEraseWarning: ohne Rueckfrage warnt der Bildschirm in Warnfarbe. get showEraseWarning() { return this.isDebian && !this.form.askBeforeErase; @@ -311,7 +317,9 @@ } // Die Netze in Reichweite brauchen einen Suchlauf von einigen // Sekunden. Der Bildschirm wartet nicht darauf. - this.loadNetworks(); + if (!this.noNetworkScan) { + this.loadNetworks(); + } await this.checkName(); }, @@ -481,7 +489,7 @@ // nur das Ergebnis. Eine Antwort zu alten Eingaben wird verworfen. async checkWifi() { var seq = ++this.wifiSeq; - if (!this.form.wifiOn || !this.form.ssid || !this.form.wifiPassword) { + if (this.noNetworkScan || !this.form.wifiOn || !this.form.ssid || !this.form.wifiPassword) { this.wifiState = ''; this.wifiVia = ''; return; @@ -862,9 +870,9 @@ return this.running && !!(this.job && this.job.cancelling); }, - // rightsNote: der Hinweis auf die Abfrage von Windows, solange sie noch kommt oder offen ist. + // rightsNote: der Hinweis auf die Abfrage von Windows oder macOS, solange sie noch kommt oder offen ist. rightsNote(row) { - return row.id === 'rights' && this.platform === 'windows' && (row.state === 'pending' || row.state === 'active'); + return row.id === 'rights' && (this.platform === 'windows' || this.platform === 'darwin') && (row.state === 'pending' || row.state === 'active'); }, // track: merkt sich, wann sich Schritt und Prozent zuletzt geaendert haben. diff --git a/installer/webui/templates/screen-media.html b/installer/webui/templates/screen-media.html index b2f7900a..b55c28ef 100644 --- a/installer/webui/templates/screen-media.html +++ b/installer/webui/templates/screen-media.html @@ -291,7 +291,7 @@

aria-labelledby="media-country" autocomplete="off" spellcheck="false"> -
+ @@ -468,7 +468,7 @@

- + diff --git a/installer/webui/test/e2e/media.spec.mjs b/installer/webui/test/e2e/media.spec.mjs index ca5b5a1b..ac0352fd 100644 --- a/installer/webui/test/e2e/media.spec.mjs +++ b/installer/webui/test/e2e/media.spec.mjs @@ -171,3 +171,14 @@ test('windows ohne Imager zeigt Webseite und den winget-Befehl, auf 390 px ohne assertNoOverflow(await layoutAt(page), 'media-device (Windows ohne Imager)'); await context.close(); })); + +test('darwin ohne Imager zeigt Webseite und den Homebrew-Befehl, auf 390 px ohne Scroll', () => withHost(['--media-platform', 'darwin', '--media-imager-missing'], async (host) => { + const { page, context } = await openPage(browser, host.url); + await page.setViewportSize({ width: 390, height: 800 }); + await page.locator('.mode-i', { hasText: 'Medium' }).click(); + await page.locator('.app[data-screen="media-device"] .media-notice').waitFor(); + const command = (await page.locator('.media-cmd').textContent()).trim(); + assert.equal(command, 'brew install --cask raspberry-pi-imager'); + assertNoOverflow(await layoutAt(page), 'media-device (macOS ohne Imager)'); + await context.close(); +})); diff --git a/installer/webui/test/screen-media.test.mjs b/installer/webui/test/screen-media.test.mjs index 19a44a4f..f4bc3c21 100644 --- a/installer/webui/test/screen-media.test.mjs +++ b/installer/webui/test/screen-media.test.mjs @@ -1206,3 +1206,67 @@ test('ein kleines Medium bekommt beim Pi einen Hinweis und bleibt waehlbar', asy screen.group = 'debian'; assert.equal(screen.tightForSetup, false); }); + +const BREW = 'brew install --cask raspberry-pi-imager'; +const DARWIN_MISSING = Object.assign({}, STATUS, { + platform: 'darwin', + imager: { found: false, kind: '', version: '', too_old: false }, + links: [{ kind: 'website', url: 'https://www.raspberrypi.com/software/' }, { kind: 'brew', command: BREW }], +}); + +test('darwin missing card shows website and brew command', async () => { + const { screen, shell } = device({ 'GET /api/media/status': DARWIN_MISSING }); + await screen.init(); + + assert.equal(screen.state, 'missing'); + assert.equal(shell.shared.mediaPlatform, 'darwin'); + assert.deepEqual(screen.links.map((link) => link.kind), ['website', 'brew']); + assert.equal(screen.links[1].command, BREW); + assert.equal(screen.imagerTextKey, 'media.imager.missing.text.darwin'); +}); + +test('darwin rights hint', async (t) => { + const { screen, shell } = writer(); + t.after(() => screen.destroy()); + shell.shared.mediaPlatform = 'darwin'; + await screen.init(); + assert.equal(screen.rightsNote({ id: 'rights', state: 'active' }), true); + assert.equal(screen.rightsNote({ id: 'rights', state: 'done' }), false); + shell.shared.mediaPlatform = 'linux'; + assert.equal(screen.rightsNote({ id: 'rights', state: 'active' }), false); + + const note = guardOf(mediaTemplate(), '.media-step-note'); + assert.equal(note.getAttribute('x-if'), 'rightsNote(row)'); + assert.equal(note.content.querySelector('.media-step-note').getAttribute('x-text'), "t('media.rights.' + platform)"); + assert.ok(realCatalog('de')['media.rights.darwin'], 'der Text fuer macOS ist im Katalog'); +}); + +// Ein Pi-Lauf auf macOS, der Schritt 2 mit leerer WLAN-Liste oeffnet. +function darwinSettings(platform, responses = {}) { + return settings(responses, { + shell: { shared: { media: { device: 'pi4', settings: null, drive: null, confirm: '' }, mediaPlatform: platform } }, + }); +} + +test('darwin step 2 shows no networks in range', async () => { + const { screen, calls } = darwinSettings('darwin'); + await screen.init(); + + assert.equal(calls.filter((call) => call.key === 'GET /api/media/wifi-networks').length, 0, 'kein Suchlauf'); + assert.equal(screen.scanning, false); + assert.deepEqual(plain(screen.rows), []); + assert.equal(screen.showInput, true, 'nur das Namensfeld bleibt'); + assert.equal(screen.noNetworkScan, true); + + screen.form.wifiOn = true; + screen.form.ssid = 'Werkstatt'; + screen.form.wifiPassword = 'egal-1234'; + await screen.checkWifi(); + assert.equal(calls.filter((call) => call.key === 'POST /api/media/wifi-check').length, 0, 'keine Passwortpruefung'); + assert.equal(screen.wifiState, ''); + + const linux = darwinSettings('linux'); + await linux.screen.init(); + assert.equal(linux.calls.filter((call) => call.key === 'GET /api/media/wifi-networks').length, 1, 'Linux sucht weiter'); + assert.equal(linux.screen.noNetworkScan, false); +}); From 97eb68b01d4e2805b82a99a04d938f76f2809afe Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:52:55 +0100 Subject: [PATCH 09/16] fix(installer): keep the Wi-Fi password hint on macOS Co-Authored-By: Claude Sonnet 5.5 --- installer/webui/templates/screen-media.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/installer/webui/templates/screen-media.html b/installer/webui/templates/screen-media.html index b55c28ef..5bdc0fb5 100644 --- a/installer/webui/templates/screen-media.html +++ b/installer/webui/templates/screen-media.html @@ -291,7 +291,7 @@

aria-labelledby="media-country" autocomplete="off" spellcheck="false"> - +
From f1eb28ccae35395280eb69479bc486f862a7ca4f Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:54:45 +0100 Subject: [PATCH 10/16] ci: check the media mode on a macOS runner with a RAM disk Adds the workflow that runs the media mode end to end on macos-latest: the imager writes a 64 MiB test image to a RAM disk, the written bytes are compared, and a 1 GiB write is cancelled at its first write. The test is build-tagged darwin and mediae2e and skips without EN_MAC_RAMDISK. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/installer-macos-media.yml | 82 +++++++ .../internal/host/media_darwin_e2e_test.go | 206 ++++++++++++++++++ 2 files changed, 288 insertions(+) create mode 100644 .github/workflows/installer-macos-media.yml create mode 100644 installer/internal/host/media_darwin_e2e_test.go diff --git a/.github/workflows/installer-macos-media.yml b/.github/workflows/installer-macos-media.yml new file mode 100644 index 00000000..a843e5b0 --- /dev/null +++ b/.github/workflows/installer-macos-media.yml @@ -0,0 +1,82 @@ +name: Installer media (macOS) + +# Abnahme der Medien-Vorbereitung auf macOS. Laeuft auf einem Wegwerf-Runner +# mit RAM-Disk. Nicht Teil von ci-ok, der Lauf kostet macOS-Minuten. + +on: + workflow_dispatch: + pull_request: + paths: + - installer/internal/media/** + - installer/internal/host/** + - .github/workflows/installer-macos-media.yml + push: + branches: + - feat/installer-media-macos + paths: + - installer/internal/media/** + - installer/internal/host/** + - .github/workflows/installer-macos-media.yml + +permissions: + contents: read + +jobs: + media-macos: + name: Installer media end to end (macOS) + runs-on: macos-latest + timeout-minutes: 30 + defaults: + run: + shell: bash + working-directory: installer + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: installer/go.mod + - name: Install the Raspberry Pi Imager + run: brew install --cask raspberry-pi-imager + - name: Unit tests of the media mode + run: go test ./internal/media/... ./internal/host/... ./cmd/installer/... + - name: Create the RAM disk + run: | + dev=$(hdiutil attach -nomount ram://2500000 | awk '{print $1}') + if ! [[ "$dev" =~ ^/dev/disk[0-9]+$ ]]; then + echo "::error::keine RAM-Disk: '$dev'" + exit 1 + fi + echo "EN_MAC_RAMDISK=$dev" >> "$GITHUB_ENV" + - name: Give the RAM disk the node layout of a stick + run: | + dev="$EN_MAC_RAMDISK" + if ! [[ "$dev" =~ ^/dev/disk[0-9]+$ ]]; then + echo "::error::ungueltiges Geraet: '$dev'" + exit 1 + fi + sudo chown root:operator "$dev" "/dev/r${dev#/dev/}" + sudo chmod 640 "$dev" "/dev/r${dev#/dev/}" + - name: Allow the imager to open the RAM disk + run: | + dev="$EN_MAC_RAMDISK" + if ! [[ "$dev" =~ ^/dev/disk[0-9]+$ ]]; then + echo "::error::ungueltiges Geraet: '$dev'" + exit 1 + fi + sudo security authorizationdb write "sys.openfile.readwrite./dev/r${dev#/dev/}" allow + - name: End-to-end test on the RAM disk + run: go test -tags mediae2e ./internal/host -run TestMacMediaEndToEnd -v + - name: Remove the right + if: always() + run: | + dev="${EN_MAC_RAMDISK:-}" + if [[ "$dev" =~ ^/dev/disk[0-9]+$ ]]; then + sudo security authorizationdb remove "sys.openfile.readwrite./dev/r${dev#/dev/}" || true + fi + - name: Detach the RAM disk + if: always() + run: | + dev="${EN_MAC_RAMDISK:-}" + if [[ "$dev" =~ ^/dev/disk[0-9]+$ ]]; then + hdiutil detach "$dev" -force || true + fi diff --git a/installer/internal/host/media_darwin_e2e_test.go b/installer/internal/host/media_darwin_e2e_test.go new file mode 100644 index 00000000..bd7bc34f --- /dev/null +++ b/installer/internal/host/media_darwin_e2e_test.go @@ -0,0 +1,206 @@ +//go:build darwin && mediae2e + +package host + +import ( + "bufio" + "bytes" + "context" + "crypto/rand" + "encoding/json" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-installer/internal/media" +) + +// Der Test laeuft nur auf dem macOS-Wegwerf-Runner des Workflows +// installer-macos-media.yml. EN_MAC_RAMDISK zeigt auf eine RAM-Disk +// (Disk-Image), auf die der Imager schreibt. Auf jedem anderen Rechner +// wird der Test uebersprungen. +var macRAMDiskRE = regexp.MustCompile(`^/dev/disk[0-9]+$`) + +// macDiskInfo liest "diskutil info -plist " als JSON-Objekt. +func macDiskInfo(ctx context.Context, target string) (map[string]any, error) { + plist, err := exec.CommandContext(ctx, "diskutil", "info", "-plist", target).Output() + if err != nil { + return nil, fmt.Errorf("diskutil info %s: %w", target, err) + } + cmd := exec.CommandContext(ctx, "plutil", "-convert", "json", "-o", "-", "-") + cmd.Stdin = bytes.NewReader(plist) + out, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("plutil: %w", err) + } + var info map[string]any + if err := json.Unmarshal(out, &info); err != nil { + return nil, fmt.Errorf("diskutil info %s: %w", target, err) + } + return info, nil +} + +// macWholeDiskRE holt die ganze Platte aus einer Kennung wie disk0s2. +var macWholeDiskRE = regexp.MustCompile(`^(disk[0-9]+)`) + +func TestMacMediaEndToEnd(t *testing.T) { + dev := os.Getenv("EN_MAC_RAMDISK") + if dev == "" { + t.Skip("EN_MAC_RAMDISK ist nicht gesetzt, der Test laeuft nur auf dem macOS-Runner") + } + if !macRAMDiskRE.MatchString(dev) { + t.Fatalf("EN_MAC_RAMDISK = %q, erwartet /dev/diskN", dev) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Minute) + defer cancel() + + // Sicherheitsnetz: nur ein Disk-Image darf beschrieben werden. + ramInfo, err := macDiskInfo(ctx, dev) + if err != nil { + t.Fatal(err) + } + if bus, _ := ramInfo["BusProtocol"].(string); bus != "Disk Image" { + t.Fatalf("%s hat BusProtocol %q, erwartet \"Disk Image\", Abbruch ohne Schreiben", dev, bus) + } + + // (1) Imager finden, Version mindestens 2.0.12. + imager, ok := media.LocateMacImager() + if !ok { + t.Fatal("Raspberry Pi Imager nicht gefunden") + } + t.Logf("Imager %s, Version %s", imager.Path, imager.Version) + if imager.TooOld() { + t.Fatalf("Imager-Version %s ist zu alt, mindestens 2.0.12 noetig", imager.Version) + } + + // (2) Die Liste der Wechselmedien enthaelt weder die RAM-Disk noch eine Systemplatte. + drives, err := media.ListDrives(ctx) + if err != nil { + t.Fatalf("ListDrives: %v", err) + } + for _, d := range media.Visible(drives, true) { + if d.Path == dev { + t.Fatalf("die RAM-Disk %s steht in der Platten-Liste", dev) + } + } + rootInfo, err := macDiskInfo(ctx, "/") + if err != nil { + t.Fatal(err) + } + systemDisks := []string{} + if parent, _ := rootInfo["ParentWholeDisk"].(string); parent != "" { + systemDisks = append(systemDisks, parent) + } + if stores, _ := rootInfo["APFSPhysicalStores"].([]any); stores != nil { + for _, s := range stores { + entry, _ := s.(map[string]any) + id, _ := entry["APFSPhysicalStore"].(string) + if m := macWholeDiskRE.FindStringSubmatch(id); m != nil { + systemDisks = append(systemDisks, m[1]) + } + } + } + if len(systemDisks) == 0 { + t.Fatal("diskutil info / nennt keine Systemplatte") + } + for _, d := range media.Visible(drives, true) { + if slices.Contains(systemDisks, strings.TrimPrefix(d.Path, "/dev/")) { + t.Fatalf("Systemplatte %s steht in der Platten-Liste", d.Path) + } + } + + // (3) Ein 64-MiB-Testimage mit Zufall schreiben. + dir := t.TempDir() + small := filepath.Join(dir, "small.img") + smallData := make([]byte, 64<<20) + if _, err := io.ReadFull(rand.Reader, smallData); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(small, smallData, 0o600); err != nil { + t.Fatal(err) + } + phases, code := runMacImager(ctx, t, imager, small, dev, nil) + for _, want := range []media.Phase{media.PhaseAuthorizing, media.PhaseAuthorized, media.PhaseWrite, media.PhaseDone} { + if !slices.Contains(phases, want) { + t.Fatalf("Phase %q fehlt im Imager-Output, gesehen: %v", want, phases) + } + } + if code != 0 { + t.Fatalf("Imager beendet mit Exitcode %d", code) + } + + // (4) Die RAM-Disk beginnt mit dem Testimage. + got, err := exec.CommandContext(ctx, "sudo", "-n", "dd", "if="+dev, "bs=1048576", "count=64").Output() + if err != nil { + t.Fatalf("dd von %s: %v", dev, err) + } + if !bytes.Equal(got, smallData) { + t.Fatalf("die ersten 64 MiB von %s stimmen nicht mit dem Testimage ueberein", dev) + } + + // (5) Ein 1-GiB-Image wird beim ersten write abgebrochen. + big := filepath.Join(dir, "big.img") + if err := os.WriteFile(big, nil, 0o600); err != nil { + t.Fatal(err) + } + if err := os.Truncate(big, 1<<30); err != nil { + t.Fatal(err) + } + abortCtx, abort := context.WithCancel(ctx) + defer abort() + start := time.Time{} + phases, code = runMacImager(abortCtx, t, imager, big, dev, func(p media.Progress) { + if p.Phase == media.PhaseWrite && start.IsZero() { + start = time.Now() + abort() + } + }) + if start.IsZero() { + t.Fatalf("kein write vor dem Ende des Imagers, gesehen: %v", phases) + } + if code == 0 { + t.Fatal("der abgebrochene Imager meldet Exitcode 0") + } + if took := time.Since(start); took >= 5*time.Second { + t.Fatalf("Abbruch brauchte %s, erwartet unter 5 s", took) + } + if err := exec.CommandContext(ctx, "pgrep", "-x", "rpi-imager").Run(); err == nil { + t.Fatal("nach dem Abbruch laeuft noch ein rpi-imager-Prozess") + } +} + +// runMacImager startet den Imager wie der Installer und liest die Ausgabe. +// onProgress (optional) sieht jedes erkannte Ereignis. Die Ausgabe wird bis +// zum Ende gelesen, bevor der Exitcode steht, damit der erste write ankommt. +func runMacImager(ctx context.Context, t *testing.T, im media.Imager, image, drive string, onProgress func(media.Progress)) ([]media.Phase, int) { + t.Helper() + args := []string{"--cli", "--disable-eject", "--enable-writing-system-drives", image, drive} + out, wait, err := mediaRunner(ctx, im.Path, args...) + if err != nil { + t.Fatalf("Imager starten: %v", err) + } + var phases []media.Phase + err = media.ParseImagerOutput(bufio.NewReader(out), func(p media.Progress) { + if !slices.Contains(phases, p.Phase) { + phases = append(phases, p.Phase) + } + if onProgress != nil { + onProgress(p) + } + }) + if err != nil { + t.Fatalf("Imager-Ausgabe lesen: %v", err) + } + code, err := wait() + if err != nil { + t.Fatalf("Imager warten: %v", err) + } + return phases, code +} From d9d0b34ab71c85aa6dbd1be0908c6fec1067dcba Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:55:49 +0100 Subject: [PATCH 11/16] docs(installer): describe the media mode on macOS Co-Authored-By: Claude Sonnet 5.5 --- docs/installer.md | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/docs/installer.md b/docs/installer.md index 7dfe01d8..1946295b 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -84,8 +84,8 @@ such as a quicker package build for a first try. ## Preparing a storage medium The **Media** tab writes an SD card for a Raspberry Pi so that you do not need a -second tool for the image. The tab works on Linux and Windows. macOS follows. It -needs the Raspberry Pi Imager 2.0 or newer. +second tool for the image. The tab works on Linux, Windows and macOS. It needs +the Raspberry Pi Imager 2.0 or newer. On macOS it needs version 2.0.12 or newer. On Linux that is the Flatpak or a package. If it is missing, the tab links to Discover and to the download page. On Windows the tab links to the download page @@ -95,6 +95,15 @@ command or install the Imager from the page, then use **check again**. The Image setup also installs a USB driver (`rpiboot-winusb`) and may ask you to confirm it. +On macOS the tab links to the download page of the Imager and shows the command +`brew install --cask raspberry-pi-imager` for Homebrew. Run the command or +install the Imager from the page, then use **check again**. The installer does +not accept version 2.0.11.1 on macOS, because that version can hang when the +card is ejected. + +macOS support has so far only been checked by automated tests, not on a real +Mac. + The same tab also builds a USB stick that installs Debian on other hardware, see [Other hardware (Debian)](#other-hardware-debian). @@ -114,12 +123,15 @@ The same tab also builds a USB stick that installs Debian on other hardware, see networks in range or choose **Other network** and type its name. The network this computer is connected to is selected first. On Windows this needs location access for desktop apps. Without it no networks are suggested, you - type the name yourself, and the password check still works. If this computer + type the name yourself, and the password check still works. On macOS no + networks are suggested and the installer does not check the password, so + type the name and the password yourself. If this computer knows the password of that network, or of the same network on the other band, the installer tells you whether yours matches, and otherwise says that it cannot check it. The Wi-Fi password only goes onto the card and the installer does - not store it. The Wi-Fi country follows the time zone. A Raspberry Pi 3B or + not store it. The Wi-Fi country follows the time zone. On macOS the time zone, + the keyboard layout and the Wi-Fi country come from the Mac. A Raspberry Pi 3B or Zero W only reaches 2.4 GHz networks, so the installer warns about a network that only uses 5 GHz and offers the 2.4 GHz network of the same name when there is one. @@ -131,7 +143,10 @@ The same tab also builds a USB stick that installs Debian on other hardware, see card with the Imager and ejects it. The Imager asks for administrator rights through the system's own dialog. On Windows the prompt names the Energy Node installer, because only a small helper started from it runs with those - rights. If you refuse, the job ends without writing. Cancelling takes a few + rights. On macOS the Imager asks for your administrator password. If you + refuse, the job ends without writing. On macOS the Imager then opens the + privacy settings, where you may need to allow access to removable volumes + before you try again. Cancelling takes a few seconds until the Imager has ended, and the card is then incomplete, so write it again. 5. **Done.** Put the card into the Pi, connect it and switch it on. The installer From 9e86f2e612b442addfbfd633f4c3043b58636fad Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:57:02 +0100 Subject: [PATCH 12/16] test(installer): use a neutral home folder in the macOS imager tests Co-Authored-By: Claude Sonnet 5.5 --- installer/internal/media/imager_test.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/installer/internal/media/imager_test.go b/installer/internal/media/imager_test.go index f6b56c0c..126a3e1f 100644 --- a/installer/internal/media/imager_test.go +++ b/installer/internal/media/imager_test.go @@ -287,9 +287,9 @@ func macEnv(home string, existing []string, version string, versionErr error) Ma } func TestFindMacImagerPrefersApplications(t *testing.T) { - env := macEnv("/Users/simon", []string{ + env := macEnv("/Users/tester", []string{ "/Applications/Raspberry Pi Imager.app", - "/Users/simon/Applications/Raspberry Pi Imager.app", + "/Users/tester/Applications/Raspberry Pi Imager.app", }, "2.0.12", nil) im, ok := FindMacImager(env) if !ok { @@ -302,7 +302,7 @@ func TestFindMacImagerPrefersApplications(t *testing.T) { } func TestFindMacImagerStripsTheLeadingV(t *testing.T) { - env := macEnv("/Users/simon", []string{ + env := macEnv("/Users/tester", []string{ "/Applications/Raspberry Pi Imager.app", }, "v2.0.12", nil) im, ok := FindMacImager(env) @@ -315,20 +315,20 @@ func TestFindMacImagerStripsTheLeadingV(t *testing.T) { } func TestFindMacImagerFallsBackToHomeApplications(t *testing.T) { - env := macEnv("/Users/simon", []string{ - "/Users/simon/Applications/Raspberry Pi Imager.app", + env := macEnv("/Users/tester", []string{ + "/Users/tester/Applications/Raspberry Pi Imager.app", }, "2.0.12", nil) im, ok := FindMacImager(env) if !ok { t.Fatal("imager not found") } - if im.Path != "/Users/simon/Applications/Raspberry Pi Imager.app/Contents/MacOS/rpi-imager" { + if im.Path != "/Users/tester/Applications/Raspberry Pi Imager.app/Contents/MacOS/rpi-imager" { t.Fatalf("Path = %q", im.Path) } } func TestFindMacImagerNotInstalled(t *testing.T) { - if _, ok := FindMacImager(macEnv("/Users/simon", nil, "", nil)); ok { + if _, ok := FindMacImager(macEnv("/Users/tester", nil, "", nil)); ok { t.Fatal("expected ok == false") } } From 0035899049df46f46b2e979c51f8316b11985048 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:00:06 +0100 Subject: [PATCH 13/16] test(installer): skip the unsupported answer check on macOS The media mode is supported on macOS, so TestMediaUnsupportedWithoutLinux no longer gets the unsupported answer there. Co-Authored-By: Claude Sonnet 5.5 --- installer/internal/host/media_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/installer/internal/host/media_test.go b/installer/internal/host/media_test.go index 80f07cd1..49911953 100644 --- a/installer/internal/host/media_test.go +++ b/installer/internal/host/media_test.go @@ -79,8 +79,8 @@ func TestMediaUnsupportedWithoutLinux(t *testing.T) { if runtime.GOOS == "linux" { t.Skip("checks the non-Linux answer") } - if runtime.GOOS == "windows" { - t.Skip("media mode is supported on Windows, so the unsupported answer does not apply") + if runtime.GOOS == "windows" || runtime.GOOS == "darwin" { + t.Skip("media mode is supported on Windows and macOS, so the unsupported answer does not apply") } h := newMediaHost(t, t.TempDir()) _, err := h.MediaCatalog(context.Background()) From 797563b1adf8af7e9eb5e619775fa2c76c7a700c Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:11:00 +0100 Subject: [PATCH 14/16] ci: drop the temporary push trigger of the macOS media workflow Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/installer-macos-media.yml | 7 ------- 1 file changed, 7 deletions(-) diff --git a/.github/workflows/installer-macos-media.yml b/.github/workflows/installer-macos-media.yml index a843e5b0..1ea11939 100644 --- a/.github/workflows/installer-macos-media.yml +++ b/.github/workflows/installer-macos-media.yml @@ -10,13 +10,6 @@ on: - installer/internal/media/** - installer/internal/host/** - .github/workflows/installer-macos-media.yml - push: - branches: - - feat/installer-media-macos - paths: - - installer/internal/media/** - - installer/internal/host/** - - .github/workflows/installer-macos-media.yml permissions: contents: read From e7f8c50586fd12c0e98bfeb033088a98c2cc5b5d Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 29 Nov 2026 22:11:31 +0000 Subject: [PATCH 15/16] chore(release): bump component versions --- installer/VERSION | 2 +- installer/webui/VERSION | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/installer/VERSION b/installer/VERSION index 1afca5d7..06a71cc1 100644 --- a/installer/VERSION +++ b/installer/VERSION @@ -1 +1 @@ -v0.3.4-pre.7 +v0.3.4-pre.8 diff --git a/installer/webui/VERSION b/installer/webui/VERSION index 1c0be1b6..c4d6f52b 100644 --- a/installer/webui/VERSION +++ b/installer/webui/VERSION @@ -1 +1 @@ -v0.3.4-pre.10 +v0.3.4-pre.11 From 3a7ae526106fc26370f16ac2245f5fa4a917f0c0 Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 29 Nov 2026 22:12:33 +0000 Subject: [PATCH 16/16] docs(changelog): update changelogs --- changelog/highlights/301.json | 8 ++++++++ installer/CHANGELOG.md | 14 ++++++++++++-- installer/webui/CHANGELOG.md | 8 ++++++-- 3 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 changelog/highlights/301.json diff --git a/changelog/highlights/301.json b/changelog/highlights/301.json new file mode 100644 index 00000000..d273dfdd --- /dev/null +++ b/changelog/highlights/301.json @@ -0,0 +1,8 @@ +{ + "de": { + "*": "Der Installer bereitet Speichermedien jetzt auch unter macOS vor" + }, + "en": { + "*": "Prepare storage media on macOS" + } +} diff --git a/installer/CHANGELOG.md b/installer/CHANGELOG.md index c16ee094..3bbdd886 100644 --- a/installer/CHANGELOG.md +++ b/installer/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.3.4-pre.7 (2026-11-15) +## v0.3.4-pre.8 (2026-11-15) ### Features @@ -10,6 +10,12 @@ - **installer:** write a Debian install stick from the media mode (#255) (cb9e1aa) - **installer:** The configure screen of the installer shows its services and tuning as modules (#280) (f85e2a6) - **installer:** apply a changed service selection without a full update (#282) (ab11a7a) +- **installer:** prepare storage media on Windows (#298) (96ffa09) +- **installer:** find the Raspberry Pi Imager on macOS (539c6c9) +- **installer:** write media on macOS with the imager's own authorization (2dde909) +- **installer:** list macOS drives for the media mode (c76d1ae) +- **installer:** take timezone, keyboard and country from macOS (5864fd9) +- **installer:** prepare storage media on macOS (#301) - **installer:** check the target again before writing and read Windows imager output (c0a7cd7) - **installer:** add the zone tables for the media defaults (d895abc) - **installer:** add the media helper that runs the imager on behalf of the installer (b24ec8d) @@ -20,7 +26,6 @@ - **installer:** take timezone, keyboard and country from Windows (d89dfb6) - **installer:** read Wi-Fi networks and stored keys on Windows (f643b40) - **installer:** eject the written medium on Windows (670a16f) -- **installer:** prepare storage media on Windows (#298) - **installer:** compute the steps an apply-selection run needs (c855116) - **installer:** prepare from the package stored on the node (f5b1c87) - **installer:** run only the changed services in apply-selection mode (7af7686) @@ -85,6 +90,10 @@ ### Tests +- **installer:** add recorded macOS outputs for the media mode (f0fbf39) +- **installer:** feed the macOS imager lines with their carriage returns (7ac1ea0) +- **installer:** use a neutral home folder in the macOS imager tests (9e86f2e) +- **installer:** skip the unsupported answer check on macOS (0035899) - **installer:** add recorded Windows outputs for the media mode (55e7a70) - **installer:** compare the state dirs with the system path separator (bc24cad) - **installer:** cover the ISO layout failures of isopatch (f52f4cc) @@ -95,6 +104,7 @@ ### CI +- check the media mode on a macOS runner with a RAM disk (f1eb28c) - run the installer media tests on Windows (c7d413f) ## v0.3.3 (2026-11-16) diff --git a/installer/webui/CHANGELOG.md b/installer/webui/CHANGELOG.md index e7d018a7..05d191e0 100644 --- a/installer/webui/CHANGELOG.md +++ b/installer/webui/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.3.4-pre.10 (2026-11-06) +## v0.3.4-pre.11 (2026-11-06) ### Features @@ -13,10 +13,13 @@ - **installer:** The configure screen of the installer shows its services and tuning as modules (#280) (f85e2a6) - **installer:** apply a changed service selection without a full update (#282) (ab11a7a) - **installer:** highlight that the Debian stick needs a network cable (#286) (01a23f2) +- **installer:** prepare storage media on Windows (#298) (96ffa09) +- **installer:** add the macOS texts of the media mode (6f270aa) +- **installer:** show the macOS install paths for the imager (1141119) +- **installer:** prepare storage media on macOS (#301) - **installer:** show the Windows install paths for the imager (4b4a5c1) - **installer:** add texts for the running and cancelling write (2fb9672) - **installer:** add the hint text for small media (b4d7e92) -- **installer:** prepare storage media on Windows (#298) - **installer:** prepare from the package stored on the node (f5b1c87) - **installer:** accept the apply-selection run mode (5dc8abe) - **installer:** offer the package stored on the node as a source (1ac4e7a) @@ -68,6 +71,7 @@ ### Fixes +- **installer:** keep the Wi-Fi password hint on macOS (97eb68b) - **installer:** keep a cancelled write running until the imager has ended (693afe7) - **installer:** keep the write screen moving and show cancelling (cbfa3ce) - **installer:** name only known used space and warn about small cards (b502ec8)