Skip to content

Fix winreg and Update test_launcher from v3.14.3#7155

Merged
youknowone merged 4 commits intoRustPython:mainfrom
youknowone:winreg
Feb 15, 2026
Merged

Fix winreg and Update test_launcher from v3.14.3#7155
youknowone merged 4 commits intoRustPython:mainfrom
youknowone:winreg

Conversation

@youknowone
Copy link
Member

@youknowone youknowone commented Feb 15, 2026

Summary by CodeRabbit

  • Refactor
    • Unified Windows registry error handling to provide more consistent OS error mapping across registry operations.
    • Simplified value-name handling for registry writes, making value presence optional and streamlining error reporting and data preparation.
    • Reduced repetitive, per-call error message construction in favor of a single, consistent error pathway.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 15, 2026

📝 Walkthrough

Walkthrough

Refactors winreg error handling: os_error_from_windows_code now takes only (vm, code); SetValueEx's value_name changed to Option<String>; call sites updated to use unified OS error mapping and removed per-call formatted error messages.

Changes

Cohort / File(s) Summary
Windows registry implementation
crates/vm/src/stdlib/winreg.rs
Signature change: os_error_from_windows_code(vm, code) (removed func_name) and SetValueEx(..., value_name: Option<String>, ...). Updated all local call sites to pass only the error code and to use unified OS error construction; removed per-branch/manual formatted error messages and adjusted value-name/data handling for RegSetValueExW calls.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 I hopped through code with nimble paws,
Streamlined errors, trimmed the claws,
One code, one call, no stringy fray,
Registry dances tidy today!

🚥 Pre-merge checks | ✅ 2 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Merge Conflict Detection ⚠️ Warning ⚠️ Unable to check for merge conflicts: Failed to fetch base branch: From https://github.com/RustPython/RustPython
! [rejected] main -> main (non-fast-forward)
+ fbbd020...2567355 main -> origin/main (forced update)
Title check ❓ Inconclusive The title mentions 'Fix winreg' which aligns with the main changes, but 'Update test_launcher from v3.14.3' appears unrelated to the provided changeset that only documents winreg.rs modifications. Clarify whether test_launcher changes are included in this PR. If so, update the title to reflect both changes clearly; if not, remove the test_launcher reference.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
⚔️ Resolve merge conflicts (beta)
  • Auto-commit resolved conflicts to branch winreg
  • Post resolved changes as copyable diffs in a comment

No actionable comments were generated in the recent review. 🎉

🧹 Recent nitpick comments
crates/vm/src/stdlib/winreg.rs (2)

297-298: Remaining call sites still use the old vm.new_os_error(format!("error code: ...")) pattern.

Since this PR's goal is to fix winreg error handling, consider migrating the remaining ~15 call sites (e.g., ConnectRegistry, CreateKey, CreateKeyEx, DeleteKey, DeleteValue, DeleteKeyEx, FlushKey, LoadKey, QueryInfoKey, SaveKey, DisableReflectionKey, EnableReflectionKey, QueryReflectionKey, EnumValue, PyHkey::Close) to use os_error_from_windows_code(vm, res as i32) for consistent, human-readable Windows error descriptions.

Example fix for ConnectRegistry (same pattern applies elsewhere)
         if res == 0 {
             Ok(PyHkey::new(ret_key))
         } else {
-            Err(vm.new_os_error(format!("error code: {res}")))
+            Err(os_error_from_windows_code(vm, res as i32))
         }

278-310: Duplicated logic across Some/None branches.

The two branches differ only in the pointer value passed for computer_name but duplicate the entire FFI call and error handling.

Suggested consolidation
 fn ConnectRegistry(
     computer_name: Option<String>,
     key: PyRef<PyHkey>,
     vm: &VirtualMachine,
 ) -> PyResult<PyHkey> {
-    if let Some(computer_name) = computer_name {
-        let mut ret_key = core::ptr::null_mut();
-        let wide_computer_name = computer_name.to_wide_with_nul();
-        let res = unsafe {
-            Registry::RegConnectRegistryW(
-                wide_computer_name.as_ptr(),
-                key.hkey.load(),
-                &mut ret_key,
-            )
-        };
-        if res == 0 {
-            Ok(PyHkey::new(ret_key))
-        } else {
-            Err(vm.new_os_error(format!("error code: {res}")))
-        }
-    } else {
-        let mut ret_key = core::ptr::null_mut();
-        let res = unsafe {
-            Registry::RegConnectRegistryW(core::ptr::null_mut(), key.hkey.load(), &mut ret_key)
-        };
-        if res == 0 {
-            Ok(PyHkey::new(ret_key))
-        } else {
-            Err(vm.new_os_error(format!("error code: {res}")))
-        }
-    }
+    let wide_name = computer_name.as_deref().map(|s| s.to_wide_with_nul());
+    let name_ptr = wide_name
+        .as_deref()
+        .map_or(core::ptr::null(), |s| s.as_ptr());
+    let mut ret_key = core::ptr::null_mut();
+    let res = unsafe {
+        Registry::RegConnectRegistryW(name_ptr, key.hkey.load(), &mut ret_key)
+    };
+    if res == 0 {
+        Ok(PyHkey::new(ret_key))
+    } else {
+        Err(os_error_from_windows_code(vm, res as i32))
+    }
 }

As per coding guidelines, "When branches differ only in a value but share common logic, extract the differing value first, then call the common logic once to avoid duplicate code."


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 and others added 3 commits February 15, 2026 16:35
- SetValueEx: accept None for value_name (default registry value)
- os_error_from_windows_code: use std::io::Error to properly
  set winerror attribute on OSError
- EnumKey: use os_error_from_windows_code for proper error
@youknowone youknowone marked this pull request as ready for review February 15, 2026 07:51
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: 1

🤖 Fix all issues with AI agents
In `@crates/vm/src/stdlib/winreg.rs`:
- Around line 1058-1063: The RegSetValueExW call in the SetValueEx path
currently returns Err(vm.new_os_error(format!("error code: {res}"))) on nonzero
res; change this to use os_error_from_windows_code(vm, res as i32) so the
Windows error description is preserved (locate the Registry::RegSetValueExW
invocation and replace the vm.new_os_error path with
os_error_from_windows_code(vm, res as i32), matching the pattern used in
EnumKey, OpenKey, and SetValue).
🧹 Nitpick comments (1)
crates/vm/src/stdlib/winreg.rs (1)

297-297: Consider migrating remaining error sites to os_error_from_windows_code for consistency.

Several unchanged call sites (e.g., ConnectRegistry, CreateKey, CreateKeyEx, DeleteKey, FlushKey, LoadKey, CloseKey, etc.) still use vm.new_os_error(format!("error code: {res}")), which produces bare numeric error codes instead of human-readable Windows error messages. A follow-up pass to unify these would improve the user experience across all registry operations.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@github-actions
Copy link
Contributor

📦 Library Dependencies

The following Lib/ modules were modified. Here are their dependencies:

[x] test: cpython/Lib/test/test_launcher.py

dependencies:

dependent tests: (no tests depend on launcher)

[x] lib: cpython/Lib/urllib
[x] test: cpython/Lib/test/test_urllib.py
[x] test: cpython/Lib/test/test_urllib2.py
[x] test: cpython/Lib/test/test_urllib2_localnet.py (TODO: 19)
[x] test: cpython/Lib/test/test_urllib2net.py
[x] test: cpython/Lib/test/test_urllibnet.py
[x] test: cpython/Lib/test/test_urlparse.py
[x] test: cpython/Lib/test/test_urllib_response.py
[x] test: cpython/Lib/test/test_robotparser.py

dependencies:

  • urllib

dependent tests: (27 tests)

  • urllib: test_genericalias test_http_cookiejar test_httpservers test_logging test_pathlib test_pydoc test_robotparser test_site test_sqlite3 test_ssl test_ucn test_urllib test_urllib2 test_urllib2_localnet test_urllib2net test_urllib_response test_urllibnet test_urlparse
    • email.utils: test_email test_smtplib
      • smtplib: test_smtpnet
    • http.client: test_docxmlrpc test_hashlib test_unicodedata test_wsgiref test_xmlrpc
    • pydoc: test_enum

[x] test: cpython/Lib/test/test_winreg.py

dependencies:

dependent tests: (3 tests)

  • winreg: test_importlib test_launcher test_winreg

Legend:

  • [+] path exists in CPython
  • [x] up-to-date, [ ] outdated

@youknowone youknowone merged commit f805fa7 into RustPython:main Feb 15, 2026
13 of 14 checks passed
@youknowone youknowone deleted the winreg branch February 15, 2026 13:11
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