[windows] Avoid magic numbers when checking Win32 registry errors This avoids positional `e.args` tuple indexing and hardcoded Win32 error codes, and prevents `IndexError` if an exception with fewer `args` is caught. Noticed while reviewing #1816
diff --git a/emsdk.py b/emsdk.py index aee5bfa..c39c4c9 100644 --- a/emsdk.py +++ b/emsdk.py
@@ -157,6 +157,12 @@ else: exit_with_error('unknown machine architecture: ' + machine) +# Win32 error codes checked via OSError.winerror when calling winreg. +# Python's standard library does not define Win32 ERROR_* constants, and +# emsdk avoids third-party dependencies such as pywin32. +WIN32_ERROR_FILE_NOT_FOUND = 2 +WIN32_ERROR_ACCESS_DENIED = 5 + # Don't saturate all cores to not steal the whole system, but be aggressive. CPU_CORES = int(os.getenv('EMSDK_NUM_CORES', max(multiprocessing.cpu_count() - 1, 1))) @@ -338,7 +344,7 @@ return True except Exception as e: # 'Access is denied.' - if e.args[3] == 5: + if getattr(e, 'winerror', None) == WIN32_ERROR_ACCESS_DENIED: exit_with_error(f"failed to set the environment variable '{key}'! " 'Setting environment variables permanently requires administrator access. ' 'Please rerun this command with administrative privileges. ' @@ -380,8 +386,8 @@ except Exception as e: # this catch is if both the registry key threw an exception and the key is not in os.environ - if e.args[0] != 2: - # 'The system cannot find the file specified.' + # 'The system cannot find the file specified.' + if getattr(e, 'winerror', None) != WIN32_ERROR_FILE_NOT_FOUND: errlog(f'Failed to read environment variable {key}:') errlog(str(e)) return None