|
| 1 | +use std::collections::BTreeMap; |
| 2 | + |
| 3 | +use serde::{Serialize, ser::SerializeSeq}; |
| 4 | +use snafu::{ResultExt, Snafu}; |
| 5 | + |
| 6 | +use crate::{ |
| 7 | + build::bakefile::{Targets, TargetsError, TargetsOptions}, |
| 8 | + show::images::cli::ShowImagesArguments, |
| 9 | +}; |
| 10 | + |
| 11 | +pub mod cli; |
| 12 | + |
| 13 | +#[derive(Debug, Snafu)] |
| 14 | +pub enum Error { |
| 15 | + #[snafu(display("failed to serialize list as JSON"))] |
| 16 | + SerializeList { source: serde_json::Error }, |
| 17 | + |
| 18 | + #[snafu(display("failed to build list of targets"))] |
| 19 | + BuildTargets { source: TargetsError }, |
| 20 | +} |
| 21 | + |
| 22 | +// NOTE (@Techassi): I don't know if I like this... but this makes the stdout output very convient |
| 23 | +// to consume. |
| 24 | +struct OneOrMany(BTreeMap<String, Vec<String>>); |
| 25 | + |
| 26 | +impl Serialize for OneOrMany { |
| 27 | + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 28 | + where |
| 29 | + S: serde::Serializer, |
| 30 | + { |
| 31 | + if self.0.len() == 1 { |
| 32 | + let mut seq = serializer.serialize_seq(Some(1))?; |
| 33 | + for entry in &self.0 { |
| 34 | + for version in entry.1 { |
| 35 | + seq.serialize_element(&version)?; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + Ok(seq.end()?) |
| 40 | + } else { |
| 41 | + self.0.serialize(serializer) |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +pub fn run_command(arguments: ShowImagesArguments) -> Result<(), Error> { |
| 47 | + let list: BTreeMap<_, _> = if arguments.image.is_empty() { |
| 48 | + Targets::all(TargetsOptions { only_entry: true }) |
| 49 | + .context(BuildTargetsSnafu)? |
| 50 | + .into_iter() |
| 51 | + } else { |
| 52 | + Targets::set(&arguments.image, TargetsOptions { only_entry: true }) |
| 53 | + .context(BuildTargetsSnafu)? |
| 54 | + .into_iter() |
| 55 | + } |
| 56 | + .map(|(image_name, image_versions)| { |
| 57 | + let versions: Vec<_> = image_versions |
| 58 | + .into_iter() |
| 59 | + .map(|(image_version, (_, _))| image_version) |
| 60 | + .collect(); |
| 61 | + (image_name, versions) |
| 62 | + }) |
| 63 | + .collect(); |
| 64 | + |
| 65 | + print_to_stdout(list, arguments.pretty) |
| 66 | +} |
| 67 | + |
| 68 | +fn print_to_stdout(list: BTreeMap<String, Vec<String>>, pretty: bool) -> Result<(), Error> { |
| 69 | + let stdout = std::io::stdout(); |
| 70 | + |
| 71 | + let list = OneOrMany(list); |
| 72 | + |
| 73 | + if pretty { |
| 74 | + serde_json::to_writer_pretty(stdout, &list).context(SerializeListSnafu) |
| 75 | + } else { |
| 76 | + serde_json::to_writer(stdout, &list).context(SerializeListSnafu) |
| 77 | + } |
| 78 | +} |
0 commit comments