diff --git a/changelog/64121.fixed.md b/changelog/64121.fixed.md new file mode 100644 index 000000000000..255c1ca2b288 --- /dev/null +++ b/changelog/64121.fixed.md @@ -0,0 +1 @@ +Prevent `_pygit2.GitError: error loading known_hosts` with certain pygit2/libgit2 versions. diff --git a/salt/utils/gitfs.py b/salt/utils/gitfs.py index 733ed3e29449..ffcae96f4537 100644 --- a/salt/utils/gitfs.py +++ b/salt/utils/gitfs.py @@ -119,6 +119,15 @@ with warnings.catch_warnings(): warnings.simplefilter("ignore") + if "HOME" not in os.environ: + # Make sure $HOME env variable is set before importing pygit2 to prevent + # _pygit2.GitError: error loading known_hosts in some libgit2 versions. + # The internal "git_sysdir__dirs" from libgit2, is initializated + # when importing pygit2. The $HOME env must be present to allow libgit2 + # guessing function to successfully set the homedir in the initializated + # libgit2 stack. + # https://github.com/saltstack/salt/issues/64121 + os.environ["HOME"] = os.path.expanduser("~") import pygit2 PYGIT2_VERSION = Version(pygit2.__version__) LIBGIT2_VERSION = Version(pygit2.LIBGIT2_VERSION) @@ -2012,13 +2021,9 @@ def init_remote(self): """ # https://github.com/libgit2/pygit2/issues/339 # https://github.com/libgit2/libgit2/issues/2122 - # https://github.com/saltstack/salt/issues/64121 - home = os.path.expanduser("~") - if "HOME" not in os.environ: - # Make sure $HOME env variable is set to prevent - # _pygit2.GitError: error loading known_hosts in some libgit2 versions. - os.environ["HOME"] = home - pygit2.settings.search_path[pygit2.GIT_CONFIG_LEVEL_GLOBAL] = home + pygit2.settings.search_path[pygit2.GIT_CONFIG_LEVEL_GLOBAL] = ( + os.path.expanduser("~") + ) new = False if not os.listdir(self._cachedir): # Repo cachedir is empty, initialize a new repo there diff --git a/tests/pytests/unit/utils/test_gitfs.py b/tests/pytests/unit/utils/test_gitfs.py index 683ac1a0333a..4df5b9af7bea 100644 --- a/tests/pytests/unit/utils/test_gitfs.py +++ b/tests/pytests/unit/utils/test_gitfs.py @@ -1,3 +1,4 @@ +import importlib import os import time @@ -264,7 +265,7 @@ def test_checkout_pygit2_with_home_env_unset(_prepare_provider): provider.credentials = None with patched_environ(__cleanup__=["HOME"]): assert "HOME" not in os.environ - provider.init_remote() + importlib.reload(salt.utils.gitfs) assert "HOME" in os.environ