repos / starfx

supercharged async flow control library.
git clone https://github.com/neurosnap/starfx.git

starfx / scripts
Jacob Bolda · 30 Jan 24

branch-exists.ts

 1import { call, main, type Operation } from "./deps.ts";
 2
 3await main(function* (): Operation<void> {
 4  // based on env created from ${{ secrets.GITHUB_TOKEN }} in CI
 5  const token = Deno.env.get("GITHUB_TOKEN");
 6  const [branch, ownerRepo] = Deno.args;
 7  console.dir({ branch, ownerRepo });
 8
 9  const response = yield* call(
10    fetch(`https://api.github.com/repos/${ownerRepo}/branches`, {
11      headers: {
12        Accept: "application/vnd.github+json",
13        "X-GitHub-Api-Version": "2022-11-28",
14        // the token isn't required but helps with rate limiting
15        ...(token ? { Authorization: `Bearer ${token}` } : {}),
16      },
17    }),
18  );
19
20  if (response.ok) {
21    const branches = yield* call(response.json());
22    const branchList = branches.map((branch: { name: string }) => branch.name);
23    // for CI debug purposes
24    console.dir({ branchList });
25    // GitHub Actions maintains the step output through a file which you append keys into
26    //   the path that file is available as an env var
27    if (Deno.env.get("CI")) {
28      const output = Deno.env.get("GITHUB_OUTPUT");
29      if (!output) throw new Error("$GITHUB_OUTPUT is not set");
30      const encoder = new TextEncoder();
31      if (branchList.includes(branch)) {
32        const data = encoder.encode(`branch=${branch}`);
33        yield* call(Deno.writeFile(output, data, { append: true }));
34      } else {
35        const data = encoder.encode("branch=main");
36        yield* call(Deno.writeFile(output, data, { append: true }));
37      }
38    }
39    // always log out the branch for both CI and local running
40    if (branchList.includes(branch)) {
41      console.log(`branch=${branch}`);
42    } else {
43      console.log(`branch=main`);
44    }
45  } else {
46    console.error(
47      `Error trying to fetch https://api.github.com/repos/${ownerRepo}/branches and check for ${branch}`,
48    );
49    const text = yield* call(response.text());
50    throw new Error(text);
51  }
52});