|
| 1 | +// PicoClaw - Ultra-lightweight personal AI agent |
| 2 | +// Inspired by and based on nanobot: https://github.com/HKUDS/nanobot |
| 3 | +// License: MIT |
| 4 | +// |
| 5 | +// Copyright (c) 2026 PicoClaw contributors |
| 6 | + |
| 7 | +// Package fileutil provides file manipulation utilities. |
| 8 | +package fileutil |
| 9 | + |
| 10 | +import ( |
| 11 | + "fmt" |
| 12 | + "os" |
| 13 | + "path/filepath" |
| 14 | + "time" |
| 15 | +) |
| 16 | + |
| 17 | +// WriteFileAtomic atomically writes data to a file using a temp file + rename pattern. |
| 18 | +// |
| 19 | +// This guarantees that the target file is either: |
| 20 | +// - Completely written with the new data |
| 21 | +// - Unchanged (if any step fails before rename) |
| 22 | +// |
| 23 | +// The function: |
| 24 | +// 1. Creates a temp file in the same directory (original untouched) |
| 25 | +// 2. Writes data to temp file |
| 26 | +// 3. Syncs data to disk (critical for SD cards/flash storage) |
| 27 | +// 4. Sets file permissions |
| 28 | +// 5. Syncs directory metadata (ensures rename is durable) |
| 29 | +// 6. Atomically renames temp file to target path |
| 30 | +// |
| 31 | +// Safety guarantees: |
| 32 | +// - Original file is NEVER modified until successful rename |
| 33 | +// - Temp file is always cleaned up on error |
| 34 | +// - Data is flushed to physical storage before rename |
| 35 | +// - Directory entry is synced to prevent orphaned inodes |
| 36 | +// |
| 37 | +// Parameters: |
| 38 | +// - path: Target file path |
| 39 | +// - data: Data to write |
| 40 | +// - perm: File permission mode (e.g., 0o600 for secure, 0o644 for readable) |
| 41 | +// |
| 42 | +// Returns: |
| 43 | +// - Error if any step fails, nil on success |
| 44 | +// |
| 45 | +// Example: |
| 46 | +// |
| 47 | +// // Secure config file (owner read/write only) |
| 48 | +// err := utils.WriteFileAtomic("config.json", data, 0o600) |
| 49 | +// |
| 50 | +// // Public readable file |
| 51 | +// err := utils.WriteFileAtomic("public.txt", data, 0o644) |
| 52 | +func WriteFileAtomic(path string, data []byte, perm os.FileMode) error { |
| 53 | + dir := filepath.Dir(path) |
| 54 | + if err := os.MkdirAll(dir, 0o755); err != nil { |
| 55 | + return fmt.Errorf("failed to create directory: %w", err) |
| 56 | + } |
| 57 | + |
| 58 | + // Create temp file in the same directory (ensures atomic rename works) |
| 59 | + // Using a hidden prefix (.tmp-) to avoid issues with some tools |
| 60 | + tmpFile, err := os.OpenFile( |
| 61 | + filepath.Join(dir, fmt.Sprintf(".tmp-%d-%d", os.Getpid(), time.Now().UnixNano())), |
| 62 | + os.O_WRONLY|os.O_CREATE|os.O_EXCL, |
| 63 | + perm, |
| 64 | + ) |
| 65 | + if err != nil { |
| 66 | + return fmt.Errorf("failed to create temp file: %w", err) |
| 67 | + } |
| 68 | + |
| 69 | + tmpPath := tmpFile.Name() |
| 70 | + cleanup := true |
| 71 | + |
| 72 | + defer func() { |
| 73 | + if cleanup { |
| 74 | + tmpFile.Close() |
| 75 | + _ = os.Remove(tmpPath) |
| 76 | + } |
| 77 | + }() |
| 78 | + |
| 79 | + // Write data to temp file |
| 80 | + // Note: Original file is untouched at this point |
| 81 | + if _, err := tmpFile.Write(data); err != nil { |
| 82 | + return fmt.Errorf("failed to write temp file: %w", err) |
| 83 | + } |
| 84 | + |
| 85 | + // CRITICAL: Force sync to storage medium before any other operations. |
| 86 | + // This ensures data is physically written to disk, not just cached. |
| 87 | + // Essential for SD cards, eMMC, and other flash storage on edge devices. |
| 88 | + if err := tmpFile.Sync(); err != nil { |
| 89 | + return fmt.Errorf("failed to sync temp file: %w", err) |
| 90 | + } |
| 91 | + |
| 92 | + // Set file permissions before closing |
| 93 | + if err := tmpFile.Chmod(perm); err != nil { |
| 94 | + return fmt.Errorf("failed to set permissions: %w", err) |
| 95 | + } |
| 96 | + |
| 97 | + // Close file before rename (required on Windows) |
| 98 | + if err := tmpFile.Close(); err != nil { |
| 99 | + return fmt.Errorf("failed to close temp file: %w", err) |
| 100 | + } |
| 101 | + |
| 102 | + // Atomic rename: temp file becomes the target |
| 103 | + // On POSIX: rename() is atomic |
| 104 | + // On Windows: Rename() is atomic for files |
| 105 | + if err := os.Rename(tmpPath, path); err != nil { |
| 106 | + return fmt.Errorf("failed to rename temp file: %w", err) |
| 107 | + } |
| 108 | + |
| 109 | + // Sync directory to ensure rename is durable |
| 110 | + // This prevents the renamed file from disappearing after a crash |
| 111 | + if dirFile, err := os.Open(dir); err == nil { |
| 112 | + _ = dirFile.Sync() |
| 113 | + dirFile.Close() |
| 114 | + } |
| 115 | + |
| 116 | + // Success: skip cleanup (file was renamed, no temp to remove) |
| 117 | + cleanup = false |
| 118 | + return nil |
| 119 | +} |
0 commit comments