Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ A `fast-forward` merge refuses a pull request that still has merge commits, beca

## Rebasing a branch

`then: rebase` brings a pull request that has fallen behind its base up to date: its commits are replayed onto the base and pushed to its branch with a lease on the head that was read, so CI runs on the new head and a later run can merge it. It is a different effect from `linearise`, which removes merge commits: a branch that is both behind and holds merge commits is left alone by `rebase`, which says to linearise it first, since a rebase would drop those merge commits and any conflict resolved inside one. A rebase that conflicts pushes nothing and the run says the branch needs updating by hand. A fork's pull request is left alone, and the credential rules are those of `linearise`: `merge-token`, `app-id` or `ssh-key`, never `GITHUB_TOKEN`, with no `merge-method` or `update-behind`.
`then: rebase` brings a pull request that has fallen behind its base up to date: its commits are replayed onto the base and pushed to its branch with a lease on the head that was read, so CI runs on the new head and a later run can merge it. It is a different effect from `linearise`, which removes merge commits: a branch that is both behind and holds merge commits is left alone by `rebase`, which says to linearise it first, since a rebase would drop those merge commits and any conflict resolved inside one. A pull request whose head already contains its base is left alone, whatever the conditions say. A rebase that conflicts pushes nothing and the run says the branch needs updating by hand. A fork's pull request is left alone, and the credential rules are those of `linearise`: `merge-token`, `app-id` or `ssh-key`, never `GITHUB_TOKEN`, with no `merge-method` or `update-behind`.

What triggers it is a push to the base branch, which moves every open pull request's base and changes no pull request's head, so unlike the other effects it does not look for the pull requests that have the triggering commit at their head. It considers every open pull request, each at the head it has now, and the `when` lines decide which are rebased. `behind` is the condition that makes the run a no-op for those already up to date; `label` keeps it to the pull requests that opted in, and a `not-draft` line leaves drafts alone.

Expand Down Expand Up @@ -204,7 +204,7 @@ How the merge is made decides which credential you give. At most one of `merge-t

A deploy key is an SSH key and cannot call the API, so it only works with `fast-forward`. Use a credential other than `GITHUB_TOKEN` when the merge should start workflows (a release on `main`), because GitHub does not start workflows from pushes made with `GITHUB_TOKEN`. A protected base branch needs the credential's identity to be a bypass actor.

`fast-forward` fetches the pull request's head and pushes that exact commit to the base branch, which GitHub records as the pull request being merged. Because it is a push of existing commits, a pull request that is behind its base is not merged (the push is rejected) and is left for its author to update, unless `update-behind: true`: the action then rebases the head branch onto the base and pushes it back with a lease on the head it saw, so CI runs on the new head and a later run merges it. Fork pull requests and rebases that conflict are left alone.
`fast-forward` fetches the pull request's head and pushes that exact commit to the base branch, which GitHub records as the pull request being merged. Because it is a push of existing commits, a pull request that is behind its base is not merged (the push is rejected) and is left for its author to update, unless `update-behind: true`: the action then rebases the head branch onto the base and pushes it back with a lease on the head it saw, so CI runs on the new head and a later run merges it. Fork pull requests and rebases that conflict are left alone. A pull request counts as behind only when the base, fetched again after the rejected push, is not contained in its head; any other failed push fails the run with git's error. A fetch or push whose connection fails is tried up to three times in all, for every effect that uses git.

## Inputs

Expand Down
58 changes: 48 additions & 10 deletions merge.sh
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,35 @@ esac
owner="${REPO%%/*}"
name="${REPO##*/}"

# How many times a fetch or push is tried in all while its connection keeps failing, and the seconds waited before the second try, which each later wait grows by.
GIT_ATTEMPTS=3
GIT_RETRY_DELAY=5
# What ssh and git write when the connection failed, as opposed to the remote answering and refusing. "Could not read from remote repository" is not here, because a refused credential ends with it too.
transport_failure='Connection (closed|reset|refused|timed out)|Operation timed out|kex_exchange_identification|ssh: connect to host|Could not resolve host|Failed to connect to|Broken pipe|remote end hung up|early EOF|RPC failed|returned error: 5[0-9][0-9]|SSL_ERROR_SYSCALL|GnuTLS recv error'

# Runs a fetch or push in $work with the push credential, writing git's output to stderr. A transport failure is tried again, up to GIT_ATTEMPTS times in all, which is safe because a push that reached the remote before the connection failed is up to date when repeated. Returns git's status from the last try.
git_remote() {
local attempt=1 code output
while true; do
code=0
output=$(git -C "$work" ${git_auth[@]+"${git_auth[@]}"} "$@" 2>&1) || code=$?
[ -z "$output" ] || printf '%s\n' "$output" >&2
[ "$code" != 0 ] || return 0
{ [ "$attempt" -lt "$GIT_ATTEMPTS" ] && [[ "$output" =~ $transport_failure ]]; } || return "$code"
echo "git $1 lost its connection on try $attempt of $GIT_ATTEMPTS; trying again." >&2
sleep "$((attempt * GIT_RETRY_DELAY))"
attempt=$((attempt + 1))
done
}

# Returns 0 when commit $1 is an ancestor of commit $2 in $work and 1 when it is not. Any other answer from git settles neither, so it ends the run.
is_ancestor() {
local code=0
git -C "$work" merge-base --is-ancestor "$1" "$2" || code=$?
[ "$code" -le 1 ] || exit "$code"
return "$code"
}

# Sets $reason and returns 1 when a condition doesn't hold for pull request $2, whose JSON is $3.
holds() {
local condition="$1" number="$2" pr="$3" value
Expand Down Expand Up @@ -293,7 +322,7 @@ for number in $pulls; do
fi
work=$(mktemp -d)
git -C "$work" init -q
git -C "$work" ${git_auth[@]+"${git_auth[@]}"} fetch -q "$remote" "refs/pull/$number/head" "refs/heads/$base:refs/remotes/base"
git_remote fetch -q "$remote" "refs/pull/$number/head" "refs/heads/$base:refs/remotes/base"
if [ -z "$(git -C "$work" rev-list --merges "refs/remotes/base..$HEAD_SHA")" ]; then
echo "#$number has no merge commits."
else
Expand All @@ -302,7 +331,7 @@ for number in $pulls; do
git -C "$work" checkout -q --detach "$HEAD_SHA" &&
git -C "$work" -c user.name=github-actions[bot] -c user.email=github-actions[bot]@users.noreply.github.com rebase -q refs/remotes/base &&
[ "$(git -C "$work" rev-parse 'HEAD^{tree}')" = "$merged" ]; then
git -C "$work" ${git_auth[@]+"${git_auth[@]}"} push -q "$remote" "HEAD:refs/heads/$head_ref" "--force-with-lease=refs/heads/$head_ref:$HEAD_SHA"
git_remote push -q "$remote" "HEAD:refs/heads/$head_ref" "--force-with-lease=refs/heads/$head_ref:$HEAD_SHA"
echo "#$number had merge commits; rebased it onto $base, and CI will run on the new head."
else
git -C "$work" rebase --abort 2>/dev/null || true
Expand All @@ -322,14 +351,17 @@ for number in $pulls; do
fi
work=$(mktemp -d)
git -C "$work" init -q
git -C "$work" ${git_auth[@]+"${git_auth[@]}"} fetch -q "$remote" "refs/pull/$number/head" "refs/heads/$base:refs/remotes/base"
git_remote fetch -q "$remote" "refs/pull/$number/head" "refs/heads/$base:refs/remotes/base"
# A branch that contains its base would come out of a rebase unchanged, whether or not the conditions include behind.
if is_ancestor refs/remotes/base "$HEAD_SHA"; then
echo "#$number isn't behind $base."
# A rebase drops merge commits, and a conflict resolved inside one would be lost; linearise is the effect that proves nothing is.
if [ -n "$(git -C "$work" rev-list --merges "refs/remotes/base..$HEAD_SHA")" ]; then
elif [ -n "$(git -C "$work" rev-list --merges "refs/remotes/base..$HEAD_SHA")" ]; then
echo "#$number has merge commits, which a rebase would drop; linearise it first."
else
git -C "$work" checkout -q --detach "$HEAD_SHA"
if git -C "$work" -c user.name=github-actions[bot] -c user.email=github-actions[bot]@users.noreply.github.com rebase -q refs/remotes/base; then
git -C "$work" ${git_auth[@]+"${git_auth[@]}"} push -q "$remote" "HEAD:refs/heads/$head_ref" "--force-with-lease=refs/heads/$head_ref:$HEAD_SHA"
git_remote push -q "$remote" "HEAD:refs/heads/$head_ref" "--force-with-lease=refs/heads/$head_ref:$HEAD_SHA"
echo "#$number was behind $base; rebased it, and CI will run on the new head."
else
git -C "$work" rebase --abort 2>/dev/null || true
Expand All @@ -355,7 +387,7 @@ for number in $pulls; do
base=$(jq -r '.baseRefName' <<<"$pr")
work=$(mktemp -d)
git -C "$work" init -q
git -C "$work" ${git_auth[@]+"${git_auth[@]}"} fetch -q "$remote" "refs/pull/$number/head" "refs/heads/$base:refs/remotes/base"
git_remote fetch -q "$remote" "refs/pull/$number/head" "refs/heads/$base:refs/remotes/base"
# The push puts the head's own commits on the base branch, merge commits included, so they are kept only when allow-merge-commits says they belong there (a subtree merge, say, whose merge commit is the content a rebase would lose).
has_merge_commits=false
if [ -n "$(git -C "$work" rev-list --merges "refs/remotes/base..$HEAD_SHA")" ]; then
Expand All @@ -366,8 +398,14 @@ for number in $pulls; do
continue
fi
fi
if ! git -C "$work" ${git_auth[@]+"${git_auth[@]}"} push -q "$remote" "${HEAD_SHA}:refs/heads/$base"; then
if [ "${UPDATE_BEHIND-}" != true ]; then
if ! git_remote push -q "$remote" "${HEAD_SHA}:refs/heads/$base"; then
# A push fails for many reasons, so only the base as it is after the failure says whether this pull request is behind it.
git_remote fetch -q "$remote" "+refs/heads/$base:refs/remotes/base"
if is_ancestor "$HEAD_SHA" refs/remotes/base; then
echo "#$number's head is already on $base."
elif is_ancestor refs/remotes/base "$HEAD_SHA"; then
fail "#$number could not be pushed to $base, and it isn't behind $base; git's error is above."
elif [ "${UPDATE_BEHIND-}" != true ]; then
echo "#$number can't be fast-forwarded onto $base; it needs updating first."
elif [ "$(jq -r '.isCrossRepository' <<<"$pr")" = "true" ]; then
echo "#$number is behind $base but comes from a fork, so its branch can't be updated."
Expand All @@ -378,14 +416,14 @@ for number in $pulls; do
if [ "$has_merge_commits" = true ]; then
# A rebase drops merge commits, and with them the content a subtree merge brought, so the base is merged into the branch instead and the branch only grows.
if git -C "$work" "${identity[@]}" merge -q --no-edit refs/remotes/base; then
git -C "$work" ${git_auth[@]+"${git_auth[@]}"} push -q "$remote" "HEAD:refs/heads/$head_ref" "--force-with-lease=refs/heads/$head_ref:$HEAD_SHA"
git_remote push -q "$remote" "HEAD:refs/heads/$head_ref" "--force-with-lease=refs/heads/$head_ref:$HEAD_SHA"
echo "#$number was behind $base; merged $base into it, and CI will run on the new head."
else
git -C "$work" merge --abort
echo "#$number is behind $base and doesn't merge cleanly; it needs updating by hand."
fi
elif git -C "$work" "${identity[@]}" rebase -q refs/remotes/base; then
git -C "$work" ${git_auth[@]+"${git_auth[@]}"} push -q "$remote" "HEAD:refs/heads/$head_ref" "--force-with-lease=refs/heads/$head_ref:$HEAD_SHA"
git_remote push -q "$remote" "HEAD:refs/heads/$head_ref" "--force-with-lease=refs/heads/$head_ref:$HEAD_SHA"
echo "#$number was behind $base; rebased it, and CI will run on the new head."
else
git -C "$work" rebase --abort
Expand Down
26 changes: 22 additions & 4 deletions test/helpers.bash
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ setup() {
export GH_TOKEN=read REPO=o/r HEAD_SHA=abc THEN=merge MERGE_METHOD=rebase MERGE_TOKEN=write
export WHEN=$'label: automerge\ncheck: Required checks\nnot-draft\nthreads-resolved'
unset SSH_KEY UPDATE_BEHIND ALLOW_MERGE_COMMITS RERUN_LOST_RUNNERS RUN_ID
unset BASE_MOVED HEAD_ON_BASE ANCESTRY_FAILS PUSH_ERROR PUSH_ERROR_TIMES FETCH_ERROR FETCH_ERROR_TIMES
export GITHUB_STEP_SUMMARY="$BATS_TEST_TMPDIR/summary"
: >"$GITHUB_STEP_SUMMARY"
}
Expand Down Expand Up @@ -43,27 +44,44 @@ case "$1 $2" in
*) echo "unexpected gh call: $*" >&2; exit 99 ;;
esac
STUB
# Records pushes, and fails a push onto the base branch when PUSH_FAILS is set, as a moved base would.
# Records pushes. BASE_MOVED makes the base hold commits the head lacks, so a push onto it is rejected as GitHub would; HEAD_ON_BASE makes the base already contain the head. PUSH_ERROR and FETCH_ERROR fail that command with the given stderr, every time or only the first PUSH_ERROR_TIMES or FETCH_ERROR_TIMES times.
cat >"$STUB_DIR/git" <<'STUB'
#!/usr/bin/env bash
shift 2 # -C <dir>
while [ "$1" = -c ]; do
case "$2" in http.extraheader=*) echo "auth $2" >>"$MERGE_LOG" ;; esac
shift 2
done
# Fails with stderr $2 while the command $1 has been tried no more than $3 times (always, when $3 is empty).
injected() {
[ -n "$2" ] || return 0
echo "attempt $1" >>"$MERGE_LOG"
if [ -z "$3" ] || [ "$(grep -c "^attempt $1\$" "$MERGE_LOG")" -le "$3" ]; then
printf '%s\nfatal: Could not read from remote repository.\n' "$2" >&2
exit 128
fi
}
case "$1" in
init | fetch | checkout) ;;
init | checkout) ;;
fetch) injected fetch "${FETCH_ERROR-}" "${FETCH_ERROR_TIMES-}" ;;
rev-list) if [ -n "${MERGE_COMMITS-}" ]; then echo "$MERGE_COMMITS"; fi ;;
merge-base)
if [ -n "${ANCESTRY_FAILS-}" ]; then echo "fatal: Not a valid commit name" >&2; exit 128; fi
if [ "$3" = refs/remotes/base ]; then [ -z "${BASE_MOVED-}" ] || exit 1; else [ -n "${HEAD_ON_BASE-}" ] || exit 1; fi
;;
merge-tree) if [ -n "${MERGE_TREE_FAILS-}" ]; then exit 1; fi; echo "${MERGE_TREE-tree1}" ;;
rev-parse) echo "${REBASED_TREE-tree1}" ;;
rebase) if [ -n "${REBASE_FAILS-}" ] && [ "$2" != --abort ]; then exit 1; fi ;;
merge) echo "merge ${*:2}" >>"$MERGE_LOG"; if [ -n "${MERGE_FAILS-}" ] && [ "$2" != --abort ]; then exit 1; fi ;;
push)
case "$*" in *refs/heads/main) if [ -n "${PUSH_FAILS-}" ]; then exit 1; fi ;; esac
injected push "${PUSH_ERROR-}" "${PUSH_ERROR_TIMES-}"
case "$*" in *refs/heads/main) if [ -n "${BASE_MOVED-}" ]; then echo " ! [rejected] abc -> main (non-fast-forward)" >&2; exit 1; fi ;; esac
echo "push ${*:3}" >>"$MERGE_LOG"
;;
*) echo "unexpected git call: $*" >&2; exit 99 ;;
esac
STUB
chmod +x "$STUB_DIR/gh" "$STUB_DIR/git"
# The waits between transport attempts take no time here.
printf '#!/usr/bin/env bash\n' >"$STUB_DIR/sleep"
chmod +x "$STUB_DIR/gh" "$STUB_DIR/git" "$STUB_DIR/sleep"
}
14 changes: 7 additions & 7 deletions test/methods.bats
Original file line number Diff line number Diff line change
Expand Up @@ -65,29 +65,29 @@ run_merge() { run "$BATS_TEST_DIRNAME/../merge.sh"; }
}

@test "fast-forward onto a moved base leaves the pull request alone" {
MERGE_METHOD=fast-forward PUSH_FAILS=1 run_merge
MERGE_METHOD=fast-forward BASE_MOVED=1 run_merge
assert_success
assert_output --partial "needs updating first"
run cat "$MERGE_LOG"
refute_output --partial "push "
}

@test "update-behind rebases and pushes the head branch with a lease" {
MERGE_METHOD=fast-forward PUSH_FAILS=1 UPDATE_BEHIND=true run_merge
MERGE_METHOD=fast-forward BASE_MOVED=1 UPDATE_BEHIND=true run_merge
assert_output --partial "rebased it"
run cat "$MERGE_LOG"
assert_output --partial "HEAD:refs/heads/topic --force-with-lease=refs/heads/topic:abc"
}

@test "update-behind leaves a fork alone" {
MERGE_METHOD=fast-forward PUSH_FAILS=1 UPDATE_BEHIND=true PR_FORK=true run_merge
MERGE_METHOD=fast-forward BASE_MOVED=1 UPDATE_BEHIND=true PR_FORK=true run_merge
assert_output --partial "comes from a fork"
run cat "$MERGE_LOG"
refute_output --partial "push "
}

@test "update-behind pushes nothing when the rebase conflicts" {
MERGE_METHOD=fast-forward PUSH_FAILS=1 UPDATE_BEHIND=true REBASE_FAILS=1 run_merge
MERGE_METHOD=fast-forward BASE_MOVED=1 UPDATE_BEHIND=true REBASE_FAILS=1 run_merge
assert_output --partial "doesn't rebase cleanly"
run cat "$MERGE_LOG"
refute_output --partial "push "
Expand All @@ -109,7 +109,7 @@ run_merge() { run "$BATS_TEST_DIRNAME/../merge.sh"; }
}

@test "allow-merge-commits merges the base into a behind pull request instead of rebasing it" {
MERGE_METHOD=fast-forward MERGE_COMMITS=m1 ALLOW_MERGE_COMMITS=true PUSH_FAILS=1 UPDATE_BEHIND=true run_merge
MERGE_METHOD=fast-forward MERGE_COMMITS=m1 ALLOW_MERGE_COMMITS=true BASE_MOVED=1 UPDATE_BEHIND=true run_merge
assert_success
assert_output --partial "merged main into it"
run cat "$MERGE_LOG"
Expand All @@ -118,15 +118,15 @@ run_merge() { run "$BATS_TEST_DIRNAME/../merge.sh"; }
}

@test "allow-merge-commits pushes nothing when the base does not merge cleanly" {
MERGE_METHOD=fast-forward MERGE_COMMITS=m1 ALLOW_MERGE_COMMITS=true PUSH_FAILS=1 UPDATE_BEHIND=true MERGE_FAILS=1 run_merge
MERGE_METHOD=fast-forward MERGE_COMMITS=m1 ALLOW_MERGE_COMMITS=true BASE_MOVED=1 UPDATE_BEHIND=true MERGE_FAILS=1 run_merge
assert_success
assert_output --partial "doesn't merge cleanly"
run cat "$MERGE_LOG"
refute_output --partial "push "
}

@test "update-behind still rebases a pull request without merge commits when merge commits are allowed" {
MERGE_METHOD=fast-forward ALLOW_MERGE_COMMITS=true PUSH_FAILS=1 UPDATE_BEHIND=true run_merge
MERGE_METHOD=fast-forward ALLOW_MERGE_COMMITS=true BASE_MOVED=1 UPDATE_BEHIND=true run_merge
assert_output --partial "rebased it"
run cat "$MERGE_LOG"
refute_output --partial "merge -q"
Expand Down
12 changes: 11 additions & 1 deletion test/rebase.bats
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ run_merge() { run "$BATS_TEST_DIRNAME/../merge.sh"; }

# The pull request is behind its base and carries the label unless a test says otherwise; credentials are an ssh-key because rebase takes no merge method.
setup_rebase() {
export THEN=rebase MERGE_METHOD= MERGE_TOKEN= SSH_KEY=key BEHIND_BY=2 HEAD_SHA=
export THEN=rebase MERGE_METHOD= MERGE_TOKEN= SSH_KEY=key BEHIND_BY=2 HEAD_SHA= BASE_MOVED=1
export WHEN=$'label: automerge\nbehind'
}

Expand Down Expand Up @@ -106,3 +106,13 @@ setup_rebase() {
assert_failure
assert_output --partial "update-behind is only used by then: merge"
}

@test "rebase reports no rebase for a branch that already contains its base" {
setup_rebase
BASE_MOVED= WHEN="label: automerge" run_merge
assert_success
assert_output --partial "#7 isn't behind main"
refute_output --partial "rebased it"
run cat "$MERGE_LOG"
refute_output --partial "push "
}
Loading
Loading