Get the root directory of the main branch

This endpoint redirects the client to the directory listing of the root directory on the main branch. This is equivalent to directly hitting [/2.0/repositories/{username}/{repo_slug}/src/{commit}/{path}](src/%7Bcommit%7D/%7Bpath%7D) without having to know the name or SHA1 of the repo's main branch. To create new commits, [POST to this endpoint](#post)

Script bitbucket Verified

by hugo697 ยท 10/24/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 375 days ago
1
type Bitbucket = {
2
  username: string;
3
  password: string;
4
};
5
/**
6
 * Get the root directory of the main branch
7
 * This endpoint redirects the client to the directory listing of the
8
root directory on the main branch.
9

10
This is equivalent to directly hitting
11
[/2.0/repositories/{username}/{repo_slug}/src/{commit}/{path}](src/%7Bcommit%7D/%7Bpath%7D)
12
without having to know the name or SHA1 of the repo's main branch.
13

14
To create new commits, [POST to this endpoint](#post)
15
 */
16
export async function main(
17
  auth: Bitbucket,
18
  repo_slug: string,
19
  workspace: string,
20
  format: "meta" | undefined
21
) {
22
  const url = new URL(
23
    `https://api.bitbucket.org/2.0/repositories/${workspace}/${repo_slug}/src`
24
  );
25
  for (const [k, v] of [["format", format]]) {
26
    if (v !== undefined && v !== "") {
27
      url.searchParams.append(k, v);
28
    }
29
  }
30
  const response = await fetch(url, {
31
    method: "GET",
32
    headers: {
33
      Authorization: "Basic " + btoa(`${auth.username}:${auth.password}`),
34
    },
35
    body: undefined,
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