vcom/internal/ssh/internal/atomicwrite/atomicwrite.go
vrubelroman 8584a638f1 feat(ssh): add sshconfig resolver and host store (2B.1)
Resolve host aliases through ~/.ssh/config with kevinburke/ssh_config:
HostName defaults to the alias, key=value syntax, Host * defaults,
Include, quotes, several IdentityFile, '#' inside values (N-P1-5).
Endpoint.Key includes the user (N-P2-3). Port the hosts.dat store with
atomic writes and a base64 password field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 23:27:58 +03:00

48 lines
1.2 KiB
Go

// Package atomicwrite is a stop-gap atomic file writer for internal/ssh.
//
// TODO(2C.1): replace with internal/atomicfile.WriteFile once it is merged;
// this package exists only so that 2B can land independently of 2C.
package atomicwrite
import (
"os"
"path/filepath"
)
// WriteFile writes data to path atomically: a temp file in the same
// directory is written, fsynced, renamed over path, and the directory is
// fsynced. Readers see either the old or the new content, never a prefix.
func WriteFile(path string, data []byte, perm os.FileMode) (err error) {
dir := filepath.Dir(path)
f, err := os.CreateTemp(dir, "."+filepath.Base(path)+".tmp-*")
if err != nil {
return err
}
tmp := f.Name()
defer func() {
if err != nil {
f.Close()
os.Remove(tmp)
}
}()
if err = f.Chmod(perm); err != nil {
return err
}
if _, err = f.Write(data); err != nil {
return err
}
if err = f.Sync(); err != nil {
return err
}
if err = f.Close(); err != nil {
return err
}
if err = os.Rename(tmp, path); err != nil {
return err
}
if d, derr := os.Open(dir); derr == nil {
d.Sync() // best effort: not every filesystem supports fsync on a directory
d.Close()
}
return nil
}