Complete
Repository: https://github.com/bitranox/lib_registry Related Files:
- src/lib_registry/registry.py
- src/lib_registry/cli.py
- src/lib_registry/main.py
- src/lib_registry/init.py
- src/lib_registry/init__conf.py
- tests/test_cli.py
- tests/test_module_entry.py
- tests/test_metadata.py
Python's built-in winreg module provides low-level access to the Windows
registry but requires manual handle management, verbose error handling, and
platform-specific code. lib_registry wraps winreg (and fake_winreg on
non-Windows platforms) with a high-level Registry class that provides
connection caching, automatic type detection, recursive operations, and a
cross-platform development experience.
registry.pycontains theRegistryclass, exception hierarchy, helper functions (includingnormalize_separatorsfor forward-slash support), type aliases, named winerror constants, and all winreg constant re-exports.cli.pyprovides a rich-click CLI adapter with 12 commands for registry operations, delegating toRegistrymethods.__main__.pydelegates tocli.main()forpython -mexecution.__init__.pyre-exports the public API for library consumers.__init__conf__.pyholds static metadata constants synced frompyproject.tomlby automation.
Layer Structure:
CLI adapter (cli.py, __main__.py)
|
v
Domain (registry.py)
|
v
winreg / fake_winreg
Data Flow:
- Library consumers import
Registryfromlib_registryand call methods directly. Both/and\are accepted in key paths. - CLI commands parse arguments with rich-click, delegate to
Registrymethods. resolve_key()normalizes forward slashes to backslashes, parses hive names, and returns (hive_int, sub_key) tuples.Registrymethods manage cached connections/handles and delegate towinregAPI functions.- On non-Windows,
fake_winregprovides an in-memory simulated registry.
System Dependencies:
winreg(stdlib, Windows only) orfake_winreg(PyPI, non-Windows)rich_clickfor CLI UXrichfor enhanced tracebacks, console output, and table rendering
- Purpose: High-level Windows registry accessor with connection caching, handle management, and context manager with proper cleanup.
- Key features:
- Connection caching by hive
- Key handle caching by (hive, subkey, access) tuple
close_all()closes all cached handles (called by__exit__and__call__)- Automatic value type inference in
set_value() - Recursive key creation/deletion
- Remote computer support
- SID enumeration and username resolution
- Save/load subtrees to/from files
- WOW64 reflection control
delete_key_excleans all cached access masks for the deleted key
- Location: src/lib_registry/registry.py
- Purpose: Typed exceptions for specific registry failure modes.
- Base:
RegistryError - Key subclasses:
RegistryKeyNotFoundError,RegistryKeyCreateError,RegistryKeyDeleteError,RegistryValueNotFoundError,RegistryValueWriteError(chains root cause viafrom exc),RegistryHKeyError,RegistryNetworkConnectionError - Location: src/lib_registry/registry.py
normalize_separators()- Convert/to\for cross-platform key pathsresolve_key()- Parse key string/int into (hive_key, sub_key) tupleget_hkey_int()- Extract HKEY constant from key name stringget_key_as_string()- Format key as human-readable stringget_value_type_as_string()- Format registry type as stringstrip_backslashes()- Strip leading/trailing backslashesget_first_part_of_the_key()- Extract first path componentremove_hive_from_key_str_if_present()- Strip hive prefix
_WINERROR_FILE_NOT_FOUND,_WINERROR_ACCESS_DENIED,_WINERROR_INVALID_HANDLE,_WINERROR_NETWORK_PATH_NOT_FOUND,_WINERROR_NO_MORE_DATA,_WINERROR_KEY_MARKED_FOR_DELETION,_WINERROR_NETWORK_ADDRESS_INVALID— replace magic numbers in error handling
RegData = None | bytes | int | str | list[str]- Union of valid registry value types.
- All
HKEY_*hive constants (7 hives with short aliases) - All
REG_*type constants (12 types) - All
KEY_*access constants (12 constants including WOW64) l_hive_names—frozensetfor O(1) hive name lookups- Lookup dicts:
main_key_hashed_by_name,hive_names_hashed_by_int,reg_type_names_hashed_by_int
All commands are defined in src/lib_registry/cli.py and delegate to
Registry methods. Forward slashes are accepted in all key paths.
| Command | Purpose |
|---|---|
info |
Print package metadata |
get KEY VALUE_NAME |
Read and print a registry value (--type shows REG_* type) |
set KEY VALUE_NAME DATA |
Write a value (REG_SZ by default; --type for other types) |
delete-value KEY VALUE_NAME |
Delete a value |
list KEY |
List subkeys and values (--keys, --values filters) |
exists KEY |
Check if key exists (exit code 0/1 for shell scripting) |
create-key KEY |
Create a key (--parents for intermediates) |
delete-key KEY |
Delete a key (--recursive for subtrees) |
export KEY FILE |
Save key subtree to JSON file |
import KEY SUB_KEY FILE |
Load key subtree from JSON file |
search KEY |
Recursive search by --name or --data glob patterns |
users |
List SIDs with resolved usernames (rich table output) |
CLI set behavior: Without --type, data is always stored as REG_SZ
(string). Use --type REG_DWORD explicitly for integers. With --type,
integer parsing accepts decimal, hex (0xFF), and octal (0o77), with
overflow validation for REG_DWORD (0..4294967295).
- Purpose: Entry point for console scripts and module execution.
- Input: Optional argv sequence (defaults to sys.argv[1:]).
- Output: Integer exit code.
- Location: src/lib_registry/cli.py
- Purpose: Render statically-defined project metadata for the CLI
infocommand. - Location: src/lib_registry/init__conf.py
__init__.pyre-exports the full Registry API, exception hierarchy, helper functions,normalize_separators, constants, andprint_infovia explicit__all__.
Dependencies:
- External:
winreg/fake_winreg,rich_click,rich - Internal:
__init__conf__static metadata constants
Key Configuration:
- No environment variables required for registry operations.
- Traceback preferences controlled via CLI
--tracebackflag. - On non-Windows,
fake_winregloads a minimal test registry at import time.
Error Handling Strategy:
- Typed exception hierarchy maps winreg OS errors to semantic exceptions.
- Named
_WINERROR_*constants replace magic numbers for readability. set_valuechains root cause exceptions viafrom exc.from Nonesuppresses implicit exception chaining in_reg_connect.- Rich tracebacks installed by default;
--no-tracebacksuppresses them. - CLI
userscatchesRegistryError(not bareException) for SID resolution.
Resource Management:
__exit__callsclose_all()to close all cached handles and connections.__call__callsclose_all()before re-initializing to prevent leaks.delete_key_exiterates all cached access masks for the deleted key.
Manual Testing Steps:
lib_registry info- prints package metadata.lib_registry get "HKLM/SOFTWARE/Microsoft/Windows NT/CurrentVersion" CurrentBuild- reads a value.lib_registry exists HKLM/SOFTWARE- exit code 0 (exists).lib_registry list HKEY_USERS- lists subkeys and values.lib_registry users- lists SIDs with usernames.python -m lib_registry info- matches console script behavior.
Automated Tests:
tests/test_cli.py— 30+ tests covering all 12 CLI commands including forward-slash paths, error cases (missing values, overflow, invalid types), and round-trip create/set/get/delete/export/import. Usestemp_keyandtemp_filepytest fixtures for guaranteed teardown cleanup.tests/test_module_entry.pyensurespython -mentry mirrors the console script.tests/test_metadata.pyvalidates that__init__conf__constants matchpyproject.tomlusing Pydantic models.- Doctests in
registry.pycover all public methods including key CRUD, value operations, SID enumeration, save/load, and error paths.
Current Limitations:
registry.pyandcli.pyare excluded from pyright strict checking becausefake_winreglacks type stubs.- Coverage threshold at 70% due to Windows-only error handling branches.
save_key/load_keyparameter order is asymmetric (intentional — see CLAUDE.md Code Quality section).
Future Enhancements:
- Add type stubs for fake_winreg to enable strict type checking.
- Add
--jsonoutput flag tolist,search,usersfor scripting. - Add
--recursiveflag tolist --keysfor tree traversal. - Add
--forceflag for destructive operations.
Created: 2025-09-26 by Codex (automation) Last Updated: 2026-04-02 by Claude Code Review Cycle: Evaluate when CLI commands or Registry methods change