swapDirectoryContents replaces the entries inside dest with the entries inside src, preserving dest's inode. It first moves every existing entry into a sibling backup directory, then moves the staged entries into dest. If any step fails, the original contents are restored from the backup. src and d
(dest, src string)
| 521 | // |
| 522 | // src and dest must live on the same filesystem so renames are atomic. |
| 523 | func swapDirectoryContents(dest, src string) error { |
| 524 | backup, err := os.MkdirTemp(filepath.Dir(dest), "."+filepath.Base(dest)+".gh-skill-backup-") |
| 525 | if err != nil { |
| 526 | return fmt.Errorf("could not create backup directory: %w", err) |
| 527 | } |
| 528 | |
| 529 | existing, err := os.ReadDir(dest) |
| 530 | if err != nil { |
| 531 | _ = os.RemoveAll(backup) |
| 532 | return fmt.Errorf("could not read skill directory %s: %w", dest, err) |
| 533 | } |
| 534 | var movedOut []string |
| 535 | for _, entry := range existing { |
| 536 | if err := os.Rename(filepath.Join(dest, entry.Name()), filepath.Join(backup, entry.Name())); err != nil { |
| 537 | restoreBackup(dest, backup, movedOut, nil) |
| 538 | return fmt.Errorf("could not move %s aside: %w", entry.Name(), err) |
| 539 | } |
| 540 | movedOut = append(movedOut, entry.Name()) |
| 541 | } |
| 542 | |
| 543 | staged, err := os.ReadDir(src) |
| 544 | if err != nil { |
| 545 | restoreBackup(dest, backup, movedOut, nil) |
| 546 | return fmt.Errorf("could not read staged skill directory %s: %w", src, err) |
| 547 | } |
| 548 | var movedIn []string |
| 549 | for _, entry := range staged { |
| 550 | from := filepath.Join(src, entry.Name()) |
| 551 | to := filepath.Join(dest, entry.Name()) |
| 552 | if err := os.Rename(from, to); err != nil { |
| 553 | restoreBackup(dest, backup, movedOut, movedIn) |
| 554 | return fmt.Errorf("could not move %s into place: %w", entry.Name(), err) |
| 555 | } |
| 556 | movedIn = append(movedIn, entry.Name()) |
| 557 | } |
| 558 | |
| 559 | _ = os.RemoveAll(backup) |
| 560 | return nil |
| 561 | } |
| 562 | |
| 563 | // restoreBackup undoes a partial swap by removing any freshly installed |
| 564 | // entries and moving the original entries back from backup into dest. |