# HG changeset patch # User Matt Harbison # Date 2022-10-10 15:28:19 # Node ID 805419729e11c040bf8b354e7a35a78865847c13 # Parent f0a3aaa07d6a38f398b95de3eddcc9eaf24f8ffe windows: gracefully handle when the username cannot be determined This assumes implementation details, but I don't see any other way than to check the environment variables ourselves (which would miss out on any future enhancements that Python may make). This was originally reported as https://foss.heptapod.net/mercurial/tortoisehg/thg/-/issues/5835. diff --git a/mercurial/windows.py b/mercurial/windows.py --- a/mercurial/windows.py +++ b/mercurial/windows.py @@ -581,7 +581,13 @@ def username(uid=None): If uid is None, return the name of the current user.""" if not uid: - return pycompat.fsencode(getpass.getuser()) + try: + return pycompat.fsencode(getpass.getuser()) + except ModuleNotFoundError: + # getpass.getuser() checks for a few environment variables first, + # but if those aren't set, imports pwd and calls getpwuid(), none of + # which exists on Windows. + pass return None diff --git a/tests/test-issue1102.t b/tests/test-issue1102.t --- a/tests/test-issue1102.t +++ b/tests/test-issue1102.t @@ -14,4 +14,18 @@ tip 3:a49829c4fc11 t1 0:f7b1eb17ad24 +Ensure that the username access fails gracefully if assumptions about the +environment made by python do not hold. + +#if windows + >>> import os + >>> from mercurial import util + >>> os.environ.pop('LOGNAME', None) and None + >>> os.environ.pop('USER', None) and None + >>> os.environ.pop('LNAME', None) and None + >>> os.environ.pop('USERNAME', None) and None + >>> print(util.username()) + None +#endif + $ cd ..