-
Notifications
You must be signed in to change notification settings - Fork 261
Expand file tree
/
Copy pathgithub.ts
More file actions
177 lines (157 loc) · 5.62 KB
/
Copy pathgithub.ts
File metadata and controls
177 lines (157 loc) · 5.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import {outputContent, outputDebug, outputToken} from './output.js'
import {err, ok, Result} from './result.js'
import {fetch, Response} from './http.js'
import {mkdir, inTemporaryDirectory, moveFile, chmod, createFileWriteStream} from './fs.js'
import {dirname, joinPath} from './path.js'
import {runWithTimer} from './metadata.js'
import {AbortError} from './error.js'
import {pipeline} from 'stream/promises'
class GitHubClientError extends Error {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(url: string, statusCode: number, bodyJson: any) {
super(
`The request to GitHub API URL ${url} failed with status code ${statusCode} and the following error message: ${bodyJson.message}`,
)
}
}
export interface GithubRelease {
id: number
url: string
tag_name: string
name: string
body: string
draft: boolean
prerelease: boolean
created_at: string
published_at: string
tarball_url: string
}
interface GetLatestGitHubReleaseOptions {
filter: (release: GithubRelease) => boolean
}
/**
* Given a GitHub repository it obtains the latest release.
* @param owner - Repository owner (e.g., shopify)
* @param repo - Repository name (e.g., cli)
* @param options - Options
*/
export async function getLatestGitHubRelease(
owner: string,
repo: string,
options: GetLatestGitHubReleaseOptions = {filter: () => true},
): Promise<GithubRelease> {
outputDebug(outputContent`Getting the latest release of GitHub repository ${owner}/${repo}...`)
const url = `https://api.github.com/repos/${owner}/${repo}/releases`
const fetchResult = await fetch(url)
try {
const responseText = await fetchResult.text()
const jsonBody = JSON.parse(responseText)
if (fetchResult.status !== 200) {
throw new GitHubClientError(url, fetchResult.status, jsonBody)
}
return jsonBody.find(options.filter)
} catch (error) {
if (error instanceof SyntaxError) {
throw new AbortError(
`Received invalid response from GitHub API (HTTP ${fetchResult.status}).`,
'The response could not be parsed as JSON. The service may be temporarily unavailable. Please try again.',
)
}
throw error
}
}
interface ParseRepositoryURLOutput {
full: string
site: string
user: string
name: string
ref: string
subDirectory: string
ssh: string
http: string
}
/**
* Given a GitHub repository URL, it parses it and returns its coomponents.
* @param url - The GitHub repository URL
*/
export function parseGitHubRepositoryURL(url: string): Result<ParseRepositoryURLOutput, Error> {
const match =
/^(?:(?:https:\/\/)?([^:/]+\.[^:/]+)\/|git@([^:/]+)[:/]|([^/]+):)?([^/\s]+)\/([^/\s#]+)(?:((?:\/[^/\s#]+)+))?(?:\/)?(?:#(.+))?/.exec(
url,
)
if (!match) {
const exampleFormats = [
'github:user/repo',
'user/repo/subdirectory',
'git@github.com:user/repo',
'user/repo#dev',
'https://github.com/user/repo',
]
return err(new Error(`Parsing the url ${url} failed. Supported formats are ${exampleFormats.join(', ')}.`))
}
const site = match[1] ?? match[2] ?? match[3] ?? 'github.com'
const normalizedSite = site === 'github' ? 'github.com' : site
const user = match[4]!
const name = match[5]!.replace(/\.git$/, '')
const subDirectory = match[6]?.slice(1)!
const ref = match[7]!
const branch = ref ? `#${ref}` : ''
const ssh = `git@${normalizedSite}:${user}/${name}`
const http = `https://${normalizedSite}/${user}/${name}`
const full = ['https:/', normalizedSite, user, name, subDirectory].join('/').concat(branch)
return ok({full, site: normalizedSite, user, name, ref, subDirectory, ssh, http})
}
export interface GithubRepositoryReference {
baseURL: string
branch?: string
filePath?: string
}
/**
* Given a GitHub repository URL it parses it and extracts the branch, file path,
* and base URL components
* @param reference - A GitHub repository URL (e.g. https://github.com/Shopify/cli/blob/main/package.json)
*/
export function parseGitHubRepositoryReference(reference: string): GithubRepositoryReference {
const url = new URL(reference)
const branch = url.hash ? url.hash.slice(1) : undefined
const [_, user, repo, ...repoPath] = url.pathname.split('/')
const filePath = repoPath.length > 0 ? repoPath.join('/') : undefined
return {
baseURL: `${url.origin}/${user}/${repo}`,
branch,
filePath,
}
}
export async function downloadGitHubRelease(
repo: string,
version: string,
assetName: string,
targetPath: string,
): Promise<void> {
const url = `https://github.com/${repo}/releases/download/${version}/${assetName}`
return runWithTimer('cmd_all_timing_network_ms')(async () => {
outputDebug(outputContent`Downloading ${outputToken.link(assetName, url)}`)
await inTemporaryDirectory(async (tmpDir) => {
const tempPath = joinPath(tmpDir, assetName)
let response: Response
try {
response = await fetch(url, undefined, 'slow-request')
if (!response.ok) {
throw new AbortError(`Failed to download ${assetName}: ${response.statusText}`)
}
} catch (error) {
throw new AbortError(
`Failed to download ${assetName}: ${error instanceof Error ? error.message : 'unknown error'}`,
)
}
if (!response.body) {
throw new AbortError(`Failed to download ${assetName}: No response body`)
}
await pipeline(response.body, createFileWriteStream(tempPath))
await chmod(tempPath, 0o755)
await mkdir(dirname(targetPath))
await moveFile(tempPath, targetPath)
})
outputDebug(outputContent`${outputToken.successIcon()} Successfully downloaded ${outputToken.path(targetPath)}`)
})
}