forked from astral-sh/python-build-standalone
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.rs
More file actions
326 lines (270 loc) · 9.93 KB
/
github.rs
File metadata and controls
326 lines (270 loc) · 9.93 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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use {
crate::release::{produce_install_only, RELEASE_TRIPLES},
anyhow::{anyhow, Result},
clap::ArgMatches,
futures::StreamExt,
octocrab::{models::workflows::WorkflowListArtifact, Octocrab, OctocrabBuilder},
rayon::prelude::*,
std::{
collections::{BTreeMap, BTreeSet},
io::Read,
path::PathBuf,
},
zip::ZipArchive,
};
async fn fetch_artifact(client: &Octocrab, artifact: WorkflowListArtifact) -> Result<bytes::Bytes> {
println!("downloading {}", artifact.name);
let res = client
.execute(client.request_builder(artifact.archive_download_url, reqwest::Method::GET))
.await?;
Ok(res.bytes().await?)
}
pub async fn command_fetch_release_distributions(args: &ArgMatches) -> Result<()> {
let dest_dir = PathBuf::from(args.value_of("dest").expect("dest directory should be set"));
let org = args
.value_of("organization")
.expect("organization should be set");
let repo = args.value_of("repo").expect("repo should be set");
let client = OctocrabBuilder::new()
.personal_token(
args.value_of("token")
.expect("token should be required argument")
.to_string(),
)
.build()?;
let workflows = client.workflows(org, repo);
let workflow_ids = workflows
.list()
.send()
.await?
.into_iter()
.map(|wf| wf.id)
.collect::<Vec<_>>();
let mut runs: Vec<octocrab::models::workflows::Run> = vec![];
for workflow_id in workflow_ids {
runs.push(
workflows
.list_runs(format!("{}", workflow_id))
.event("push")
.status("success")
.send()
.await?
.into_iter()
.find(|run| {
run.head_sha == args.value_of("commit").expect("commit should be defined")
})
.ok_or_else(|| anyhow!("could not find workflow run for commit"))?,
);
}
let mut fs = vec![];
for run in runs {
let page = client
.actions()
.list_workflow_run_artifacts(org, repo, run.id)
.send()
.await?;
let artifacts = client
.all_pages::<octocrab::models::workflows::WorkflowListArtifact>(
page.value.expect("untagged request should have page"),
)
.await?;
for artifact in artifacts {
if matches!(
artifact.name.as_str(),
"pythonbuild" | "sccache" | "toolchain"
) || artifact.name.contains("install-only")
{
continue;
}
fs.push(fetch_artifact(&client, artifact));
}
}
let mut buffered = futures::stream::iter(fs).buffer_unordered(4);
let mut install_paths = vec![];
while let Some(res) = buffered.next().await {
let data = res?;
let mut za = ZipArchive::new(std::io::Cursor::new(data))?;
for i in 0..za.len() {
let mut zf = za.by_index(i)?;
let name = zf.name().to_string();
if let Some((triple, release)) = RELEASE_TRIPLES.iter().find_map(|(triple, release)| {
if name.contains(triple) {
Some((triple, release))
} else {
None
}
}) {
let stripped_name = if let Some(s) = name.strip_suffix(".tar.zst") {
s
} else {
println!("{} not a .tar.zst artifact", name);
continue;
};
let stripped_name = &stripped_name[0..stripped_name.len() - "-YYYYMMDDTHHMM".len()];
let triple_start = stripped_name
.find(triple)
.expect("validated triple presence above");
let build_suffix = &stripped_name[triple_start + triple.len() + 1..];
if !release
.suffixes
.iter()
.any(|suffix| build_suffix == *suffix)
{
println!("{} not a release artifact for triple", name);
continue;
}
let dest_path = dest_dir.join(&name);
let mut buf = vec![];
zf.read_to_end(&mut buf)?;
std::fs::write(&dest_path, &buf)?;
println!("releasing {}", name);
if build_suffix == release.install_only_suffix {
install_paths.push(dest_path);
}
} else {
println!("{} does not match any registered release triples", name);
}
}
}
install_paths
.par_iter()
.try_for_each(|path| -> Result<()> {
println!(
"producing install_only archive from {}",
path.file_name()
.expect("should have file name")
.to_string_lossy()
);
let dest_path = produce_install_only(&path)?;
println!(
"releasing {}",
dest_path
.file_name()
.expect("should have file name")
.to_string_lossy()
);
Ok(())
})?;
Ok(())
}
pub async fn command_upload_release_distributions(args: &ArgMatches) -> Result<()> {
let dist_dir = PathBuf::from(args.value_of("dist").expect("dist should be specified"));
let datetime = args
.value_of("datetime")
.expect("datetime should be specified");
let tag = args.value_of("tag").expect("tag should be specified");
let ignore_missing = args.is_present("ignore_missing");
let token = args
.value_of("token")
.expect("token should be specified")
.to_string();
let organization = args
.value_of("organization")
.expect("organization should be specified");
let repo = args.value_of("repo").expect("repo should be specified");
let dry_run = args.is_present("dry_run");
let mut filenames = std::fs::read_dir(&dist_dir)?
.into_iter()
.map(|x| {
let path = x?.path();
let filename = path
.file_name()
.ok_or_else(|| anyhow!("unable to resolve file name"))?;
Ok(filename.to_string_lossy().to_string())
})
.collect::<Result<Vec<_>>>()?;
filenames.sort();
let filenames = filenames
.into_iter()
.filter(|x| x.contains(datetime) && x.starts_with("cpython-"))
.collect::<BTreeSet<_>>();
let mut python_versions = BTreeSet::new();
for filename in &filenames {
let parts = filename.split('-').collect::<Vec<_>>();
python_versions.insert(parts[1]);
}
let mut wanted_filenames = BTreeMap::new();
for version in python_versions {
for (triple, release) in RELEASE_TRIPLES.iter() {
if let Some(req) = &release.python_version_requirement {
let python_version = semver::Version::parse(version)?;
if !req.matches(&python_version) {
continue;
}
}
for suffix in &release.suffixes {
wanted_filenames.insert(
format!(
"cpython-{}-{}-{}-{}.tar.zst",
version, triple, suffix, datetime
),
format!("cpython-{}+{}-{}-{}.tar.zst", version, tag, triple, suffix),
);
}
wanted_filenames.insert(
format!(
"cpython-{}-{}-install_only-{}.tar.gz",
version, triple, datetime
),
format!("cpython-{}+{}-{}-install_only.tar.gz", version, tag, triple),
);
}
}
let missing = wanted_filenames
.keys()
.filter(|x| !filenames.contains(*x))
.collect::<Vec<_>>();
for f in &missing {
println!("missing release artifact: {}", f);
}
if !missing.is_empty() && !ignore_missing {
return Err(anyhow!("missing release artifacts"));
}
let client = OctocrabBuilder::new().personal_token(token).build()?;
let repo = client.repos(organization, repo);
let releases = repo.releases();
let release = if let Ok(release) = releases.get_by_tag(tag).await {
release
} else {
return Err(anyhow!(
"release {} does not exist; create it via GitHub web UI",
tag
));
};
for (source, dest) in wanted_filenames {
if !filenames.contains(&source) {
continue;
}
if release.assets.iter().any(|asset| asset.name == dest) {
println!("release asset {} already present; skipping", dest);
continue;
}
let path = dist_dir.join(&source);
let file_data = std::fs::read(&path)?;
let mut url = release.upload_url.clone();
let path = url.path().to_string();
if let Some(path) = path.strip_suffix("%7B") {
url.set_path(path);
}
url.query_pairs_mut()
.clear()
.append_pair("name", dest.as_str());
println!("uploading {} to {}", source, url);
let request = client
.request_builder(url, reqwest::Method::POST)
.header("Content-Length", file_data.len())
.header("Content-Type", "application/x-tar")
.body(file_data);
if dry_run {
continue;
}
let response = client.execute(request).await?;
if !response.status().is_success() {
return Err(anyhow!("HTTP {}", response.status()));
}
}
Ok(())
}