Skip to main content

isothrum_runner/downloads/
adopt.rs

1//! Downloads fetched outside the runs (by an earlier program that kept its own record of what it
2//! fetched), adopted into the home's record so they are listed and removed like the runs' own
3//! ([`Runner::adopt_downloads`]). Only what is on this computer now, as it was fetched, is
4//! adopted: an image whose reference stands for another id now, or a box no longer held, is
5//! someone else's, or gone.
6
7use serde::{Deserialize, Serialize};
8
9use super::{Download, DownloadItem};
10use crate::Result;
11use crate::cli::{CliError, docker, vagrant};
12use crate::runner::Runner;
13use crate::tool_output::vagrant::InstalledBox;
14
15/// A download to adopt, as the program that fetched it recorded it.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(tag = "kind", rename_all = "snake_case")]
18#[non_exhaustive]
19pub enum DownloadToAdopt {
20    /// A container image, on this computer's engine (its current Docker context).
21    Image {
22        /// The reference it was pulled as (`nginx:1.27`).
23        reference: String,
24        /// The id the reference stood for once pulled, when recorded: one standing for another
25        /// id now isn't adopted. None: whatever the reference stands for now.
26        #[serde(default, skip_serializing_if = "Option::is_none")]
27        image_id: Option<String>,
28    },
29    /// A Vagrant box version for a provider, of whichever architectures are held.
30    Box {
31        /// Its name (`bento/debian-12`).
32        name: String,
33        /// The provider it is for (`virtualbox`).
34        provider: String,
35        /// Its version.
36        version: String,
37    },
38}
39
40impl Runner {
41    /// Records `adopted` as downloads with no run, each one on this computer now: an image while
42    /// its reference stands for the id given (any, when none is), a box for each architecture
43    /// Vagrant holds it in. One recorded already keeps its row. With no engine or no Vagrant
44    /// installed, nothing of that kind is held, so nothing of it is adopted. The downloads recorded
45    /// for `adopted`, new or not.
46    ///
47    /// # Errors
48    ///
49    /// The engine or Vagrant couldn't say what they hold (adopt again later: nothing was
50    /// recorded); the store can't be written.
51    pub async fn adopt_downloads(&self, adopted: &[DownloadToAdopt]) -> Result<Vec<Download>> {
52        let mut items = Vec::new();
53        let processes = self.docker(None);
54        let images = self.call(&processes);
55        let mut held_boxes: Option<Vec<InstalledBox>> = None;
56        for one in adopted {
57            match one {
58                DownloadToAdopt::Image { reference, image_id } => match docker::image_id(&images, reference).await {
59                    Ok(Some(now)) if image_id.as_ref().is_none_or(|was| *was == now) => items.push(DownloadItem::Image {
60                        reference: reference.clone(),
61                        image_id: now,
62                        docker_context: None,
63                    }),
64                    Ok(_) | Err(CliError::Missing { .. }) => {}
65                    Err(e) => return Err(crate::formats::tool_error("adopt", e)),
66                },
67                DownloadToAdopt::Box { name, provider, version } => {
68                    let held = match &held_boxes {
69                        Some(held) => held,
70                        None => held_boxes.insert(match vagrant::boxes(&self.call(self.config.processes.as_ref())).await {
71                            Ok(held) => held,
72                            Err(CliError::Missing { .. }) => Vec::new(),
73                            Err(e) => return Err(crate::formats::tool_error("adopt", e)),
74                        }),
75                    };
76                    items.extend(
77                        held.iter()
78                            .filter(|b| b.name == *name && b.provider == *provider && b.version == *version)
79                            .cloned()
80                            .map(DownloadItem::of_box),
81                    );
82                }
83            }
84        }
85        self.store
86            .db()
87            .write(|tx| items.iter().try_for_each(|item| tx.record_download(None, item).map(drop)))?;
88        let recorded = self.store.db().read(super::recorded)?;
89        Ok(recorded.into_iter().filter(|d| items.contains(&d.item)).collect())
90    }
91}