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

Function config_write_atomic

src/ui/config.c:242–298  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

240}
241
242static bool config_write_atomic(const char *path, const char *json, size_t json_length) {
243 wchar_t *wide_path = cbm_path_to_wide(path);
244 if (!wide_path) {
245 return false;
246 }
247 size_t temporary_capacity = wcslen(wide_path) + 40U;
248 wchar_t *temporary = calloc(temporary_capacity, sizeof(*temporary));
249 HANDLE file = INVALID_HANDLE_VALUE;
250 if (temporary) {
251 for (unsigned int attempt = 0; attempt < 128U; attempt++) {
252 ULONG sequence = (ULONG)InterlockedIncrement(&g_config_temp_sequence);
253 int written = swprintf(temporary, temporary_capacity, L"%ls.tmp.%08lX.%08lX", wide_path,
254 (unsigned long)GetCurrentProcessId(), (unsigned long)sequence);
255 if (written <= 0 || (size_t)written >= temporary_capacity) {
256 break;
257 }
258 /* DELETE access on the temp handle is what permits the
259 * rename-by-handle publish below. */
260 file = CreateFileW(temporary, GENERIC_WRITE | DELETE, 0, NULL, CREATE_NEW,
261 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
262 if (file != INVALID_HANDLE_VALUE || GetLastError() != ERROR_FILE_EXISTS) {
263 break;
264 }
265 }
266 }
267 bool ok = file != INVALID_HANDLE_VALUE;
268 size_t offset = 0;
269 while (ok && offset < json_length) {
270 size_t remaining = json_length - offset;
271 DWORD chunk = remaining > UINT32_MAX ? UINT32_MAX : (DWORD)remaining;
272 DWORD written = 0;
273 ok = WriteFile(file, json + offset, chunk, &written, NULL) != 0 && written > 0;
274 offset += written;
275 }
276 if (ok) {
277 ok = FlushFileBuffers(file) != 0;
278 }
279 bool published = ok && config_posix_rename_handle(file, wide_path);
280 if (file != INVALID_HANDLE_VALUE && !CloseHandle(file)) {
281 ok = false;
282 }
283 if (ok && !published) {
284 /* Error-driven fallback, not a version probe: POSIX rename needs
285 * NTFS-class filesystem support, so exFAT/SMB-homed configs land
286 * here, keeping the pre-POSIX behavior (replace can fail while a
287 * reader holds the destination open). */
288 published = MoveFileExW(temporary, wide_path,
289 MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;
290 }
291 ok = ok && published;
292 if (!ok && temporary) {
293 (void)DeleteFileW(temporary);
294 }
295 free(temporary);
296 free(wide_path);
297 return ok;
298}
299#else

Callers 1

cbm_ui_config_saveFunction · 0.85

Calls 8

cbm_path_to_wideFunction · 0.85
cbm_mkstempFunction · 0.85
config_write_allFunction · 0.85
config_sync_descriptorFunction · 0.85
cbm_unlinkFunction · 0.85
closeFunction · 0.50

Tested by

no test coverage detected