Create a tree

The tree creation API accepts nested entries.

Script github Verified

by hugo697 ยท 10/25/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 366 days ago
1
type Github = {
2
  token: string;
3
};
4
/**
5
 * Create a tree
6
 * The tree creation API accepts nested entries.
7
 */
8
export async function main(
9
  auth: Github,
10
  owner: string,
11
  repo: string,
12
  body: {
13
    base_tree?: string;
14
    tree: {
15
      content?: string;
16
      mode?: "100644" | "100755" | "040000" | "160000" | "120000";
17
      path?: string;
18
      sha?: string;
19
      type?: "blob" | "tree" | "commit";
20
      [k: string]: unknown;
21
    }[];
22
    [k: string]: unknown;
23
  }
24
) {
25
  const url = new URL(
26
    `https://api.github.com/repos/${owner}/${repo}/git/trees`
27
  );
28

29
  const response = await fetch(url, {
30
    method: "POST",
31
    headers: {
32
      "Content-Type": "application/json",
33
      Authorization: "Bearer " + auth.token,
34
    },
35
    body: JSON.stringify(body),
36
  });
37
  if (!response.ok) {
38
    const text = await response.text();
39
    throw new Error(`${response.status} ${text}`);
40
  }
41
  return await response.json();
42
}
43