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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
|
# github_release_context.bzl: A "class" which allows multiple rules to share
# code for downloading GitHub release assets
#
# Example usage:
# gh = github_release_context(repository_ctx)
# gh.download(gh, owner, repo, tag_name, asset_name, output)
load(
"@bazel_tools//tools/build_defs/repo:utils.bzl",
"read_netrc",
"read_user_netrc",
"use_netrc",
)
def _calculate_sha256(gh, file):
"""Calculates the sha256 hash of a file"""
res = gh.execute(["sha256sum", file])
if res.return_code != 0:
fail("sha256sum failed: " + res.stderr)
actual_sha256 = res.stdout.split(" ")[0]
return actual_sha256
def _download_ex(gh, url, output, executable = False, sha256 = "", headers = {}):
"""Simplified repository_ctx.download() with support for specifying custom
HTTP request headers."""
if not gh.which("curl"):
fail("curl binary not found")
args = ["curl", "--silent", "-o", output, "--write-out", "%{http_code}", "--location"]
for k, v in headers.items():
args.extend(["-H", "{k}: {v}".format(k = k, v = v)])
args.append(url)
res = gh.execute(args)
if res.return_code != 0:
fail("curl failed: " + res.stderr)
http_response_code = int(res.stdout)
if http_response_code < 200 or http_response_code > 299:
fail("Download of {url} failed with HTTP response code {http_response_code}".format(
url = url,
http_response_code = http_response_code
))
actual_sha256 = gh._calculate_sha256(gh, output)
if sha256 and actual_sha256 != sha256:
fail("sha256 mismatch: expected {} actual {}".format(sha256, actual_sha256))
if executable:
res = gh.execute(["chmod", "+x", output])
if res.return_code != 0:
fail("marking file executable failed: " + res.stderr)
return struct(
success = True,
sha256 = actual_sha256,
)
def _get_github_auth_token(gh, netrc):
"""Gets the github auth token from ~/.netrc"""
if netrc:
netrc = read_netrc(gh, netrc)
elif "NETRC" in gh.os.environ:
netrc = read_netrc(gh, gh.os.environ["NETRC"])
else:
netrc = read_user_netrc(gh)
for host in ["github.com", "api.github.com"]:
url = "https://{host}/".format(host = host)
auth_dict = use_netrc(netrc, [url], {host: "Bearer <password>"})
if auth_dict:
return auth_dict[url]["password"]
fail("""Could not find GitHub auth token. Add the following line to your ~/.netrc:
machine github.com password ghp_...
Where ghp_... is a GitHub personal access token with permissions to download release assets.
""")
def _get_github_release_id(gh, owner, repo, tag_name, auth_token):
"""Gets the release id of a GitHub release"""
releases_file = "releases.json"
gh._download_ex(
gh,
url = "https://api.github.com/repos/{owner}/{repo}/releases".format(
owner = owner,
repo = repo),
output = releases_file,
headers = {
"Accept": "application/vnd.github+json",
"Authorization": "Bearer {auth_token}".format(auth_token = auth_token),
"X-GitHub-Api-Version": "2022-11-28",
},
)
releases = json.decode(gh.read(releases_file))
gh.delete(releases_file)
for release in releases:
if release["tag_name"] == tag_name:
return release["id"]
fail("Could not find release with tag {tag_name} in {owner}/{repo}".format(
tag_name = tag_name,
owner = owner,
repo = repo))
def _get_github_release_asset_id(gh, owner, repo, release_id, asset_name, auth_token):
"""Gets the asset id of an asset within a GitHub release"""
assets_file = "assets.json"
gh._download_ex(
gh,
url = "https://api.github.com/repos/{owner}/{repo}/releases/{release_id}/assets".format(
owner = owner,
repo = repo,
release_id = release_id),
output = assets_file,
headers = {
"Accept": "application/vnd.github+json",
"Authorization": "Bearer {auth_token}".format(auth_token = auth_token),
"X-GitHub-Api-Version": "2022-11-28",
},
)
assets = json.decode(gh.read(assets_file))
gh.delete(assets_file)
for asset in assets:
if asset["name"] == asset_name:
return asset["id"]
fail("Could not find asset named {asset_name} in {owner}/{repo} release {release_id}".format(
asset_name = asset_name,
owner = owner,
repo = repo,
release_id = release_id))
def _download_with_http_client(gh, owner, repo, tag_name, asset_name, output,
executable = False, netrc = None, sha256 = ""):
"""Downloads an asset from github using HTTP requests"""
github_auth_token = gh._get_github_auth_token(gh, netrc)
release_id = gh._get_github_release_id(
gh,
owner = owner,
repo = repo,
tag_name = tag_name,
auth_token = github_auth_token,
)
asset_id = gh._get_github_release_asset_id(
gh,
owner = owner,
repo = repo,
release_id = release_id,
asset_name = asset_name,
auth_token = github_auth_token,
)
return gh._download_ex(
gh,
url = "https://api.github.com/repos/{owner}/{repo}/releases/assets/{asset_id}".format(
owner = owner,
repo = repo,
asset_id = asset_id),
headers = {
# Note the required use of a custom request header to download the release _content_
"Accept": "application/octet-stream",
"X-GitHub-Api-Version": "2022-11-28",
"Authorization": "Bearer {}".format(github_auth_token),
},
sha256 = sha256,
executable = executable,
output = output,
)
def _download_with_gh_cli(gh, owner, repo, tag_name, asset_name, output,
executable = False, sha256 = ""):
"""Downloads an asset from github using the gh(1) tool"""
if not gh.which("gh"):
fail("gh binary not found")
owner_repo = "{}/{}".format(owner, repo)
res = gh.execute([
"gh", "release", "download",
"--repo", owner_repo,
"--pattern", asset_name,
"--output", output,
tag_name])
if res.return_code != 0:
fail("gh release download --repo {r} --pattern {a} {t} failed: {stderr}".format(
r = owner_repo,
a = asset_name,
t = tag_name,
stderr = res.stderr))
actual_sha256 = gh._calculate_sha256(gh, output)
if sha256 and actual_sha256 != sha256:
fail("sha256 mismatch: expected {} actual {}".format(sha256, actual_sha256))
if executable:
res = gh.execute(["chmod", "+x", output])
if res.return_code != 0:
fail("marking file executable failed: " + res.stderr)
return struct(
success = True,
sha256 = actual_sha256,
)
def _download(gh, owner, repo, tag_name, asset_name, output, executable = False,
netrc = None, sha256 = ""):
"""download() that works with a GitHub release asset"""
if gh.which("gh"):
return gh._download_with_gh_cli(
gh,
owner = owner,
repo = repo,
tag_name = tag_name,
asset_name = asset_name,
executable = executable,
sha256 = sha256,
output = output,
)
else:
return gh._download_with_http_client(
gh,
owner = owner,
repo = repo,
tag_name = tag_name,
asset_name = asset_name,
executable = executable,
netrc = netrc,
sha256 = sha256,
output = output,
)
def _download_and_extract(gh, owner, repo, tag_name, asset_name, netrc = None,
sha256 = "", strip_prefix = ""):
"""download_and_extract() that works with a GitHub release asset"""
download_file = "downloaded_file.tar.gz"
res = gh.download(
gh,
owner = owner,
repo = repo,
tag_name = tag_name,
asset_name = asset_name,
output = download_file,
netrc = netrc,
sha256 = sha256,
)
gh.extract(download_file, stripPrefix = strip_prefix)
gh.delete(download_file)
return struct(
success = True,
sha256 = res.sha256,
)
def github_release_context(repository_ctx):
return struct(
# Private members
_calculate_sha256 = _calculate_sha256,
_download_ex = _download_ex,
_get_github_auth_token = _get_github_auth_token,
_get_github_release_id = _get_github_release_id,
_get_github_release_asset_id = _get_github_release_asset_id,
_download_with_http_client = _download_with_http_client,
_download_with_gh_cli = _download_with_gh_cli,
# Forwarding methods to repository_ctx
delete = repository_ctx.delete,
execute = repository_ctx.execute,
extract = repository_ctx.extract,
os = repository_ctx.os,
path = repository_ctx.path,
read = repository_ctx.read,
which = repository_ctx.which,
# Public members
download = _download,
download_and_extract = _download_and_extract,
)
|