bundle_licenses_lib/
format.rs1use crate::bundle::Bundle;
3use std::io::{self, Read, Write};
4use strum::{EnumString, VariantNames};
5use thiserror::Error;
6
7#[derive(Debug, Error)]
8pub enum FormatError {
9 #[error(transparent)]
10 Io(#[from] io::Error),
11 #[error(transparent)]
12 Json(#[from] serde_json::Error),
13 #[error(transparent)]
14 TomlDeserialize(#[from] toml::de::Error),
15 #[error(transparent)]
16 TomlSerialize(#[from] toml::ser::Error),
17 #[error(transparent)]
18 Yaml(#[from] serde_yaml::Error),
19}
20
21#[derive(EnumString, VariantNames, Debug, Copy, Clone)]
22#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
23#[strum(serialize_all = "kebab-case")]
24pub enum Format {
25 #[strum(serialize = "json")]
26 Json,
27 #[strum(serialize = "toml", serialize = "tml")]
28 Toml,
29 #[strum(serialize = "yaml", serialize = "yml")]
30 Yaml,
31}
32
33impl Format {
34 pub fn serialize_to_writer<W: Write>(
35 self,
36 mut writer: W,
37 bundle: &Bundle,
38 ) -> Result<(), FormatError> {
39 match self {
40 Format::Json => {
41 writer.write_all(serde_json::to_string_pretty(&bundle)?.as_bytes())?;
42 }
43 Format::Toml => {
44 writer.write_all(toml::to_string(&bundle)?.as_bytes())?;
45 }
46 Format::Yaml => {
47 writer.write_all(serde_yaml::to_string(&bundle)?.as_bytes())?;
48 }
49 }
50 Ok(())
51 }
52
53 pub fn deserialize_from_reader<R: Read>(self, mut reader: R) -> Result<Bundle, FormatError> {
54 let bundle: Bundle = match self {
55 Format::Json => serde_json::from_reader(reader)?,
56 Format::Toml => {
57 let mut buffer = String::new();
58 reader.read_to_string(&mut buffer)?;
59 toml::from_str(&buffer)?
60 }
61 Format::Yaml => serde_yaml::from_reader(reader)?,
62 };
63 Ok(bundle)
64 }
65}