From c668294f04040bb84811ec41a0e1f8b4c0860053 Mon Sep 17 00:00:00 2001 From: xbj110825 Date: Fri, 12 Jul 2024 13:25:09 +0800 Subject: [PATCH] fix(git): handle missing remote-tracking branch (#82007) Signed-off-by: xbj110825 --- ...git-fix-missing-remote-tracking-branch.yml | 3 +++ lib/ansible/modules/git.py | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 changelogs/fragments/82007-git-fix-missing-remote-tracking-branch.yml diff --git a/changelogs/fragments/82007-git-fix-missing-remote-tracking-branch.yml b/changelogs/fragments/82007-git-fix-missing-remote-tracking-branch.yml new file mode 100644 index 00000000000..86f5bf394bc --- /dev/null +++ b/changelogs/fragments/82007-git-fix-missing-remote-tracking-branch.yml @@ -0,0 +1,3 @@ +--- +bugfixes: +- git - Fixed the issue where fetching a specific branch would fail if the remote tracking branch was missing. This typically occurs when the initial git clone was performed using the --single-branch or --depth parameters." (https://github.com/ansible/ansible/issues/82007). diff --git a/lib/ansible/modules/git.py b/lib/ansible/modules/git.py index 747acf0f1ba..6142933b511 100644 --- a/lib/ansible/modules/git.py +++ b/lib/ansible/modules/git.py @@ -1018,6 +1018,30 @@ def set_remote_branch(git_path, module, dest, remote, version, depth): module.fail_json(msg="Failed to fetch branch from remote: %s" % version, stdout=out, stderr=err, rc=rc) +def fix_remote_tracking_branch(git_path, module, dest, remote, version, single_branch): + """ + Fix the remote tracking branch configuration for a Git repository. + + When a Git repository is cloned with the --single-branch or --depth options, it may not fetch other branches. + This function checks if the current branch is not a local branch but exists on the remote. + If so, it updates the remote tracking branch configuration to allow fetching the specified branch. + """ + if single_branch: + fetch_ref = '+refs/heads/%s:refs/remotes/origin/%s' % (version, version) + else: + fetch_ref = '+refs/heads/*:refs/remotes/origin/*' + + cmd = [git_path, 'config', 'remote.origin.fetch', fetch_ref] + (rc, out, err) = module.run_command(cmd, cwd=dest) + if rc != 0: + module.fail_json( + msg='Failed to fix remote tracking branch.', + stdout=out, + stderr=err, + rc=rc, + cmd=cmd) + + def switch_version(git_path, module, dest, remote, version, verify_commit, depth, gpg_allowlist): cmd = '' if version == 'HEAD': @@ -1381,6 +1405,9 @@ def main(): result['diff'] = diff module.exit_json(**result) else: + if not is_local_branch(git_path, module, dest, version) and is_remote_branch(git_path, module, dest, remote, version): + fix_remote_tracking_branch(git_path, module, dest, remote, version, single_branch) + result.update(changed=True) fetch(git_path, module, repo, dest, version, remote, depth, bare, refspec, git_version_used, force=force) result['after'] = get_version(module, git_path, dest)