cherry_pick_pull.sh 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. #!/usr/bin/env bash
  2. # Copyright 2015 The Kubernetes Authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # Usage Instructions: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-release/cherry-picks.md
  16. # Checkout a PR from GitHub. (Yes, this is sitting in a Git tree. How
  17. # meta.) Assumes you care about pulls from remote "upstream" and
  18. # checks them out to a branch named:
  19. # automated-cherry-pick-of-<pr>-<target branch>-<timestamp>
  20. set -o errexit
  21. set -o nounset
  22. set -o pipefail
  23. REPO_ROOT="$(git rev-parse --show-toplevel)"
  24. declare -r REPO_ROOT
  25. cd "${REPO_ROOT}"
  26. function git_remote_get_url() {
  27. git remote get-url $1 2>/dev/null
  28. if [ "$?" -ne "0" ]; then
  29. git config remote.$1.url 2>/dev/null
  30. fi
  31. if [ "$?" -ne "0" ]; then
  32. echo "git fail get remote url for $1"
  33. exit 1
  34. fi
  35. }
  36. STARTINGBRANCH=$(git symbolic-ref --short HEAD)
  37. declare -r STARTINGBRANCH
  38. declare -r REBASEMAGIC="${REPO_ROOT}/.git/rebase-apply"
  39. DRY_RUN=${DRY_RUN:-""}
  40. UPSTREAM_REMOTE=${UPSTREAM_REMOTE:-upstream}
  41. FORK_REMOTE=${FORK_REMOTE:-origin}
  42. MAIN_REPO_ORG=${MAIN_REPO_ORG:-$(git_remote_get_url "$UPSTREAM_REMOTE" | awk '{gsub(/http[s]:\/\/|git@/,"")}1' | awk -F'[@:./]' 'NR==1{print $3}')}
  43. MAIN_REPO_NAME=${MAIN_REPO_NAME:-$(git_remote_get_url "$UPSTREAM_REMOTE" | awk '{gsub(/http[s]:\/\/|git@/,"")}1' | awk -F'[@:./]' 'NR==1{print $4}')}
  44. if [[ -z ${GITHUB_USER:-} ]]; then
  45. echo "Please export GITHUB_USER=<your-user> (or GH organization, if that's where your fork lives)"
  46. exit 1
  47. fi
  48. if ! which hub > /dev/null; then
  49. echo "Can't find 'hub' tool in PATH, please install from https://github.com/github/hub"
  50. exit 1
  51. fi
  52. if [[ "$#" -lt 2 ]]; then
  53. echo "${0} <remote branch> <pr-number>...: cherry pick one or more <pr> onto <remote branch> and leave instructions for proposing pull request"
  54. echo
  55. echo " Checks out <remote branch> and handles the cherry-pick of <pr> (possibly multiple) for you."
  56. echo " Examples:"
  57. echo " $0 upstream/release-3.14 12345 # Cherry-picks PR 12345 onto upstream/release-3.14 and proposes that as a PR."
  58. echo " $0 upstream/release-3.14 12345 56789 # Cherry-picks PR 12345, then 56789 and proposes the combination as a single PR."
  59. echo
  60. echo " Set the DRY_RUN environment var to skip git push and creating PR."
  61. echo " This is useful for creating patches to a release branch without making a PR."
  62. echo " When DRY_RUN is set the script will leave you in a branch containing the commits you cherry-picked."
  63. echo
  64. echo " Set UPSTREAM_REMOTE (default: upstream) and FORK_REMOTE (default: origin)"
  65. echo " To override the default remote names to what you have locally."
  66. exit 2
  67. fi
  68. if git_status=$(git status --porcelain --untracked=no 2>/dev/null) && [[ -n "${git_status}" ]]; then
  69. echo "!!! Dirty tree. Clean up and try again."
  70. exit 1
  71. fi
  72. if [[ -e "${REBASEMAGIC}" ]]; then
  73. echo "!!! 'git rebase' or 'git am' in progress. Clean up and try again."
  74. exit 1
  75. fi
  76. declare -r BRANCH="$1"
  77. shift 1
  78. declare -r PULLS=( "$@" )
  79. function join { local IFS="$1"; shift; echo "$*"; }
  80. declare -r PULLDASH=$(join - "${PULLS[@]/#/#}") # Generates something like "#12345-#56789"
  81. declare -r PULLSUBJ=$(join " " "${PULLS[@]/#/#}") # Generates something like "#12345 #56789"
  82. echo "+++ Updating remotes..."
  83. git remote update "${UPSTREAM_REMOTE}" "${FORK_REMOTE}"
  84. if ! git log -n1 --format=%H "${BRANCH}" >/dev/null 2>&1; then
  85. echo "!!! '${BRANCH}' not found. The second argument should be something like ${UPSTREAM_REMOTE}/release-0.21."
  86. echo " (In particular, it needs to be a valid, existing remote branch that I can 'git checkout'.)"
  87. exit 1
  88. fi
  89. declare -r NEWBRANCHREQ="automated-cherry-pick-of-${PULLDASH}" # "Required" portion for tools.
  90. declare -r NEWBRANCH="$(echo "${NEWBRANCHREQ}-${BRANCH}" | sed 's/\//-/g')"
  91. declare -r NEWBRANCHUNIQ="${NEWBRANCH}-$(date +%s)"
  92. echo "+++ Creating local branch ${NEWBRANCHUNIQ}"
  93. cleanbranch=""
  94. prtext=""
  95. gitamcleanup=false
  96. function return_to_kansas {
  97. if [[ "${gitamcleanup}" == "true" ]]; then
  98. echo
  99. echo "+++ Aborting in-progress git am."
  100. git am --abort >/dev/null 2>&1 || true
  101. fi
  102. # return to the starting branch and delete the PR text file
  103. if [[ -z "${DRY_RUN}" ]]; then
  104. echo
  105. echo "+++ Returning you to the ${STARTINGBRANCH} branch and cleaning up."
  106. git checkout -f "${STARTINGBRANCH}" >/dev/null 2>&1 || true
  107. if [[ -n "${cleanbranch}" ]]; then
  108. git branch -D "${cleanbranch}" >/dev/null 2>&1 || true
  109. fi
  110. if [[ -n "${prtext}" ]]; then
  111. rm "${prtext}"
  112. fi
  113. fi
  114. }
  115. trap return_to_kansas EXIT
  116. SUBJECTS=()
  117. function make-a-pr() {
  118. local rel="$(echo "${BRANCH}" | sed "s|$UPSTREAM_REMOTE/||g")"
  119. echo
  120. echo "+++ Creating a pull request on GitHub at ${GITHUB_USER}:${NEWBRANCH}"
  121. # This looks like an unnecessary use of a tmpfile, but it avoids
  122. # https://github.com/github/hub/issues/976 Otherwise stdin is stolen
  123. # when we shove the heredoc at hub directly, tickling the ioctl
  124. # crash.
  125. prtext="$(mktemp -t prtext.XXXX)" # cleaned in return_to_kansas
  126. local numandtitle=$(printf '%s\n' "${SUBJECTS[@]}")
  127. cat >"${prtext}" <<EOF
  128. Automated cherry pick of ${numandtitle}
  129. Cherry pick of ${PULLSUBJ} on ${rel}.
  130. ${numandtitle}
  131. EOF
  132. hub pull-request -F "${prtext}" -h "${GITHUB_USER}:${NEWBRANCH}" -b "${MAIN_REPO_ORG}:${rel}"
  133. }
  134. function python_bin() {
  135. command -v python3 >/dev/null 2>&1 && echo python3 || echo python
  136. }
  137. function extract-subject {
  138. local patch="$1"
  139. $(python_bin) -c '
  140. import os
  141. import email.parser
  142. import email.header
  143. with open("'"$patch"'", "r") as f:
  144. m = email.parser.Parser().parse(f, headersonly=True)
  145. subj = m["subject"]
  146. subj = email.header.decode_header(subj)
  147. s = u""
  148. for txt, enc in subj:
  149. txt = txt.decode(enc) if enc else txt
  150. txt = txt.decode("ascii") if isinstance(txt, bytes) else txt
  151. txt = txt.replace(u"\n", u"")
  152. if txt.startswith(u"[PATCH"):
  153. i = txt.index(u"]")
  154. txt = txt[i+1:]
  155. s += txt
  156. s = s.strip() + u"\n"
  157. s = s.encode("utf-8") # write out utf-8 bytes whatsoever
  158. os.write(1, s)
  159. '
  160. }
  161. git checkout -b "${NEWBRANCHUNIQ}" "${BRANCH}"
  162. cleanbranch="${NEWBRANCHUNIQ}"
  163. gitamcleanup=true
  164. for pull in "${PULLS[@]}"; do
  165. echo "+++ Downloading patch to /tmp/${pull}.patch (in case you need to do this again)"
  166. curl -o "/tmp/${pull}.patch" -sSL "https://github.com/${MAIN_REPO_ORG}/${MAIN_REPO_NAME}/pull/${pull}.patch"
  167. echo
  168. echo "+++ About to attempt cherry pick of PR. To reattempt:"
  169. echo " $ git am -3 /tmp/${pull}.patch"
  170. echo
  171. git am -3 "/tmp/${pull}.patch" || {
  172. conflicts=false
  173. while unmerged=$(git status --porcelain | grep ^U) && [[ -n ${unmerged} ]] \
  174. || [[ -e "${REBASEMAGIC}" ]]; do
  175. conflicts=true # <-- We should have detected conflicts once
  176. echo
  177. echo "+++ Conflicts detected:"
  178. echo
  179. (git status --porcelain | grep ^U) || echo "!!! None. Did you git am --continue?"
  180. echo
  181. echo "+++ Please resolve the conflicts in another window (and remember to 'git add / git am --continue')"
  182. read -p "+++ Proceed (anything but 'y' aborts the cherry-pick)? [y/n] " -r
  183. echo
  184. if ! [[ "${REPLY}" =~ ^[yY]$ ]]; then
  185. echo "Aborting." >&2
  186. exit 1
  187. fi
  188. done
  189. if [[ "${conflicts}" != "true" ]]; then
  190. echo "!!! git am failed, likely because of an in-progress 'git am' or 'git rebase'"
  191. exit 1
  192. fi
  193. }
  194. # set the subject
  195. subject=$(extract-subject "/tmp/${pull}.patch")
  196. SUBJECTS+=("#${pull}: ${subject}")
  197. # remove the patch file from /tmp
  198. rm -f "/tmp/${pull}.patch"
  199. done
  200. gitamcleanup=false
  201. if [[ -n "${DRY_RUN}" ]]; then
  202. echo "!!! Skipping git push and PR creation because you set DRY_RUN."
  203. echo "To return to the branch you were in when you invoked this script:"
  204. echo
  205. echo " git checkout ${STARTINGBRANCH}"
  206. echo
  207. echo "To delete this branch:"
  208. echo
  209. echo " git branch -D ${NEWBRANCHUNIQ}"
  210. exit 0
  211. fi
  212. if git remote -v | grep ^${FORK_REMOTE} | grep ${MAIN_REPO_ORG}/${MAIN_REPO_NAME}.git; then
  213. echo "!!! You have ${FORK_REMOTE} configured as your ${MAIN_REPO_ORG}/${MAIN_REPO_NAME}.git"
  214. echo "This isn't normal. Leaving you with push instructions:"
  215. echo
  216. echo "+++ First manually push the branch this script created:"
  217. echo
  218. echo " git push REMOTE ${NEWBRANCHUNIQ}:${NEWBRANCH}"
  219. echo
  220. echo "where REMOTE is your personal fork (maybe ${UPSTREAM_REMOTE}? Consider swapping those.)."
  221. echo "OR consider setting UPSTREAM_REMOTE and FORK_REMOTE to different values."
  222. echo
  223. make-a-pr
  224. cleanbranch=""
  225. exit 0
  226. fi
  227. echo
  228. echo "+++ I'm about to do the following to push to GitHub (and I'm assuming ${FORK_REMOTE} is your personal fork):"
  229. echo
  230. echo " git push ${FORK_REMOTE} ${NEWBRANCHUNIQ}:${NEWBRANCH}"
  231. echo
  232. read -p "+++ Proceed (anything but 'y' aborts the cherry-pick)? [y/n] " -r
  233. if ! [[ "${REPLY}" =~ ^[yY]$ ]]; then
  234. echo "Aborting." >&2
  235. exit 1
  236. fi
  237. git push "${FORK_REMOTE}" -f "${NEWBRANCHUNIQ}:${NEWBRANCH}"
  238. make-a-pr