Skip to content

Conversation

@youknowone
Copy link
Member

@youknowone youknowone commented Dec 25, 2025

Summary by CodeRabbit

  • New Features
    • Added two Windows path utilities to the winapi module: GetShortPathName and GetLongPathName, allowing conversion between short (DOS-style) and long path formats from Python.
    • Both functions provide robust handling of Windows path APIs and return properly encoded path strings on success.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 25, 2025

📝 Walkthrough

Walkthrough

Adds two _winapi module functions, GetShortPathName and GetLongPathName, that call a shared helper to query Windows path-name APIs, perform a two-step buffer sizing/fill, convert UTF-16 results to WTF-8 strings, and return or map errors to vm.new_last_os_error().

Changes

Cohort / File(s) Summary
Windows Path Utilities
crates/vm/src/stdlib/winapi.rs
Added GetShortPathName and GetLongPathName plus private helper get_path_name_impl. Both convert input to UTF-16, perform size-query then buffer-fill calls to the respective Windows APIs, handle errors via vm.new_last_os_error(), truncate to actual length, convert to Wtf-8 and return PyStrRef.

Sequence Diagram(s)

sequenceDiagram
  participant Py as Python caller
  participant VM as Rust VirtualMachine
  participant Impl as get_path_name_impl
  participant WinAPI as Windows API (GetShortPathNameW / GetLongPathNameW)

  Py->>VM: call GetShortPathName(path) / GetLongPathName(path)
  VM->>Impl: convert path -> UTF-16, invoke API (size query)
  Impl->>WinAPI: call API with buffer size 0
  WinAPI-->>Impl: required size (n) or 0 on error
  Impl->>WinAPI: allocate buffer of size n, call API to fill buffer
  WinAPI-->>Impl: filled UTF-16 data or 0 on error
  Impl-->>VM: convert UTF-16 -> Wtf-8 string or map error via vm.new_last_os_error()
  VM-->>Py: return PyStrRef or raise OS error
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15 minutes

Poem

🐰 I hopped through paths both short and long,

Wide strings sang me a tiny song.
Buffers sized, then filled with care,
Returned as strings for all to share.
Hooray — path names tidy, neat, and strong!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title focuses on implementing GetLongPathName, but the changeset also introduces GetShortPathName and a helper function, making the title only partially representative of the full scope.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 402ba1e and 22fd00d.

⛔ Files ignored due to path filters (1)
  • Lib/test/test_winapi.py is excluded by !Lib/**
📒 Files selected for processing (1)
  • crates/vm/src/stdlib/winapi.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.rs: Follow the default rustfmt code style by running cargo fmt to format Rust code
Always run clippy to lint Rust code (cargo clippy) before completing tasks and fix any warnings or lints introduced by changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass, pymodule, pyfunction, etc.) when implementing Python functionality in Rust

Files:

  • crates/vm/src/stdlib/winapi.rs
🧬 Code graph analysis (1)
crates/vm/src/stdlib/winapi.rs (1)
crates/wtf8/src/lib.rs (1)
  • from_wide (336-352)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Check Rust code with clippy
  • GitHub Check: Run tests under miri
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Check the WASM package and demo
🔇 Additional comments (3)
crates/vm/src/stdlib/winapi.rs (3)

682-713: Excellent helper function design!

The implementation correctly handles the Windows API two-step buffer sizing pattern and properly converts between WTF-8 and UTF-16. The buffer sizing logic is accurate: the first call returns size including the null terminator, which is then allocated, and the second call returns the length excluding the null terminator, which is used for truncation.


717-720: LGTM!

Clean wrapper that correctly delegates to the helper function with the appropriate Windows API.


724-727: LGTM!

Clean wrapper that correctly delegates to the helper function with the appropriate Windows API.


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.

@youknowone youknowone marked this pull request as ready for review December 25, 2025 12:46
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
crates/vm/src/stdlib/winapi.rs (2)

680-708: Consider using Wtf8Buf for proper WTF-8/surrogate handling.

The function currently uses String::from_utf16 (line 707), but LCMapStringEx (line 630) uses Wtf8Buf::from_wide to properly handle unpaired surrogates in WTF-8. Since the input is PyStrRef which supports WTF-8, the output should preserve this capability for consistency and robustness. While Windows paths with unpaired surrogates are rare, they are technically valid.

Additionally, this function has nearly identical implementation to GetLongPathName below—consider extracting a generic helper to reduce duplication.

🔎 Proposed refactor using Wtf8Buf pattern
+    use rustpython_common::wtf8::Wtf8Buf;
+
     /// GetShortPathName - Return the short version of the provided path.
     #[pyfunction]
-    fn GetShortPathName(path: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
+    fn GetShortPathName(path: PyStrRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
         use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW;
 
         let path_wide = path.as_wtf8().to_wide_with_nul();
 
         // First call to get required buffer size
         let size = unsafe { GetShortPathNameW(path_wide.as_ptr(), null_mut(), 0) };
 
         if size == 0 {
             return Err(vm.new_last_os_error());
         }
 
         // Second call to get the actual short path
         let mut buffer: Vec<u16> = vec![0; size as usize];
         let result = unsafe {
             GetShortPathNameW(path_wide.as_ptr(), buffer.as_mut_ptr(), buffer.len() as u32)
         };
 
         if result == 0 {
             return Err(vm.new_last_os_error());
         }
 
         // Truncate to actual length (excluding null terminator)
         buffer.truncate(result as usize);
-        String::from_utf16(&buffer).map_err(|e| vm.new_runtime_error(e.to_string()))
+        let result_str = Wtf8Buf::from_wide(&buffer);
+        Ok(vm.ctx.new_str(result_str))
     }

710-737: Consider using Wtf8Buf for proper WTF-8/surrogate handling.

The function currently uses String::from_utf16 (line 736), but LCMapStringEx (line 630) uses Wtf8Buf::from_wide to properly handle unpaired surrogates in WTF-8. Since the input is PyStrRef which supports WTF-8, the output should preserve this capability for consistency and robustness. While Windows paths with unpaired surrogates are rare, they are technically valid.

Additionally, this function has nearly identical implementation to GetShortPathName above—consider extracting a generic helper to reduce duplication.

🔎 Proposed refactor using Wtf8Buf pattern
+    use rustpython_common::wtf8::Wtf8Buf;
+
     /// GetLongPathName - Return the long version of the provided path.
     #[pyfunction]
-    fn GetLongPathName(path: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
+    fn GetLongPathName(path: PyStrRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
         use windows_sys::Win32::Storage::FileSystem::GetLongPathNameW;
 
         let path_wide = path.as_wtf8().to_wide_with_nul();
 
         // First call to get required buffer size
         let size = unsafe { GetLongPathNameW(path_wide.as_ptr(), null_mut(), 0) };
 
         if size == 0 {
             return Err(vm.new_last_os_error());
         }
 
         // Second call to get the actual long path
         let mut buffer: Vec<u16> = vec![0; size as usize];
         let result = unsafe {
             GetLongPathNameW(path_wide.as_ptr(), buffer.as_mut_ptr(), buffer.len() as u32)
         };
 
         if result == 0 {
             return Err(vm.new_last_os_error());
         }
 
         // Truncate to actual length (excluding null terminator)
         buffer.truncate(result as usize);
-        String::from_utf16(&buffer).map_err(|e| vm.new_runtime_error(e.to_string()))
+        let result_str = Wtf8Buf::from_wide(&buffer);
+        Ok(vm.ctx.new_str(result_str))
     }
📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 61ddd98 and 402ba1e.

⛔ Files ignored due to path filters (1)
  • Lib/test/test_winapi.py is excluded by !Lib/**
📒 Files selected for processing (1)
  • crates/vm/src/stdlib/winapi.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.rs: Follow the default rustfmt code style by running cargo fmt to format Rust code
Always run clippy to lint Rust code (cargo clippy) before completing tasks and fix any warnings or lints introduced by changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass, pymodule, pyfunction, etc.) when implementing Python functionality in Rust

Files:

  • crates/vm/src/stdlib/winapi.rs
🧬 Code graph analysis (1)
crates/vm/src/stdlib/winapi.rs (2)
crates/vm/src/stdlib/nt.rs (2)
  • path (1067-1067)
  • path (1071-1071)
crates/vm/src/stdlib/os.rs (1)
  • path (584-586)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Run snippets and cpython tests (windows-latest)

@youknowone youknowone merged commit 2063c1e into RustPython:main Dec 25, 2025
13 checks passed
@youknowone youknowone deleted the winapi branch December 25, 2025 13:38
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