1use std::path::Path;
10
11use bynk_project::manifest::{DependencySource, package_config_from};
12
13use super::archive;
14use super::{Client, TokenSource};
15use crate::fetch::{FetchError, fail};
16
17pub(crate) const PUBLISH_REFUSED: &str = "bynk.registry.publish_refused";
18
19#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct Published {
22 pub name: String,
23 pub version: String,
24 pub checksum: String,
25 pub registry: String,
26 pub dry_run: bool,
28 pub files: Vec<(String, u64)>,
30}
31
32pub fn publish(
37 project: &Path,
38 dry_run: bool,
39 expect_checksum: Option<&str>,
40) -> Result<Published, FetchError> {
41 let doc = crate::fetch::read_manifest(project)
42 .ok_or_else(|| fail(PUBLISH_REFUSED, "there is no readable `bynk.toml` here"))?;
43 let package = doc
44 .get("package")
45 .and_then(|v| v.as_table())
46 .and_then(|t| package_config_from(t).ok())
47 .ok_or_else(|| {
48 fail(
49 PUBLISH_REFUSED,
50 "this project isn't a package: `bynk.toml` has no `[package]`",
51 )
52 })?;
53 let version = package.version.clone().ok_or_else(|| {
54 fail(
55 PUBLISH_REFUSED,
56 "`[package]` has no `version`, which publishing needs",
57 )
58 })?;
59 for spec in crate::fetch::specs(&doc, "dependencies") {
60 if !matches!(spec.source, DependencySource::Version(_)) {
61 return Err(fail(
62 PUBLISH_REFUSED,
63 format!(
64 "the dependency `{}` is a path or git dependency, which a registry refuses — publish it, and depend on it by `version`",
65 spec.alias
66 ),
67 ));
68 }
69 }
70 let name = format!("{}/{}", package.org, package.package);
71 let archive::Packed {
72 bytes,
73 checksum,
74 files,
75 } = archive::pack_listing(project)
76 .map_err(|e| fail(PUBLISH_REFUSED, format!("could not pack the package: {e}")))?;
77 if let Some(expected) = expect_checksum
78 && expected != checksum
79 {
80 return Err(fail(
81 PUBLISH_REFUSED,
82 format!(
83 "the package changed since it was planned: it packs to {checksum}, not the expected {expected} — plan it again"
84 ),
85 ));
86 }
87 let (mut client, registry) = client_for(project, &package.org);
88 client.writable(®istry)?;
90 let mut out = Published {
91 name: name.clone(),
92 version: version.clone(),
93 checksum: checksum.clone(),
94 registry: registry.clone(),
95 dry_run,
96 files,
97 };
98 if dry_run {
99 return Ok(out);
100 }
101 let (status, body) =
102 client.api_write(®istry, "PUT", &format!("{name}/{version}"), Some(&bytes))?;
103 if status != 201 && status != 200 {
104 return Err(refused(&client, ®istry, &package.org, status, &body));
105 }
106 client.forget(®istry, &name);
108 let lines = client.lines(®istry, &name)?;
109 let line = lines.iter().find(|l| l.version == version).ok_or_else(|| {
110 fail(
111 PUBLISH_REFUSED,
112 format!(
113 "registry `{registry}` accepted `{name}` {version}, but its index doesn't list it"
114 ),
115 )
116 })?;
117 if line.checksum != checksum {
118 return Err(fail(
119 crate::fetch::CHECKSUM_MISMATCH,
120 format!(
121 "registry `{registry}` signed `{name}` {version} as the tree {}, but bynk sent {checksum}",
122 line.checksum
123 ),
124 ));
125 }
126 out.checksum = line.checksum.clone();
127 Ok(out)
128}
129
130pub fn yank(
133 project: &Path,
134 package: &str,
135 version: &str,
136 undo: bool,
137) -> Result<String, FetchError> {
138 let org = package.split('/').next().unwrap_or_default();
139 let (mut client, registry) = client_for(project, org);
140 let verb = if undo { "unyank" } else { "yank" };
141 let (status, body) = client.api_write(
142 ®istry,
143 "POST",
144 &format!("{package}/{version}/{verb}"),
145 None,
146 )?;
147 if !(200..300).contains(&status) {
148 return Err(refused(&client, ®istry, org, status, &body));
149 }
150 client.forget(®istry, package);
151 let lines = client.lines(®istry, package)?;
152 match lines.iter().find(|l| l.version == version) {
153 Some(l) if l.yanked == undo => Err(fail(
154 PUBLISH_REFUSED,
155 format!("registry `{registry}` accepted the {verb}, but its index doesn't show it"),
156 )),
157 Some(_) => Ok(registry),
158 None => Err(fail(
159 PUBLISH_REFUSED,
160 format!("registry `{registry}` has no `{package}` {version}"),
161 )),
162 }
163}
164
165fn client_for(project: &Path, org: &str) -> (Client, String) {
168 let root = bynk_project::lock::lock_root(project);
169 let lock = std::fs::read_to_string(root.join(bynk_project::lock::LOCK_FILE))
170 .ok()
171 .and_then(|t| bynk_project::lock::parse_lock(&t).ok());
172 let client = Client::new(super::commands::registries_of(&root), lock.as_ref()).acting_for(org);
173 let registry = client.route(org);
174 (client, registry)
175}
176
177fn refused(client: &Client, registry: &str, org: &str, status: u16, body: &[u8]) -> FetchError {
180 let parsed: Option<(String, String)> = serde_json::from_slice::<serde_json::Value>(body)
181 .ok()
182 .and_then(|v| {
183 Some((
184 v.get("error")?.as_str()?.to_owned(),
185 v.get("message")?.as_str()?.to_owned(),
186 ))
187 });
188 let source = client.token_source(registry);
189 let hint = token_hint(registry, org, status, source);
190 let why = match parsed {
191 Some((code, message)) => {
192 format!("registry `{registry}` refused it (HTTP {status}, `{code}`): {message}")
193 }
194 None if status == 401 => format!("registry `{registry}` needs a publish token (HTTP 401)"),
195 None => format!("registry `{registry}` refused it (HTTP {status})"),
196 };
197 fail(PUBLISH_REFUSED, format!("{why}{hint}"))
198}
199
200fn token_hint(registry: &str, org: &str, status: u16, source: Option<&TokenSource>) -> String {
203 let save = format!("save one for `{org}` with `bynk org token mint {org} --save`");
204 match (status, source) {
205 (401, None) => format!(
206 "\n = note: no token was found: set `{}`, or {save}",
207 bynk_project::manifest::registry_token_var(registry)
208 ),
209 (401, Some(source @ TokenSource::Organisation { .. })) => format!(
210 "\n = note: the token came from {source}; if it expired or was revoked, replace it with `bynk org token mint {org} --save --force`"
211 ),
212 (403, Some(source @ TokenSource::Organisation { .. })) => {
213 format!("\n = note: the token came from {source}")
214 }
215 (401 | 403, Some(source @ TokenSource::Var(_))) => format!(
216 "\n = note: the token came from {source}, which is used instead of any saved token"
217 ),
218 (401 | 403, Some(source @ TokenSource::Registry(_))) => {
219 format!("\n = note: the token came from {source}; {save}")
220 }
221 _ => String::new(),
222 }
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228
229 #[test]
230 fn a_refused_token_s_source_is_named() {
231 let var = TokenSource::Var("BYNK_REGISTRY_BYNK_TOKEN".into());
232 let wide = TokenSource::Registry("bynk".into());
233 let own = TokenSource::Organisation {
234 registry: "bynk".into(),
235 org: "acme".into(),
236 };
237 assert_eq!(
238 token_hint("bynk", "acme", 401, None),
239 "\n = note: no token was found: set `BYNK_REGISTRY_BYNK_TOKEN`, or save one for `acme` with `bynk org token mint acme --save`"
240 );
241 assert_eq!(
242 token_hint("bynk", "acme", 403, Some(&wide)),
243 "\n = note: the token came from `[registries.bynk] token`; save one for `acme` with `bynk org token mint acme --save`"
244 );
245 assert_eq!(
246 token_hint("bynk", "acme", 403, Some(&own)),
247 "\n = note: the token came from `[registries.bynk.organisations.acme] token`"
248 );
249 assert!(token_hint("bynk", "acme", 401, Some(&var)).contains("instead of any saved token"));
250 assert!(
251 token_hint("bynk", "acme", 401, Some(&own))
252 .ends_with("`bynk org token mint acme --save --force`")
253 );
254 assert_eq!(token_hint("bynk", "acme", 409, Some(&own)), "");
255 }
256}