1use std::collections::{HashMap, HashSet};
25use std::fs::File;
26use std::hash::Hash;
27use std::os::unix::fs::FileExt;
28use std::path::Path;
29use std::sync::Arc;
30
31use anyhow::{anyhow, Result};
32use arrow::array::{Array, StringArray};
33use arrow::record_batch::RecordBatch;
34
35use crate::codec;
36use crate::index::{read_znippy_index_filtered, IndexFilter};
37use crate::plugin::file_name;
38
39pub const RUST_PKG_TYPE: i8 = 1;
51pub const PYTHON_PKG_TYPE: i8 = 2;
53pub const MAVEN_PKG_TYPE: i8 = 3;
55pub const NPM_PKG_TYPE: i8 = 6;
57pub const GEM_PKG_TYPE: i8 = 11;
59pub const RPM_PKG_TYPE: i8 = 8;
61pub const DEB_PKG_TYPE: i8 = 9;
63pub const CONDA_PKG_TYPE: i8 = 14;
65
66#[derive(Debug, Clone)]
70#[non_exhaustive]
71pub struct FileLoc {
72 pub relative_path: String,
85 pub chunks: Vec<ChunkRef>,
87 pub uncompressed_size: u64,
89}
90
91#[derive(Debug, Clone, Copy)]
93#[non_exhaustive]
94pub struct ChunkRef {
95 pub blob_offset: u64,
96 pub blob_size: u64,
97 pub fdata_offset: u64,
98 pub compressed: bool,
99}
100
101impl FileLoc {
102 fn read_bytes(&self, archive: &File) -> Result<Vec<u8>> {
105 let mut result = Vec::with_capacity(self.uncompressed_size as usize);
106 let mut blob = Vec::new();
107 let mut decomp = Vec::new();
108 for chunk in &self.chunks {
109 blob.resize(chunk.blob_size as usize, 0);
110 archive.read_exact_at(&mut blob, chunk.blob_offset)?;
111 if chunk.compressed {
112 codec::decompress_into(&blob, &mut decomp)?;
113 result.extend_from_slice(&decomp);
114 } else {
115 result.extend_from_slice(&blob);
116 }
117 }
118 Ok(result)
119 }
120}
121
122fn group_rows_by_file(batch: &RecordBatch) -> Result<HashMap<String, FileLoc>> {
125 use arrow::array::{BooleanArray, UInt64Array};
126
127 let col = |n: &str| {
128 batch
129 .column_by_name(n)
130 .ok_or_else(|| anyhow!("index missing column {n}"))
131 };
132 let paths = col("relative_path")?
133 .as_any()
134 .downcast_ref::<StringArray>()
135 .ok_or_else(|| anyhow!("relative_path not StringArray"))?;
136 let compressed = col("compressed")?
137 .as_any()
138 .downcast_ref::<BooleanArray>()
139 .ok_or_else(|| anyhow!("compressed not BooleanArray"))?;
140 let sizes = col("uncompressed_size")?
141 .as_any()
142 .downcast_ref::<UInt64Array>()
143 .ok_or_else(|| anyhow!("uncompressed_size not UInt64Array"))?;
144 let blob_offset = col("blob_offset")?
145 .as_any()
146 .downcast_ref::<UInt64Array>()
147 .ok_or_else(|| anyhow!("blob_offset not UInt64Array"))?;
148 let blob_size = col("blob_size")?
149 .as_any()
150 .downcast_ref::<UInt64Array>()
151 .ok_or_else(|| anyhow!("blob_size not UInt64Array"))?;
152 let fdata = col("fdata_offset")?
153 .as_any()
154 .downcast_ref::<UInt64Array>()
155 .ok_or_else(|| anyhow!("fdata_offset not UInt64Array"))?;
156
157 let mut by_path: HashMap<String, FileLoc> = HashMap::new();
158 for i in 0..batch.num_rows() {
159 let path = paths.value(i);
160 let entry = by_path.entry(path.to_string()).or_insert_with(|| FileLoc {
161 relative_path: path.to_string(),
162 chunks: Vec::new(),
163 uncompressed_size: 0,
164 });
165 entry.uncompressed_size += sizes.value(i);
166 entry.chunks.push(ChunkRef {
167 blob_offset: blob_offset.value(i),
168 blob_size: blob_size.value(i),
169 fdata_offset: fdata.value(i),
170 compressed: compressed.value(i),
171 });
172 }
173 for f in by_path.values_mut() {
174 f.chunks.sort_by_key(|c| c.fdata_offset);
175 }
176 Ok(by_path)
177}
178
179
180
181mod sealed {
186 pub trait Sealed {}
187}
188
189pub trait CoordSpec: sealed::Sealed + Send + Sync + 'static {
194 const PKG_TYPE: i8;
196 const SLOT: usize;
198 const COLS: &'static [&'static str];
201 const REQUIRED: usize;
202 type Key: Eq + Hash + Clone + Send + Sync;
204 type Extra: Clone + Send + Sync;
206 fn row(c: &Cells<'_>, path: &str) -> (Self::Key, Self::Extra);
208 fn replaces(_new: &Self::Extra) -> bool {
210 true
211 }
212}
213
214pub struct Cells<'a> {
216 cols: &'a [Option<&'a StringArray>],
217 i: usize,
218}
219
220impl Cells<'_> {
221 pub fn opt(&self, j: usize) -> Option<String> {
223 self.cols[j].filter(|a| !a.is_null(self.i)).map(|a| a.value(self.i).to_string())
224 }
225 pub fn get(&self, j: usize) -> String {
227 self.opt(j).unwrap_or_default()
228 }
229 pub fn non_empty(&self, j: usize) -> Option<String> {
231 self.opt(j).filter(|s| !s.is_empty())
232 }
233}
234
235pub struct CoordView<S: CoordSpec> {
238 archive: Arc<File>,
239 coords: HashMap<S::Key, (FileLoc, S::Extra)>,
240}
241
242pub struct Package<S: CoordSpec> {
245 archive: Arc<File>,
246 loc: FileLoc,
247 key: S::Key,
248 extra: S::Extra,
249}
250
251impl<S: CoordSpec> CoordView<S> {
252 pub(crate) fn build(path: &Path, archive: Arc<File>) -> Result<Self> {
253 let (_schema, batches) =
254 read_znippy_index_filtered(path, &IndexFilter { pkg_type: Some(S::PKG_TYPE), repo: None })?;
255 let mut coords: HashMap<S::Key, (FileLoc, S::Extra)> = HashMap::new();
256 for batch in &batches {
257 let cols: Vec<Option<&StringArray>> = S::COLS
258 .iter()
259 .map(|n| batch.column_by_name(n).and_then(|c| c.as_any().downcast_ref::<StringArray>()))
260 .collect();
261 if cols[..S::REQUIRED].iter().any(Option::is_none) {
262 continue;
263 }
264 let paths = batch
265 .column_by_name("relative_path")
266 .and_then(|c| c.as_any().downcast_ref::<StringArray>())
267 .ok_or_else(|| anyhow!("missing relative_path"))?;
268 let locs = group_rows_by_file(batch)?;
269 let mut seen = HashSet::new();
270 for i in 0..batch.num_rows() {
271 let p = paths.value(i);
272 if !seen.insert(p) || cols[..S::REQUIRED].iter().any(|c| c.is_some_and(|a| a.is_null(i))) {
274 continue;
275 }
276 let Some(loc) = locs.get(p) else { continue };
277 let (key, extra) = S::row(&Cells { cols: &cols, i }, p);
278 if S::replaces(&extra) || !coords.contains_key(&key) {
279 coords.insert(key, (loc.clone(), extra));
280 }
281 }
282 }
283 Ok(Self { archive, coords })
284 }
285
286 fn package(&self, key: &S::Key) -> Option<Package<S>> {
287 let (loc, extra) = self.coords.get(key)?;
288 Some(Package { archive: Arc::clone(&self.archive), loc: loc.clone(), key: key.clone(), extra: extra.clone() })
289 }
290
291 fn entries(&self) -> impl Iterator<Item = (&S::Key, &S::Extra)> {
293 self.coords.iter().map(|(k, (_, e))| (k, e))
294 }
295
296 pub fn len(&self) -> usize {
298 self.coords.len()
299 }
300 pub fn is_empty(&self) -> bool {
301 self.coords.is_empty()
302 }
303}
304
305impl<S: CoordSpec> Package<S> {
306 pub fn relative_path(&self) -> &str {
310 &self.loc.relative_path
311 }
312 pub fn size(&self) -> u64 {
314 self.loc.uncompressed_size
315 }
316 pub fn bytes(&self) -> Result<Vec<u8>> {
318 self.loc.read_bytes(&self.archive)
319 }
320 pub fn into_bytes(self) -> Result<Vec<u8>> {
321 self.loc.read_bytes(&self.archive)
322 }
323}
324
325macro_rules! spec {
327 ($t:ident) => {
328 #[doc = concat!("The coord spec behind [`", stringify!($t), "`]'s view.")]
329 pub struct $t;
330 impl sealed::Sealed for $t {}
331 };
332}
333
334fn s2(k: &(String, String)) -> (String, String) {
335 k.clone()
336}
337
338spec!(RustSpec);
341impl CoordSpec for RustSpec {
342 const PKG_TYPE: i8 = RUST_PKG_TYPE;
343 const SLOT: usize = 0;
344 const COLS: &'static [&'static str] = &["crate_name", "version"];
345 const REQUIRED: usize = 2;
346 type Key = (String, String);
347 type Extra = ();
348 fn row(c: &Cells<'_>, _: &str) -> (Self::Key, ()) {
349 ((c.get(0), c.get(1)), ())
350 }
351}
352pub type RustView = CoordView<RustSpec>;
354pub type RustPackage = Package<RustSpec>;
356
357impl RustView {
358 pub fn get(&self, name: &str, version: &str) -> Option<RustPackage> {
360 self.package(&(name.to_string(), version.to_string()))
361 }
362 pub fn list(&self) -> Vec<(String, String)> {
364 self.entries().map(|(k, _)| s2(k)).collect()
365 }
366}
367impl RustPackage {
368 pub fn name(&self) -> &str {
370 &self.key.0
371 }
372 pub fn version(&self) -> &str {
373 &self.key.1
374 }
375}
376
377spec!(MavenSpec);
380impl CoordSpec for MavenSpec {
381 const PKG_TYPE: i8 = MAVEN_PKG_TYPE;
382 const SLOT: usize = 1;
383 const COLS: &'static [&'static str] = &["group_id", "artifact_id", "version", "classifier"];
384 const REQUIRED: usize = 3;
385 type Key = (String, String, String, Option<String>);
387 type Extra = ();
388 fn row(c: &Cells<'_>, path: &str) -> (Self::Key, ()) {
389 let (g, a, v) = (c.get(0), c.get(1), c.get(2));
390 let classifier = c.non_empty(3).or_else(|| derive_classifier(file_name(path), &a, &v));
392 ((g, a, v, classifier), ())
393 }
394}
395pub type MavenView = CoordView<MavenSpec>;
397pub type MavenPackage = Package<MavenSpec>;
399
400impl MavenView {
401 pub fn get(&self, group: &str, artifact: &str, version: &str) -> Option<MavenPackage> {
403 self.get_classified(group, artifact, version, None)
404 }
405 pub fn get_classified(
407 &self,
408 group: &str,
409 artifact: &str,
410 version: &str,
411 classifier: Option<&str>,
412 ) -> Option<MavenPackage> {
413 self.package(&(group.into(), artifact.into(), version.into(), classifier.map(str::to_string)))
414 }
415 pub fn list(&self) -> Vec<(String, String, String, Option<String>)> {
417 self.entries().map(|(k, _)| k.clone()).collect()
418 }
419}
420
421fn derive_classifier(filename: &str, artifact: &str, version: &str) -> Option<String> {
424 let stem = filename.rsplit_once('.').map(|(s, _)| s).unwrap_or(filename);
425 let rest = stem.strip_prefix(&format!("{artifact}-{version}"))?.strip_prefix('-')?;
426 (!rest.is_empty()).then(|| rest.to_string())
427}
428
429impl MavenPackage {
430 pub fn group(&self) -> &str {
431 &self.key.0
432 }
433 pub fn artifact(&self) -> &str {
434 &self.key.1
435 }
436 pub fn version(&self) -> &str {
437 &self.key.2
438 }
439 pub fn classifier(&self) -> Option<&str> {
441 self.key.3.as_deref()
442 }
443 pub fn coords(&self) -> (&str, &str, &str, Option<&str>) {
445 (&self.key.0, &self.key.1, &self.key.2, self.key.3.as_deref())
446 }
447}
448
449#[derive(Debug, Clone, Copy, PartialEq, Eq)]
453pub enum PythonKind {
454 Wheel,
455 Sdist,
456}
457
458spec!(PythonSpec);
459impl CoordSpec for PythonSpec {
460 const PKG_TYPE: i8 = PYTHON_PKG_TYPE;
461 const SLOT: usize = 2;
462 const COLS: &'static [&'static str] = &["name", "version"];
463 const REQUIRED: usize = 2;
464 type Key = (String, String);
465 type Extra = PythonKind;
466 fn row(c: &Cells<'_>, path: &str) -> (Self::Key, PythonKind) {
467 let kind = if file_name(path).ends_with(".whl") { PythonKind::Wheel } else { PythonKind::Sdist };
468 ((c.get(0), c.get(1)), kind)
469 }
470 fn replaces(new: &PythonKind) -> bool {
472 *new == PythonKind::Wheel
473 }
474}
475pub type PythonView = CoordView<PythonSpec>;
477pub type PythonPackage = Package<PythonSpec>;
479
480impl PythonView {
481 pub fn get(&self, name: &str, version: &str) -> Option<PythonPackage> {
483 self.package(&(name.to_string(), version.to_string()))
484 }
485 pub fn list(&self) -> Vec<(String, String)> {
487 self.entries().map(|(k, _)| s2(k)).collect()
488 }
489}
490impl PythonPackage {
491 pub fn name(&self) -> &str {
492 &self.key.0
493 }
494 pub fn version(&self) -> &str {
495 &self.key.1
496 }
497 pub fn kind(&self) -> PythonKind {
499 self.extra
500 }
501}
502
503spec!(NpmSpec);
506impl CoordSpec for NpmSpec {
507 const PKG_TYPE: i8 = NPM_PKG_TYPE;
508 const SLOT: usize = 3;
509 const COLS: &'static [&'static str] = &["name", "version"];
510 const REQUIRED: usize = 2;
511 type Key = (String, String);
514 type Extra = ();
515 fn row(c: &Cells<'_>, _: &str) -> (Self::Key, ()) {
516 ((c.get(0), c.get(1)), ())
517 }
518}
519pub type NpmView = CoordView<NpmSpec>;
521pub type NpmPackage = Package<NpmSpec>;
523
524impl NpmView {
525 pub fn get(&self, name: &str, version: &str) -> Option<NpmPackage> {
527 self.package(&(name.to_string(), version.to_string()))
528 }
529 pub fn list(&self) -> Vec<(String, String)> {
531 self.entries().map(|(k, _)| s2(k)).collect()
532 }
533}
534impl NpmPackage {
535 pub fn name(&self) -> &str {
537 &self.key.0
538 }
539 pub fn version(&self) -> &str {
540 &self.key.1
541 }
542}
543
544spec!(GemSpec);
547impl CoordSpec for GemSpec {
548 const PKG_TYPE: i8 = GEM_PKG_TYPE;
549 const SLOT: usize = 4;
550 const COLS: &'static [&'static str] = &["name", "version", "platform"];
551 const REQUIRED: usize = 2;
552 type Key = (String, String, String);
555 type Extra = ();
556 fn row(c: &Cells<'_>, _: &str) -> (Self::Key, ()) {
557 ((c.get(0), c.get(1), c.non_empty(2).unwrap_or_else(|| "ruby".into())), ())
558 }
559}
560pub type GemView = CoordView<GemSpec>;
562pub type GemPackage = Package<GemSpec>;
564
565impl GemView {
566 pub fn get(&self, name: &str, version: &str) -> Option<GemPackage> {
568 self.get_platform(name, version, "ruby")
569 }
570 pub fn get_platform(&self, name: &str, version: &str, platform: &str) -> Option<GemPackage> {
572 self.package(&(name.into(), version.into(), platform.into()))
573 }
574 pub fn list(&self) -> Vec<(String, String, String)> {
576 self.entries().map(|(k, _)| k.clone()).collect()
577 }
578}
579impl GemPackage {
580 pub fn name(&self) -> &str {
581 &self.key.0
582 }
583 pub fn version(&self) -> &str {
584 &self.key.1
585 }
586 pub fn platform(&self) -> &str {
588 &self.key.2
589 }
590}
591
592spec!(CondaSpec);
595impl CoordSpec for CondaSpec {
596 const PKG_TYPE: i8 = CONDA_PKG_TYPE;
597 const SLOT: usize = 5;
598 const COLS: &'static [&'static str] = &["name", "version", "build", "subdir"];
599 const REQUIRED: usize = 2;
600 type Key = (String, String, String, String);
603 type Extra = ();
604 fn row(c: &Cells<'_>, _: &str) -> (Self::Key, ()) {
605 ((c.get(0), c.get(1), c.get(2), c.get(3)), ())
606 }
607}
608pub type CondaView = CoordView<CondaSpec>;
610pub type CondaPackage = Package<CondaSpec>;
612
613impl CondaView {
614 pub fn get(&self, name: &str, version: &str) -> Option<CondaPackage> {
617 let key = self.coords.keys().find(|k| k.0 == name && k.1 == version)?.clone();
618 self.package(&key)
619 }
620 pub fn get_exact(&self, name: &str, version: &str, build: &str, subdir: &str) -> Option<CondaPackage> {
622 self.package(&(name.into(), version.into(), build.into(), subdir.into()))
623 }
624 pub fn list(&self) -> Vec<(String, String, String, String)> {
626 self.entries().map(|(k, _)| k.clone()).collect()
627 }
628}
629impl CondaPackage {
630 pub fn name(&self) -> &str {
631 &self.key.0
632 }
633 pub fn version(&self) -> &str {
634 &self.key.1
635 }
636 pub fn build(&self) -> &str {
638 &self.key.2
639 }
640 pub fn subdir(&self) -> &str {
642 &self.key.3
643 }
644}
645
646#[derive(Debug, Clone, PartialEq, Eq)]
651pub struct RpmMetaRow {
652 pub name: String,
653 pub version: String,
654 pub release: String,
655 pub arch: String,
656 pub epoch: Option<String>,
657 pub summary: Option<String>,
658 pub license: Option<String>,
659 pub url: Option<String>,
660 pub vendor: Option<String>,
661 pub sourcerpm: Option<String>,
662 pub provides: Vec<String>,
663 pub requires: Vec<String>,
664}
665
666spec!(RpmSpec);
667impl CoordSpec for RpmSpec {
668 const PKG_TYPE: i8 = RPM_PKG_TYPE;
669 const SLOT: usize = 6;
670 const COLS: &'static [&'static str] = &[
671 "name", "version", "release", "arch", "epoch", "summary", "license", "url", "vendor",
672 "sourcerpm", "provides", "requires",
673 ];
674 const REQUIRED: usize = 2;
675 type Key = (String, String, String, String);
678 type Extra = RpmMetaRow;
680 fn row(c: &Cells<'_>, _: &str) -> (Self::Key, RpmMetaRow) {
681 let lines = |j| split_lines(c.opt(j));
682 let m = RpmMetaRow {
683 name: c.get(0),
684 version: c.get(1),
685 release: c.get(2),
686 arch: c.get(3),
687 epoch: c.opt(4),
688 summary: c.opt(5),
689 license: c.opt(6),
690 url: c.opt(7),
691 vendor: c.opt(8),
692 sourcerpm: c.opt(9),
693 provides: lines(10),
694 requires: lines(11),
695 };
696 ((m.name.clone(), m.version.clone(), m.release.clone(), m.arch.clone()), m)
697 }
698}
699pub type RpmView = CoordView<RpmSpec>;
701pub type RpmPackage = Package<RpmSpec>;
703
704impl RpmView {
705 pub fn get(&self, name: &str, version: &str, release: &str, arch: &str) -> Option<RpmPackage> {
707 self.package(&(name.into(), version.into(), release.into(), arch.into()))
708 }
709 pub fn list(&self) -> Vec<(String, String, String, String, Option<String>)> {
711 self.entries().map(|(k, e)| (k.0.clone(), k.1.clone(), k.2.clone(), k.3.clone(), e.epoch.clone())).collect()
712 }
713 pub fn list_meta(&self) -> Vec<RpmMetaRow> {
715 self.entries().map(|(_, e)| e.clone()).collect()
716 }
717}
718impl RpmPackage {
719 pub fn name(&self) -> &str {
720 &self.key.0
721 }
722 pub fn version(&self) -> &str {
723 &self.key.1
724 }
725 pub fn release(&self) -> &str {
726 &self.key.2
727 }
728 pub fn arch(&self) -> &str {
729 &self.key.3
730 }
731 pub fn epoch(&self) -> Option<&str> {
733 self.extra.epoch.as_deref()
734 }
735}
736
737fn split_lines(v: Option<String>) -> Vec<String> {
740 v.map(|s| s.lines().filter(|l| !l.is_empty()).map(str::to_string).collect()).unwrap_or_default()
741}
742
743spec!(DebSpec);
746impl CoordSpec for DebSpec {
747 const PKG_TYPE: i8 = DEB_PKG_TYPE;
748 const SLOT: usize = 7;
749 const COLS: &'static [&'static str] = &["name", "version", "arch", "control"];
750 const REQUIRED: usize = 1;
751 type Key = (String, String, String);
752 type Extra = Option<String>;
755 fn row(c: &Cells<'_>, _: &str) -> (Self::Key, Option<String>) {
756 ((c.get(0), c.get(1), c.get(2)), c.opt(3))
757 }
758}
759pub type DebView = CoordView<DebSpec>;
761pub type DebPackage = Package<DebSpec>;
763
764impl DebView {
765 pub fn get(&self, name: &str, version: &str, arch: &str) -> Option<DebPackage> {
767 self.package(&(name.into(), version.into(), arch.into()))
768 }
769 pub fn list(&self) -> Vec<(String, String, String, Option<String>)> {
771 self.entries().map(|(k, e)| (k.0.clone(), k.1.clone(), k.2.clone(), e.clone())).collect()
772 }
773}
774impl DebPackage {
775 pub fn name(&self) -> &str {
776 &self.key.0
777 }
778 pub fn version(&self) -> &str {
779 &self.key.1
780 }
781 pub fn arch(&self) -> &str {
782 &self.key.2
783 }
784 pub fn control(&self) -> Option<&str> {
786 self.extra.as_deref()
787 }
788}
789
790pub(crate) const VIEW_SLOTS: usize = 8;