Get file or directory contents

This endpoints is used to retrieve the contents of a single file, or the contents of a directory at a specified revision.

Script bitbucket Verified

by hugo697 ยท 10/25/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 file or directory contents
7
 * This endpoints is used to retrieve the contents of a single file,
8
or the contents of a directory at a specified revision.
9
 */
10
export async function main(
11
  auth: Bitbucket,
12
  commit: string,
13
  path: string,
14
  repo_slug: string,
15
  workspace: string,
16
  format: "meta" | "rendered" | undefined,
17
  q: string | undefined,
18
  sort: string | undefined,
19
  max_depth: string | undefined
20
) {
21
  const url = new URL(
22
    `https://api.bitbucket.org/2.0/repositories/${workspace}/${repo_slug}/src/${commit}/${path}`
23
  );
24
  for (const [k, v] of [
25
    ["format", format],
26
    ["q", q],
27
    ["sort", sort],
28
    ["max_depth", max_depth],
29
  ]) {
30
    if (v !== undefined && v !== "") {
31
      url.searchParams.append(k, v);
32
    }
33
  }
34
  const response = await fetch(url, {
35
    method: "GET",
36
    headers: {
37
      Authorization: "Basic " + btoa(`${auth.username}:${auth.password}`),
38
    },
39
    body: undefined,
40
  });
41
  if (!response.ok) {
42
    const text = await response.text();
43
    throw new Error(`${response.status} ${text}`);
44
  }
45
  return await response.json();
46
}
47