gldf-rs 0.3.4

GLDF (General Lighting Data Format) parser and writer for Rust, specifically for the Rust/WASM target as such designed for JSON format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#![allow(unused_variables)]

use std::env;
use std::fs;

use anyhow::Result;
use serde::de::StdError;

#[cfg(feature = "http")]
use super::fetch_content_from_url;
use crate::gldf::{FormatVersion, GldfProduct};

const GLDF_FILE_NAME: &str = "../../tests/data/R2MCOBSIK-30.gldf";

#[test]
fn test_default() {
    let gldf = GldfProduct::default();
    println!("{:?}", gldf);
    println!("{:?}", gldf.to_json());
}

#[test]
fn parsing_gldf_container() -> Result<(), Box<dyn StdError>> {
    use serde_json::from_str as serde_from_str;
    let loaded: GldfProduct = GldfProduct::load_gldf(GLDF_FILE_NAME).unwrap();
    let general_files = loaded.get_all_file_definitions().unwrap();
    println!("{:?}", loaded);

    // Test JSON round-trip
    let gldf_to_json = loaded.to_json()?;
    let gldf_to_xml = loaded.to_xml()?;
    let json_to_xml = GldfProduct::from_json(&gldf_to_json)?.to_xml()?;
    assert_eq!(gldf_to_xml, json_to_xml);

    // Test XML round-trip
    let result = GldfProduct::from_xml(&gldf_to_xml)?;
    let xml_to_json = result.to_json().unwrap();

    let x_serialized = loaded.to_xml().unwrap();
    println!("{}", x_serialized);

    let json_str = serde_json::to_string(&loaded).unwrap();
    println!("{}", json_str);

    let j_loaded: GldfProduct = serde_from_str(&json_str).unwrap();
    let x_reserialized = j_loaded.to_xml().unwrap();
    println!("{}", x_reserialized);

    assert_eq!(x_serialized, x_reserialized);
    Ok(())
}

#[test]
fn test_gldf_product_impls() {
    let loaded: GldfProduct = GldfProduct::load_gldf(GLDF_FILE_NAME).unwrap();
    println!("{:?}", loaded);

    // Display pretty printed XML
    let x_serialized = loaded.to_xml().unwrap();
    println!("{}", x_serialized);

    let json_str = loaded.to_json().unwrap();
    let j_loaded: GldfProduct = GldfProduct::from_json(&json_str).unwrap();
    let x_reserialized = j_loaded.to_xml().unwrap();
    println!("{}", x_reserialized);
    println!(r#"{{"product":"#);
    println!("{}", loaded.to_json().unwrap());
    println!("}}");

    assert_eq!(x_serialized, x_reserialized);
}

#[allow(dead_code)]
fn read_test_gldf() -> std::io::Result<Vec<u8>> {
    use std::io::Read;
    let mut gldf_file = std::fs::File::open(GLDF_FILE_NAME)?;
    let mut file_buf = Vec::new();
    gldf_file.read_to_end(&mut file_buf)?;
    Ok(file_buf)
}

#[test]
fn test_gldf_from_buf() {
    // Get the current directory.
    let current_dir = env::current_dir().expect("Failed to get current directory");

    // Define the relative path to your test data from the project root.
    // From crates/gldf-rs-lib/ we need to go up two levels to workspace root
    let test_data_dir = current_dir
        .parent()
        .expect("Failed to get parent directory")
        .parent()
        .expect("Failed to get workspace root")
        .join("tests")
        .join("data");

    let mut success_count = 0;
    let mut failure_count = 0;
    let mut failed_files: Vec<String> = Vec::new();

    // Get all gldf files in the directory.
    for entry in fs::read_dir(&test_data_dir).expect("Failed to read test data directory") {
        let entry = match entry {
            Ok(e) => e,
            Err(e) => {
                eprintln!("Failed to read directory entry: {}", e);
                continue;
            }
        };
        let path = entry.path();
        if path.extension() == Some(std::ffi::OsStr::new("gldf")) {
            let file_name = path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_else(|| "unknown".to_string());

            println!("\n=== Testing: {} ===", file_name);

            let file_buf = match fs::read(&path) {
                Ok(buf) => buf,
                Err(e) => {
                    eprintln!("  ERROR: Failed to read file: {}", e);
                    failure_count += 1;
                    failed_files.push(format!("{}: read error - {}", file_name, e));
                    continue;
                }
            };

            let loaded = match GldfProduct::load_gldf_from_buf_all(file_buf) {
                Ok(l) => l,
                Err(e) => {
                    eprintln!("  ERROR: Failed to parse GLDF: {:?}", e);
                    // Print the full error chain
                    let mut source = e.source();
                    while let Some(cause) = source {
                        eprintln!("    Caused by: {}", cause);
                        source = cause.source();
                    }
                    failure_count += 1;
                    failed_files.push(format!("{}: parse error - {:?}", file_name, e));
                    continue;
                }
            };

            // Test XML serialization
            let x_serialized = match loaded.gldf.to_xml() {
                Ok(xml) => xml,
                Err(e) => {
                    eprintln!("  ERROR: Failed to serialize to XML: {}", e);
                    failure_count += 1;
                    failed_files.push(format!("{}: XML serialization error - {}", file_name, e));
                    continue;
                }
            };

            // Test JSON serialization
            let json_str = match loaded.gldf.to_json() {
                Ok(json) => json,
                Err(e) => {
                    eprintln!("  ERROR: Failed to serialize to JSON: {}", e);
                    failure_count += 1;
                    failed_files.push(format!("{}: JSON serialization error - {}", file_name, e));
                    continue;
                }
            };

            // Test JSON round-trip
            let j_loaded = match GldfProduct::from_json(&json_str) {
                Ok(l) => l,
                Err(e) => {
                    eprintln!("  ERROR: Failed to deserialize from JSON: {}", e);
                    failure_count += 1;
                    failed_files.push(format!("{}: JSON deserialization error - {}", file_name, e));
                    continue;
                }
            };

            let j_reserialized = match j_loaded.to_xml() {
                Ok(xml) => xml,
                Err(e) => {
                    eprintln!("  ERROR: Failed to re-serialize to XML: {}", e);
                    failure_count += 1;
                    failed_files.push(format!("{}: XML re-serialization error - {}", file_name, e));
                    continue;
                }
            };

            // Verify round-trip
            if x_serialized != j_reserialized {
                eprintln!("  WARNING: Round-trip XML mismatch");
            }

            // Get photometric files
            if let Ok(phot_files) = GldfProduct::get_phot_files(&loaded.gldf) {
                println!("  Photometric files: {}", phot_files.len());
                for p_f in phot_files.iter() {
                    println!("    - {}", p_f.file_name);
                }
            }

            println!("  SUCCESS: {} parsed and serialized correctly", file_name);
            success_count += 1;
        }
    }

    // Print summary
    println!("\n=== Summary ===");
    println!("Success: {}", success_count);
    println!("Failures: {}", failure_count);
    if !failed_files.is_empty() {
        println!("\nFailed files:");
        for f in &failed_files {
            println!("  - {}", f);
        }
    }

    // Assert all files parsed successfully
    assert!(
        failed_files.is_empty(),
        "Some GLDF files failed to parse: {:?}",
        failed_files
    );
}

#[tokio::test]
async fn test_gldf_get_phot_files() {
    let loaded: GldfProduct = GldfProduct::load_gldf(GLDF_FILE_NAME).unwrap();
    let phot_files = loaded.get_phot_files().unwrap();
    let mut ldc_contents: Vec<String> = Vec::new();
    for f in phot_files.iter() {
        let file_id = f.id.to_string();
        let result = loaded.get_ldc_by_id(file_id).await.unwrap();
        ldc_contents.push(result);
        println!("{}", f.file_name);
    }
}

#[cfg(feature = "http")]
#[tokio::test]
async fn test_gldf_get_pic_files() {
    let loaded: GldfProduct = GldfProduct::load_gldf(GLDF_FILE_NAME).unwrap();
    let image_files = loaded.get_image_def_files().unwrap();
    let mut file_contents: Vec<Vec<u8>> = Vec::new();
    for f in image_files.iter() {
        let file_id = f.id.to_string();
        let result = fetch_content_from_url(&f.file_name).await.unwrap();
        file_contents.push(result);
        println!("{}", f.file_name);
    }
}

/// Test round-trip: Load -> Modify -> Save -> Reload -> Verify
#[test]
fn test_editable_gldf_round_trip() {
    use crate::gldf::general_definitions::files::File;
    use crate::EditableGldf;

    // Load GLDF into EditableGldf
    let mut editable = EditableGldf::from_gldf(GLDF_FILE_NAME).expect("Failed to load GLDF");

    // Verify initial state
    let original_author = editable.product.header.author.clone();
    let original_file_count = editable.product.general_definitions.files.file.len();
    assert!(!editable.is_modified());

    // Make modifications
    editable.product.header.author = "Test Author - Round Trip".to_string();
    editable.mark_modified();

    // Add a new file definition
    let new_file = File {
        id: "roundtrip_test_file".to_string(),
        content_type: "other".to_string(),
        type_attr: "localFileName".to_string(),
        file_name: "test_roundtrip.txt".to_string(),
        language: String::new(),
    };
    editable
        .product
        .add_file(new_file.clone())
        .expect("Failed to add file");

    // Add embedded content for the file
    let test_content = b"This is test content for round-trip verification".to_vec();
    editable.add_embedded_file("roundtrip_test_file", test_content.clone());

    // Verify modifications are tracked
    assert!(editable.is_modified());

    // Save to buffer
    let saved_buf = editable.save_to_buf().expect("Failed to save to buffer");
    println!("Saved GLDF size: {} bytes", saved_buf.len());

    // Reload from buffer
    let reloaded = EditableGldf::from_buf(saved_buf).expect("Failed to reload GLDF from buffer");

    // Verify modifications were preserved
    assert_eq!(reloaded.product.header.author, "Test Author - Round Trip");
    assert_eq!(
        reloaded.product.general_definitions.files.file.len(),
        original_file_count + 1
    );

    // Verify new file exists
    let found_file = reloaded.product.get_file("roundtrip_test_file");
    assert!(found_file.is_some(), "New file not found after reload");
    assert_eq!(found_file.unwrap().file_name, "test_roundtrip.txt");

    // Verify embedded content was preserved
    let embedded = reloaded.get_embedded_file("roundtrip_test_file");
    assert!(embedded.is_some(), "Embedded file content not found");
    assert_eq!(embedded.unwrap(), test_content.as_slice());

    // Verify original data is still intact
    assert_ne!(reloaded.product.header.author, original_author);

    println!("Round-trip test passed!");
}

/// Test creating a new GLDF from scratch and saving it
#[test]
fn test_create_new_gldf() {
    use crate::gldf::general_definitions::files::File;
    use crate::gldf::product_definitions::Variant;
    use crate::EditableGldf;

    // Create new EditableGldf
    let mut editable = EditableGldf::new();

    // Set header info
    editable.product.header.author = "New Product Author".to_string();
    editable.product.header.manufacturer = "Test Manufacturer".to_string();
    editable.product.header.format_version = FormatVersion::from_string("1.0.0-rc.3");

    // Add a file definition
    let file = File {
        id: "photometry_1".to_string(),
        content_type: "ldc/eulumdat".to_string(),
        type_attr: "localFileName".to_string(),
        file_name: "test.ldt".to_string(),
        language: String::new(),
    };
    editable.product.add_file(file).expect("Failed to add file");

    // Add fake photometry content
    editable.add_embedded_file("photometry_1", b"FAKE LDT CONTENT".to_vec());

    // Add a variant
    let variant = Variant {
        id: "variant_1".to_string(),
        ..Default::default()
    };
    editable
        .product
        .add_variant(variant)
        .expect("Failed to add variant");

    // Validate the product
    let validation = editable.product.validate_structure();
    println!("Validation errors: {}", validation.errors.len());
    for err in &validation.errors {
        println!("  {:?}: {} - {}", err.level, err.path, err.message);
    }

    // Save to buffer
    let saved_buf = editable.save_to_buf().expect("Failed to save new GLDF");
    println!("New GLDF size: {} bytes", saved_buf.len());

    // Verify it can be reloaded
    let reloaded = EditableGldf::from_buf(saved_buf).expect("Failed to reload new GLDF");

    assert_eq!(reloaded.product.header.author, "New Product Author");
    assert_eq!(reloaded.product.header.manufacturer, "Test Manufacturer");
    assert!(reloaded.product.get_file("photometry_1").is_some());
    assert!(reloaded.product.get_variant("variant_1").is_some());

    println!("Create new GLDF test passed!");
}

/// Test loading GLDF with embedded WASM viewer plugin (star_sky.gldf)
#[test]
fn test_star_sky_gldf_with_plugin() {
    // Load the star_sky.gldf test file
    let test_file = "../../tests/data/star_sky.gldf";

    // Check if file exists (test may be skipped if not generated)
    if !std::path::Path::new(test_file).exists() {
        println!("Skipping test: {} not found", test_file);
        println!("Generate with: python3 scripts/create_star_sky_test.py");
        return;
    }

    let file_buf = fs::read(test_file).expect("Failed to read star_sky.gldf");
    let loaded =
        GldfProduct::load_gldf_from_buf_all(file_buf).expect("Failed to parse star_sky.gldf");

    // Verify basic GLDF structure
    assert_eq!(loaded.gldf.header.manufacturer, "Star Sky Test");
    println!("Manufacturer: {}", loaded.gldf.header.manufacturer);

    // Check for embedded files
    println!("Embedded files: {}", loaded.files.len());
    for file in &loaded.files {
        println!(
            "  - {:?}: {} bytes",
            file.name,
            file.content.as_ref().map(|c| c.len()).unwrap_or(0)
        );
    }

    // Find sky_data.json
    let sky_data = loaded.files.iter().find(|f| {
        f.name
            .as_ref()
            .map(|n| n.contains("sky_data.json"))
            .unwrap_or(false)
    });
    assert!(sky_data.is_some(), "sky_data.json not found in GLDF");

    // Verify sky_data.json contains star data
    if let Some(sky_file) = sky_data {
        let content = sky_file
            .content
            .as_ref()
            .expect("sky_data.json has no content");
        let json_str = String::from_utf8_lossy(content);
        assert!(
            json_str.contains("\"stars\""),
            "sky_data.json missing stars array"
        );
        assert!(
            json_str.contains("Sirius"),
            "sky_data.json missing Sirius star"
        );
        println!("sky_data.json: {} bytes, contains star data", content.len());
    }

    // Find viewer plugin manifest
    let manifest = loaded.files.iter().find(|f| {
        f.name
            .as_ref()
            .map(|n| n.contains("other/viewer/starsky/manifest.json"))
            .unwrap_or(false)
    });
    assert!(
        manifest.is_some(),
        "Plugin manifest not found at other/viewer/starsky/manifest.json"
    );

    // Verify manifest content
    if let Some(manifest_file) = manifest {
        let content = manifest_file
            .content
            .as_ref()
            .expect("manifest.json has no content");
        let json_str = String::from_utf8_lossy(content);
        assert!(
            json_str.contains("\"type\": \"starsky\""),
            "manifest missing type: starsky"
        );
        assert!(
            json_str.contains("gldf_starsky_wasm.js"),
            "manifest missing js file reference"
        );
        assert!(
            json_str.contains("gldf_starsky_wasm_bg.wasm"),
            "manifest missing wasm file reference"
        );
        println!("Plugin manifest: valid starsky plugin");
    }

    // Find WASM binary
    let wasm = loaded.files.iter().find(|f| {
        f.name
            .as_ref()
            .map(|n| n.ends_with(".wasm"))
            .unwrap_or(false)
    });
    assert!(wasm.is_some(), "WASM binary not found in GLDF");

    if let Some(wasm_file) = wasm {
        let content = wasm_file
            .content
            .as_ref()
            .expect("WASM file has no content");
        // WASM files start with magic bytes: 0x00 0x61 0x73 0x6D ("\0asm")
        assert!(content.len() > 4, "WASM file too small");
        assert_eq!(&content[0..4], b"\0asm", "Invalid WASM magic bytes");
        println!("WASM binary: {} bytes, valid WASM format", content.len());
    }

    // Find JS loader
    let js = loaded.files.iter().find(|f| {
        f.name
            .as_ref()
            .map(|n| n.contains("gldf_starsky_wasm.js"))
            .unwrap_or(false)
    });
    assert!(js.is_some(), "JS loader not found in GLDF");

    println!("\nStar Sky GLDF plugin test passed!");
    println!("  - GLDF structure: valid");
    println!("  - Sky data: present");
    println!("  - Plugin manifest: valid");
    println!("  - WASM binary: valid");
    println!("  - JS loader: present");
}