windows: gracefully handle when the username cannot be determined stable
authorMatt Harbison <matt_harbison@yahoo.com>
Mon, 10 Oct 2022 11:28:19 -0400
branchstable
changeset 49518 805419729e11
parent 49507 f0a3aaa07d6a
child 49523 a5f551f8b723
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.
mercurial/windows.py
tests/test-issue1102.t
--- a/mercurial/windows.py	Tue Oct 04 14:33:31 2022 +0200
+++ b/mercurial/windows.py	Mon Oct 10 11:28:19 2022 -0400
@@ -581,7 +581,13 @@
 
     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
 
 
--- a/tests/test-issue1102.t	Tue Oct 04 14:33:31 2022 +0200
+++ b/tests/test-issue1102.t	Mon Oct 10 11:28:19 2022 -0400
@@ -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 ..