MCPcopy Create free account
hub / github.com/daodst/chat / WriteTempFile

Function WriteTempFile

mediaapi/fileutils/fileutils.go:110–147  ·  view source on GitHub ↗

WriteTempFile writes to a new temporary file. The file is deleted if there was an error while writing.

(
	ctx context.Context, reqReader io.Reader, absBasePath config.Path,
)

Source from the content-addressed store, hash-verified

108// WriteTempFile writes to a new temporary file.
109// The file is deleted if there was an error while writing.
110func WriteTempFile(
111 ctx context.Context, reqReader io.Reader, absBasePath config.Path,
112) (hash types.Base64Hash, size types.FileSizeBytes, path types.Path, err error) {
113 size = -1
114 logger := util.GetLogger(ctx)
115 tmpFileWriter, tmpFile, tmpDir, err := createTempFileWriter(absBasePath)
116 if err != nil {
117 return
118 }
119 defer func() {
120 err2 := tmpFile.Close()
121 if err == nil {
122 err = err2
123 }
124 }()
125
126 // Hash the file data. The hash will be returned. The hash is useful as a
127 // method of deduplicating files to save storage, as well as a way to conduct
128 // integrity checks on the file data in the repository.
129 hasher := sha256.New()
130 teeReader := io.TeeReader(reqReader, hasher)
131 bytesWritten, err := io.Copy(tmpFileWriter, teeReader)
132 if err != nil && err != io.EOF {
133 RemoveDir(tmpDir, logger)
134 return
135 }
136
137 err = tmpFileWriter.Flush()
138 if err != nil {
139 RemoveDir(tmpDir, logger)
140 return
141 }
142
143 hash = types.Base64Hash(base64.RawURLEncoding.EncodeToString(hasher.Sum(nil)[:]))
144 size = types.FileSizeBytes(bytesWritten)
145 path = tmpDir
146 return
147}
148
149// moveFile attempts to move the file src to dst
150func moveFile(src types.Path, dst types.Path) error {

Callers

nothing calls this directly

Calls 3

createTempFileWriterFunction · 0.85
RemoveDirFunction · 0.85
CloseMethod · 0.65

Tested by

no test coverage detected