|
| 1 | +import { pathToFileURL } from 'node:url' |
| 2 | +import { SourceLocation, SourceLocationResolver } from './ErrorStackResolver' |
| 3 | +import { spawn } from 'node:child_process' |
| 4 | + |
| 5 | +export class GitHubResolver implements SourceLocationResolver { |
| 6 | + constructor( |
| 7 | + readonly GITHUB_WORKSPACE = process.env.GITHUB_WORKSPACE, |
| 8 | + readonly GITHUB_SHA = process.env.GITHUB_SHA, |
| 9 | + readonly GITHUB_REPOSITORY = process.env.GITHUB_REPOSITORY, |
| 10 | + readonly GITHUB_SERVER_URL = process.env.GITHUB_SERVER_URL, |
| 11 | + ) { |
| 12 | + if (GITHUB_WORKSPACE) { |
| 13 | + this.workspaceUrl = String(pathToFileURL(GITHUB_WORKSPACE)) |
| 14 | + if (!this.workspaceUrl.endsWith('/')) { |
| 15 | + this.workspaceUrl += '/' |
| 16 | + } |
| 17 | + } |
| 18 | + if (GITHUB_SHA && GITHUB_REPOSITORY && GITHUB_SERVER_URL) { |
| 19 | + this.resolvedWorkspaceUrl = `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/blob/${GITHUB_SHA}/` |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + protected workspaceUrl?: string |
| 24 | + protected resolvedWorkspaceUrl?: string |
| 25 | + protected treeObjects?: Promise<string[]> |
| 26 | + |
| 27 | + async resolve(loc: SourceLocation): Promise<SourceLocation | undefined> { |
| 28 | + if (!this.workspaceUrl || !this.resolvedWorkspaceUrl || !loc.file?.startsWith(this.workspaceUrl)) { |
| 29 | + return undefined |
| 30 | + } |
| 31 | + const path = loc.file.substring(this.workspaceUrl.length) |
| 32 | + |
| 33 | + if (!this.treeObjects) { |
| 34 | + this.treeObjects = this.getGitTreeObjects() |
| 35 | + } |
| 36 | + const tree = await this.treeObjects |
| 37 | + if (tree.includes(path)) { |
| 38 | + return {...loc, |
| 39 | + url: this.resolvedWorkspaceUrl + path + (loc.position ? `#L${loc.position.line}` : ''), |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + protected getGitTreeObjects(): Promise<string[]> { |
| 45 | + if (!this.GITHUB_WORKSPACE) { |
| 46 | + return Promise.reject(`GITHUB_WORKSPACE is not set.`) |
| 47 | + } |
| 48 | + |
| 49 | + return new Promise((res, rej) => { |
| 50 | + const child = spawn('git', [ |
| 51 | + 'ls-tree', |
| 52 | + '--name-only', |
| 53 | + '-r', |
| 54 | + 'HEAD', |
| 55 | + ], { |
| 56 | + cwd: this.GITHUB_WORKSPACE, |
| 57 | + stdio: ['ignore', 'pipe', 'pipe'], |
| 58 | + }) |
| 59 | + let out = '', err = '' |
| 60 | + child.stdout.on('data', c => { |
| 61 | + out += String(c) |
| 62 | + }) |
| 63 | + child.stderr.on('data', c => { |
| 64 | + err += String(c) |
| 65 | + }) |
| 66 | + child.on('exit', (code, signal) => { |
| 67 | + if (code || signal) { |
| 68 | + rej(`Could not list tree objects:\n` + err) |
| 69 | + } else { |
| 70 | + const list = out.split('\n') |
| 71 | + res(list) |
| 72 | + } |
| 73 | + }) |
| 74 | + }) |
| 75 | + } |
| 76 | +} |
0 commit comments