0

Create Branch

by
Published today

Create a branch from the head of from_branch (the repository's default branch when empty).

Script github Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 1 hour ago
1
//native
2

3
/**
4
 * Create Branch
5
 * Create a branch from the head of from_branch (the repository's default branch when empty).
6
 */
7
export async function main(
8
  auth: RT.Github,
9
  owner: string,
10
  repo: string,
11
  branch: string,
12
  from_branch: string | undefined
13
) {
14
  const headers = {
15
    Authorization: `Bearer ${auth.token}`,
16
    Accept: "application/vnd.github+json",
17
    "X-GitHub-Api-Version": "2022-11-28",
18
  }
19
  const base = `https://api.github.com/repos/${owner}/${repo}`
20

21
  if (!from_branch) {
22
    const r = await fetch(base, { headers })
23
    if (!r.ok) throw new Error(`${r.status} ${await r.text()}`)
24
    from_branch = ((await r.json()) as { default_branch: string })
25
      .default_branch
26
  }
27
  const ref = await fetch(`${base}/git/ref/heads/${from_branch}`, { headers })
28
  if (!ref.ok) throw new Error(`${ref.status} ${await ref.text()}`)
29
  const { object } = (await ref.json()) as { object: { sha: string } }
30

31
  const response = await fetch(`${base}/git/refs`, {
32
    method: "POST",
33
    headers: { ...headers, "Content-Type": "application/json" },
34
    body: JSON.stringify({ ref: `refs/heads/${branch}`, sha: object.sha }),
35
  })
36

37
  if (!response.ok) {
38
    throw new Error(`${response.status} ${await response.text()}`)
39
  }
40

41
  return await response.json()
42
}
43