|
| 1 | +//go:build !linux |
| 2 | + |
| 3 | +package staticpod |
| 4 | + |
| 5 | +import ( |
| 6 | + "fmt" |
| 7 | + "math/rand/v2" |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | +) |
| 11 | + |
| 12 | +// SwapDirectoriesAtomic swaps two directories, but NOT atomically in this case. |
| 13 | +// Atomic implementation is only available for Linux. |
| 14 | +// This function is essentially a mock for tests, and it simply uses os.Rename. |
| 15 | +// In case there is any error, the swapping process is simply left in an inconsistent state. |
| 16 | +func SwapDirectoriesAtomic(dirA, dirB string) error { |
| 17 | + // Still retain the constraints as in the Linux implementation. |
| 18 | + if !filepath.IsAbs(dirA) { |
| 19 | + return fmt.Errorf("not an absolute path: %q", dirA) |
| 20 | + } |
| 21 | + if !filepath.IsAbs(dirB) { |
| 22 | + return fmt.Errorf("not an absolute path: %q", dirB) |
| 23 | + } |
| 24 | + |
| 25 | + // Rename dirA -> prevDirA. |
| 26 | + prevDirA := fmt.Sprintf("%s-%d", dirA, rand.Int64()) |
| 27 | + if err := os.Rename(dirA, prevDirA); err != nil { |
| 28 | + return fmt.Errorf("failed to rename %q to %q: %w", dirA, prevDirA, err) |
| 29 | + } |
| 30 | + |
| 31 | + // Rename dirB -> dirA. |
| 32 | + if err := os.Rename(dirB, dirA); err != nil { |
| 33 | + return fmt.Errorf("failed to rename %q to %q: %w", dirB, dirA, err) |
| 34 | + } |
| 35 | + |
| 36 | + // Rename prevDirA -> dirB. |
| 37 | + if err := os.Rename(prevDirA, dirB); err != nil { |
| 38 | + return fmt.Errorf("failed to rename %q to %q: %w", prevDirA, dirB, err) |
| 39 | + } |
| 40 | + return nil |
| 41 | +} |
0 commit comments