Skip to main content

bynk/registry/
query.rs

1//! Read-only registry queries for editors and scripts (#2472): `bynk search`
2//! and `bynk deps`, and the JSON documents `bynk add`, `bynk fetch` and
3//! `bynk publish` print under `--format json`.
4//!
5//! The registry protocol is a static, per-package index (packaging ยง6.2): it
6//! has no listing or free-text search, so `search` is an exact `org/package`
7//! lookup through the same verifying `Client` a build uses.
8//! Everything here goes through the driver so that routing, trust, tokens and
9//! caching stay in one place (#2472, decision A).
10
11use std::path::Path;
12
13use bynk_project::lock::{parse_registry_source, read_lock};
14use bynk_project::manifest::DependencySource;
15use serde_json::{Value, json};
16
17use super::publish::Published;
18use crate::fetch::Prepared;
19
20/// One version of a package, as `search` reports it.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct Version {
23    pub version: String,
24    pub checksum: String,
25    pub yanked: bool,
26    pub withdrawn: Option<String>,
27}
28
29/// What `bynk search <package>` found.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Found {
32    pub package: String,
33    pub registry: String,
34    /// Oldest first, as the index lists them.
35    pub versions: Vec<Version>,
36}
37
38impl Found {
39    /// The highest version that is neither yanked nor withdrawn (a
40    /// pre-release only when nothing else is offered).
41    pub fn latest(&self) -> Option<&str> {
42        let usable = || {
43            self.versions
44                .iter()
45                .filter(|v| !v.yanked && v.withdrawn.is_none())
46                .filter_map(|v| semver::Version::parse(&v.version).ok().map(|s| (s, v)))
47        };
48        let stable = usable()
49            .filter(|(s, _)| s.pre.is_empty())
50            .max_by(|a, b| a.0.cmp(&b.0));
51        stable
52            .or_else(|| usable().max_by(|a, b| a.0.cmp(&b.0)))
53            .map(|(_, v)| v.version.as_str())
54    }
55
56    pub fn to_json(&self) -> Value {
57        json!({
58            "package": self.package,
59            "registry": self.registry,
60            "latest": self.latest(),
61            "versions": self.versions.iter().map(|v| json!({
62                "version": v.version,
63                "checksum": v.checksum,
64                "yanked": v.yanked,
65                "withdrawn": v.withdrawn,
66            })).collect::<Vec<_>>(),
67        })
68    }
69}
70
71/// Look `package` (`org/package`) up on the registry its organisation routes
72/// to, from the project at `project`.
73pub fn search(project: &Path, package: &str) -> Result<Found, String> {
74    if let Some(problem) = bynk_project::manifest::package_name_problem(package) {
75        return Err(format!("`{package}` {problem}"));
76    }
77    let org = package.split_once('/').map_or(package, |(o, _)| o);
78    let root = bynk_project::lock::lock_root(project);
79    let mut client = super::Client::new(super::commands::registries_of(&root), None);
80    let registry = client.route(org);
81    let lines = client.lines(&registry, package).map_err(|e| e.message)?;
82    Ok(Found {
83        package: package.to_string(),
84        registry,
85        versions: lines
86            .into_iter()
87            .map(|l| Version {
88                version: l.version,
89                checksum: l.checksum,
90                yanked: l.yanked,
91                withdrawn: l.withdrawn,
92            })
93            .collect(),
94    })
95}
96
97/// One `[dependencies]` or `[dev-dependencies]` entry with what `bynk.lock`
98/// resolved it to.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct Dependency {
101    pub alias: String,
102    pub package: String,
103    pub dev: bool,
104    /// `registry`, `git` or `path`.
105    pub kind: &'static str,
106    /// The version range, git revision or path the manifest asks for.
107    pub requested: String,
108    /// The registry name, git URL or path.
109    pub source: String,
110    /// The version `bynk.lock` pins, when it records one.
111    pub locked: Option<String>,
112}
113
114/// The dependencies of the project at `project`, offline: the manifest's
115/// entries joined to `bynk.lock`.
116pub fn dependencies(project: &Path) -> Result<Vec<Dependency>, String> {
117    let doc = crate::fetch::read_manifest(project)
118        .ok_or_else(|| "there is no readable `bynk.toml` here".to_string())?;
119    let root = bynk_project::lock::lock_root(project);
120    let lock = read_lock(&root, &Default::default()).map_err(|e| e.to_string())?;
121    let configs = super::commands::registries_of(&root);
122    let mut out = Vec::new();
123    for (table, dev) in [("dependencies", false), ("dev-dependencies", true)] {
124        for spec in crate::fetch::specs(&doc, table) {
125            let locked = lock.as_ref().and_then(|l| l.package(&spec.package));
126            let (kind, requested, source) = match &spec.source {
127                DependencySource::Version(range) => {
128                    let org = spec.package.split_once('/').map_or("", |(o, _)| o);
129                    let registry = locked
130                        .and_then(|p| parse_registry_source(&p.source))
131                        .map(str::to_string)
132                        .or_else(|| {
133                            configs
134                                .iter()
135                                .find(|c| c.organisations.iter().any(|o| o == org))
136                                .map(|c| c.name.clone())
137                        })
138                        .unwrap_or_else(|| bynk_project::lock::FIRST_PARTY_REGISTRY.to_string());
139                    ("registry", range.clone(), registry)
140                }
141                DependencySource::Git { url, rev } => ("git", rev.clone(), url.clone()),
142                DependencySource::Path(p) => ("path", p.clone(), p.clone()),
143            };
144            out.push(Dependency {
145                alias: spec.alias,
146                package: spec.package,
147                dev,
148                kind,
149                requested,
150                source,
151                locked: locked.and_then(|p| p.version.clone()),
152            });
153        }
154    }
155    Ok(out)
156}
157
158/// The `bynk deps --format json` document.
159pub fn dependencies_json(deps: &[Dependency]) -> Value {
160    json!({
161        "dependencies": deps.iter().map(|d| json!({
162            "alias": d.alias,
163            "package": d.package,
164            "dev": d.dev,
165            "kind": d.kind,
166            "requested": d.requested,
167            "source": d.source,
168            "locked": d.locked,
169        })).collect::<Vec<_>>(),
170    })
171}
172
173/// The `bynk add --format json` document: the manifest line written.
174pub fn added_json(alias: &str, package: &str, version: &str) -> Value {
175    json!({ "added": { "alias": alias, "package": package, "version": version } })
176}
177
178/// The `bynk fetch --format json` document.
179pub fn fetched_json(done: &Prepared) -> Value {
180    json!({
181        "wrote_lock": done.wrote_lock,
182        "fetched": done.fetched,
183        "warnings": done.warnings,
184        "pending_npm": done.pending.iter().map(|n| json!({
185            "package": n.package,
186            "range": n.range,
187            "required_by": n.required_by,
188        })).collect::<Vec<_>>(),
189    })
190}
191
192/// The `bynk publish --format json` document (also for `--dry-run`).
193pub fn published_json(p: &Published) -> Value {
194    json!({
195        "package": p.name,
196        "version": p.version,
197        "checksum": p.checksum,
198        "registry": p.registry,
199        "dry_run": p.dry_run,
200        "files": p.files.iter().map(|(path, bytes)| json!({ "path": path, "bytes": bytes })).collect::<Vec<_>>(),
201    })
202}