0

Get Repository Content

by
Published today

Get a file or directory listing at a path. File content comes back base64-encoded unless raw is set, which returns the file as text.

Script github Verified

The script

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

3
/**
4
 * Get Repository Content
5
 * Get a file or directory listing at a path. File content comes back base64-encoded unless raw is set, which returns the file as text.
6
 */
7
export async function main(
8
  auth: RT.Github,
9
  owner: string,
10
  repo: string,
11
  path: string | undefined,
12
  ref: string | undefined,
13
  raw: boolean = false
14
) {
15
  const url = new URL(
16
    `https://api.github.com/repos/${owner}/${repo}/contents/${path ?? ""}`
17
  )
18
  if (ref !== undefined && ref !== "") {
19
    url.searchParams.append("ref", ref)
20
  }
21

22
  const response = await fetch(url, {
23
    headers: {
24
      Authorization: `Bearer ${auth.token}`,
25
      Accept: raw
26
        ? "application/vnd.github.raw+json"
27
        : "application/vnd.github+json",
28
      "X-GitHub-Api-Version": "2022-11-28",
29
    },
30
  })
31

32
  if (!response.ok) {
33
    throw new Error(`${response.status} ${await response.text()}`)
34
  }
35

36
  return raw ? await response.text() : await response.json()
37
}
38