MCPcopy
hub / github.com/mudler/LocalAI / writeFileAtomic

Function writeFileAtomic

core/services/modeladmin/atomic.go:18–46  ·  view source on GitHub ↗

writeFileAtomic writes data to path via a sibling temp file followed by an os.Rename. If the process is killed mid-write, the original file is preserved intact instead of being truncated/partial — which os.WriteFile + O_TRUNC|O_WRONLY would leave behind. The temp file lives in the same directory so

(path string, data []byte, mode os.FileMode)

Source from the content-addressed store, hash-verified

16// runs on every error path so stray temps don't accumulate when the
17// destination directory is read-only or out of inodes.
18func writeFileAtomic(path string, data []byte, mode os.FileMode) error {
19 dir := filepath.Dir(path)
20 f, err := os.CreateTemp(dir, "."+filepath.Base(path)+".tmp-*")
21 if err != nil {
22 return fmt.Errorf("create temp file: %w", err)
23 }
24 tmp := f.Name()
25 cleanup := func() { _ = os.Remove(tmp) }
26
27 if _, err := f.Write(data); err != nil {
28 _ = f.Close()
29 cleanup()
30 return fmt.Errorf("write temp file: %w", err)
31 }
32 if err := f.Chmod(mode); err != nil {
33 _ = f.Close()
34 cleanup()
35 return fmt.Errorf("chmod temp file: %w", err)
36 }
37 if err := f.Close(); err != nil {
38 cleanup()
39 return fmt.Errorf("close temp file: %w", err)
40 }
41 if err := os.Rename(tmp, path); err != nil {
42 cleanup()
43 return fmt.Errorf("rename temp file: %w", err)
44 }
45 return nil
46}

Callers 4

atomic_test.goFile · 0.70
mutateYAMLBoolFlagFunction · 0.70
PatchConfigMethod · 0.70
EditYAMLMethod · 0.70

Calls 5

cleanupFunction · 0.85
NameMethod · 0.65
CloseMethod · 0.65
RemoveMethod · 0.45
WriteMethod · 0.45

Tested by

no test coverage detected