-
Notifications
You must be signed in to change notification settings - Fork 1
/
git-create-pr
executable file
·89 lines (66 loc) · 2.38 KB
/
git-create-pr
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
#!/bin/bash
set -ex
function usage() {
bold=$(tput bold)
normal=$(tput sgr0)
cat << EOF
${bold}NAME${normal}
git-create-pr - Create a pull request from current branch
${bold}SYNOPSIS${normal}
git create-pr
${bold}Usage: git create-pr [--help]${normal}
Create a pull request for the current branch in the terminal.
${bold}Options:${normal}
--help Display this help message and exit.
This script performs the following actions:
1. Ensures the current branch is up-to-date with the upstream default branch (target branch).
2. Automatically determines the name of the remote (e.g., "origin").
3. Automatically determines the remote default branch (target branch) for which to create the pull request.
4. Uses the first commit on the branch as the pull request title and description without opening an editor.
EOF
}
# actually parse the options and do stuff
while [[ $1 = -?* ]]; do
case $1 in
-h|--help)
usage
exit 0
;;
*) ;;
esac
shift
done
# Check if hub is installed
if ! command -v hub >/dev/null 2>&1; then
echo "Error: 'hub' command not found. Please install 'hub' first."
exit 1
fi
# Get the current branch name
current_branch="$(git rev-parse --abbrev-ref HEAD)"
remote_name="origin"
# Get the remote URL
remote_url="$(git remote get-url "$remote_name")"
# Regex pattern to extract org/repo from a URL such as git@example.com:org/repo.git
pattern='[.:\/]([[:alnum:]_-]+\/[[:alnum:]_-]+)\.git'
# Extract org/repo using regex
if [[ $remote_url =~ $pattern ]]; then
upstream_repo="${BASH_REMATCH[1]}"
else
# exit on error
echo "Error: Could not extract org/repo from remote URL: $remote_url"
exit 1
fi
# Get the remote default branch (target branch)
upstream_default_branch="$(hub api "repos/$upstream_repo" | jq -r '.default_branch')"
# Exit with error if upstream_default_branch is empty
if [ -z "$upstream_default_branch" ]; then
echo "Error: Could not get the default branch for $upstream_repo"
exit 1
fi
# Ensure the current branch is up-to-date with the upstream default branch (target branch)
git fetch "$remote_name" "$upstream_default_branch"
git rebase "$remote_name/$upstream_default_branch"
# Push the current branch to the remote repository
git push -u "$remote_name" "$current_branch"
# Create a pull request using 'hub pull-request' against the remote default branch
hub pull-request --no-edit -b "$upstream_default_branch"