1use serde::de::DeserializeOwned;
2use serde::{Deserialize, Serialize};
3
4#[derive(Clone)]
5#[derive(Deserialize)]
6#[derive(Serialize)]
7#[derive(Hash)]
8#[derive(Debug)]
9pub enum FlatpakManifestFormat {
12 YAML,
13 JSON,
14 #[cfg(feature = "toml")]
15 TOML,
16}
17impl Default for FlatpakManifestFormat {
18 fn default() -> Self {
19 FlatpakManifestFormat::YAML
20 }
21}
22impl FlatpakManifestFormat {
23 pub fn from_path(file_path: &str) -> Option<FlatpakManifestFormat> {
24 if file_path.to_lowercase().ends_with("yaml") || file_path.to_lowercase().ends_with("yml") {
25 return Some(FlatpakManifestFormat::YAML);
26 }
27 if file_path.to_lowercase().ends_with("json") {
28 return Some(FlatpakManifestFormat::JSON);
29 }
30 #[cfg(feature = "toml")]
31 if file_path.to_lowercase().ends_with("toml") {
32 return Some(FlatpakManifestFormat::TOML);
33 }
34 None
35 }
36
37 pub fn parse<T>(&self, content: &str) -> Result<T, String>
38 where
39 T: DeserializeOwned,
40 {
41 match self {
42 FlatpakManifestFormat::YAML => serde_yaml::from_str::<T>(content).map_err(|e| e.to_string()),
43 FlatpakManifestFormat::JSON => {
44 let json_content_without_comments = crate::utils::remove_comments_from_json(content);
45 serde_json::from_str::<T>(&json_content_without_comments).map_err(|e| e.to_string())
46 }
47 #[cfg(feature = "toml")]
48 FlatpakManifestFormat::TOML => toml::from_str::<T>(content).map_err(|e| e.to_string()),
49 }
50 }
51
52 pub fn dump<T>(&self, manifest: &T) -> Result<String, String>
53 where
54 T: Serialize,
55 {
56 match self {
57 FlatpakManifestFormat::YAML => serde_yaml::to_string::<T>(manifest).map_err(|e| e.to_string()),
58 FlatpakManifestFormat::JSON => {
59 serde_json::to_string_pretty::<T>(manifest).map_err(|e| e.to_string())
60 }
61 #[cfg(feature = "toml")]
62 FlatpakManifestFormat::TOML => toml::to_string_pretty::<T>(manifest).map_err(|e| e.to_string()),
63 }
64 }
65}