#!/bin/bash

# machete-post-slide-out hook is invoked by 'git machete slide-out' and 'git machete traverse' after a branch
# (or possibly multiple branches, in case of 'slide-out') of are slid out.

# This sample retargets all GitHub PRs (using 'hub' CLI and GitHub API - authorizing with the token from ~/.config/hub)
# corresponding to the children of the slid-out branch.

# Note: since around May 2020, GitHub automatically retargets a PR Z->Y to Z->X once any PR Y->X (for some X) is merged.
# It obviously won't automatically retarget PR Z->Y to Z->X, however, when Y is slid out locally without any PR Y->X getting merged.

[[ -n "$1" || -n "$2" ]] || { echo "usage: $(basename "$0") <new-upstream> <slid-out-branch> [<new-downstreams>...]"; exit 1; }

set -e

new_downstreams=("${@:3}")

for new_downstream in "${new_downstreams[@]}"; do
  git machete github retarget-pr --branch="$new_downstream" --ignore-if-missing
done
