Create Branch

Create a new branch in a Github repo. [See docs here](https://docs.github.com/en/rest/git/refs?apiVersion=2022-11-28#create-a-reference)

Script github Verified

by hugo697 ยท 8/26/2024

The script

Submitted by hugo697 Bun
Verified 620 days ago
1
import { Octokit } from 'octokit'
2

3
type Github = {
4
	token: string
5
}
6

7
export async function main(
8
	resource: Github,
9
	owner: string,
10
	repo: string,
11
	sourceBranchName: string,
12
	newBranchName: string
13
) {
14
	// setup auth
15
	const octokit = new Octokit({
16
		auth: resource.token
17
	})
18

19
	// get sha of source branch
20
	const { data: sourceBranch } = await octokit.rest.repos.getBranch({
21
		branch: sourceBranchName,
22
		repo,
23
		owner
24
	})
25
	const sha = sourceBranch.commit.sha
26

27
	// create new branch
28
	const response = await octokit.rest.git.createRef({
29
		owner,
30
		repo,
31
		ref: `refs/heads/${newBranchName}`,
32
		sha
33
	})
34

35
	return response.data
36
}
37