summaryrefslogtreecommitdiff
path: root/zsh/bitbucket.sh
blob: 97ad6a687dfcb2edfcc251b7b94ccc2d50710298 (plain)
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
# run this after adding one or more commits on target branch (e.g. develop)

# creates temp branch
# pushes it
# makes a PR
# merges a PR
# switches back to target branch
# deletes temp branch
bpush () {
	# PR title is the latest commit message
	local title
	title=$(git log -1 --pretty=%s)

	# save destination branch to go back to it after we're done
	local dest
	dest=$(git branch --show-current)

	# create and push source branch
	local src="temp"
	git switch -c "$src"
	git push # make sure the branch is on remote

	local slug
	# the string between last slash and .git
	slug=$(git remote get-url origin | sed 's|.*/\(.*\)\.git$|\1|')

	local pr_create_request
	pr_create_request=$(jq -nc --arg src "$src" --arg dest "$dest" --arg title "$title" '{
		reviewers: [],
		title: $title,
		source: {branch: {name: $src}},
		destination: {branch: {name: $dest}}
	}')

	# create a PR
	local api_url_pr_create="https://api.bitbucket.org/2.0/repositories/grapecity/$slug/pullrequests"
	local pr_create_response
	pr_create_response=$(curl -X POST "$api_url_pr_create" --fail-with-body -u "$BB_AUTH" --header 'Content-Type: application/json' --data "$pr_create_request") || {
		exit_code=$?
		echo "$pr_create_response" | jq
		return $exit_code
	}
	local pr_id
	pr_id=$(echo "$pr_create_response" | jq -r '.id')
	echo -e "PR CREATED: \e[4mhttps://bitbucket.org/grapecity/$slug/pull-requests/$pr_id\e[0m"

	local pr_merge_request
	pr_merge_request=$(jq -nc --arg src "$src" --arg dest "$dest" --arg title "$title" '{
		type: "pullrequest",
		merge_strategy: "fast_forward",
		close_source_branch: true,
	}')

	# merge a PR
	local api_url_pr_merge="https://api.bitbucket.org/2.0/repositories/grapecity/$slug/pullrequests/$pr_id/merge"
	local pr_merge_response
	pr_merge_response=$(curl -X POST "$api_url_pr_merge" --fail-with-body -u "$BB_AUTH" --header 'Content-Type: application/json' --data "$pr_merge_request") || {
		exit_code=$?
		echo "$pr_merge_response" | jq
		return $exit_code
	}
	echo "PR MERGED"

	# switch back to destination branch, pull the changes
	git switch "$dest"
	git pull
	# remove source/temp branch
	git branch -d "$src"

}