CLI for SidePulse
Python
Flush LED program writes through to the device on Omarchy Linux
Peter Kuhar95f9bbdf3844
diff --git a/src/sidepulse/device_writer.py b/src/sidepulse/device_writer.pyindex 397ddd0..c2e748a 100644--- a/src/sidepulse/device_writer.py+++ b/src/sidepulse/device_writer.py@@ -60,10 +60,49 @@ def write_normalized_led_program(return targettarget.parent.mkdir(parents=True, exist_ok=True)- target.write_text(program, encoding="utf-8")+ write_text_synced(target, program)return target+def write_text_synced(target: Path, text: str) -> None:+ """Write text and force it to the device before returning.++ Removable devices buffer writes, so the LED firmware may not see the+ program until the data reaches the disk. Syncing is best effort: the+ bytes are already handed to the OS once the file is closed, so a+ filesystem that refuses to sync must not fail the write.+ """++ is_new = not path_exists(target)+ with target.open("w", encoding="utf-8") as handle:+ handle.write(text)+ handle.flush()+ sync_fd(handle.fileno())++ if is_new:+ sync_directory(target.parent)+++def sync_fd(fd: int) -> None:+ try:+ os.fsync(fd)+ except OSError:+ pass+++def sync_directory(directory: Path) -> None:+ """Flush a new file's directory entry, where the platform supports it."""++ try:+ fd = os.open(directory, getattr(os, "O_DIRECTORY", os.O_RDONLY))+ except OSError:+ return+ try:+ sync_fd(fd)+ finally:+ os.close(fd)++def normalize_led_text(text: str) -> str:return decode_simple_escapes(text)diff --git a/tests/test_sidepulse.py b/tests/test_sidepulse.pyindex ec12d33..d735acd 100644--- a/tests/test_sidepulse.py+++ b/tests/test_sidepulse.py@@ -4028,6 +4028,32 @@ class AgentMonitorTests(unittest.TestCase):self.assertEqual(target, device / "LEDS.LED")self.assertEqual(target.read_text(), "off\n#FF00FF pulse")+ def test_sidepulse_write_syncs_program_to_the_device(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ device = Path(tmp) / "SidePulsePro"+ device.mkdir()+ synced: list[int] = []++ with patch("sidepulse.device_writer.os.fsync", synced.append):+ target = write_led_program("off", device_path=device)++ self.assertEqual(target.read_text(), "off")+ # The file itself, plus the directory entry for the new file.+ self.assertEqual(len(synced), 2)++ def test_sidepulse_write_survives_a_filesystem_that_cannot_sync(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ device = Path(tmp) / "SidePulsePro"+ device.mkdir()++ def refuse(fd: int) -> None:+ raise OSError("sync not supported")++ with patch("sidepulse.device_writer.os.fsync", refuse):+ target = write_led_program("off", device_path=device)++ self.assertEqual(target.read_text(), "off")+def test_sidepulse_write_uses_leds_led_even_when_old_file_exists(self) -> None:with tempfile.TemporaryDirectory() as tmp:device = Path(tmp) / "SidePulseDot"