-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
registry.rs
243 lines (206 loc) · 7.16 KB
/
registry.rs
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
use anyhow::{anyhow, bail, Context};
use secstr::SecUtf8;
use serde::Deserialize;
use std::fmt::{Display, Formatter};
use std::path::PathBuf;
use std::process::Command;
use std::str::FromStr;
use std::thread::sleep;
use std::time::{Duration, Instant};
#[derive(thiserror::Error, Debug)]
enum Error {
#[error("crate was not found on crates.io")]
CrateNotFound,
}
pub struct Registry {
token: SecUtf8,
crates: Vec<Crate>,
dry_run: bool,
}
#[derive(Clone, Debug)]
pub struct Crate {
path: PathBuf,
}
enum CrateState {
/// Our crate version is ahead of the registry and should be published
Ahead,
/// Our crate version is behind the registry; you'll be warned about this
Behind,
/// Our crate version matches the registry version
Published,
/// We encountered an unknown state while processing the crate
Unknown,
}
impl Registry {
pub fn new(token: &SecUtf8, crates: &[Crate], dry_run: bool) -> Self {
Self {
token: token.to_owned(),
crates: crates.to_vec(),
dry_run,
}
}
pub fn publish_crates(&self) -> anyhow::Result<()> {
for c in &self.crates {
c.validate()?;
match c.determine_state()? {
CrateState::Published | CrateState::Behind => continue,
CrateState::Unknown | CrateState::Ahead => {
c.submit(&self.token, self.dry_run)?;
}
}
}
Ok(())
}
}
impl Crate {
fn validate(&self) -> anyhow::Result<()> {
match self.path.exists() {
true => Ok(()),
false => Err(anyhow!(
"given path to the '{self}' crate is either not readable or does not exist"
)),
}
}
fn get_local_version(&self) -> anyhow::Result<semver::Version> {
let name = format!("{self}");
let cargo_toml_location = std::fs::canonicalize(&self.path)
.context("absolute path to Cargo.toml")?;
let mut cmd = cargo_metadata::MetadataCommand::new();
cmd.manifest_path(format!(
"{}/Cargo.toml",
cargo_toml_location.to_string_lossy()
))
.no_deps();
let metadata = cmd.exec()?;
let package = metadata
.packages
.iter()
.find(|p| p.name == name)
.ok_or_else(|| anyhow!("could not find package"))?;
let version = package.version.to_owned();
log::debug!("{self} found as {version} on our side");
Ok(version)
}
fn get_upstream_version(&self) -> anyhow::Result<semver::Version> {
#[derive(Deserialize)]
struct CrateVersions {
versions: Vec<CrateVersion>,
}
#[derive(Deserialize)]
struct CrateVersion {
#[serde(rename = "num")]
version: semver::Version,
}
let client = reqwest::blocking::ClientBuilder::new()
.user_agent(concat!(
env!("CARGO_PKG_NAME"),
"/",
env!("CARGO_PKG_VERSION")
))
.build()
.context("build http client")?;
let resp = client
.get(format!("https://crates.io/api/v1/crates/{self}"))
.send()
.context("fetching crate versions from the registry")?;
if resp.status() == reqwest::StatusCode::NOT_FOUND {
return Err(anyhow::Error::new(Error::CrateNotFound));
}
if resp.status() != reqwest::StatusCode::OK {
return Err(anyhow!(
"{self} request to crates.io failed with {} '{}'",
resp.status(),
resp.text().unwrap_or_else(|_| {
"[response body could not be read]".to_string()
})
));
}
let versions =
serde_json::from_str::<CrateVersions>(resp.text()?.as_str())
.context("deserializing crates.io response")?;
Ok(versions.versions.get(0).unwrap().version.to_owned())
}
fn determine_state(&self) -> anyhow::Result<CrateState> {
let theirs = match self.get_upstream_version() {
Ok(version) => version,
Err(error) => match error.downcast_ref::<Error>() {
Some(Error::CrateNotFound) => return Ok(CrateState::Unknown),
None => return Err(error),
},
};
let ours = self.get_local_version()?;
match theirs.cmp(&ours) {
std::cmp::Ordering::Less => Ok(CrateState::Ahead),
std::cmp::Ordering::Equal => {
log::info!("{self} has already been published as {ours}");
Ok(CrateState::Published)
}
std::cmp::Ordering::Greater => {
log::warn!("{self} has already been published as {ours}, which is a newer version");
Ok(CrateState::Behind)
}
}
}
fn submit(&self, token: &SecUtf8, dry_run: bool) -> anyhow::Result<()> {
log::info!("{self} publishing new version");
let ours = self.get_local_version()?;
let delay = Duration::from_secs(10);
let start_time = Instant::now();
let timeout = Duration::from_secs(600);
let mut attempt = 1;
let maximum_attempts = 10;
loop {
if Instant::now() - start_time > timeout {
bail!("{self} could not be published to the registry within {timeout:?}");
}
if attempt > maximum_attempts {
bail!("{self} could not be published to the registry; tried {attempt} times");
}
let mut command = Command::new("cargo");
command
.arg("publish")
.args(["--token", token.unsecure()])
// By this point in the process, the crates have been built
// successfully multiple times. No reason to slow down the
// release by building them again.
.arg("--no-verify")
.current_dir(&self.path);
if dry_run {
command.arg("--dry-run");
}
let exit_status = command.status()?;
if !exit_status.success() {
match exit_status.code() {
Some(code) => {
log::warn!("`cargo publish` failed with exit code {code}; trying again in {delay:?}");
sleep(delay);
attempt += 1;
continue;
}
None => {
bail!("`cargo publish` was terminated by signal")
}
}
}
log::info!("{self} published as {ours}");
break;
}
Ok(())
}
}
impl FromStr for Crate {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self {
path: PathBuf::from(s),
})
}
}
impl Display for Crate {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if let Some(name) = self.path.file_name() {
return write!(f, "{}", name.to_string_lossy());
}
write!(f, "{:?}", self.path)
}
}