Skip to content

Commit 239123d

Browse files
committed
Commit files changed/added in apply-github-patch.
1 parent 6c1fc39 commit 239123d

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

ML-Frameworks/utils/git-utils.sh

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,23 +45,42 @@ function apply-github-patch {
4545
# Apply a specific GitHub commit.
4646
# $1 is 'organisation/repo', $2 is the commit hash
4747
# To use an API token, which may avoid rate limits, set the environment variable GITHUB_TOKEN
48-
4948
set -u
49+
50+
local github_url='https://github.com'
51+
local github_api_url='https://api.github.com/repos'
52+
5053
patch_file="$patch_cache_dir/$2.patch"
5154
if [ ! -f "$patch_file" ]; then
52-
local github_api_url='https://api.github.com/repos'
53-
local github_url='https://github.com'
54-
5555
# Download the .patch file.
5656
if [[ "${GITHUB_TOKEN+x}" ]]; then
57-
curl --silent -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.patch" -L $github_api_url/$1/commits/$2 -o "$patch_file"
57+
curl --silent \
58+
-H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.patch" -L $github_api_url/$1/commits/$2 -o "$patch_file"
5859
else
5960
curl --silent -L $github_url/$1/commit/$2.patch -o "$patch_file"
6061
fi
6162
fi
6263

63-
# Apply the patch
64+
# Three-way merge is less brittle than plain 'git am'. It can handle scenarios in which
65+
# the context of the patch has moved. However, we need the parent commit of the patch for
66+
# this so we'll try to fetch it with the '--depth=2'
67+
local fetch_url="${github_url}/$1.git"
68+
if [[ "${GITHUB_TOKEN+x}" ]]; then
69+
# See https://docs.github.com/en/apps/creating-github-apps/writing-code-for-a-github-app/building-ci-checks-with-a-github-app?versionId=free-pro-team%40latest&productId=code-security&restPage=dependabot%2Cworking-with-dependabot%2Cconfiguring-access-to-private-registries-for-dependabot#add-code-to-clone-a-repository
70+
fetch_url="https://x-access-token:${GITHUB_TOKEN}@github.com/$1.git"
71+
fi
72+
git fetch --no-tags --quiet --depth=2 "$fetch_url" "$2" || true
73+
74+
# Try three-way merge
75+
git am -3 --keep-cr "$patch_file" && return 0
76+
git am --abort || true
77+
78+
# Fall back to GNU 'patch'
6479
patch -p1 < "$patch_file"
80+
81+
# Commit with dummy credentials
82+
git add -A
83+
git -c user.name="apply-github-patch" -c user.email="noreply@example.com" commit -m "Applied patch $2 from $1."
6584
return 0
6685
}
6786

0 commit comments

Comments
 (0)