miho 8.3.1

Repository management tools
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use crate::agent::Agent;
use crate::release::Release;
use crate::return_if_ne;
use crate::version::{ComparatorExt, VersionExt, VersionReqExt};
use anyhow::{Result, bail};
use itertools::Itertools;
use jiff::tz::TimeZone;
use jiff::{Timestamp, Zoned};
use reqwest::Client;
use reqwest::header::ACCEPT;
use semver::{Comparator, Version, VersionReq};
use serde_json::Value;
use std::cmp::Ordering;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::sync::nonpoison::Mutex;
use std::sync::{Arc, LazyLock};
use std::{fmt, mem};
use strum::{AsRefStr, Display, EnumIs, EnumString};
use tokio::task::JoinSet;

pub type Cache = HashSet<DependencyCache>;

const CARGO_REGISTRY: &str = "https://crates.io/api/v1/crates";
const NPM_REGISTRY: &str = "https://registry.npmjs.org";

const USER_AGENT: &str = concat!(
  "miho/",
  env!("CARGO_PKG_VERSION"),
  " (https://github.com/ferreira-tb/miho)"
);

static HTTP_CLIENT: LazyLock<Client> = LazyLock::new(|| {
  Client::builder()
    .tls_backend_rustls()
    .user_agent(USER_AGENT)
    .brotli(true)
    .gzip(true)
    .build()
    .expect("failed to create http client")
});

#[derive(Debug)]
pub struct DependencyTree {
  pub agent: Agent,
  pub dependencies: Vec<Dependency>,
}

impl DependencyTree {
  pub fn new(agent: Agent) -> Self {
    Self { agent, dependencies: Vec::new() }
  }

  pub fn add(&mut self, name: impl AsRef<str>, comparator: Comparator, kind: DependencyKind) {
    let dependency = Dependency {
      name: name.as_ref().to_owned(),
      comparator,
      kind,
      versions: Vec::new(),
    };

    self.dependencies.push(dependency);
  }

  /// Add dependencies to the tree.
  pub fn add_many<I, N, V>(&mut self, dependencies: I, kind: DependencyKind)
  where
    I: IntoIterator<Item = (N, V)>,
    N: AsRef<str>,
    V: AsRef<str>,
  {
    for (name, version) in dependencies {
      let version = version.as_ref();
      if let Ok(comparator) = Comparator::parse(version) {
        self.add(name, comparator, kind);
      }
    }
  }

  /// Update the dependency tree, fetching metadata from the registry.
  pub async fn fetch(&mut self, cache: Arc<Mutex<Cache>>) -> Result<()> {
    let mut set = JoinSet::new();

    let dependencies = mem::take(&mut self.dependencies);
    self.dependencies.reserve(dependencies.len());

    for mut dependency in dependencies {
      let agent = self.agent;
      let cache = Arc::clone(&cache);

      {
        let cache = cache.lock();
        if let Some(cached) = find_cached(&cache, &dependency.name, agent) {
          dependency
            .versions
            .clone_from(&cached.versions);

          self.dependencies.push(dependency);
          continue;
        }
      }

      set.spawn(async move {
        dependency.versions = match agent {
          Agent::Cargo => fetch_cargo(&dependency, agent, cache).await?,
          Agent::Npm | Agent::Pnpm => fetch_npm(&dependency, agent, cache).await?,
          Agent::Tauri => bail!("tauri is not a package manager"),
        };

        dependency.versions.shrink_to_fit();

        Ok(dependency)
      });
    }

    while let Some(result) = set.join_next().await {
      let dependency = result??;
      if !dependency.versions.is_empty() {
        self.dependencies.push(dependency);
      }
    }

    self.dependencies.shrink_to_fit();

    Ok(())
  }

  pub fn remove(&mut self, name: &str) {
    self
      .dependencies
      .retain(|it| it.name != name);
  }

  pub fn is_empty(&self) -> bool {
    self.dependencies.is_empty()
  }
}

#[derive(Debug)]
pub struct Dependency {
  pub name: String,
  pub comparator: Comparator,
  pub kind: DependencyKind,
  versions: Vec<DependencyVersion>,
}

impl Dependency {
  pub fn latest(&self) -> Option<&DependencyVersion> {
    self
      .versions
      .iter()
      .max_by(|a, b| Version::cmp_precedence(&a.version, &b.version))
  }

  pub fn latest_with_req(&self, requirement: &VersionReq) -> Option<&DependencyVersion> {
    self
      .versions
      .iter()
      .filter(|it| requirement.matches_any(&it.version))
      .max_by(|a, b| Version::cmp_precedence(&a.version, &b.version))
  }

  pub fn as_target(&self, release: &Release) -> Option<Target<'_>> {
    let comparator = &self.comparator;
    let requirement = comparator
      .with_release(release)
      .as_version_req();

    let (mut target_cmp, time) = self
      .latest_with_req(&requirement)
      .and_then(|version| {
        let cmp = version.as_comparator(comparator.op);
        let cmp = (cmp != *comparator).then_some(cmp)?;
        Some((cmp, version.time.as_ref()))
      })?;

    comparator.normalize(&mut target_cmp);

    if target_cmp == *comparator {
      None
    } else {
      Some(Target {
        dependency: self,
        comparator: target_cmp,
        time,
      })
    }
  }
}

impl PartialEq for Dependency {
  fn eq(&self, other: &Self) -> bool {
    self.name == other.name && self.comparator == other.comparator && self.kind == other.kind
  }
}

impl Eq for Dependency {}

impl PartialOrd for Dependency {
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl Ord for Dependency {
  fn cmp(&self, other: &Self) -> Ordering {
    return_if_ne!(self.kind.cmp(&other.kind));
    self.name.cmp(&other.name)
  }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, AsRefStr, Display, EnumIs, EnumString)]
#[strum(serialize_all = "kebab-case")]
pub enum DependencyKind {
  Build,
  #[strum(to_string = "dev")]
  Development,
  #[strum(to_string = "")]
  Normal,
  Peer,
  PackageManager,
}

impl DependencyKind {
  fn precedence(self) -> u8 {
    match self {
      DependencyKind::Normal => 0,
      DependencyKind::Development => 1,
      DependencyKind::Build => 2,
      DependencyKind::Peer => 3,
      DependencyKind::PackageManager => 4,
    }
  }
}

impl PartialOrd for DependencyKind {
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl Ord for DependencyKind {
  fn cmp(&self, other: &Self) -> Ordering {
    self.precedence().cmp(&other.precedence())
  }
}

#[derive(Clone, Debug)]
pub struct DependencyVersion {
  pub version: Version,
  pub time: Option<Zoned>,
}

#[derive(Debug)]
pub struct Target<'a> {
  pub dependency: &'a Dependency,
  pub comparator: Comparator,
  pub time: Option<&'a Zoned>,
}

impl fmt::Display for Target<'_> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "{}", self.comparator)
  }
}

#[derive(Debug)]
pub struct DependencyCache {
  pub agent: Agent,
  pub name: String,
  pub versions: Vec<DependencyVersion>,
}

impl PartialEq for DependencyCache {
  fn eq(&self, other: &Self) -> bool {
    self.name == other.name && self.agent == other.agent
  }
}

impl Eq for DependencyCache {}

impl Hash for DependencyCache {
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.name.hash(state);
    self.agent.hash(state);
  }
}

/// <https://doc.rust-lang.org/cargo/reference/registry-web-api.html>
async fn fetch_cargo(
  dependency: &Dependency,
  agent: Agent,
  cache: Arc<Mutex<Cache>>,
) -> Result<Vec<DependencyVersion>> {
  let url = format!("{CARGO_REGISTRY}/{}/versions", dependency.name);
  let response = HTTP_CLIENT.get(&url).send().await?;

  let json: Value = response.json().await?;
  let Some(versions) = json
    .get("versions")
    .and_then(Value::as_array)
  else {
    bail!("no versions found for {}", dependency.name);
  };

  let versions = versions
    .iter()
    .filter_map(|value| {
      if value
        .get("yanked")
        .and_then(Value::as_bool)?
      {
        return None;
      }

      let version = value
        .get("num")
        .and_then(Value::as_str)
        .and_then(|it| Version::parse(it).ok())?;

      let time = if let Some(created_at) = value.get("created_at")
        && let Some(created_at) = created_at.as_str()
        && let Ok(timestamp) = created_at.parse::<Timestamp>()
      {
        Some(timestamp.to_zoned(TimeZone::UTC))
      } else {
        None
      };

      Some(DependencyVersion { version, time })
    })
    .collect_vec();

  add_to_cache(&mut cache.lock(), &dependency.name, agent, &versions);

  Ok(versions)
}

/// <https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md>
async fn fetch_npm(
  dependency: &Dependency,
  agent: Agent,
  cache: Arc<Mutex<Cache>>,
) -> Result<Vec<DependencyVersion>> {
  let url = format!("{NPM_REGISTRY}/{}", dependency.name);
  let response = HTTP_CLIENT
    .get(&url)
    .header(ACCEPT, "application/json")
    .send()
    .await?;

  let json: Value = response.json().await?;
  let Some(versions) = json
    .get("versions")
    .and_then(Value::as_object)
  else {
    bail!("no versions found for {}", dependency.name);
  };

  let time_table = json.get("time").and_then(Value::as_object);

  let versions = versions
    .values()
    .filter_map(|value| {
      if value
        .get("deprecated")
        .and_then(Value::as_str)
        .is_some_and(|it| !it.is_empty())
      {
        return None;
      }

      let version = value
        .get("version")
        .and_then(Value::as_str)
        .and_then(|it| Version::parse(it).ok())?;

      let time = if let Some(time_table) = time_table
        && let Some(value) = time_table.get(&version.to_string())
        && let Some(value) = value.as_str()
        && let Ok(timestamp) = value.parse::<Timestamp>()
      {
        Some(timestamp.to_zoned(TimeZone::UTC))
      } else {
        None
      };

      Some(DependencyVersion { version, time })
    })
    .collect_vec();

  add_to_cache(&mut cache.lock(), &dependency.name, agent, &versions);

  Ok(versions)
}

fn add_to_cache(cache: &mut Cache, name: &str, agent: Agent, versions: &[DependencyVersion]) {
  if find_cached(cache, name, agent).is_none() {
    let dependency = DependencyCache {
      agent,
      name: name.to_owned(),
      versions: versions.to_vec(),
    };

    cache.insert(dependency);
  }
}

fn find_cached<'a>(cache: &'a Cache, name: &str, agent: Agent) -> Option<&'a DependencyCache> {
  cache
    .iter()
    .find(|c| c.name == name && c.agent == agent)
}