| 68 | /** This represent the GitHub API */ |
| 69 | |
| 70 | export class GitHubAPI { |
| 71 | fetch: typeof fetch |
| 72 | additionalHeaders: any |
| 73 | private readonly d = debug("GitHubAPI") |
| 74 | |
| 75 | private pr: GitHubPRDSL | undefined |
| 76 | |
| 77 | constructor(public readonly repoMetadata: RepoMetaData, public readonly token?: APIToken) { |
| 78 | // This allows Peril to DI in a new Fetch function |
| 79 | // which can handle unique API edge-cases around integrations |
| 80 | this.fetch = fetch |
| 81 | this.additionalHeaders = {} |
| 82 | } |
| 83 | |
| 84 | /** |
| 85 | * Bit weird, yes, but we want something that can be exposed to an end-user. |
| 86 | * I wouldn't have a problem with moving this to use this API under the hood |
| 87 | * but for now that's just a refactor someone can try. |
| 88 | */ |
| 89 | getExternalAPI = (accessTokenForApp?: string): GitHubNodeAPI => { |
| 90 | // A token should have been set by this point |
| 91 | const token = accessTokenForApp || this.token! |
| 92 | |
| 93 | const host = process.env["DANGER_GITHUB_API_BASE_URL"] || "https://api.github.com" |
| 94 | const options: ConstructorParameters<typeof GitHubNodeAPI>[0] & { debug: boolean } = { |
| 95 | debug: !!process.env.LOG_FETCH_REQUESTS, |
| 96 | baseUrl: host, |
| 97 | auth: `token ${token}`, |
| 98 | } |
| 99 | |
| 100 | if (this.additionalHeaders) { |
| 101 | options.headers = this.additionalHeaders |
| 102 | } |
| 103 | |
| 104 | return new GitHubNodeAPI(options) |
| 105 | } |
| 106 | |
| 107 | /** |
| 108 | * Grabs the contents of an individual file on GitHub |
| 109 | * |
| 110 | * @param {string} path path to the file |
| 111 | * @param {string} [ref] an optional sha |
| 112 | * @returns {Promise<string>} text contents |
| 113 | * |
| 114 | */ |
| 115 | fileContents = async (path: string, repoSlug?: string, ref?: string): Promise<string> => { |
| 116 | // Use the current state of PR if no repo/ref is passed |
| 117 | if (!repoSlug || !ref) { |
| 118 | const prJSON = await this.getPullRequestInfo() |
| 119 | repoSlug = prJSON.head.repo.full_name |
| 120 | ref = prJSON.head.ref |
| 121 | } |
| 122 | |
| 123 | const data = await this.getFileContents(path, repoSlug, ref) |
| 124 | const buffer = Buffer.from(data.content, "base64") |
| 125 | return buffer.toString() |
| 126 | } |
| 127 |
nothing calls this directly
no test coverage detected