Create or update file contents

Creates a new file or replaces an existing file in a repository. You must authenticate using an access token with the `workflow` scope to use this endpoint. **Note:** If you use this endpoint and the "[Delete a file](https://docs.github.com/rest/reference/repos/#delete-file)" endpoint in parallel, the concurrent requests will conflict and you will receive errors. You must use these endpoints serially instead.

Script github Verified

by hugo697 ยท 10/25/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 367 days ago
1
type Github = {
2
  token: string;
3
};
4
/**
5
 * Create or update file contents
6
 * Creates a new file or replaces an existing file in a repository. You must authenticate using an access token with the `workflow` scope to use this endpoint.
7

8
**Note:** If you use this endpoint and the "[Delete a file](https://docs.github.com/rest/reference/repos/#delete-file)" endpoint in parallel, the concurrent requests will conflict and you will receive errors. You must use these endpoints serially instead.
9
 */
10
export async function main(
11
  auth: Github,
12
  owner: string,
13
  repo: string,
14
  path: string,
15
  body: {
16
    author?: {
17
      date?: string;
18
      email: string;
19
      name: string;
20
      [k: string]: unknown;
21
    };
22
    branch?: string;
23
    committer?: {
24
      date?: string;
25
      email: string;
26
      name: string;
27
      [k: string]: unknown;
28
    };
29
    content: string;
30
    message: string;
31
    sha?: string;
32
    [k: string]: unknown;
33
  }
34
) {
35
  const url = new URL(
36
    `https://api.github.com/repos/${owner}/${repo}/contents/${path}`
37
  );
38

39
  const response = await fetch(url, {
40
    method: "PUT",
41
    headers: {
42
      "Content-Type": "application/json",
43
      Authorization: "Bearer " + auth.token,
44
    },
45
    body: JSON.stringify(body),
46
  });
47
  if (!response.ok) {
48
    const text = await response.text();
49
    throw new Error(`${response.status} ${text}`);
50
  }
51
  return await response.json();
52
}
53