WriteHostConfig writes or updates a host configuration to ~/.ssh/config If overwrite is true, replaces existing host block If overwrite is false and host exists, returns error
(cfg *HostConfig, overwrite bool)
| 12 | // If overwrite is true, replaces existing host block |
| 13 | // If overwrite is false and host exists, returns error |
| 14 | func WriteHostConfig(cfg *HostConfig, overwrite bool) error { |
| 15 | // 1. Validate configuration |
| 16 | if err := ValidateHostConfig(cfg); err != nil { |
| 17 | return fmt.Errorf("invalid config: %w", err) |
| 18 | } |
| 19 | |
| 20 | // 2. Create backup |
| 21 | backupPath, err := backupSSHConfig() |
| 22 | if err != nil { |
| 23 | return fmt.Errorf("backup failed: %w", err) |
| 24 | } |
| 25 | |
| 26 | // 3. Read current config |
| 27 | lines, err := readSSHConfigLines() |
| 28 | if err != nil { |
| 29 | return err |
| 30 | } |
| 31 | |
| 32 | // 4. Find existing host block |
| 33 | start, end, found := findHostBlock(lines, cfg.Name) |
| 34 | |
| 35 | // 5. Check overwrite policy |
| 36 | if found && !overwrite { |
| 37 | return fmt.Errorf("host %s already exists (use overwrite=true to replace)", cfg.Name) |
| 38 | } |
| 39 | |
| 40 | // 6. Render new host block |
| 41 | newBlock := renderHostBlock(cfg) |
| 42 | newBlockLines := strings.Split(strings.TrimRight(newBlock, "\n"), "\n") |
| 43 | |
| 44 | // 7. Construct updated config |
| 45 | var result []string |
| 46 | if found { |
| 47 | // Replace existing block |
| 48 | result = append(result, lines[:start]...) |
| 49 | result = append(result, newBlockLines...) |
| 50 | result = append(result, lines[end:]...) |
| 51 | } else { |
| 52 | // Append new block |
| 53 | result = append(result, lines...) |
| 54 | if len(result) > 0 && result[len(result)-1] != "" { |
| 55 | result = append(result, "") // Blank line before new host |
| 56 | } |
| 57 | result = append(result, newBlockLines...) |
| 58 | } |
| 59 | |
| 60 | // 8. Write updated config |
| 61 | if err := writeSSHConfigLines(result); err != nil { |
| 62 | // Attempt to restore backup on failure |
| 63 | if backupPath != "" { |
| 64 | configPath := sshConfigPath() |
| 65 | _ = copyFile(backupPath, configPath) |
| 66 | } |
| 67 | return err |
| 68 | } |
| 69 | |
| 70 | return nil |
| 71 | } |
no test coverage detected