-
Notifications
You must be signed in to change notification settings - Fork 1
/
git-pr-merge
executable file
·557 lines (483 loc) · 17.4 KB
/
git-pr-merge
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
#!/bin/bash
#
# Merge and update branches for GitHub Pull Requests (PRs).
#
# Usage: git <pr-merge|pr-update>
#
# git pr-merge
# ------------
# Merge the current "feature" branch into the base "master" branch and push
# to GitHub, closing the PR.
#
# Alternatively, merge a PR by number with `-p NN` into the base "master"
# branch and push to GitHub.
#
# GitHub allows you to push a merge commit on a branch even when that branch is
# protected, if that commit is the result of merging a PR and that PR is
# suitable to be merged (all required checks have been satisfied, the required
# number of approvals are present, the branch is up-to-date WRT the target
# branch, etc). This feature allows you to operate from the command line
# instead of needing to use the GitHub web-ui to merge and close a PR.
#
# git pr-update
# -------------
# Update the current "feature" branch by merging the base "master" branch
# into it, ready for merging with "git pr-merge".
#
# If you have "Require branches to be up-to-date" on branch protection, you
# cannot merge a PR if the base "master" branch has moved on from where the
# feature branch was branched from master. The GitHub UI has an "Update Branch"
# button that merges master into the branch, which gets it up-to-date from the
# base branch, but the merge commit added to the branch is a "back merge". If
# that is fast-forward merged into master, you end up with a "foxtrot" merge
# where the first parent is the feature branch, not the master branch, breaking
# `git log --first-parent`. If you do a merge commit back into master, you end
# up with merges going back and forth between master and feature branches,
# making a mess of your history. Neither is ideal.
#
# When run as "git pr-update", this script will create a merge commit from
# master on the head of the feature branch, but that commit will have the
# correct order of parents and a complete merge commit message such that it
# can be fast-forward merged into master. This will allow CI to run on the
# result of merging master as the branch will be up-to-date, but no foxtrot
# or criss-cross merges will occur. If the head commit is already a merge
# commit from this script, it will be removed before re-merging so as to
# not have a bunch of unnecessary merges.
#
# Requirements
# ------------
# This scripts relies on the github `gh` tool to retrieve information about
# the merge branch PR. It will fail if not installed. Install it from
# https://github.com/cli/cli.
main() {
set -e
set -u
set -o pipefail
shopt -s extglob
case "${0##*/}" in
git-pr-merge)
prmerge "$@"
;;
git-pr-update)
prupdate "$@"
;;
*)
printf 'Unknown command name: %s\n' "$0" >&2
exit 1
;;
esac
}
prmerge::usage() {
cat <<EOF
Usage: ${0##*/} {<options>...}
-m Merge PR with a merge commit (overrides git-config)
-p NN Merge PR <NN> instead of the current branch
-s Merge PR with a squash merge (overrides git-config)
${0##*/} merges the current branch's GitHub pull request (PR) to the
base branch of the PR, or the PR specified with "-p NN", using the PR
description as the merge commit message along with a diff stat and a
one-line log of the commits in the PR. The markdown in the PR
description is cleaned up a little to be more suitable for a git commit
message.
By default a merge commit is created, but the PR can be squash-merged
by running with "-s" or by setting the git comfig setting:
git config pr.merge.squash true
You can have single commit PRs squash merged and multi-commit PRs merged
with a merge commit by setting the git config setting:
git config pr.merge.squash-singles true
The title of the merge commit can have a prefix prepended to the title,
which by default is "✨ ". It can be overridden by a git config setting:
git config pr.merge.title-prefix ''
After merging, the PR branch is automatically deleted both locally and on the
remote. This can be changed with the git config setting:
git config pr.merge.delete-remote-branch false
EOF
}
prmerge() {
args=()
common::read_config
prmerge::parse_args "$@"
common::setup ${args[@]+"${args[@]}"}
prmerge::prepare
prmerge::merge
prmerge::clean
}
prupdate() {
common::read_config
common::setup "$@"
prupdate::prepare
prupdate::update
}
# Read the config variables used by this script. For example, set them with:
# git config pr.merge.title-prefix ''
# git config pr.merge.delete-remote-branch false
# git config --global pr.merge.sleep-time-before-delete 10
# git config pr.merge.squash true
# git config pr.merge.squash-singles true
title_prefix='✨ '
cli_pr_num=''
delete_remote_branch='true'
sleep_time_before_delete='15'
squash_merge='false'
squash_singles='false'
common::read_config() {
common::get_config title_prefix title-prefix
common::get_config delete_remote_branch delete-remote-branch
common::get_config sleep_time_before_delete sleep-time-before-delete
common::get_config squash_merge squash
common::get_config squash_singles squash-singles
}
prmerge::parse_args() {
OPTSTRING=':hmp:s'
while getopts "${OPTSTRING}" opt; do
case "${opt}" in
h)
prmerge::usage
exit 0
;;
m)
squash_merge='false'
;;
p)
cli_pr_num="${OPTARG}"
;;
s)
squash_merge='true'
;;
\?)
printf 'Invalid option: -%s\n\n' "${OPTARG}" >&2
usage >&2
exit 1
;;
:)
printf 'Option -%s requires an argument\n\n' "${OPTARG}" >&2
usage >&2
exit 1
;;
esac
done
shift $((OPTIND - 1))
args=("$@")
}
common::setup() {
if ! command -v gh >/dev/null; then
printf 'You need to install gh (https://github.com/cli/cli)\n' >&2
return 1
fi
# If called with a PR number, check out that PR using `gh`. This is used
# when merging someone elses PR (either from a fork or you just dont have
# the local branch).
if [[ -n "${cli_pr_num}" ]]; then
if ! gh pr checkout "${cli_pr_num}"; then
printf 'Could not checkout PR#%s\n' "${cli_pr_num}"
return 1
fi
fi
if ! feature=$(git symbolic-ref --short --quiet HEAD); then
printf 'Not on a branch. Ignoring.\n' >&2
return 1
fi
if [[ -n "${cli_pr_num}" ]]; then
pr_ref="${cli_pr_num}"
else
pr_ref="${feature}"
fi
if ! master=$(gh pr view --json baseRefName --jq .baseRefName "${pr_ref}"); then
printf 'Cannot get base branch for pull request. Is there a PR?\n' >&2
return 1
fi
pr_num="$(gh pr view --json number --jq .number "${pr_ref}")"
if [[ "${squash_singles}" == 'true' && "${squash_merge}" == 'false' ]]; then
if [[ "$(git rev-list --count "${feature}" "^${master}" --)" == 1 ]]; then
squash_merge=true
fi
fi
}
common::prepare() {
# cd to root of repo as master may not contain CWD, but switch back
# when we're done.
# shellcheck disable=SC2064
# We want to evaluate $(pwd) now and not later.
trap "cd \"$(pwd)\"" EXIT
cd "$(git rev-parse --show-toplevel)"
# Fetch from all remotes so we can check if local branch is up-to-date
git remote update >/dev/null
}
prmerge::prepare() {
common::prepare
local do_pull=false
if [[ "$(git rev-parse "${master}")" != "$(git rev-parse "${master}@{upstream}")" ]]; then
printf '\n%s is not up-to-date. To update, press enter (^C to abort):' "${master}"
read -r
do_pull=true
fi
git switch --quiet "${master}"
if "${do_pull}"; then
git pull
if ! git merge-base --is-ancestor "${master}" "${feature}"; then
# If we are merging via PR number and not a local branch, delete the branch we
# created with `gh pr checkout` earlier. This will leave us on master.
if [[ -n "${cli_pr_num}" ]]; then
git branch --delete "${feature}"
else
git switch "${feature}"
fi
printf 'Local %s is not up-to-date. Update %s before merging\n' "${master}" "${feature}"
exit 1
fi
fi
}
prupdate::prepare() {
common::prepare
if git merge-base --is-ancestor "${master}@{upstream}" "${feature}"; then
printf 'Already up to date\n'
exit 0
fi
# If we create an update-merge and push that to the feature branch, GitHub
# shows the commits from master as well as the feature branch on the PR.
# It also removes any approval which may have been grated. This defeats the
# purpose of pushing an update merge - the point is to retain approval.
#
# Through experimentation, we have determined that if you push a foxtrot
# update merge, GitHub updates the PRs base.sha field, which is what is
# necessary to not have GitHub show the commits on master on the PR. You
# can then remove that merge commit and force push it, which leaves the
# base.sha updated, and it does not remove approval. The PR/branch is
# then read to receive a proper update merge commit successfully.
#
# If the head commit on the branch is an update merge we have previously
# put there, prepare the branch by removing it, so there is only ever one
# merge commit on the branch. Otherwise, perform the steps described above
# (push and remove a foxtrot update merge), so we can push a proper
# update merge without dropping approval on the PR.
read -ra parents < <(git show --no-patch --format='%P' "${feature}" --)
if ((${#parents[@]} == 2)) && git merge-base --is-ancestor "${master}" "${parents[0]}"; then
printf '\nHEAD looks to be a previous git-pr-update merge commit.\n'
read -r -p 'Will first undo this (reset, force-push). Press enter (^C to abort):'
printf '\nRemoving previous update merge\n'
git reset --hard @^2
else
printf '\nCreating bogus foxtrot merge\n'
git merge --no-edit --no-ff "${master}@{upstream}"
printf '\nPushing bogus foxtrot merge\n'
git push
printf '\nRemoving bogus foxtrot merge\n'
git reset --hard @^1
fi
printf '\nForce pushing merge removal\n'
git push --force
}
prmerge::merge() {
if "${squash_merge}"; then
prmerge::squash_merge
else
prmerge::local_merge
fi
}
prmerge::local_merge() {
echo merging "${feature}" to "${master}"
#open 'https://gist.github.com/rxaviers/7360908'
#open 'https://gitmoji.carloscuesta.me'
# If the feature branch has been updated with git-pr-update, then the head
# of the feature branch will be a merge commit that has the master branch
# as the first parent. In that case, just fast-forward merge instead of
# creating a merge commit.
read -ra parents < <(git show --no-patch --format='%P' "${feature}" --)
master_hash=$(git rev-parse "${master}")
if ((${#parents[@]} == 2)) && [[ "${parents[0]}" == "${master_hash}" ]]; then
git merge --ff --no-edit "${feature}"
else
merge_message="$(common::merge_message "${feature}" "${master}" "${pr_ref}")"
if ! git merge --edit --no-ff -m "${merge_message}" "${feature}"; then
printf 'merge aborted\n' >&2
git merge --abort
git switch --quiet "${feature}"
return 1
fi
fi
# Pushing the merge commit will merge the PR with a merge commit, both
# for local changes and PRs of forked repos when merged by PR num
# (-p flag).
git push
}
prmerge::squash_merge() {
echo squash merging "${feature}" to "${master}"
commit_msg_file=$(mktemp "git-prmerge.${pr_num}.XXXXXXXXX")
# shellcheck disable=SC2064
trap "rm ${commit_msg_file}" EXIT
common::merge_message "${feature}" "${master}" "${pr_ref}" >"${commit_msg_file}"
common::editor "${commit_msg_file}"
if ! grep -E -q -v -e '^[[:space:]]*(#|$)' "${commit_msg_file}"; then
printf 'no commit message. merge aborted\n'
git switch --quiet "${feature}"
return 1
fi
local commit_title commit_message
commit_title=$(grep -v '^[[:space:]]*#' "${commit_msg_file}" | head -n 1)
commit_message=$(grep -v '^[[:space:]]*#' "${commit_msg_file}" | tail -n +3)
local result
if ! result=$(
gh api "repos/{owner}/{repo}/pulls/${pr_num}/merge" \
--method PUT \
--header 'Accept: application/vnd.github.v3+json' \
--raw-field "commit_title=${commit_title}" \
--raw-field "commit_message=${commit_message}"$'\n' \
--raw-field "sha=$(git rev-parse "${feature}")" \
--raw-field "merge_method=squash"
); then
jq --raw-output .message <<<"${result}"
git switch --quiet "${feature}"
return 1
fi
# Fetch the new merge commit
git pull
}
prupdate::update() {
echo updating "${feature}" from "${master}"
# Create a temporary branch from ${master} so we can merge the
# feature branch into it.
local tmpmaster="prupdate/${feature}"
git branch --force "${tmpmaster}" "${master}@{upstream}"
git switch --quiet "${tmpmaster}"
merge_message="$(common::merge_message "${feature}" "${tmpmaster}" "${pr_ref}")"
if ! git merge --edit --no-ff -m "${merge_message}" "${feature}"; then
printf 'merge aborted\n' >&2
git merge --abort
git switch --quiet "${feature}"
git branch --delete --force "${tmpmaster}"
return 1
fi
# reset feature branch to updated feature branch
git switch --quiet "${feature}"
git reset --hard "${tmpmaster}"
git branch --delete --force "${tmpmaster}"
git push
}
prmerge::clean() {
# Feature branches need to be force-deleted after a squash merge as they
# appear unmerged locally. So just always force delete.
git branch --delete --force "${feature}"
if remote=$(git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null); then
remote=${remote%%/*} # strip off branch name
else
remote='origin' # default if tracking not set
fi
# Allow a delay before deleting the remote branch as some syncing programs
# try to sync the merge commit and the branch deletion in parallel, leaving
# one to fail, mucking up the github status. This delay is also used to wait
# before pruning remote branches as automatic delete on merge does not
# usually happen immediately.
if ((sleep_time_before_delete > 0)); then
printf 'Waiting before deleting/pruning remote branch (%s)...\n' "${sleep_time_before_delete}"
sleep "${sleep_time_before_delete}"
fi
local autodelete
autodelete=$(gh repo view --json deleteBranchOnMerge --jq .deleteBranchOnMerge)
if [[ "${delete_remote_branch}" == 'true' ]] && [[ "${autodelete}" == 'false' ]]; then
if ! git push "${remote}" --delete "${feature}"; then
echo 'Perhaps GitHub already deleted the branch? Disable deletion with:'
echo 'git config pr.merge.delete-remote-branch false'
fi
else
# Assume the remote branch is automatically deleted. Prune remote refs.
git remote prune "${remote}"
fi
}
common::get_config() {
local var="$1" name="$2"
local val
if val=$(git config --get pr.merge."${name}"); then
eval "${var}='${val}'"
fi
}
common::editor() {
local e
if ! e=$(git config --get core.editor); then
e=${VISUAL:-${EDITOR:-vi}}
fi
$e "$@"
}
common::merge_message() {
local from_branch="$1"
local to_branch="$2"
local pr_ref="$3"
# Create default merge log message by making a title prefix (from config),
# title from the PR title and the PR number, then adding a short log of
# what is being merged and add a diff stat of the files changed by the merge.
# Get the PR body to be the commit message. Remove any trailers so we
# can re-add them after the log and diff-stat along with our own
# Pull-request: trailer.
local body trailers title pr_url
title="$(gh pr view --json title --jq .title "${pr_ref}")"
body=$(gh pr view --json body --jq .body "${pr_ref}" | tr -d '\015')
body=$(awk "${markdown_for_commit_awk}" <<<"${body}") # clean up markdown for readability
body="${body%%*($'\n')}" # strip trailing newlines.
trailers=$(git interpret-trailers --parse <<<"${body}")
body="${body%%*($'\n')"${trailers}"}" # strip trailers and preceding newlines
pr_url="$(gh pr view --json url --jq .url "${pr_ref}")"
cat <<EOF
${title_prefix}${title} (#${pr_num})
${body}
EOF
# Don't include the commit titles or diff stat if squash merging - it doesn't
# make sense, because usually there are fixup commits with irrelevant titles
# and the diff stat can be easily shown with `git log --stat=72 ...`.
if ! "${squash_merge}"; then
cat <<EOF
This merges the following commits:
$(git log --reverse --pretty=tformat:"* %s" "${to_branch}..${from_branch}")
$(git diff --no-color --stat=72 "${to_branch}...${from_branch}" | sed 's/^/ /')
EOF
fi
# Put a newline ahead of $trailers only if it is non-empty, otherwise we end
# up with two newlines in the empty trailers case.
trailers="${trailers:+$'\n'${trailers}}"
cat <<EOF
${trailers}
Pull-request: ${pr_url}
# Gitmoji: https://gitmoji.carloscuesta.me
# rxaviers list: https://gist.github.com/rxaviers/7360908
#
EOF
}
# shellcheck disable=SC2016
# We don't want to expand shell expressions (it's awk!), so single quotes.
markdown_for_commit_awk='
# print_heading converts a heading starting with a hash to one with an
# underline, as a line starting with a hash in a git commit message is
# ignored.
function print_heading(line)
{
level1heading = match(line, /^# /) != 0
sub(/^##* /, "", line)
marker = level1heading ? "=" : "-"
printf("%s\n", line)
for (i = 0; i < length(line); i++)
printf marker
printf "\n"
}
# If there is a triple dash line --- preceded by a blank line, throw
# it out and everything after it. These are reviewer notes and do not
# go into the commit message.
/^---$/ && last_blank { exit }
# If we want a blank and the current line is not blank, inject a blank line.
/\S/ && want_blank { print "" }
{ want_blank = 0 }
# Lines starting with one or more hashes, followed by a space and one more
# char at least are headings. Convert to underline headings.
/^##* .+/ { print_heading($0); next }
# Convert triple-backtick code blocks to indented code blocks. Ensure there
# is a blank line before and after the block, but dont add extra unnecessary
# blank lines.
/^\s*```/ {
in_code_block = !in_code_block
want_blank = !last_blank
next
}
# Print other lines, indenting code blocks
{
last_blank = (gsub(/^\s*$/, "") > 0)
printf("%s%s\n", in_code_block ? " " : "", $0)
}'
# Only run main if executed as a script and not sourced.
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then main "$@"; fi