MCPcopy Index your code
hub / github.com/docker/docker-agent / writeUniqueFile

Function writeUniqueFile

cmd/root/record_tui.go:35–62  ·  view source on GitHub ↗

writeUniqueFile writes content to _test.go, or _N_test.go when that already exists, and never overwrites: --record paths are user-controlled, so silently clobbering an unrelated *_test.go would be destructive.

(base string, content []byte)

Source from the content-addressed store, hash-verified

33// user-controlled, so silently clobbering an unrelated *_test.go would be
34// destructive.
35func writeUniqueFile(base string, content []byte) (string, error) {
36 for n := 1; n <= 100; n++ {
37 path := base + "_test.go"
38 if n > 1 {
39 path = fmt.Sprintf("%s_%d_test.go", base, n)
40 }
41 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
42 if os.IsExist(err) {
43 continue
44 }
45 if err != nil {
46 return "", err
47 }
48 // Remove on failure: a leftover empty file would permanently occupy
49 // this O_EXCL slot on every subsequent --record run.
50 if _, err := f.Write(content); err != nil {
51 f.Close()
52 os.Remove(path)
53 return "", err
54 }
55 if err := f.Close(); err != nil {
56 os.Remove(path)
57 return "", err
58 }
59 return path, nil
60 }
61 return "", fmt.Errorf("no available file name for %s_test.go", base)
62}

Calls 3

CloseMethod · 0.65
WriteMethod · 0.45
RemoveMethod · 0.45