| import axios from "axios"; |
| import { z } from "zod"; |
| |
| export const GithubRepositorySchema = z.object({ |
| id: z.number(), |
| name: z.string(), |
| full_name: z.string(), |
| html_url: z.string(), |
| ssh_url: z.string(), |
| }); |
| |
| const DeployKeysSchema = z.array( |
| z.object({ |
| id: z.number(), |
| key: z.string(), |
| }), |
| ); |
| |
| export type GithubRepository = z.infer<typeof GithubRepositorySchema>; |
| |
| export class GithubClient { |
| private token: string; |
| |
| constructor(token: string) { |
| this.token = token; |
| } |
| |
| private getHeaders() { |
| return { |
| Authorization: `Bearer ${this.token}`, |
| Accept: "application/vnd.github.v3+json", |
| }; |
| } |
| |
| async getRepositories(): Promise<GithubRepository[]> { |
| const response = await axios.get("https://api.github.com/user/repos", { |
| headers: this.getHeaders(), |
| }); |
| return z.array(GithubRepositorySchema).parse(response.data); |
| } |
| |
| async addDeployKey(repoPath: string, key: string) { |
| const sshUrl = repoPath; |
| const repoOwnerAndName = sshUrl.replace("git@github.com:", "").replace(".git", ""); |
| await axios.post( |
| `https://api.github.com/repos/${repoOwnerAndName}/keys`, |
| { |
| title: "dodo", |
| key: key, |
| read_only: true, |
| }, |
| { |
| headers: this.getHeaders(), |
| }, |
| ); |
| } |
| |
| async removeDeployKey(repoPath: string, key: string) { |
| const sshUrl = repoPath; |
| const repoOwnerAndName = sshUrl.replace("git@github.com:", "").replace(".git", ""); |
| const response = await axios.get(`https://api.github.com/repos/${repoOwnerAndName}/keys`, { |
| headers: this.getHeaders(), |
| }); |
| const result = DeployKeysSchema.safeParse(response.data); |
| if (!result.success) { |
| throw new Error("Failed to parse deploy keys response"); |
| } |
| const deployKeys = result.data.filter((k) => k.key === key); |
| await Promise.all( |
| deployKeys.map((deployKey) => |
| axios.delete(`https://api.github.com/repos/${repoOwnerAndName}/keys/${deployKey.id}`, { |
| headers: this.getHeaders(), |
| }), |
| ), |
| ); |
| } |
| } |