MCPcopy Create free account
hub / github.com/DeusData/codebase-memory-mcp / write_file_atomic

Function write_file_atomic

src/pipeline/artifact.c:177–222  ·  view source on GitHub ↗

Write buffer to file atomically (write to tmp, rename). Returns 0 on success. */

Source from the content-addressed store, hash-verified

175
176/* Write buffer to file atomically (write to tmp, rename). Returns 0 on success. */
177static int write_file_atomic(const char *path, const char *data, size_t len,
178 artifact_file_error_t *out_err) {
179 file_error_clear(out_err);
180
181 char tmp[CBM_SZ_4K];
182 int n = snprintf(tmp, sizeof(tmp), "%s.tmp", path);
183 if (n < 0 || (size_t)n >= sizeof(tmp)) {
184 file_error_set(out_err, "path_too_long", 0);
185 return CBM_NOT_FOUND;
186 }
187
188 /* cbm_fopen / cbm_rename_replace: wide paths on Windows. The ANSI CRT fopen
189 * and MoveFileExA mangled a repo path outside the active code page (a CJK
190 * checkout), so every persistent export failed there (#1171). */
191 FILE *fp = cbm_fopen(tmp, "wb");
192 if (!fp) {
193 file_error_set(out_err, "open_temp", errno);
194 return CBM_NOT_FOUND;
195 }
196
197 size_t wr = fwrite(data, ART_NUL, len, fp);
198 if (wr != len) {
199 int saved_errno = ferror(fp) ? errno : 0;
200 (void)fclose(fp);
201 cbm_unlink(tmp);
202 file_error_set(out_err, "write_temp", saved_errno);
203 return CBM_NOT_FOUND;
204 }
205
206 if (fclose(fp) != 0) {
207 int saved_errno = errno;
208 cbm_unlink(tmp);
209 file_error_set(out_err, "close_temp", saved_errno);
210 return CBM_NOT_FOUND;
211 }
212
213 /* Replace-existing rename (MoveFileExW write-through on Windows, the
214 * approach suggested by @Ayush7Ranjan in #492); errno carries the cause. */
215 if (cbm_rename_replace(tmp, path) != 0) {
216 int saved_errno = errno;
217 cbm_unlink(tmp);
218 file_error_set(out_err, "rename_temp", saved_errno);
219 return CBM_NOT_FOUND;
220 }
221 return 0;
222}
223
224#ifdef _WIN32
225#define ARTIFACT_NULL_DEV "NUL"

Callers 3

write_metadataFunction · 0.85
cbm_artifact_exportFunction · 0.85
cbm_artifact_importFunction · 0.85

Calls 6

file_error_clearFunction · 0.85
file_error_setFunction · 0.85
cbm_fopenFunction · 0.85
fwriteFunction · 0.85
cbm_unlinkFunction · 0.85
cbm_rename_replaceFunction · 0.85

Tested by

no test coverage detected