Skip to content

io: implement dirCreateFileAtomic - #382

Merged
lalinsky merged 4 commits into
mainfrom
io-create-file-atomic
May 11, 2026
Merged

lalinsky merged 4 commits into
mainfrom
io-create-file-atomic

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Implement dirCreateFileAtomicImpl for atomic file creation
  • Creates temporary files with random hex names, supports link() for atomic create and replace() for atomic overwrite
  • Handles make_path option to create parent directories

Test plan

  • Added tests for createFileAtomic link, replace, and make_path scenarios

Creates temporary files with random hex names for atomic file operations.
Supports link() for atomic create and replace() for atomic overwrite.
@coderabbitai

coderabbitai Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d9e4d73c-6508-4efe-b1b0-962d3696a90b

📥 Commits

Reviewing files that changed from the base of the PR and between 5c31778 and 8b66e59.

📒 Files selected for processing (1)
  • src/io.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/io.zig

📝 Walkthrough

Walkthrough

This PR implements atomic file creation (dirCreateFileAtomicImpl) with optional parent-directory creation, adds Windows UTF‑8→wide path separator normalization, introduces FileOpenFlags.allow_directory, and implements Windows renameatPreserve and conditional openat behavior.

Changes

Atomic File Creation with Windows Path Handling

Layer / File(s) Summary
Windows Path Normalization
src/os/windows.zig
utf8ToWide now converts forward slashes to backslashes after UTF‑8→wide conversion to normalize path separators.
FileOpenFlags Extension
src/os/fs.zig
FileOpenFlags gains allow_directory: bool = true to control directory access on Windows via FILE_FLAG_BACKUP_SEMANTICS.
Windows File Operations
src/os/fs.zig
Windows openat() conditionally enables FILE_FLAG_BACKUP_SEMANTICS based on allow_directory; renameatPreserve() is implemented with MoveFileExW (no replace flag) and Windows error mapping.
Atomic File Implementation
src/io.zig
dirCreateFileAtomicImpl creates/opens parent directory (via make_path if requested), uses atomicFileInit to generate an exclusive random-hex temp file with retry logic, and returns Io.File.Atomic with temp handle and deinit flags; dirOpenFileImpl forwards allow_directory.
Atomic File Tests
src/io.zig
Tests validate atomic link, atomic replace, and make_path-driven nested directory creation.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • lalinsky/zio#381: Implements createDirPath / createDirPathOpen in src/io.zig, which overlaps parent-directory creation used when make_path is enabled.
  • lalinsky/zio#198: Modifies Windows path conversion helpers; related to the forward-slash→backslash normalization in utf8ToWide.
  • lalinsky/zio#156: Changes directory create/open logic and earlier dirCreateFile behavior touching similar code paths.

Poem

A temp file blooms with a random hex name,
Written in silence, avoiding the same,
Slashes flip to backslashes on Windows' lane,
A move that refuses to overwrite by blame,
Linked in place — atomic, tidy, and sane.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title directly describes the main implementation added: dirCreateFileAtomic in the io module, which matches the core changes in src/io.zig.
Description check ✅ Passed The description covers the core functionality implemented: atomic file creation with temp files, link/replace operations, make_path support, and mentions test coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch io-create-file-atomic

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@lalinsky

This comment was marked as resolved.

@claude

This comment was marked as resolved.

Three issues:

1. Implement renameatPreserve for Windows using MoveFileExW without
   MOVEFILE_REPLACE_EXISTING, which fails if the destination exists.

2. Remove panic for allow_directory=false in dirOpenFileImpl and pass
   the flag through to openat. On Windows, CreateFileW without
   FILE_FLAG_BACKUP_SEMANTICS already blocks opening directories.
   Add allow_directory field to FileOpenFlags.

3. Normalize forward slashes to backslashes in utf8ToWide. Wine's
   CreateFileW with FILE_FLAG_BACKUP_SEMANTICS returns INVALID_NAME
   for paths that use forward slashes as separators.

Co-authored-by: Lukáš Lalinský <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/os/fs.zig (1)

574-599: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

allow_directory=false currently returns the wrong error on Windows.

Line 108 documents error.IsDir, but in Line 597 ACCESS_DENIED is returned as error.AccessDenied. For directory targets this breaks the contract and caller behavior.

💡 Suggested fix
         if (handle == w.INVALID_HANDLE_VALUE) {
-            return switch (w.GetLastError()) {
+            return switch (w.GetLastError()) {
                 .FILE_NOT_FOUND => error.FileNotFound,
                 .PATH_NOT_FOUND => error.FileNotFound,
-                .ACCESS_DENIED => error.AccessDenied,
+                .ACCESS_DENIED => blk: {
+                    if (!flags.allow_directory) {
+                        const attrs = w.GetFileAttributesW(path_w.ptr);
+                        if (attrs != w.INVALID_FILE_ATTRIBUTES and (attrs & w.FILE_ATTRIBUTE_DIRECTORY) != 0) {
+                            break :blk error.IsDir;
+                        }
+                    }
+                    break :blk error.AccessDenied;
+                },
                 else => |err| return unexpectedError(err),
             };
         }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/os/fs.zig` around lines 574 - 599, The code maps w.ACCESS_DENIED to
error.AccessDenied after CreateFileW, but when flags.allow_directory is false
Windows returns ACCESS_DENIED for directory targets and the API contract expects
error.IsDir; update the GetLastError switch in the CreateFileW failure handling
so that when the error is .ACCESS_DENIED and flags.allow_directory is false
(i.e., when FILE_FLAG_BACKUP_SEMANTICS was not set) you return error.IsDir
instead of error.AccessDenied; keep other mappings
(.FILE_NOT_FOUND/.PATH_NOT_FOUND => error.FileNotFound) unchanged and reference
the symbols flags.allow_directory, file_flags/FILE_FLAG_BACKUP_SEMANTICS,
CreateFileW and the GetLastError switch to locate where to change the mapping.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/io.zig`:
- Around line 625-643: The new directory handle created by
dirCreateDirPathOpenImpl or dirOpenDirImpl (assigned to new_dir) is not closed
if the subsequent atomicFileInit call fails, leaking handles; modify the block
around dirCreateDirPathOpenImpl/dirOpenDirImpl and atomicFileInit so that when
atomicFileInit returns an error you close new_dir (call its close method or use
a defer/cleanup pattern) before returning the error, and apply the same fix to
the analogous block that covers the other branch (the code paths referenced by
dirCreateDirPathOpenImpl, dirOpenDirImpl, atomicFileInit and the new_dir
variable).

---

Outside diff comments:
In `@src/os/fs.zig`:
- Around line 574-599: The code maps w.ACCESS_DENIED to error.AccessDenied after
CreateFileW, but when flags.allow_directory is false Windows returns
ACCESS_DENIED for directory targets and the API contract expects error.IsDir;
update the GetLastError switch in the CreateFileW failure handling so that when
the error is .ACCESS_DENIED and flags.allow_directory is false (i.e., when
FILE_FLAG_BACKUP_SEMANTICS was not set) you return error.IsDir instead of
error.AccessDenied; keep other mappings (.FILE_NOT_FOUND/.PATH_NOT_FOUND =>
error.FileNotFound) unchanged and reference the symbols flags.allow_directory,
file_flags/FILE_FLAG_BACKUP_SEMANTICS, CreateFileW and the GetLastError switch
to locate where to change the mapping.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0e3653ce-2054-4273-9081-d54f8ed69c18

📥 Commits

Reviewing files that changed from the base of the PR and between 13ab298 and 5c31778.

📒 Files selected for processing (3)
  • src/io.zig
  • src/os/fs.zig
  • src/os/windows.zig

Comment thread src/io.zig Resolved
Add errdefer to close the parent directory handle if atomicFileInit
returns an error, preventing handle leaks under repeated failures.

Co-authored-by: Lukáš Lalinský <[email protected]>
@lalinsky
lalinsky merged commit b0891e5 into main May 11, 2026
27 checks passed
@lalinsky
lalinsky deleted the io-create-file-atomic branch May 11, 2026 09:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant