-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathgithub_releases.rs
More file actions
183 lines (165 loc) · 5.47 KB
/
Copy pathgithub_releases.rs
File metadata and controls
183 lines (165 loc) · 5.47 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
use crate::{
changelogs::Changelog,
config::GitHubReleasesConfig,
github::{CreateEvent, CreateKind, Event},
handlers::Context,
};
use anyhow::Context as _;
use octocrab::Page;
use std::{collections::HashMap, time::Duration};
use tracing as log;
pub(super) async fn handle(
ctx: &Context,
event: &Event,
config: &GitHubReleasesConfig,
) -> anyhow::Result<()> {
// Only allow commit pushed to the changelog branch or tags being created.
match event {
Event::Push(push) if push.git_ref == format!("refs/heads/{}", config.changelog_branch) => {}
Event::Create(CreateEvent {
ref_type: CreateKind::Tag,
..
}) => {}
_ => return Ok(()),
}
log::info!("handling github releases");
log::debug!("loading the changelog");
let content = load_changelog(ctx, event, config).await.with_context(|| {
format!(
"failed to load changelog file {} from repo {} in branch {}",
config.changelog_path,
event.repo().full_name,
config.changelog_branch
)
})?;
let changelog = Changelog::parse(config.format, &content)?;
log::debug!("loading the git tags");
let tags = load_paginated(
ctx,
&format!("/repos/{}/git/matching-refs/tags", event.repo().full_name),
|git_ref: &GitRef| {
git_ref
.name
.strip_prefix("refs/tags/")
.unwrap_or(git_ref.name.as_str())
.to_string()
},
)
.await?;
log::debug!("loading the existing releases");
let releases = load_paginated(
ctx,
&format!("/repos/{}/releases", event.repo().full_name),
|release: &Release| release.tag_name.clone(),
)
.await?;
for tag in tags.keys() {
if let Some(expected_body) = changelog.version(tag) {
let expected_name = format!("{} {}", config.project_name, tag);
if let Some(release) = releases.get(tag) {
if release.name != expected_name || release.body != expected_body {
log::info!("updating release {} on {}", tag, event.repo().full_name);
let _: serde_json::Value = ctx
.octocrab
.patch(
&release.url,
Some(&serde_json::json!({
"name": expected_name,
"body": expected_body,
})),
)
.await?;
} else {
// Avoid waiting for the delay below.
continue;
}
} else {
log::info!("creating release {} on {}", tag, event.repo().full_name);
let e: octocrab::Result<serde_json::Value> = ctx
.octocrab
.post(
format!("/repos/{}/releases", event.repo().full_name),
Some(&serde_json::json!({
"tag_name": tag,
"name": expected_name,
"body": expected_body,
})),
)
.await;
match e {
Ok(v) => log::debug!("created release: {:?}", v),
Err(e) => {
log::error!("Failed to create release: {:?}", e);
// Don't stop creating future releases just because this
// one failed.
}
}
}
log::debug!("sleeping for one second to avoid hitting any rate limit");
tokio::time::sleep(Duration::from_secs(1)).await;
} else {
log::trace!("skipping tag {tag} since it doesn't have a changelog entry");
}
}
Ok(())
}
async fn load_changelog(
ctx: &Context,
event: &Event,
config: &GitHubReleasesConfig,
) -> anyhow::Result<String> {
let resp = ctx
.github
.raw_file(
&event.repo().full_name,
&config.changelog_branch,
&config.changelog_path,
)
.await?
.ok_or_else(|| anyhow::Error::msg("missing file"))?;
Ok(String::from_utf8(resp.to_vec())?)
}
async fn load_paginated<T, R, F>(ctx: &Context, url: &str, key: F) -> anyhow::Result<HashMap<R, T>>
where
T: serde::de::DeserializeOwned,
R: Eq + PartialEq + std::hash::Hash,
F: Fn(&T) -> R,
{
let mut current_page: Page<T> = ctx
.octocrab
.get::<Page<T>, _, ()>(url, None)
.await
.with_context(|| format!("failed to load {url}"))?;
let mut items = current_page
.take_items()
.into_iter()
.map(|val| (key(&val), val))
.collect::<HashMap<R, T>>();
while let Some(mut new_page) = ctx
.octocrab
.get_page::<T>(¤t_page.next)
.await
.with_context(|| format!("failed to load next page {:?}", current_page.next))?
{
items.extend(
new_page
.take_items()
.into_iter()
.map(|val| (key(&val), val)),
);
current_page = new_page;
}
Ok(items)
}
#[derive(Debug, serde::Deserialize)]
struct GitRef {
#[serde(rename = "ref")]
name: String,
}
#[derive(Debug, serde::Deserialize)]
struct Release {
url: String,
tag_name: String,
name: String,
body: String,
}