1use dirs::home_dir;
2use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
3use std::{
4 env,
5 io::Write,
6 path::{Path, PathBuf},
7 process::Command,
8 sync::{
9 Mutex, MutexGuard,
10 atomic::{AtomicBool, Ordering},
11 },
12};
13
14use color_eyre::{Result, Section};
15use eyre::{Context, eyre};
16use std::collections::BTreeMap;
17use thiserror::Error;
18
19use std::{fs, fs::File, io::Read};
20
21#[derive(Error, Debug)]
22pub enum SerdeFileError {
23 #[error("File error: {0}")]
24 FileError(#[from] std::io::Error),
25 #[error("JSON parse error: {0}")]
26 JsonParseError(#[from] serde_json::Error),
27 #[error("YAML parse error: {0}")]
28 YamlParseError(#[from] serde_yaml::Error),
29 #[error("TOML parse error: {0}")]
30 TomlParseError(#[from] toml::de::Error),
31 #[error("Unknown file extension: {0}")]
32 UnknownExtension(String),
33 #[error("Could not determine file extension of file {0}")]
34 NoExtension(String),
35}
36
37pub(crate) mod map_as_pairs {
39 use serde::{Deserialize, Deserializer};
40
41 pub fn deserialize<'de, T, K, V, D>(deserializer: D) -> Result<T, D::Error>
42 where
43 D: Deserializer<'de>,
44 T: FromIterator<(K, V)>,
45 K: Deserialize<'de>,
46 V: Deserialize<'de>,
47 {
48 let entries: Vec<_> = Deserialize::deserialize(deserializer)?;
49 Ok(entries.into_iter().collect())
50 }
51}
52
53pub(crate) fn deserialize_nonnegative_finite_f64<'de, D>(
54 deserializer: D,
55) -> std::result::Result<f64, D::Error>
56where
57 D: Deserializer<'de>,
58{
59 let value = f64::deserialize(deserializer)?;
60 if value.is_finite() && value >= 0.0 {
61 Ok(value)
62 } else {
63 Err(serde::de::Error::custom(
64 "expected a finite, nonnegative floating-point value",
65 ))
66 }
67}
68
69fn current_git_commit(git_dir: &Path) -> Option<String> {
70 let output = Command::new("git")
71 .arg("rev-parse")
72 .arg("HEAD")
73 .current_dir(git_dir)
74 .output()
75 .ok()?;
76 if !output.status.success() {
77 return None;
78 }
79
80 let commit = String::from_utf8(output.stdout).ok()?;
81 let commit = commit.trim();
82 if commit.is_empty() {
83 None
84 } else {
85 Some(commit.to_owned())
86 }
87}
88
89fn schema_ref() -> String {
90 env::var("GAMMALOOP_SCHEMA_REF")
91 .ok()
92 .or_else(|| current_git_commit(Path::new(".")))
93 .or_else(|| current_git_commit(Path::new(env!("CARGO_MANIFEST_DIR"))))
94 .unwrap_or_else(|| format!("v{}", env!("CARGO_PKG_VERSION")))
95}
96
97pub trait SmartSerde: Serialize + DeserializeOwned {
98 fn to_file(&self, file_path: impl AsRef<Path>, override_existing: bool) -> Result<()> {
99 if let Some(parent) = file_path.as_ref().parent()
100 && !parent.as_os_str().is_empty()
101 {
102 fs::create_dir_all(parent)?;
103 }
104
105 let mut f = if override_existing {
106 File::create(file_path.as_ref())?
107 } else {
108 File::create_new(file_path.as_ref())?
109 };
110
111 if let Some(ext) = file_path.as_ref().extension() {
112 if let Some(ext) = ext.to_str() {
113 match ext {
114 "json" => serde_json::to_writer_pretty(f, self)
115 .map_err(|e| eyre!(format!("Error serializing json: {}", e)))?,
116 "yaml" | "yml" => serde_yaml::to_writer(f, self)
117 .map_err(|e| eyre!(format!("Error serializing yaml: {}", e)))?,
118 "toml" => {
119 let mut toml_string = if let Some(schema_path) = self.has_schema_path(true)
120 {
121 let schema_path = schema_path?;
122 format!("#:schema {}\n", schema_path.display())
123 } else {
124 String::new()
125 };
126
127 toml_string.push_str(&toml::to_string_pretty(&self)?);
128
129 f.write_all(toml_string.as_bytes())?;
130 }
131 _ => return Err(eyre!(format!("Unknown file extension: {}", ext))),
132 }
133 } else {
134 return Err(eyre!(format!(
135 "Could not determine file extension of file {}",
136 file_path.as_ref().display()
137 )));
138 }
139 } else {
140 return Err(eyre!(format!(
141 "Could not determine file extension of file {}",
142 file_path.as_ref().display()
143 )));
144 }
145
146 Ok(())
147 }
148
149 fn from_file_typed(file_path: impl AsRef<Path>) -> std::result::Result<Self, SerdeFileError> {
162 let mut f = File::open(file_path.as_ref())?;
163
164 if let Some(ext) = file_path.as_ref().extension() {
165 if let Some(ext) = ext.to_str() {
166 match ext {
167 "json" => Ok(serde_json::from_reader(f)?),
168 "yaml" | "yml" => Ok(serde_yaml::from_reader(f)?),
169 "toml" => {
170 let mut buf = String::new();
171 let _bytes = f.read_to_string(&mut buf)?;
172 Ok(toml::from_str(&buf)?)
173 }
174 _ => Err(SerdeFileError::UnknownExtension(ext.to_string())),
175 }
176 } else {
177 Err(SerdeFileError::NoExtension(
178 file_path.as_ref().display().to_string(),
179 ))
180 }
181 } else {
182 Err(SerdeFileError::NoExtension(
183 file_path.as_ref().display().to_string(),
184 ))
185 }
186 }
187
188 fn from_file(file_path: impl AsRef<Path>, name: &str) -> Result<Self> {
189 Self::from_file_typed(file_path.as_ref()).map_err(|e| match e {
190 SerdeFileError::FileError(io_err) => eyre::Report::from(io_err)
191 .wrap_err(format!(
192 "Could not open {} file {}",
193 name,
194 file_path.as_ref().display()
195 ))
196 .suggestion("Does the path exist?"),
197 SerdeFileError::JsonParseError(json_err) => eyre::Report::from(json_err)
198 .wrap_err(format!("Error parsing {} json", name))
199 .suggestion("Is it a correct json file?"),
200 SerdeFileError::YamlParseError(yaml_err) => eyre::Report::from(yaml_err)
201 .wrap_err(format!("Error parsing {} yaml", name))
202 .suggestion("Is it a correct yaml file?"),
203 SerdeFileError::TomlParseError(toml_err) => eyre::Report::from(toml_err)
204 .wrap_err(format!("Error parsing {} toml", name))
205 .suggestion("Is it a correct toml file?"),
206 SerdeFileError::UnknownExtension(ext) => {
207 eyre::eyre!("Unknown {} file extension: {}", name, ext)
208 .suggestion("Is it a .json, .yaml, or .toml file?")
209 }
210 SerdeFileError::NoExtension(path) => eyre::eyre!(
211 "Could not determine file extension of {} file {}",
212 name,
213 path
214 )
215 .suggestion("Does the path exist?"),
216 })
217 }
218
219 fn from_str(contents: String, format: &str, name: &str) -> Result<Self> {
220 match format {
221 "json" => serde_json::from_str(&contents)
222 .map_err(|e| eyre!(format!("Error parsing {name} json: {}", e)))
223 .suggestion("Is it a correct json file"),
224 "yaml" | "yml" => serde_yaml::from_str(&contents)
225 .map_err(|e| eyre!(format!("Error parsing {name} yaml: {}", e)))
226 .suggestion("Is it a correct yaml file"),
227 "toml" => toml::from_str(&contents)
228 .map_err(|e| eyre!(format!("Error parsing {name} toml: {}", e)))
229 .suggestion("Is it a correct toml file"),
230
231 _ => Err(eyre!(format!("Unknown {name} file extension: {}", format)))
232 .suggestion("Is it a .json or .yaml file?"),
233 }
234 }
235
236 fn has_schema_path(&self, _online: bool) -> Option<Result<PathBuf>> {
237 Option::None
238 }
239}
240
241impl<T> SmartSerde for BTreeMap<String, (T, T)> where
242 T: Clone + From<f64> + Serialize + DeserializeOwned
243{
244}
245
246impl SmartSerde for Model {}
247impl SmartSerde for GlobalSettings {
250 fn has_schema_path(&self, online: bool) -> Option<Result<PathBuf>> {
251 Some(get_schema_folder(online).map(|f| f.join("global.json")))
252 }
253}
254impl SmartSerde for RuntimeSettings {
255 fn has_schema_path(&self, online: bool) -> Option<Result<PathBuf>> {
256 Some(get_schema_folder(online).map(|f| f.join("runtime.json")))
257 }
258}
259
260pub fn get_schema_folder(online: bool) -> Result<PathBuf> {
261 let folder = match env::var("GAMMALOOP_SCHEMA_PATH") {
262 Ok(path) => PathBuf::from(path),
263 Err(_) => {
264 if online {
265 let schema_ref = schema_ref();
266 PathBuf::from(format!(
267 "https://raw.githubusercontent.com/alphal00p/gammaloop/{schema_ref}/assets/schemas"
268 ))
269 } else {
270 match home_dir() {
271 Some(home) => home.join(".config").join("gammaloop").join("schemas"),
272 None => {
273 return Err(eyre!("Could not determine home directory")).with_suggestion(
274 || "Set the GAMMALOOP_SCHEMA_PATH environment variable",
275 );
276 }
277 }
278 }
279 }
280 };
281
282 if !online && !folder.exists() {
283 std::fs::create_dir_all(&folder).wrap_err_with(|| {
284 format!(
285 "Could not create schema folder at {}",
286 folder.to_string_lossy()
287 )
288 })?;
289 }
290
291 Ok(folder)
292}
293
294use crate::{
295 model::Model,
296 settings::{GlobalSettings, RuntimeSettings},
297 utils::F,
298};
299
300pub trait IsDefault {
301 fn is_default(&self) -> bool;
302}
303
304pub static SHOWDEFAULTS: AtomicBool = AtomicBool::new(false);
305
306pub(crate) fn show_defaults_helper(condition: bool) -> bool {
307 if SHOWDEFAULTS.load(Ordering::Relaxed) {
308 false
309 } else {
310 condition
311 }
312}
313
314pub struct ShowDefaultsGuard {
315 _lock: MutexGuard<'static, ()>,
316 previous: bool,
317}
318
319impl ShowDefaultsGuard {
320 pub fn new(show_defaults: bool) -> Self {
321 static SHOWDEFAULTS_MUTEX: Mutex<()> = Mutex::new(());
322 let lock = SHOWDEFAULTS_MUTEX
323 .lock()
324 .expect("SHOWDEFAULTS serialization mutex must not be poisoned");
325 let previous = SHOWDEFAULTS.swap(show_defaults, Ordering::Relaxed);
326 Self {
327 _lock: lock,
328 previous,
329 }
330 }
331}
332
333impl Drop for ShowDefaultsGuard {
334 fn drop(&mut self) {
335 SHOWDEFAULTS.store(self.previous, Ordering::Relaxed);
336 }
337}
338
339impl<T: Default + PartialEq> IsDefault for T {
340 fn is_default(&self) -> bool {
341 show_defaults_helper(self == &T::default())
342 }
343}
344
345pub fn is_default_pysecdec_relative_precision(val: &f64) -> bool {
346 show_defaults_helper(*val == 1.0e-7_f64)
347}
348
349pub fn is_default_esurface_existence_threshold(val: &f64) -> bool {
350 show_defaults_helper(*val == super::DEFAULT_ESURFACE_EXISTENCE_THRESHOLD)
351}
352
353pub fn is_default_vakint_normalization(val: &String) -> bool {
354 show_defaults_helper(val == "MSbar")
355}
356
357pub fn is_one_string(val: &String) -> bool {
358 show_defaults_helper(val == "1")
359}
360
361pub fn is_float<const D: i64>(val: &f64) -> bool {
362 show_defaults_helper(*val == D as f64)
363}
364pub fn is_ffloat<const D: i64>(val: &F<f64>) -> bool {
365 show_defaults_helper(*val == F(D as f64))
366}
367
368pub fn is_usize<const D: usize>(val: &usize) -> bool {
369 show_defaults_helper(*val == D)
370}
371
372pub fn is_u64<const D: u64>(val: &u64) -> bool {
373 show_defaults_helper(*val == D)
374}
375
376pub fn is_false(val: &bool) -> bool {
377 show_defaults_helper(!*val)
378}
379
380pub fn is_true(val: &bool) -> bool {
381 show_defaults_helper(*val)
382}
383
384pub fn is_default_input_rescaling(input_rescaling: &Vec<Vec<(f64, f64)>>) -> bool {
385 show_defaults_helper(input_rescaling == &_default_input_rescaling())
386}
387
388pub fn is_default_shifts(shifts: &Vec<(f64, f64, f64, f64)>) -> bool {
389 show_defaults_helper(shifts == &_default_shifts())
390}
391
392pub fn _default_input_rescaling() -> Vec<Vec<(f64, f64)>> {
393 vec![vec![(0.0, 1.0); 3]; 15]
394}
395pub fn _default_shifts() -> Vec<(f64, f64, f64, f64)> {
396 vec![(1.0, 0.0, 0.0, 0.0); 15]
397}
398
399pub fn is_default_form_path(form_path: &String) -> bool {
400 show_defaults_helper(form_path == &_default_form_path())
401}
402
403pub fn _default_form_path() -> String {
404 "form".to_string()
405}
406
407pub fn is_default_python_path(python_path: &String) -> bool {
408 show_defaults_helper(python_path == &_default_python_path())
409}
410
411pub fn _default_python_path() -> String {
412 "python3".to_string()
413}
414
415pub fn is_default_vakint_evaluation_methods(evaluation_methods: &Vec<String>) -> bool {
416 show_defaults_helper(evaluation_methods == &_default_vakint_evaluation_methods())
417}
418
419pub fn _default_vakint_evaluation_methods() -> Vec<String> {
420 vec![
421 "alphaloop".to_string(),
422 "matad".to_string(),
423 "fmft".to_string(),
424 ]
425}
426
427pub fn _default_stability_levels() -> Vec<crate::settings::runtime::StabilityLevelSetting> {
428 vec![
429 crate::settings::runtime::StabilityLevelSetting::default_double(),
430 crate::settings::runtime::StabilityLevelSetting::default_quad(),
431 crate::settings::runtime::StabilityLevelSetting::default_arb(),
432 ]
433}
434
435pub fn is_default_stability_levels(
436 levels: &Vec<crate::settings::runtime::StabilityLevelSetting>,
437) -> bool {
438 show_defaults_helper(levels == &_default_stability_levels())
439}
440
441pub fn _default_rotation_axis() -> Vec<crate::settings::runtime::RotationSetting> {
442 vec![crate::settings::runtime::RotationSetting::EulerAngles {
443 alpha: 0.1,
444 beta: 0.2,
445 gamma: 0.3,
446 }]
447}
448
449pub fn is_default_rotation_axis(
450 rotation_axis: &Vec<crate::settings::runtime::RotationSetting>,
451) -> bool {
452 show_defaults_helper(rotation_axis == &_default_rotation_axis())
453}
454
455#[cfg(test)]
456mod tests {
457 use crate::utils::{load_generic_model, test_utils::output_dir};
458 use std::fs;
459
460 use super::{SerdeFileError, SmartSerde};
461
462 #[test]
463 fn test_file_vs_parse_errors() {
464 use std::collections::BTreeMap;
465
466 let result: Result<BTreeMap<String, (f64, f64)>, SerdeFileError> =
468 SmartSerde::from_file_typed("/nonexistent/file.json");
469
470 match result {
471 Err(SerdeFileError::FileError(_)) => {
472 }
474 other => panic!("Expected FileError, got: {:?}", other),
475 }
476
477 let temp_path = std::env::temp_dir().join("test_invalid.json");
479 fs::write(&temp_path, "{ invalid json content").unwrap();
480
481 let result: Result<BTreeMap<String, (f64, f64)>, SerdeFileError> =
482 SmartSerde::from_file_typed(&temp_path);
483
484 match result {
485 Err(SerdeFileError::JsonParseError(_)) => {
486 }
488 other => panic!("Expected JsonParseError, got: {:?}", other),
489 }
490
491 let _ = fs::remove_file(&temp_path);
493
494 let temp_path = std::env::temp_dir().join("test_valid.json");
496 fs::write(&temp_path, r#"{"key": [1.0, 2.0]}"#).unwrap();
497
498 let result: Result<BTreeMap<String, (f64, f64)>, SerdeFileError> =
499 SmartSerde::from_file_typed(&temp_path);
500
501 assert!(result.is_ok());
502 let data = result.unwrap();
503 assert_eq!(data.get("key"), Some(&(1.0, 2.0)));
504
505 let _ = fs::remove_file(&temp_path);
507 }
508
509 #[test]
510 fn test_from_file_backward_compatibility() {
511 use std::collections::BTreeMap;
512
513 let temp_path = std::env::temp_dir().join("test_compat.json");
515 fs::write(&temp_path, r#"{"test": [1.0, 2.0]}"#).unwrap();
516
517 let result: color_eyre::Result<BTreeMap<String, (f64, f64)>> =
518 SmartSerde::from_file(&temp_path, "test");
519
520 assert!(result.is_ok());
521 let data = result.unwrap();
522 assert_eq!(data.get("test"), Some(&(1.0, 2.0)));
523
524 let _ = fs::remove_file(&temp_path);
526 }
527
528 #[test]
529 fn test_to_file_creates_missing_parent_directories() {
530 use std::collections::BTreeMap;
531
532 let unique_dir = std::env::temp_dir().join(format!(
533 "gammaloop-smart-serde-{}-{}",
534 std::process::id(),
535 std::time::SystemTime::now()
536 .duration_since(std::time::UNIX_EPOCH)
537 .unwrap()
538 .as_nanos()
539 ));
540 let file_path = unique_dir.join("nested").join("data.json");
541
542 let mut data = BTreeMap::new();
543 data.insert("test".to_string(), (1.0, 2.0));
544
545 data.to_file(&file_path, true).unwrap();
546
547 assert!(file_path.exists());
548 let roundtrip: BTreeMap<String, (f64, f64)> =
549 SmartSerde::from_file(&file_path, "test").unwrap();
550 assert_eq!(roundtrip.get("test"), Some(&(1.0, 2.0)));
551
552 fs::remove_dir_all(&unique_dir).unwrap();
553 }
554
555 mod failing {
556 use super::*;
557
558 #[test]
559 fn convert_models() {
560 let name = "scalars";
561 load_generic_model(name)
562 .to_file(
563 output_dir().join(format!("gammaloop_models/{name}.json")),
564 true,
565 )
566 .unwrap();
567 }
568 }
569}